diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 0380b02e1e..8c7f823a07 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -4293,6 +4293,7 @@ /types/timer-machine/ @dolanmiu /types/timezone-js/ @bonnici /types/tinajs__tina/ @Jimexist +/types/tinajs__tina-redux/ @Jimexist /types/tinder/ @pingec /types/tiny-slider-react/ @screendriver /types/tinycolor2/ @M-Zuber @geertjansen @nvh diff --git a/README.ko.md b/README.ko.md new file mode 100644 index 0000000000..224967a9dc --- /dev/null +++ b/README.ko.md @@ -0,0 +1,338 @@ +# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) + +[![깃터(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) + +> 이 저장소는 고품질의 타입스크립트(TypeScript) 자료형 정의(Type definition)를 위한 저장소입니다. + +이 문서가 가장 최신 내용을 담고있긴 하지만, [공식 사이트(definitelytyped.org)](http://definitelytyped.org)도 확인해보시면 좋습니다. + +## 선언 파일(Declaration file)이 뭔가요? + +[타입스크립트 안내서(TypeScript handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)를 읽어보세요. + +## 선언 파일(Declaration file)을 어떻게 받을 수 있나요?? + +### npm 사용하기 + +아래 방법은 타입스크립트(TypeScript) 2.0+ 이상의 버전을 사용하는 사람들만 사용할 수 있는 방법이기는 합니다만, 이 방법을 사용하기를 장려합니다. + +```sh +npm install --save-dev @types/node +``` + +`node` 를 위한 자료형(Typing)이 컴파일 과정에 자동으로 포함될 겁니다. +더 자세한 내용은 [안내서(Handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html)에서 확인해보실 수 있습니다. + +NPM 의 "foo" 패키지에 대응되는 자료형 패키지는 "@types/foo" 입니다. +원하시는 패키지를 찾을 수 없는 경우, [타입서치(TypeSearch)](https://microsoft.github.io/TypeSearch/) 사이트에서 한 번 찾아보세요. + +타입서치(TypeSearch)에서도 찾을 수 없는 경우, 찾고 있는 패키지가 자료형(Typing)을 +[함께 제공](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)하고 있지는 않은지 확인해보세요. +패키지에 포함된 자료형(Typing)은 주로 `package.json` 파일의 `"types"` 나 `"typings"` 필드(Field)를 통해 제공되지만, +`/// ` 같은 주석을 사용하여 패키지 안의 ".d.ts" 파일들을 직접 가져와야 할 수도 있습니다. + + +### 그 외의 방법들 + +타입스크립트(TypeScript) 1.0 버전에서 사용할 수 있는 방법은 다음과 같습니다. + +* [Typings](https://github.com/typings/typings) 을 사용하기 +* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped) 을 사용하기~~ (다른 방법을 사용해주세요. NuGet 은 더 이상 DT 자료형(Typing)을 제공하지 않습니다.) +* 이 저장소의 `master` 브랜치를 직접 내려받기 + +위 방법을 사용할 경우 수동으로 [참조(Reference)](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html)를 추가해주어야 할 수 있습니다. + + +## 어떻게 이곳에 기여할 수 있나요? + +여러분과 같은 많은 기여자들의 도움 덕분에 이 저장소가 돌아가고 있습니다. 감사합니다. + +### 테스트 + +여러분이 만든 자료형 선언(Type declation)을 세상에 공유하기에 앞서, 여러분이 스스로 여러분의 자료형 선언(Type declation)을 사용하고 확인해주세요. + +#### 이미 존재하는 자료형 패키지를 임시로 수정하기 + +이미 존재하는 패키지의 자료형 선언(Type declaration)에 새로운 기능을 추가하려면 [모듈 증강(module augmentation)](http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)를 사용할 수 있습니다. +물론 `node_modules/@types/foo/index.d.ts` 를 직접 수정하실 수도 있으며, 이 파일을 복사한 다음 아래의 과정을 따라하실 수도 있습니다. + + +#### 새 자료형 패키지를 임시로 추가하기 + +사용하고 계신 `tsconfig.json` 에 다음 내용을 추가해주세요. + +```json +"baseUrl": "types", +"typeRoots": ["types"], +``` + +(`types` 대신 `src/types` 을 사용하실 수도 있습니다.) +그리고 "foo" 모듈(Module)에 대한 선언(Declaration)을 포함하는 `types/foo/index.d.ts` 파일을 만들어주세요. +이제 코드 안에서 여러분의 새 자료형 선언(Type declaration)을 사용하는 `"foo"` 모듈(Module)을 임포트(Import)하실 수 있을 겁니다. +코드를 컴파일하고 실행시켜서 여러분의 자료형(Typing)이 실행 중에 실제로 벌어지는 일과 잘 맞아떨어지는지 확인해주세요. +실제 코드를 통한 확인이 끝나면, [풀 리퀘스트(Pull request)](#풀-리퀘스트pull-request-만들기)를 만들어주세요. +[이미 존재하는 패키지를 수정](#이미-존재하는-패키지를-수정하기)하거나 [새 패키지를 만들기](#새-패키지-만들기)위한 과정들을 따라하시면 됩니다. + + +### 풀 리퀘스트(Pull request) 만들기 + +여러분의 자료형 선언이 잘 작동하는지 확인하셨다면, DefinitelyTyped 에 공유해주세요. + +우선, 이 저장소를 [포크(fork)](https://guides.github.com/activities/forking/)해 주시고, [node](https://nodejs.org/) 를 설치하신 뒤, `npm install` 명령을 실행해주세요. + + +#### 이미 존재하는 패키지를 수정하기 + +* `cd types/my-package-to-edit` 명령을 실행합니다. +* 자료형(Typing) 파일들을 수정합니다. 테스트를 추가하는 것도 잊지마세요! + 만약 브레이킹 체인지(Breaking change)를 만드셨다면, [메이저 버전(major version)](#i-want-to-update-a-package-to-a-new-major-version)을 꼭 올려주세요. +* 패키지 머릿주석의 "Definitions by" 부분에 여러분의 이름을 추가하실 수도 있습니다. + - 이름을 추가하시면 다른 사람들이 그 패키지에 대한 풀 리퀘스트(Pull request)나 이슈(Issue)를 만들 때 여러분에게 알람이 갑니다. + - `// Definitions by: Alice , Bob ` 와 같이 여러분의 이름을 줄의 맨 마지막에 추가할 수 있습니다. + - 사람이 너무 많을 경우엔, 다음과 같이 여러 줄로 쓰실 수도 있습니다. + ```typescript + // Definitions by: Alice + // Bob + // Steve + // John + ``` +* `tslint.json` 파일이 있는 경우에는, `npm run lint package-name` 명령을 실행시키고 결과를 확인해주세요. 그렇지 않은 경우에는, 해당 패키지가 있는 디렉토리 안에서 `tsc` 명령을 실행시키고 결과를 확인해주세요. + +이미 존재하는 패키지에 대한 풀 리퀘스트(Pull request)를 만들었을 경우에는, `dt-bot` 이 이전 저자들을 자동으로 호출하는지 확인해주세요. +그렇지 않은 경우에는, 여러분이 직접 풀 리퀘스트(Pull request)와 관계있는 사람들을 호출할 수도 있습니다. + + +#### 새 패키지를 만들기 + +만약 라이브러리를 만드는 중이고 라이브러리가 타입스크립트(TypeScript)로 쓰여있다면, DefinitelyTyped 에 선언(Declaration)을 올리는 대신 패키지에 [자동생성된 선언(Declaration) 파일을 포함](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)시킬 수 있습니다. + +NPM 패키지를 위한 자료형(Typing) 패키지를 만드시려면, 패키지의 이름과 같은 이름의 디렉토리를 만들어주세요. +NPM 에 올라가 있지 않은 패키지를 위한 자료형(Typing) 패키지를 만드시려면, 그 패키지가 NPM 에 올라와 있는 패키지와 이름이 겹치지 않는지 확인해주세요. +(`npm info foo` 명령어를 사용하여 `foo` 패키지가 NPM 에 있는지 확인할 수 있습니다.) + +새 자료형 패키지는 다음과 같은 구조로 구성되어있어야만 합니다. + +| 파일 이름 | 용도 | +| --- | --- | +| index.d.ts | 패키지를 위한 자료형(Typing)을 포함하는 파일입니다. | +| foo-tests.ts | 자료형(Typing)의 테스트를 위한 파일입니다. 이 파일의 코드는 실행되지는 않지만, 자료형 검사(Type checking)를 통과해야 합니다. | +| tsconfig.json | `tsc` 명령을 돌릴 수 있게 해주는 파일입니다. | +| tslint.json | 린터(Linter)를 사용할 수 있게 해주는 파일입니다. | + +이 파일들은, npm ≥ 5.2.0 에서는 `npx dts-gen --dt --name my-package-name --template module` 명령으로, +그 이하 경우에는 `npm install -g dts-gen` 와 `dts-gen --dt --name my-package-name --template module` 명령으로 만들 수 있습니다. +`dts-gen` 의 모든 옵션(Option)을 보고싶으시면 [dts-gen](https://github.com/Microsoft/dts-gen) 저장소를 확인해주세요. + +자료형(Typing) 패키지에 새 파일을 추가하거나, `async` 키워드를 사용하기 위해 `"target"` 을 `"es6"` 로 설정하거나, `"lib"` 를 추가하거나, `jsx` 지원을 추가하기 위해서 `tsconfig.json` 파일을 변경해야 할 수도 있습니다. + +DefinitelyTyped 의 관리자들이 주기적으로 새로운 풀 리퀘스트(Pull request)들을 확인하기는 하지만, +다른 풀 리퀘스트(Pull request)가 많을 경우 확인이 느려질 수 있다는 걸 알아주세요. + +[base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js) 패키지는 좋은 예시 중 하나입니다. + + +#### 많이 저지르는 실수들 + +* 우선, [안내서(Handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html)에 나와있는 내용들을 따라주세요. +* 코드에서는 모든 곳에서 탭(Tab)을 사용하거나, 항상 4 개의 띄어쓰기를 사용해주세요. +* `function sum(nums: number[]): number`의 경우, 만약 함수가 인자를 변경하지 않는다면 `ReadonlyArray` 를 사용해주세요. +* `interface Foo { new(): Foo; }`의 경우, + 이런 선언은 이 형(Type)을 가진 객체(Object)에 `new` 를 사용할 수 있도록 만듭니다. 많은 경우 여러분은 `declare class Foo { constructor(); }` 를 사용하려는 것일 겁니다. +* `const Class: { new(): IClass; }`의 경우, + `new` 를 사용할 수 있는 상수를 만드는 대신, `class Class { constructor(); }` 와 같이 클래스 선언(Class declaration)을 사용하는 게 더 좋습니다. +* `getMeAT(): T`의 경우, + 만일 자료형 매개변수(Type parameter)가 함수의 매개변수에 등장하지 않는다면, 그런 제너릭(Generic) 함수를 사용할 필요가 없습니다. + 그 제너릭(Generic) 함수는 단순히 자료형 단언(Type assertion)을 위장시킨 것뿐입니다. 이 경우 `getMeAT() as number` 와 같이 진짜 자료형 단언(Type assertion) 을 사용하는 게 더 좋습니다. + 다음은 괜찮은 제너릭(Generic)의 예시입니다. `function id(value: T): T;`. + 다음은 문제가 있는 제너릭(Generic)의 예시입니다. `function parseJson(json: string): T;`. + 예외적으로, `new Map()` 와 같은 경우는 괜찮습니다. +* `Function` 이나 `Object` 와 같은 형(Type)을 사용하는 것은 대부분의 경우 문제를 일으킵니다. 99% 의 경우 더 구체적인 형(Type)을 사용하는게 가능합니다. [함수(Function)](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) 를 위해서는 `(x: number) => number` 와 같은, 객체를 위해서는 `{ x: number, y: number }` 와 같은 형(Type)들을 사용할 수 있습니다. 형(Type)에 대한 정보가 전혀 없을 경우에는, `Object` 형(Type)이 아니라 [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) 형(Type)을 사용해야 합니다. 만일 어떤 형(Type)이 객체라는 사실만 알고 있는 경우, `Object` 나 `{ [key: string]: any }` 가 아니라 [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type) 를 사용해주세요. +* `var foo: string | any`의 경우, + `any` 가 합 자료형(Union type)의 안에서 사용될 경우, 결과 형(Type)은 언제나 `any` 가 됩니다. 따라서 형(Type)의 `string` 부분이 유용해 보인다 하더라도, 사실은 자료형 검사(Type checking)의 측면에서 `any` 와 다른 것이 없습니다. + 대신, `any`, `string`, 나 `string | object` 중 하나를 필요에 맞게 골라서 사용해주세요. + + +#### 패키지 삭제하기 + +패키지가 스스로의 형(Type)을 [포함](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)하게 되면, DefinitelyTyped 에 있는 자료형(Typing) 패키지를 삭제하는 것이 좋습니다. + +`npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]` 명령어를 사용하여 자료형(Typing) 패키지를 삭제할 수 있습니다. +- `typingsPackageName` 는 삭제할 디렉토리의 이름입니다. +- `asOfVersion` 는 새 스텁(Stub) 용 `@types/foo` 를 퍼블리시(Publish)할 버전입니다. 이 버전은 현재 NPM 에 올라간 버전보다 더 높은 버전이어야 합니다. +- `sourceRepoURL` 는 자료형(Typing)을 포함하게 된 저장소의 주소입니다. +- `libraryName` 는 패키지의 이름을 읽기 쉽게 쓴 것입니다. 즉, "angular2" 대신에 "Angular 2" 와 같이 쓰는 것이 좋습니다. (생략했을 경우에는 "typingsPackageName" 와 같은 것으로 취급됩니다.) + +DefinitelyTyped 의 다른 패키지들이 삭제된 자료형(Typing) 패키지를 사용하고 있을 경우, 형(Type)을 포함하기 시작한 원래 패키지를 사용하도록 수정해야합니다. 삭제된 자료형(Typing) 패키지를 사용하는 각 DefinitelyTyped 패키지들의 `package.json` 파일에 `"dependencies": { "foo": "x.y.z" }` 를 추가해주시면 됩니다. + +DefinitelyTyped 에 한 번도 올라온 적 없는 패키지가 형(Type)을 포함하게 되었다면, `notNeededPackages.json` 파일에 추가할 필요도 없습니다. + + +#### 린트(Lint)하기 + +자료형(Typing) 패키지를 린트(Lint)하려면, 패키지 디렉토리에 `{ "extends": "dtslint/dt.json" }` 를 포함하고 있는 `tslint.json` 파일을 추가해주시면 됩니다. 모든 새 패키지는 해당 파일을 가지고 있어야 합니다. +고쳐야 하지만 아직 고쳐지지 않은 린트(Lint) 결과가 있을 때에만 `tslint.json` 에서 린트 규칙(Lint rule)을 사용하지 않도록 설정할 수 있습니다. 예를 들어, + +```js +{ + "extends": "dtslint/dt.json", + "rules": { + // 이 패키지는 Function 형을 사용하고 있으며, 고치는 게 쉽지 않다. + "ban-types": false + } +} +``` + +(린트 규칙(Lint rule)이 절대로 적용되서는 안되는 경우에는, `// tslint:disable rule-name` 나 `//tslint:disable-next-line rule-name` 를 사용하는 것이 좋습니다. 후자가 더 나은 방식입니다.) + +어떤 표현식(Expression)이 특정한 형(Type)을 가진다고 단언(Assert)하고 싶을 때에는 `$ExpectType` 를 사용하시면 됩니다. 어떤 표현식(Expression)이 컴파일에 실패해야하는 경우에는 `$ExpectError` 를 하시면 됩니다. + +```js +// $ExpectType void +f(1); + +// $ExpectError +f("one"); +``` + +[dtslint](https://github.com/Microsoft/dtslint#write-tests) 저장소의 README 파일에서 더 자세한 내용을 확인하실 수 있습니다. + +이런 테스트들은 `npm run lint package-name` 명령으로 실행해볼 수 있습니다. 이 때, `package-name` 은 테스트하고 싶은 패키지의 이름입니다. +테스트 스크립트는 [dtslint](https://github.com/Microsoft/dtslint) 를 사용하고 있습니다. + + +## 자주 하는 질문들 + +#### 이 저장소와 `@types` 패키지들이 대체 무슨 관계가 있는 건가요? + +`master` 브랜치(Branch)의 내용들이 [types-publisher](https://github.com/Microsoft/types-publisher) 를 사용해 자동으로 `@types` 퍼블리시(Publish)됩니다. + +#### 풀 리퀘스트(Pull request)를 제출했습니다. 이게 합쳐질 때까지 얼마나 걸리나요? + +상황에 따라 다르지만, 대부분의 풀 리퀘스트(Pull request)들은 일주일 안에 합쳐집니다. 머릿주석에 있는 저자 중 한명에 의해 승인된 풀 리퀘스트(Pull request)는 보통 더 빨리 합쳐집니다. 새로운 패키지에 대한 풀 리퀘스트(Pull request)는 관리자의 세세한 코드 리뷰를 필요로 하기 때문에 더 오래 걸리는 경우가 많습니다. 각 PR 들은 합쳐지기 전에 TypeScript or DefinitelyTyped 팀 구성원의 코드 리뷰를 받아야 하며, 이는 사람이 하는 일이기 때문에 느려질 수도 있으니 양해를 바랍니다. [풀 리퀘스트 번다운 보드(PR Burndown Board)](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen)에서 열린 풀 리퀘스트에 대한 관리자들의 진행도를 확인하실 수 있습니다. + +#### 내 풀 리퀘스트(Pull request)는 합쳐졌습니다. 언제 NPM 에 `@types` 패키지가 갱신되나요? + +NPM 의 패키지들은 수시간 안에 갱신될 겁니다. 만약 24 시간이 지나도 갱신되지 않으면, 문제를 파악하기 위해 @RyanCavanaugh 나 @andy-ms 를 풀 리퀘스트(Pull request)에서 호출해주세요. + +#### 다른 자료형 정의(Type definition)에 의존하는 자료형 정의(Type definition)을 만들고 있습니다. `` 와 임포트(import) 중 무엇을 사용해야하나요? + +외부 모듈(`export` 를 사용하는 모듈)을 사용할 경우, 임포트(import)를 사용해주세요. +환경과 관련된 모듈(ambient module)(`declare module` 를 쓰거나 전역 변수들을 선언한 모듈)을 사용할 경우, `` 를 사용해주세요. + +#### `package.json` 파일이 가끔 보이던데? + +일반적으로는 `package.json` 파일을 사용할 필요가 없습니다. 패키지가 퍼블리시(Publish)될 때 패키지를 위한 `package.json` 파일은 자동으로 생성됩니다. +가끔 보이는 `package.json` 파일은 의존하는 것들을 표시하기 위해 사용됩니다. [예시](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json)를 한 번 보세요. +의존성을 제외한 다른 필드(Field)들, 그러니까 `"description"` 같은 것들은 사용해서는 안됩니다. +옛날 `@types` 패키지를 사용하고 싶으실 경우에도 `"dependencies": { "@types/foo": "x.y.z" }` 와 같은 내용을 `package.json` 파일에 넣으셔야 합니다. + +#### 어떤 패키지들에 `tslint.json` 이 없거나, `tsconfig.json` 에 `"noImplicitAny": true`, `"noImplicitThis": true`, 나 `"strictNullChecks": true` 가 없어요. + +그럼 그 패키지들이 잘못된 겁니다. 고쳐서 풀 리퀘스트(Pull request)를 제출해주시면 고맙겠습니다. + +#### 자료형 정의(Type definition)을 요청할 수 있나요? + +이미 요청된 자료형 정의(Type definition)들을 [여기서](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest) 보실 수 있습니다. + +#### DOM 을 위한 자료형 정의(Type definitions)는요? + +웹 표준(Web standard)과 관련이 있는 자료형(Typing)들은 [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) 저장소에 기여해서 고치실 수 있습니다. 고쳐진 자료형(Typing)은 `lib.dom.d.ts` 파일에 포함될 겁니다. + +#### 어떤 패키지가 `export =` 를 쓰고 있는데, 저는 디폴트 임포트(Default import)가 더 좋습니다. `export =` 를 `export default` 로 바꿔도 되나요? + +타입스크립트(TypeScript) 2.7 이상을 사용하고 계시면 프로젝트 안에서 `--esModuleInterop` 를 사용해주세요. +그 이하의 경우, 디폴트 임포트(Default import)가 동작하는 환경(Webpack, SystemJS, esm)에서 작업 중이시면 [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) 를 사용하는 걸 고려해보세요. +자료형 정의(Type definition)가 맞는 경우에는 자료형 정의(Type definition)을 수정하지 마세요. +NPM 패키지의 경우, `node -p 'require("foo")'` 가 원하는 값이라면 `export =` 이 맞고, `node -p 'require("foo").default'` 이 원하는 값이라면 `export default` 이 맞습니다. + +#### 자료형 선언(Type declaration)에서 타입스크립트(TypeScript) 2.1 이상의 기능을 사용하고 싶습니다. + +정의(Definition) 머릿주석(`// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`) 뒤에 `// TypeScript Version: 2.1` 를 추가해주시면 됩니다. + +#### 타입스크립트(TypeScript)에 기본으로 포함되지 않은 DOM API 를 추가하고 싶어요. + +[TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme) 저장소가 관련되어있을 가능성이 있습니다. 해당 저장소의 안내를 따라주세요. +해당 표준이 아직 초안인 상태라면, 이 저장소와 관련된 일입니다. +`dom-` 으로 시작하는 패키지를 만드신 뒤, "Project" 머릿주석 부분에 해당 표준의 링크를 써 주세요. +다만 표준이 초안을 벗어나면 DefinitelyTyped 에서 삭제되고 `@types` 패키지가 지원이 중단된(Deprecated) 것으로 표시될 수도 있습니다. + +#### 패키지를 새 메이저 버전(major version)에 맞게 갱신하고 싶어요. + +옛날 버전도 계속해서 수정할 예정이라면, 이전 버전에 해당하는 새 디렉토리(예를 들어 `2.` 버전을 위해서는 `v2`)를 만들고 현재 파일들을 그 디렉토리로 옮겨야 합니다. 새 디렉토리로 옮긴 뒤에는 + +1. `tsconfig.json` 와 `tslint.json` 에 포함된 상대경로들을 수정해주어야 합니다. +2. 경로 대응 규칙(Path mapping rule)을 추가하여 테스트가 올바른 버전을 검사하도록 해야합니다. + +예를 들어, [history 패키지의 2 버전의 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) 파일은 다음과 같이 생겼습니다. + +```json +{ + "compilerOptions": { + "baseUrl": "../../", + "typeRoots": ["../../"], + "paths": { + "history": [ "history/v2" ] + }, + }, + "files": [ + "index.d.ts", + "history-tests.ts" + ] +} +``` + +수정 중인 패키지에 의존하는 DefinitelyTyped 의 다른 패키지들이 새 버전과 호환되지 않을 경우, 그 패키지들에도 옛날 버전으로의 경로 대응 규칙(Path mapping rule)을 추가해주어야 합니다. 수정 중인 패키지에 의존하는 패키지에 의존하는 패키지들에도 똑같은 작업을 해 주셔야 합니다. + +예를 들어, `react-router` 패키지는 `history@2` 패키지에 의존하고 있기 때문에, [react-router 패키지의 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) 파일이 `"history": [ "history/v2" ]` 와 같은 경로 대응 규칙(Path mapping rule)을 가지고 있는 걸 볼 수 있습니다. +이어서 (`react-router` 패키지에 의존하는 패키지인) `react-router-bootstrap` 또한 [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json) 파일 안에 경로 대응 규칙(Path mapping rule)을 가지고 있는 것을 보실 수 있습니다. + +`/// ` 에서는 경로 대응 규칙(Path mapping rule)이 동작하지 않기 때문에, DefinitelyTyped 패키지로에 의존할 때에는 임포트(import) 를 사용해야 합니다. + +#### 전역적으로도 모듈로도 사용될 수 있는 패키지의 자료형 선언(Type declaration)은 어떻게 쓰나요? + +타입스크립트 안내서(TypeScript Handbook)은 [선언(Declaration)을 쓰는 방법에 대한 전반적인 정보](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)와 [예시들](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html)을 포함하고 있습니다. 이 내용에는 ES6 식의 모듈 문법을 사용할 수 있는 자료형 선언(Type declaration)을 만드는 방법과 객체를 전역에서 사용할 수 있도록 하는 방법이 포함되어 있습니다. [big.js 패키지의 자료형 선언(Type declaration)](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts)이 실례입니다. 이 패키지는 웹 페이지의 스크립트 태그를 사용해 불러올 수 있으며, 또한 ES6 식의 임포트(Import) 구문을 사용해서 불러올 수도 있습니다. + +여러분의 패키지가 임포트(Import) 구문을 사용했을 때와 전역적으로 불렀을 때를 테스트 해보고 싶다면, `test` 디렉토리를 추가하고 `YourLibraryName-global.test.ts` 그리고 `YourLibraryName-module.test.ts` 라는 이름으로 테스트 파일 두 개를 추가해주세요. **전역(Global)** 테스트 파일은 웹 페이지에서 전역적으로 사용될 때를 테스트하는 파일입니다. 이 파일에서는 임포트(Import) 구문을 사용하지 않아야 합니다. **모듈(Module)** 테스트 파일은 임포트(Import) 구문을 사용할 때를 테스트 하는 파일입니다. 만약 여러분의 `tsconfig.json` 파일이 `files` 필드(Field)를 가지고 있다면, 이 필드(Field)는 반드시 두 테스트 파일을 모두 포함해야 합니다. [이 방식을 사용하는 실례](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) 또한 big.js 패키지의 자료형 선언(Type declaration)에서 확인해보실 수 있습니다. + +각각의 테스트 파일에 모든 상황을 테스트할 필요는 없다는 걸 잊지마세요. 전역 테스트 파일에서는 전역적으로 사용될 때만 테스트하고, 모듈 테스트 파일에서 나머지 상황들을 모두 테스트 할 수 있으며, 그 반대의 경우도 괜찮습니다. + +#### 지역 패키지(Scoped package)의 경우는 어떻게 하죠? + +`@foo/bar` 패키지와 같은 지역 패키지(Scoped package)를 위한 자료형 패키지(Type package)는 `types/foo__bar` 디렉토리에 추가하면 됩니다. 밑줄 문자가 두 번 있는 것에 주의하세요. + +지역 패키지(Scoped package)를 위한 자료형 패키지(Type package)를 생성하기 위해 `dts-gen` 를 사용한 경우에는, +다음과 같이 생성된 `tsconfig.json` 안에 지역 패키지(Scoped package)를 위한 적절한 경로 대응 규칙(Path mapping rule)을 추가해주어야 합니다. + +```json +{ + "paths":{ + "@foo/bar": ["foo__bar"] + } +} +``` + + +#### 깃헙(GitHub)이 보여주는 파일 히스토리(History)가 불완전해요. + +깃헙은 이름이 바뀐 파일의 히스토리(History)를 [지원하지 않습니다](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames). 대신 [`git log --follow`](https://www.git-scm.com/docs/git-log) 명령을 사용하세요. + +#### ES6 에서 사용하는 임포트(Import)를 사용하기 위해 모듈을 익스포트(Export)하지 않는 패키지들에 빈 이름공간을 추가해야 하나요? + +[chai-http](https://github.com/chaijs/chai-http) 패키지와 같은 몇몇 패키지들은 함수를 익스포트(Export)합니다. + +이런 패키지들을 `import * as foo from "foo";` 와 같이 임포트(Import)하면 다음과 같은 오류가 발생합니다. + +> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct + +이 오류는 함수의 이름과 똑같은 빈 이름공간(Namespace)을 정의해서 없앨 수 있으나, 좋은 방법은 아닙니다. +[스택오버플로(Stack Overflow)의 이 질문의 답변](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this)이 이 문제와 관련되어 자주 언급됩니다. + +`import foo = require("foo");` 를 사용하여 모듈을 임포트(Import)하거나, 환경에서 ES6 모듈 변환(Module interop)을 지원한다면 `--allowSyntheticDefaultImports` 와 함께 `import foo from "foo";` 같은 디폴트 임포트(Default import)를 사용하는 것이 더 나은 방법입니다. + +## 라이센스 + +이 프로젝트는 MIT license 가 적용되어 있습니다. + +각 자료형 정의(Type definition) 파일들의 저작권은 각 기여자들에게 있으며, 기여자들은 해당 자료형 정의(Type definition) 파일들의 맨 위에 나열되어 있습니다. + +[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon) diff --git a/README.md b/README.md index 34eae06069..9a31d73da1 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Also see the [definitelytyped.org](http://definitelytyped.org) website, although information in this README is more up-to-date. -*[You can also read this README in Spanish!](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md)* +*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) and [Korean!](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md)* ## What are declaration files? diff --git a/notNeededPackages.json b/notNeededPackages.json index db3cd3f68e..8b56dbd9b5 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -678,6 +678,12 @@ "sourceRepoURL": "https://github.com/facebook/immutable-js", "asOfVersion": "3.8.7" }, + { + "libraryName": "interactjs", + "typingsPackageName": "interact.js", + "sourceRepoURL": "https://github.com/taye/interact.js", + "asOfVersion": "1.3.0" + }, { "libraryName": "inversify", "typingsPackageName": "inversify", @@ -1224,6 +1230,12 @@ "sourceRepoURL": "https://github.com/tomkp/react-split-pane", "asOfVersion": "0.1.67" }, + { + "libraryName": "react-svg", + "typingsPackageName": "react-svg", + "sourceRepoURL": "https://github.com/tanem/react-svg", + "asOfVersion": "5.0.0" + }, { "libraryName": "realm", "typingsPackageName": "realm", diff --git a/types/agenda/agenda-tests.ts b/types/agenda/agenda-tests.ts index e4de026c0e..2c011efaf7 100644 --- a/types/agenda/agenda-tests.ts +++ b/types/agenda/agenda-tests.ts @@ -67,6 +67,9 @@ var mongoConnectionString = "mongodb://127.0.0.1/agenda"; await job.save(); const jobs = await agenda.jobs({ name: 'printAnalyticsReport' }); + jobs.forEach((job) => { + job.save(); + }); let numRemoved = await agenda.cancel({ name: 'printAnalyticsReport' }); diff --git a/types/agenda/index.d.ts b/types/agenda/index.d.ts index d728a76032..be07b84aaf 100644 --- a/types/agenda/index.d.ts +++ b/types/agenda/index.d.ts @@ -96,7 +96,7 @@ declare class Agenda extends EventEmitter { * Find all Jobs matching `query` and pass same back in cb(). * @param query */ - jobs(query: any): Promise; + jobs(query: any): Promise[]>; /** * Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want diff --git a/types/agent-base/agent-base-tests.ts b/types/agent-base/agent-base-tests.ts new file mode 100644 index 0000000000..116ff8af96 --- /dev/null +++ b/types/agent-base/agent-base-tests.ts @@ -0,0 +1,23 @@ +import agent = require('agent-base'); + +agent(); // $ExpectType Agent +agent({ timeout: 1000 }); // $ExpectType Agent + +agent((req, opts) => {}); // $ExpectType Agent +agent((req, opts) => {}, { timeout: 1000 }); // $ExpectType Agent + +agent(async (req, opts) => {}); // $ExpectType Agent +agent(async (req, opts) => {}, { timeout: 1000 }); // $ExpectType Agent + +agent(0); // $ExpectError +agent(1); // $ExpectError +agent(''); // $ExpectError +agent(true); // $ExpectError +agent(null); // $ExpectError + +agent((req, opts) => {}, 0); // $ExpectError +agent((req, opts) => {}, 1); // $ExpectError +agent((req, opts) => {}, ''); // $ExpectError +agent((req, opts) => {}, true); // $ExpectError +agent((req, opts) => {}, null); // $ExpectError +agent((req, opts) => {}, (req, opts) => {}); // $ExpectError diff --git a/types/agent-base/index.d.ts b/types/agent-base/index.d.ts new file mode 100644 index 0000000000..0b1e4d3018 --- /dev/null +++ b/types/agent-base/index.d.ts @@ -0,0 +1,44 @@ +// Type definitions for agent-base 4.2 +// Project: https://github.com/TooTallNate/node-agent-base#readme +// Definitions by: Christopher Quadflieg +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import { EventEmitter } from 'events'; + +declare namespace Agent { + type AgentCallback = ( + req?: any, + opts?: { + secureEndpoint: boolean; + } + ) => void; + + interface AgentOptions { + timeout?: number; + host?: string; + port?: number; + [key: string]: any; + } + + interface Agent extends EventEmitter { + _promisifiedCallback: boolean; + timeout: number | null; + options?: AgentOptions; + callback: AgentCallback; + addRequest: (req?: any, opts?: any) => void; + freeSocket: (socket: any, opts: any) => void; + } +} + +/** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + */ +declare function Agent(opts?: Agent.AgentOptions): Agent.Agent; +declare function Agent( + callback: Agent.AgentCallback, + opts?: Agent.AgentOptions +): Agent.Agent; + +export = Agent; diff --git a/types/agent-base/tsconfig.json b/types/agent-base/tsconfig.json new file mode 100644 index 0000000000..dc6db21f70 --- /dev/null +++ b/types/agent-base/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "agent-base-tests.ts" + ] +} diff --git a/types/meteor-univserse-i18n/tslint.json b/types/agent-base/tslint.json similarity index 100% rename from types/meteor-univserse-i18n/tslint.json rename to types/agent-base/tslint.json diff --git a/types/alt/index.d.ts b/types/alt/index.d.ts index 0c69e4020a..9094642e70 100644 --- a/types/alt/index.d.ts +++ b/types/alt/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/goatslacker/alt // Definitions by: Michael Shearer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/amp/amp-tests.ts b/types/amp/amp-tests.ts index 1e17bc8507..983c1f993b 100644 --- a/types/amp/amp-tests.ts +++ b/types/amp/amp-tests.ts @@ -32,7 +32,7 @@ new Stream({ highWaterMark: 1, decodeStrings: true, objectMode: true, - destroy: (error?: Error) => { + destroy: (error: Error | null) => { return 'handle error'; }, final: (callback: (error?: Error) => void) => { diff --git a/types/angular-desktop-notification/index.d.ts b/types/angular-desktop-notification/index.d.ts index 6281396b66..2e017da49b 100644 --- a/types/angular-desktop-notification/index.d.ts +++ b/types/angular-desktop-notification/index.d.ts @@ -22,7 +22,7 @@ declare module 'angular' { * This is an experimental technology * Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/badge */ - badge?: USVString; + badge?: string; /** * The data read-only property of the Notification interface returns a structured clone of the notification's data, @@ -40,7 +40,7 @@ declare module 'angular' { * Note: This feature is available in Web Workers. * Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/image */ - image?: USVString; + image?: string; /** * The renotify read-only property of the Notification interface specifies whether the user should be notified after a diff --git a/types/angular-gettext/angular-gettext-tests.ts b/types/angular-gettext/angular-gettext-tests.ts index 766b16a963..1b1d5b6342 100644 --- a/types/angular-gettext/angular-gettext-tests.ts +++ b/types/angular-gettext/angular-gettext-tests.ts @@ -24,6 +24,8 @@ angular.module("myApp").controller("helloController", function (gettextCatalog: angular.module("myApp").controller("helloController", function (gettextCatalog: angular.gettext.gettextCatalog) { var myString2: string = gettextCatalog.getPlural(3, "Bird", "Birds"); + var myStringWithScope: string = gettextCatalog.getPlural(4, "{{color}} Bird", "{{color}} Birds", {color: 'Blue'}); + var myStringWithContext: string = gettextCatalog.getPlural(5, "pick", "picks", null, 'noun'); }); angular.module("myApp").controller("helloController", function (gettextCatalog: angular.gettext.gettextCatalog) { diff --git a/types/angular-gettext/index.d.ts b/types/angular-gettext/index.d.ts index 5b6eb1d90f..6b5fe29e73 100644 --- a/types/angular-gettext/index.d.ts +++ b/types/angular-gettext/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for angular-gettext v2.1.0 +// Type definitions for angular-gettext v2.1.1 // Project: https://angular-gettext.rocketeer.be/ // Definitions by: Ákos Lukács // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -66,7 +66,7 @@ declare module 'angular' { getString(string: string, scope?: any, context?: string): string; /** Translate a plural string with the given context. */ - getPlural(n: number, string: string, stringPlural: string, context?: any): string; + getPlural(n: number, string: string, stringPlural: string, scope?: any, context?: string): string; /** Load a set of translation strings from a given URL.This should be a JSON catalog generated with grunt-angular-gettext. More details https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ */ loadRemote(url: string): ng.IHttpPromise; diff --git a/types/angular-mocks/angular-mocks-tests.ts b/types/angular-mocks/angular-mocks-tests.ts index 2d74dd26bc..662d75c079 100644 --- a/types/angular-mocks/angular-mocks-tests.ts +++ b/types/angular-mocks/angular-mocks-tests.ts @@ -87,7 +87,6 @@ timeoutService.verifyNoPendingTasks(); let intervalService: ng.IIntervalService; let intervalServiceTimeActuallyAdvanced: number; -intervalServiceTimeActuallyAdvanced = intervalService.flush(); intervalServiceTimeActuallyAdvanced = intervalService.flush(1234); /////////////////////////////////////// @@ -1516,6 +1515,23 @@ requestHandler.respond(404, { key: 'value' }); requestHandler.respond(404, { key: 'value' }, { header: 'value' }); requestHandler.respond(404, { key: 'value' }, { header: 'value' }, 'responseText'); +/////////////////////////////////////// +// IFlushPendingTasksService +/////////////////////////////////////// +let $flushPendingTasks: ng.IFlushPendingTasksService; +$flushPendingTasks(); +$flushPendingTasks(42); + +/////////////////////////////////////// +// IVerifyNoPendingTasksService +/////////////////////////////////////// +let $verifyNoPendingTasks: ng.IVerifyNoPendingTasksService; +$verifyNoPendingTasks(); +$verifyNoPendingTasks('task type'); + +/////////////////////////////////////// +// browserTrigger +/////////////////////////////////////// browserTrigger(document.body, 'click'); browserTrigger(angular.element(document.body), 'click'); browserTrigger(angular.element(document.body), 'click', { which: 1, keys: ['ctrl'] }); diff --git a/types/angular-mocks/index.d.ts b/types/angular-mocks/index.d.ts index 53157a1f08..a2aa4fe29e 100644 --- a/types/angular-mocks/index.d.ts +++ b/types/angular-mocks/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for Angular JS (ngMock, ngMockE2E module) 1.6 +// Type definitions for Angular JS (ngMock, ngMockE2E module) 1.7 // Project: http://angularjs.org -// Definitions by: Diego Vilar , Tony Curtis +// Definitions by: Diego Vilar +// Tony Curtis +// Georgii Dolzhykov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -59,7 +61,38 @@ declare module 'angular' { // Augments the original service /////////////////////////////////////////////////////////////////////////// interface ITimeoutService { + /** + * **Deprecated** since version 1.7.3. (Use `$flushPendingTasks` instead.) + * + * --- + * Flushes the queue of pending tasks. + * + * _This method is essentially an alias of `$flushPendingTasks`._ + * + * > For historical reasons, this method will also flush non-`$timeout` pending tasks, such as + * > `$q` promises and tasks scheduled via `$applyAsync` and `$evalAsync`. + * + * @param delay - The maximum timeout amount to flush up until. + */ flush(delay?: number): void; + + /** + * **Deprecated** since version 1.7.3. (Use `$verifyNoPendingTasks` instead.) + * + * --- + * Verifies that there are no pending tasks that need to be flushed. It throws an error if there + * are still pending tasks. + * + * _This method is essentially an alias of `$verifyNoPendingTasks` (called with no arguments)._ + * + * > For historical reasons, this method will also verify non-`$timeout` pending tasks, such as + * > pending `$http` requests, in-progress `$route` transitions, unresolved `$q` promises and + * > tasks scheduled via `$applyAsync` and `$evalAsync`. + * > + * > It is recommended to use `$verifyNoPendingTasks` instead, which additionally supports + * > verifying a specific type of tasks. For example, you can verify there are no pending + * > timeouts with `$verifyNoPendingTasks('$timeout')`. + */ verifyNoPendingTasks(): void; } @@ -69,7 +102,13 @@ declare module 'angular' { // Augments the original service /////////////////////////////////////////////////////////////////////////// interface IIntervalService { - flush(millis?: number): number; + /** + * Runs interval tasks scheduled to be run in the next `millis` milliseconds. + * + * @param millis - The maximum timeout amount to flush up until. + * @return The amount of time moved forward. + */ + flush(millis: number): number; } /////////////////////////////////////////////////////////////////////////// @@ -413,6 +452,65 @@ declare module 'angular' { whenRoute(method: string, url: string): mock.IRequestHandler; } + /////////////////////////////////////////////////////////////////////////// + // FlushPendingTasksService + // see https://docs.angularjs.org/api/ngMock/service/$flushPendingTasks + /////////////////////////////////////////////////////////////////////////// + interface IFlushPendingTasksService { + /** + * Flushes all currently pending tasks and executes the corresponding callbacks. + * + * Optionally, you can also pass a `delay` argument to only flush tasks that are scheduled to be + * executed within `delay` milliseconds. Currently, `delay` only applies to timeouts, since all + * other tasks have a delay of 0 (i.e. they are scheduled to be executed as soon as possible, but + * still asynchronously). + * + * If no delay is specified, it uses a delay such that all currently pending tasks are flushed. + * + * The types of tasks that are flushed include: + * + * - Pending timeouts (via `$timeout`). + * - Pending tasks scheduled via `$applyAsync`. + * - Pending tasks scheduled via `$evalAsync`. + * These include tasks scheduled via `$evalAsync()` indirectly (such as `$q` promises). + * + * > Periodic tasks scheduled via `$interval` use a different queue and are not flushed by + * > `$flushPendingTasks()`. Use `$interval.flush(millis)` instead. + * + * @param millis - The number of milliseconds to flush. + */ + (delay?: number): void; + } + + /////////////////////////////////////////////////////////////////////////// + // VerifyNoPendingTasksService + // see https://docs.angularjs.org/api/ngMock/service/$verifyNoPendingTasks + /////////////////////////////////////////////////////////////////////////// + interface IVerifyNoPendingTasksService { + /** + * Verifies that there are no pending tasks that need to be flushed. It throws an error if there + * are still pending tasks. + * + * You can check for a specific type of tasks only, by specifying a `taskType`. + * + * Available task types: + * + * - `$timeout`: Pending timeouts (via `$timeout`). + * - `$http`: Pending HTTP requests (via `$http`). + * - `$route`: In-progress route transitions (via `$route`). + * - `$applyAsync`: Pending tasks scheduled via `$applyAsync`. + * - `$evalAsync`: Pending tasks scheduled via `$evalAsync`. + * These include tasks scheduled via `$evalAsync()` indirectly (such as `$q` promises). + * + * > Periodic tasks scheduled via `$interval` use a different queue and are not taken into + * > account by `$verifyNoPendingTasks()`. There is currently no way to verify that there are no + * > pending `$interval` tasks. + * + * @param taskType - The type of tasks to check for. + */ + (taskType?: string): void; + } + /////////////////////////////////////////////////////////////////////////// // AnimateService // see https://docs.angularjs.org/api/ngMock/service/$animate @@ -513,6 +611,11 @@ declare module 'angular' { * for keyboard events (keydown, keypress, and keyup). */ charcode?: number; + /** + * [data](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent/data) for + * [CompositionEvents](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent). + */ + data?: string; /** * The elapsedTime for * [TransitionEvent](https://developer.mozilla.org/docs/Web/API/TransitionEvent) @@ -566,10 +669,11 @@ declare global { * This is a global (window) function that is only available when the `ngMock` module is included. * It can be used to trigger a native browser event on an element, which is useful for unit testing. * - * @param element Either a wrapped jQuery/jqLite node or a DOM element - * @param eventType Optional event type. If none is specified, the function tries to determine - * the right event type for the element, e.g. `change` for `input[text]`. - * @param eventData An optional object which contains additional event data used when creating the event. + * @param element Either a wrapped jQuery/jqLite node or a DOM element. + * @param eventType Optional event type. If none is specified, the function tries to determine the + * right event type for the element, e.g. `change` for `input[text]`. + * @param eventData An optional object which contains additional event data used when creating the + * event. */ function browserTrigger( element: JQuery | Element, diff --git a/types/angular-route/angular-route-tests.ts b/types/angular-route/angular-route-tests.ts index 677c1589ed..e1e7bd43fd 100644 --- a/types/angular-route/angular-route-tests.ts +++ b/types/angular-route/angular-route-tests.ts @@ -39,6 +39,21 @@ $routeProvider return "I return a string" } }) + .when('/projects/:projectId/dashboard6', { + resolve: { + foo: () => 'foo', + bar: () => 'bar', + }, + resolveAs: 'baz', + resolveRedirectTo: [ + '$http', + ($http: ng.IHttpService) => $http.get('/is-admin').then(() => '/admin/lounge', () => undefined), + ], + }) + .when('/projects/:projectId/dashboard7', { + reloadOnUrl: false, + resolveRedirectTo: () => (Math.random() < 0.5) ? '/some/route' : undefined, + }) .otherwise({ redirectTo: '/' }) .otherwise({ redirectTo: ($routeParams?: ng.route.IRouteParamsService, $locationPath?: string, $locationSearch?: any) => "" }) .otherwise("/"); diff --git a/types/angular-route/index.d.ts b/types/angular-route/index.d.ts index 56bd3f2263..15529f1572 100644 --- a/types/angular-route/index.d.ts +++ b/types/angular-route/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for Angular JS (ngRoute module) 1.3 +// Type definitions for Angular JS (ngRoute module) 1.7 // Project: http://angularjs.org // Definitions by: Jonathan Park +// George Kalpakas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -52,7 +53,7 @@ declare module 'angular' { */ interface IRoute { /** - * {(string|function()=} + * {(string|Function)=} * Controller fn that should be associated with newly created scope or the name of a registered controller if passed as a string. */ controller?: string | InlineAnnotatedFunction; @@ -61,56 +62,122 @@ declare module 'angular' { */ controllerAs?: string; /** - * Undocumented? - */ - name?: string; - /** - * {string=|function()=} + * {(string|Function)=} * Html template as a string or a function that returns an html template as a string which should be used by ngView or ngInclude directives. This property takes precedence over templateUrl. * * If template is a function, it will be called with the following parameters: * * {Array.} - route parameters extracted from the current $location.path() by applying the current route */ - template?: string | { ($routeParams?: angular.route.IRouteParamsService): string; } + template?: string | { ($routeParams?: IRouteParamsService): string; } /** - * {string=|function()=} + * {(string|Function)=} * Path or function that returns a path to an html template that should be used by ngView. * * If templateUrl is a function, it will be called with the following parameters: * * {Array.} - route parameters extracted from the current $location.path() by applying the current route */ - templateUrl?: string | { ($routeParams?: angular.route.IRouteParamsService): string; } + templateUrl?: string | { ($routeParams?: IRouteParamsService): string; } /** - * {Object.=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. The map object is: + * {Object.=} + * An optional map of dependencies which should be injected into the controller. If any of these + * dependencies are promises, the router will wait for them all to be resolved or one to be rejected before + * the controller is instantiated. + * If all the promises are resolved successfully, the values of the resolved promises are injected and + * `$routeChangeSuccess` event is fired. If any of the promises are rejected the `$routeChangeError` event + * is fired. + * For easier access to the resolved dependencies from the template, the `resolve` map will be available on + * the scope of the route, under `$resolve` (by default) or a custom name specified by the `resolveAs` + * property (see below). This can be particularly useful, when working with components as route templates. * - * - key - {string}: a name of a dependency to be injected into the controller. - * - factory - {string|function}: If string then it is an alias for a service. Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before its value is injected into the controller. Be aware that ngRoute.$routeParams will still refer to the previous route within these resolve functions. Use $route.current.params to access the new route parameters, instead. + * > **Note:** If your scope already contains a property with this name, it will be hidden or overwritten. + * > Make sure, you specify an appropriate name for this property, that does not collide with other + * > properties on the scope. + * + * The map object is: + * + * - `key` – `{string}`: a name of a dependency to be injected into the controller. + * - `factory` - `{string|Function}`: If `string` then it is an alias for a service. Otherwise if function, + * then it is called with `$injector#invoke()` and the return value is treated as the dependency. If the + * result is a promise, it is resolved before its value is injected into the controller. Be aware that + * `ngRoute.$routeParams` will still refer to the previous route within these resolve functions. Use + * `$route.current.params` to access the new route parameters, instead. */ resolve?: { [key: string]: any }; /** - * {(string|function())=} - * Value to update $location path with and trigger route redirection. - * - * If redirectTo is a function, it will be called with the following parameters: - * - * - {Object.} - route parameters extracted from the current $location.path() by applying the current route templateUrl. - * - {string} - current $location.path() - * - {Object} - current $location.search() - * - The custom redirectTo function is expected to return a string which will be used to update $location.path() and $location.search(). + * {string=} + * The name under which the `resolve` map will be available on the scope of the route. If omitted, defaults + * to `$resolve`. */ - redirectTo?: string | { ($routeParams?: angular.route.IRouteParamsService, $locationPath?: string, $locationSearch?: any): string }; + resolveAs?: string; /** - * Reload route when only $location.search() or $location.hash() changes. + * {(string|Function)=} + * Value to update `$location` path with and trigger route redirection. * - * This option defaults to true. If the option is set to false and url in the browser changes, then $routeUpdate event is broadcasted on the root scope. + * If `redirectTo` is a function, it will be called with the following parameters: + * + * - `{Object.}` - route parameters extracted from the current `$location.path()` by applying the + * current route templateUrl. + * - `{string}` - current `$location.path()` + * - `{Object}` - current `$location.search()` + * + * The custom `redirectTo` function is expected to return a string which will be used to update + * `$location.url()`. If the function throws an error, no further processing will take place and the + * `$routeChangeError` event will be fired. + * + * Routes that specify `redirectTo` will not have their controllers, template functions or resolves called, + * the `$location` will be changed to the redirect url and route processing will stop. The exception to this + * is if the `redirectTo` is a function that returns `undefined`. In this case the route transition occurs + * as though there was no redirection. + */ + redirectTo?: string | { ($routeParams?: IRouteParamsService, $locationPath?: string, $locationSearch?: any): string }; + /** + * {Function=} + * A function that will (eventually) return the value to update `$location` URL with and trigger route + * redirection. In contrast to `redirectTo`, dependencies can be injected into `resolveRedirectTo` and the + * return value can be either a string or a promise that will be resolved to a string. + * + * Similar to `redirectTo`, if the return value is `undefined` (or a promise that gets resolved to + * `undefined`), no redirection takes place and the route transition occurs as though there was no + * redirection. + * + * If the function throws an error or the returned promise gets rejected, no further processing will take + * place and the `$routeChangeError` event will be fired. + * + * `redirectTo` takes precedence over `resolveRedirectTo`, so specifying both on the same route definition, + * will cause the latter to be ignored. + */ + resolveRedirectTo?: angular.Injectable<(...deps: any[]) => angular.IPromise | string | undefined>; + /** + * {boolean=true} + * Reload route when any part of the URL changes (including the path) even if the new URL maps to the same + * route. + * + * If the option is set to `false` and the URL in the browser changes, but the new URL maps to the same + * route, then a `$routeUpdate` event is broadcasted on the root scope (without reloading the route). + * + * Defaults to `true`. + */ + reloadOnUrl?: boolean; + /** + * {boolean=true} + * Reload route when only `$location.search()` or `$location.hash()` changes. + * + * If the option is set to `false` and the URL in the browser changes, then a `$routeUpdate` event is + * broadcasted on the root scope (without reloading the route). + * + * > Note: This option has no effect if `reloadOnUrl` is set to `false`. + * + * Defaults to `true`. */ reloadOnSearch?: boolean; /** - * Match routes without being case sensitive + * {boolean=false} + * Match routes without being case sensitive. + * If the option is set to `true`, then the particular route can be matched without being case sensitive. * - * This option defaults to false. If the option is set to true, then the particular route can be matched without being case sensitive + * Defaults to `false`. */ caseInsensitiveMatch?: boolean; } diff --git a/types/angular/angular-tests.ts b/types/angular/angular-tests.ts index 963b5deae6..f2aad6bb59 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -731,11 +731,12 @@ function test_angular_forEach() { this.push(`${key}: ${value}`); }, log); // expect(log).toEqual(['name: misko', 'gender: male']); - // $ExpectType NodeListOf - angular.forEach(document.getElementsByTagName('img'), (value, key, obj) => { + // TODO: Set minimum version to ts3.1 where this is always HTMLCollectionOf + type Collection = NodeListOf | HTMLCollectionOf; + const collection: Collection = angular.forEach(document.getElementsByTagName('img'), (value, key, obj) => { value; // $ExpectType HTMLImageElement key; // $ExpectType number - obj; // $ExpectType NodeListOf + const collection: Collection = obj; }); // $ExpectType number[] angular.forEach([1, 2, 3], (value, key, obj) => { diff --git a/types/aphrodite/index.d.ts b/types/aphrodite/index.d.ts index a82ec2f36b..bd2749f737 100644 --- a/types/aphrodite/index.d.ts +++ b/types/aphrodite/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/Khan/aphrodite // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as CSS from "csstype"; diff --git a/types/arangodb/arangodb-tests.ts b/types/arangodb/arangodb-tests.ts index 7e0fd6383e..98315235ea 100644 --- a/types/arangodb/arangodb-tests.ts +++ b/types/arangodb/arangodb-tests.ts @@ -96,3 +96,13 @@ console.log( RETURN u `.toArray() ); + +const view = db._view("yolo")!; +view.properties({ + locale: "C", + commit: { + consolidate: { + bytes: { segmentThreshold: 20 } + } + } +}); diff --git a/types/arangodb/index.d.ts b/types/arangodb/index.d.ts index 5c3f56020f..be738e6717 100644 --- a/types/arangodb/index.d.ts +++ b/types/arangodb/index.d.ts @@ -837,11 +837,68 @@ declare namespace ArangoDB { // Views - interface View { - // TODO - [key: string]: any; + interface ArangoSearchView { + _dbName: string; + _id: string; + name(): string; + type(): ViewType; + rename(newName: string): void; + properties( + newProperties?: ArangoSearchViewPropertiesOptions + ): ArangoSearchViewProperties; + } + + interface ArangoSearchViewConsolidate { + threshold: number; + segmentThreshold: number; + } + + interface ArangoSearchViewCollectionLink { + analyzers?: string[]; + fields?: { [key: string]: ArangoSearchViewCollectionLink | undefined }; + includeAllFields?: boolean; + trackListPositions?: boolean; + storeValues?: "none" | "id"; + } + + interface ArangoSearchViewProperties { + id: string; + name: string; + type: "arangosearch"; + commit: { + cleanupIntervalStep: number; + commitIntervalMsec: number; + consolidate: { + bytes?: ArangoSearchViewConsolidate; + bytes_accum?: ArangoSearchViewConsolidate; + count?: ArangoSearchViewConsolidate; + fill?: ArangoSearchViewConsolidate; + }; + }; + locale: string; + links: { + [key: string]: ArangoSearchViewCollectionLink | undefined; + }; + } + + interface ArangoSearchViewPropertiesOptions { + locale?: string; + commit?: { + consolidate?: + | "none" + | { + count?: Partial; + bytes?: Partial; + bytes_accum?: Partial; + fill?: Partial; + }; + commitIntervalMsec?: number; + cleanupIntervalStep?: number; + }; + links?: { + [key: string]: ArangoSearchViewCollectionLink | undefined; + }; } - type ViewProperties = object; // TODO // Global @@ -923,13 +980,13 @@ declare namespace ArangoDB { ): DocumentMetadata; // Views - _view(name: string): View | null; - _views(): View[]; + _view(name: string): ArangoSearchView | null; + _views(): ArangoSearchView[]; _createView( name: string, type: ViewType, - properties: ViewProperties - ): View; + properties: ArangoSearchViewPropertiesOptions + ): ArangoSearchView; _dropView(name: string): void; // Global @@ -1392,7 +1449,7 @@ declare module "@arangodb/foxx/router" { } declare module "@arangodb/foxx/graphql" { - import { GraphQLSchema, formatError } from "graphql"; + import { formatError, GraphQLSchema } from "graphql"; type GraphQLModule = object; type GraphQLFormatErrorFunction = typeof formatError; interface GraphQLOptions { diff --git a/types/assert-equal-jsx/index.d.ts b/types/assert-equal-jsx/index.d.ts index e017fcf57c..735ab5974a 100644 --- a/types/assert-equal-jsx/index.d.ts +++ b/types/assert-equal-jsx/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/thejameskyle/assert-equal-jsx // Definitions by: Josh Toft // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/atlaskit__button/index.d.ts b/types/atlaskit__button/index.d.ts index e9a613fabd..95ac1e0961 100644 --- a/types/atlaskit__button/index.d.ts +++ b/types/atlaskit__button/index.d.ts @@ -2,7 +2,7 @@ // Project: https://bitbucket.org/atlassian/atlaskit-mk-2/ // Definitions by: Jimmy Luong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, diff --git a/types/atlaskit__calendar/index.d.ts b/types/atlaskit__calendar/index.d.ts index e92776c1f3..e1c76eb397 100644 --- a/types/atlaskit__calendar/index.d.ts +++ b/types/atlaskit__calendar/index.d.ts @@ -2,7 +2,7 @@ // Project: https://bitbucket.org/atlassian/atlaskit-mk-2/src/master/ // Definitions by: Lee Standen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, HTMLAttributes, FocusEvent } from 'react'; diff --git a/types/atlaskit__inline-edit/index.d.ts b/types/atlaskit__inline-edit/index.d.ts index 4ee82ee4c3..d2d706c5a4 100644 --- a/types/atlaskit__inline-edit/index.d.ts +++ b/types/atlaskit__inline-edit/index.d.ts @@ -2,7 +2,7 @@ // Project: https://bitbucket.org/atlassian/atlaskit-mk-2/ // Definitions by: Lee Standen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { ReactElement, Component } from 'react'; export default class InlineEdit extends Component {} diff --git a/types/atlaskit__layer/index.d.ts b/types/atlaskit__layer/index.d.ts index 2f50a5abcf..03673c47a3 100644 --- a/types/atlaskit__layer/index.d.ts +++ b/types/atlaskit__layer/index.d.ts @@ -2,7 +2,7 @@ // Project: https://bitbucket.org/atlassian/atlaskit-mk-2/src/master/ // Definitions by: Lee Standen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, ReactNode } from 'react'; diff --git a/types/atlaskit__single-select/index.d.ts b/types/atlaskit__single-select/index.d.ts index 6536869512..4910c10a11 100644 --- a/types/atlaskit__single-select/index.d.ts +++ b/types/atlaskit__single-select/index.d.ts @@ -2,7 +2,7 @@ // Project: https://bitbucket.org/atlassian/atlaskit-mk-2/src/master/ // Definitions by: Lee Standen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, ReactNode, SyntheticEvent } from 'react'; diff --git a/types/auth0-js/auth0-js-tests.ts b/types/auth0-js/auth0-js-tests.ts index d05ee2251e..f13599ebae 100644 --- a/types/auth0-js/auth0-js-tests.ts +++ b/types/auth0-js/auth0-js-tests.ts @@ -9,7 +9,9 @@ webAuth.authorize({ audience: 'https://mystore.com/api/v2', scope: 'read:order write:order', responseType: 'token', - redirectUri: 'https://example.com/auth/callback' + redirectUri: 'https://example.com/auth/callback', + language: 'en', + prompt: 'login', }); webAuth.parseHash((err, authResult) => { diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index c7224599bd..e66cd5f712 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -760,6 +760,8 @@ export interface AuthorizeOptions { nonce?: string; scope?: string; audience?: string; + language?: string; + prompt?: string; } export interface CheckSessionOptions extends AuthorizeOptions { diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 1c90bb1c72..94575006ab 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -479,6 +479,7 @@ str = cloudwatchLogsDecodedData.messageType; str = cloudwatchLogsDecodedData.logEvents[0].id; num = cloudwatchLogsDecodedData.logEvents[0].timestamp; str = cloudwatchLogsDecodedData.logEvents[0].message; +str = cloudwatchLogsDecodedData.logEvents[0].extractedFields!["example"]; /* ClientContext */ clientContextClient = clientCtx.client; @@ -585,7 +586,9 @@ const CloudFrontRequestEvent: AWSLambda.CloudFrontRequestEvent = { { cf: { config: { + distributionDomainName: "d123.cloudfront.net", distributionId: "EDFDVBD6EXAMPLE", + eventType: "viewer-request", requestId: "MRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkKUFSHS9EXAMPLE==" }, request: { @@ -654,7 +657,9 @@ const CloudFrontResponseEvent: AWSLambda.CloudFrontResponseEvent = { { cf: { config: { + distributionDomainName: "d123.cloudfront.net", distributionId: "EDFDVBD6EXAMPLE", + eventType: "viewer-response", requestId: "xGN7KWpVEmB9Dp7ctcVFQC4E-nrcOcEKS3QyAez--06dV7TEXAMPLE==" }, request: { @@ -737,7 +742,7 @@ context.fail(error); context.fail(str); /* Handler */ -let handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; +const handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; /* In node8.10 runtime, handlers may return a promise for the result value, so existing async * handlers that return Promise before calling the callback will now have a `null` result. @@ -745,7 +750,7 @@ let handler: AWSLambda.Handler = (event: any, context: AWSLambda.Context, cb: AW * since the upgrade effort should be pretty low in most cases, and it points them at a nicer solution. */ // $ExpectError -let legacyAsyncHandler: AWSLambda.APIGatewayProxyHandler = async ( +const legacyAsyncHandler: AWSLambda.APIGatewayProxyHandler = async ( event: AWSLambda.APIGatewayProxyEvent, context: AWSLambda.Context, cb: AWSLambda.Callback, @@ -753,7 +758,7 @@ let legacyAsyncHandler: AWSLambda.APIGatewayProxyHandler = async ( cb(null, { statusCode: 200, body: 'No longer valid' }); }; -let node8AsyncHandler: AWSLambda.APIGatewayProxyHandler = async ( +const node8AsyncHandler: AWSLambda.APIGatewayProxyHandler = async ( event: AWSLambda.APIGatewayProxyEvent, context: AWSLambda.Context, cb: AWSLambda.Callback, @@ -761,7 +766,7 @@ let node8AsyncHandler: AWSLambda.APIGatewayProxyHandler = async ( return { statusCode: 200, body: 'Is now valid!' }; }; -let inferredHandler: AWSLambda.S3Handler = (event, context, cb) => { +const inferredHandler: AWSLambda.S3Handler = (event, context, cb) => { // $ExpectType S3Event event; str = event.Records[0].eventName; @@ -778,35 +783,35 @@ let inferredHandler: AWSLambda.S3Handler = (event, context, cb) => { }; // Test using default Callback type still works. -let defaultCallbackHandler: AWSLambda.APIGatewayProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; +const defaultCallbackHandler: AWSLambda.APIGatewayProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; // Specific types let s3Handler: AWSLambda.S3Handler = (event: AWSLambda.S3Event, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; // Test old name -let s3CreateHandler: AWSLambda.S3Handler = (event: AWSLambda.S3CreateEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +const s3CreateHandler: AWSLambda.S3Handler = (event: AWSLambda.S3CreateEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; s3Handler = s3CreateHandler; -let dynamoDBStreamHandler: AWSLambda.DynamoDBStreamHandler = (event: AWSLambda.DynamoDBStreamEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +const dynamoDBStreamHandler: AWSLambda.DynamoDBStreamHandler = (event: AWSLambda.DynamoDBStreamEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; -let snsHandler: AWSLambda.SNSHandler = (event: AWSLambda.SNSEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +const snsHandler: AWSLambda.SNSHandler = (event: AWSLambda.SNSEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; -let cognitoUserPoolHandler: AWSLambda.CognitoUserPoolTriggerHandler = (event: AWSLambda.CognitoUserPoolEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +const cognitoUserPoolHandler: AWSLambda.CognitoUserPoolTriggerHandler = (event: AWSLambda.CognitoUserPoolEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; -let cloudFormationCustomResourceHandler: AWSLambda.CloudFormationCustomResourceHandler = +const cloudFormationCustomResourceHandler: AWSLambda.CloudFormationCustomResourceHandler = (event: AWSLambda.CloudFormationCustomResourceEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; -let cloudWatchLogsHandler: AWSLambda.CloudWatchLogsHandler = (event: AWSLambda.CloudWatchLogsEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +const cloudWatchLogsHandler: AWSLambda.CloudWatchLogsHandler = (event: AWSLambda.CloudWatchLogsEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; -let scheduledHandler: AWSLambda.ScheduledHandler = (event: AWSLambda.ScheduledEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +const scheduledHandler: AWSLambda.ScheduledHandler = (event: AWSLambda.ScheduledEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; let apiGtwProxyHandler: AWSLambda.APIGatewayProxyHandler = (event: AWSLambda.APIGatewayProxyEvent, context: AWSLambda.Context, cb: AWSLambda.APIGatewayProxyCallback) => { }; // Test old names -let proxyHandler: AWSLambda.ProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.ProxyCallback) => { }; +const proxyHandler: AWSLambda.ProxyHandler = (event: AWSLambda.APIGatewayEvent, context: AWSLambda.Context, cb: AWSLambda.ProxyCallback) => { }; apiGtwProxyHandler = proxyHandler; -let codePipelineHandler: AWSLambda.CodePipelineHandler = (event: AWSLambda.CodePipelineEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; +const codePipelineHandler: AWSLambda.CodePipelineHandler = (event: AWSLambda.CodePipelineEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => {}; -let cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLambda.CloudFrontRequestEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontRequestCallback) => { +const cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLambda.CloudFrontRequestEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontRequestCallback) => { cb(); cb(null); cb(new Error('')); @@ -816,14 +821,14 @@ let cloudFrontRequestHandler: AWSLambda.CloudFrontRequestHandler = (event: AWSLa cb(null, { }); }; -let cloudFrontResponseHandler: AWSLambda.CloudFrontResponseHandler = (event: AWSLambda.CloudFrontResponseEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontResponseCallback) => { }; +const cloudFrontResponseHandler: AWSLambda.CloudFrontResponseHandler = (event: AWSLambda.CloudFrontResponseEvent, context: AWSLambda.Context, cb: AWSLambda.CloudFrontResponseCallback) => { }; -let customAuthorizerHandler: AWSLambda.CustomAuthorizerHandler = (event: AWSLambda.CustomAuthorizerEvent, context: AWSLambda.Context, cb: AWSLambda.CustomAuthorizerCallback) => { }; +const customAuthorizerHandler: AWSLambda.CustomAuthorizerHandler = (event: AWSLambda.CustomAuthorizerEvent, context: AWSLambda.Context, cb: AWSLambda.CustomAuthorizerCallback) => { }; interface CustomEvent { eventString: string; eventBool: boolean; } interface CustomResult { resultString: string; resultBool?: boolean; } type CustomCallback = AWSLambda.Callback; -let customHandler: AWSLambda.Handler = (event, context, cb) => { +const customHandler: AWSLambda.Handler = (event, context, cb) => { // $ExpectType CustomEvent event; str = event.eventString; @@ -837,9 +842,9 @@ let customHandler: AWSLambda.Handler = (event, contex cb(null, { resultString: bool }); }; -let kinesisStreamHandler: AWSLambda.KinesisStreamHandler = (event: AWSLambda.KinesisStreamEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; +const kinesisStreamHandler: AWSLambda.KinesisStreamHandler = (event: AWSLambda.KinesisStreamEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; -let SQSMessageHandler: AWSLambda.SQSHandler = (event: AWSLambda.SQSEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; +const SQSMessageHandler: AWSLambda.SQSHandler = (event: AWSLambda.SQSEvent, context: AWSLambda.Context, cb: AWSLambda.Callback) => { }; // See https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-sqs const SQSEvent: AWSLambda.SQSEvent = { @@ -863,7 +868,7 @@ const SQSEvent: AWSLambda.SQSEvent = { ] }; -let SQSMessageLegacyAsyncHandler: AWSLambda.SQSHandler = async ( +const SQSMessageLegacyAsyncHandler: AWSLambda.SQSHandler = async ( event: AWSLambda.SQSEvent, context: AWSLambda.Context, cb: AWSLambda.Callback, @@ -882,7 +887,7 @@ let SQSMessageLegacyAsyncHandler: AWSLambda.SQSHandler = async ( cb(new Error()); }; -let SQSMessageNode8AsyncHandler: AWSLambda.SQSHandler = async ( +const SQSMessageNode8AsyncHandler: AWSLambda.SQSHandler = async ( event: AWSLambda.SQSEvent, context: AWSLambda.Context ) => { @@ -895,3 +900,26 @@ let SQSMessageNode8AsyncHandler: AWSLambda.SQSHandler = async ( str = context.functionName; return; }; + +const firehoseEventHandler: AWSLambda.FirehoseTransformationHandler = ( + event: AWSLambda.FirehoseTransformationEvent, + context: AWSLambda.Context, + callback: AWSLambda.FirehoseTransformationCallback +) => { + // $ExpectType FirehoseTransformationEvent + event; + str = event.records[0].recordId; + + // $ExpectType Context + context; + str = context.functionName; + callback(null, { + records: [ + { + recordId: event.records[0].recordId, + result: 'Ok' as AWSLambda.FirehoseRecordTransformationStatus, + data: 'eyJmb28iOiJiYXIifQ==', + } + ] + }); +}; diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index aafdf4a0a0..35d0b1d7a6 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -19,6 +19,8 @@ // Chris Redekop // Aneil Mallavarapu // Jeremy Nagel +// Louis Larry +// Daniel Papukchiev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -211,27 +213,27 @@ export type S3CreateEvent = S3Event; // old name export interface CognitoUserPoolTriggerEvent { version: number; triggerSource: - | "PreSignUp_SignUp" - | "PostConfirmation_ConfirmSignUp" - | "PreAuthentication_Authentication" - | "PostAuthentication_Authentication" - | "CustomMessage_SignUp" - | "CustomMessage_AdminCreateUser" - | "CustomMessage_ResendCode" - | "CustomMessage_ForgotPassword" - | "CustomMessage_UpdateUserAttribute" - | "CustomMessage_VerifyUserAttribute" - | "CustomMessage_Authentication" - | "DefineAuthChallenge_Authentication" - | "CreateAuthChallenge_Authentication" - | "VerifyAuthChallengeResponse_Authentication" - | "PreSignUp_AdminCreateUser" - | "PostConfirmation_ConfirmForgotPassword" - | "TokenGeneration_HostedAuth" - | "TokenGeneration_Authentication" - | "TokenGeneration_NewPasswordChallenge" - | "TokenGeneration_AuthenticateDevice" - | "TokenGeneration_RefreshTokens"; + | "PreSignUp_SignUp" + | "PostConfirmation_ConfirmSignUp" + | "PreAuthentication_Authentication" + | "PostAuthentication_Authentication" + | "CustomMessage_SignUp" + | "CustomMessage_AdminCreateUser" + | "CustomMessage_ResendCode" + | "CustomMessage_ForgotPassword" + | "CustomMessage_UpdateUserAttribute" + | "CustomMessage_VerifyUserAttribute" + | "CustomMessage_Authentication" + | "DefineAuthChallenge_Authentication" + | "CreateAuthChallenge_Authentication" + | "VerifyAuthChallengeResponse_Authentication" + | "PreSignUp_AdminCreateUser" + | "PostConfirmation_ConfirmForgotPassword" + | "TokenGeneration_HostedAuth" + | "TokenGeneration_Authentication" + | "TokenGeneration_NewPasswordChallenge" + | "TokenGeneration_AuthenticateDevice" + | "TokenGeneration_RefreshTokens"; region: string; userPoolId: string; userName?: string; @@ -240,8 +242,8 @@ export interface CognitoUserPoolTriggerEvent { clientId: string; }; request: { - userAttributes: {[key: string]: string}; - validationData?: {[key: string]: string}; + userAttributes: { [key: string]: string }; + validationData?: { [key: string]: string }; codeParameter?: string; usernameParameter?: string; newDeviceUsed?: boolean; @@ -251,8 +253,8 @@ export interface CognitoUserPoolTriggerEvent { challengeMetaData?: string; }>; challengeName?: string; - privateChallengeParameters?: {[key: string]: string}; - challengeAnswer?: {[key: string]: string}; + privateChallengeParameters?: { [key: string]: string }; + challengeAnswer?: { [key: string]: string }; }; response: { autoConfirmUser?: boolean; @@ -262,8 +264,8 @@ export interface CognitoUserPoolTriggerEvent { challengeName?: string; issueTokens?: boolean; failAuthentication?: boolean; - publicChallengeParameters?: {[key: string]: string}; - privateChallengeParameters?: {[key: string]: string}; + publicChallengeParameters?: { [key: string]: string }; + privateChallengeParameters?: { [key: string]: string }; challengeMetaData?: string; answerCorrect?: boolean; }; @@ -369,6 +371,7 @@ export interface CloudWatchLogsLogEvent { id: string; timestamp: number; message: string; + extractedFields?: {[key: string]: string}; } // Context @@ -549,7 +552,7 @@ export interface CodePipelineEvent { inputArtifacts: Artifact[]; outputArtifacts: Artifact[]; artifactCredentials: Credentials; - encryptionKey?: EncryptionKey & {type: 'KMS'}; + encryptionKey?: EncryptionKey & { type: 'KMS' }; continuationToken?: string; }; }; @@ -582,7 +585,9 @@ export interface CloudFrontRequest { export interface CloudFrontEvent { config: { + distributionDomainName: string; distributionId: string; + eventType: 'origin-request' | 'origin-response' | 'viewer-request' | 'viewer-response'; requestId: string; }; } @@ -642,6 +647,47 @@ export interface KinesisStreamEvent { Records: KinesisStreamRecord[]; } +// Kinesis Data Firehose Event +// https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-kinesis-firehose +// https://docs.aws.amazon.com/firehose/latest/dev/data-transformation.html +// https://aws.amazon.com/blogs/compute/amazon-kinesis-firehose-data-transformation-with-aws-lambda/ +// Examples in the lambda blueprints +export interface FirehoseTransformationEvent { + invocationId: string; + deliveryStreamArn: string; + region: string; + records: FirehoseTransformationEventRecord[]; +} + +export interface FirehoseTransformationEventRecord { + recordId: string; + approximateArrivalTimestamp: number; + /** Base64 encoded */ + data: string; + kinesisRecordMetadata?: FirehoseRecordMetadata; +} + +export interface FirehoseRecordMetadata { + shardId: string; + partitionKey: string; + approximateArrivalTimestamp: string; + sequenceNumber: string; + subsequenceNumber: string; +} + +export type FirehoseRecordTransformationStatus = 'Ok' | 'Dropped' | 'ProcessingFailed'; + +export interface FirehoseTransformationResultRecord { + recordId: string; + result: FirehoseRecordTransformationStatus; + /** Encode in Base64 */ + data: string; +} + +export interface FirehoseTransformationResult { + records: FirehoseTransformationResultRecord[]; +} + // SQS // https://docs.aws.amazon.com/lambda/latest/dg/invoking-lambda-function.html#supported-event-source-sqs export interface SQSRecord { @@ -654,7 +700,7 @@ export interface SQSRecord { eventSource: string; eventSourceARN: string; awsRegion: string; - } +} export interface SQSEvent { Records: SQSRecord[]; @@ -754,7 +800,8 @@ export type CloudFrontResponseCallback = Callback; export type KinesisStreamHandler = Handler; -// TODO: Kinesis Firehose +export type FirehoseTransformationCallback = Callback; +export type FirehoseTransformationHandler = Handler; export type CustomAuthorizerHandler = Handler; export type CustomAuthorizerCallback = Callback; diff --git a/types/babel__core/index.d.ts b/types/babel__core/index.d.ts index 84f49c20fc..277228341b 100644 --- a/types/babel__core/index.d.ts +++ b/types/babel__core/index.d.ts @@ -10,10 +10,10 @@ import { GeneratorOptions } from "@babel/generator"; import traverse, { Visitor, NodePath } from "@babel/traverse"; import template from "@babel/template"; import * as t from "@babel/types"; -import { BabylonOptions } from "babylon"; +import { ParseOptions } from "@babel/parser"; export { - BabylonOptions, + ParseOptions, GeneratorOptions, t as types, template, @@ -217,7 +217,7 @@ export interface TransformOptions { * * Default: `{}` */ - parserOpts?: BabylonOptions | null; + parserOpts?: ParseOptions | null; /** * List of plugins to load and use diff --git a/types/babel__core/tsconfig.json b/types/babel__core/tsconfig.json index 22eb208383..2f96e019cb 100644 --- a/types/babel__core/tsconfig.json +++ b/types/babel__core/tsconfig.json @@ -22,6 +22,9 @@ "@babel/generator": [ "babel__generator" ], + "@babel/parser": [ + "babel__parser" + ], "@babel/template": [ "babel__template" ], diff --git a/types/backbone.marionette/backbone.marionette-tests.ts b/types/backbone.marionette/backbone.marionette-tests.ts index c6400b2672..2b86849622 100644 --- a/types/backbone.marionette/backbone.marionette-tests.ts +++ b/types/backbone.marionette/backbone.marionette-tests.ts @@ -135,6 +135,15 @@ class MyView extends Marionette.View { } } +class MyOtherView extends MyView { + private readonly foo: string; + + constructor(model: MyModel) { + super(model); + this.foo = 'bar'; + } +} + class MainRegion extends Marionette.Region { constructor() { super(); @@ -185,10 +194,20 @@ class MyHtmlElRegion extends Marionette.Region { } } -class MyCollectionView extends Marionette.CollectionView { +class MyCollectionView extends Marionette.CollectionView { constructor() { super(); + + this.childView = (model: MyModel) => { + if (model.get('isFoo')) { + return MyView; + } + + return MyOtherView; + }; + this.childView = MyView; + this.childViewEvents = { render() { console.log('a childView has been rendered'); @@ -282,7 +301,7 @@ function CollectionViewTests() { cv.collection.add(new MyModel()); app.mainRegion.show(cv); cv.emptyView = MyView; - const view: Marionette.CollectionView = cv.destroy(); + const view: Marionette.CollectionView = cv.destroy(); } class MyController { diff --git a/types/backbone.marionette/index.d.ts b/types/backbone.marionette/index.d.ts index 0b717c9bb1..bacd045ba1 100644 --- a/types/backbone.marionette/index.d.ts +++ b/types/backbone.marionette/index.d.ts @@ -3,7 +3,8 @@ // Definitions by: Zeeshan Hamid , // Natan Vivo , // Sven Tschui , -// Volker Nauruhn +// Volker Nauruhn , +// Ard Timmerman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -1157,7 +1158,7 @@ export interface CollectionViewOptions< /** * Specify a child view to use. */ - childView?: (() => typeof Backbone.View) | typeof Backbone.View; + childView?: ((model: TModel) => typeof Backbone.View) | typeof Backbone.View; /** * Define options to pass to the childView constructor. @@ -1219,7 +1220,7 @@ export class CollectionView { new(...args: any[]): TView }) | { new(...args: any[]): TView }; + childView: ((model: TModel) => { new(...args: any[]): TView }) | { new(...args: any[]): TView }; /** * Define options to pass to the childView constructor. diff --git a/types/blazy/blazy-tests.ts b/types/blazy/blazy-tests.ts index 835b0e6472..e3aedaabd4 100644 --- a/types/blazy/blazy-tests.ts +++ b/types/blazy/blazy-tests.ts @@ -38,7 +38,7 @@ var tester: BlazyInstance = new Blazy({ /* Functions tests */ tester.revalidate(); -var elements = document.getElementsByTagName('img'); +var elements = document.getElementsByTagName('img'); tester.load(elements, true); tester.destroy(); diff --git a/types/blazy/index.d.ts b/types/blazy/index.d.ts index 8a7183366d..661f651c0b 100644 --- a/types/blazy/index.d.ts +++ b/types/blazy/index.d.ts @@ -53,7 +53,7 @@ interface BlazyInstance { * Forces the given element(s) to load if not collapsed. If you also want to load a collapsed/hidden elements you can add true as the second parameter. * You can pass a single element or a list of elements. Tested with getElementById, getElementsByClassName, querySelectorAll, querySelector and jQuery selector. */ - load(elements: Element|Element[]|HTMLElement|HTMLElement[]|NodeList, force: boolean): void; + load(elements: Element|Element[]|HTMLElement|HTMLElement[]|HTMLCollection|NodeList, force: boolean): void; /** * Unbind events and resets image array. diff --git a/types/bootstrap/bootstrap-tests.ts b/types/bootstrap/bootstrap-tests.ts index f0bbbea7f2..9a80afc654 100755 --- a/types/bootstrap/bootstrap-tests.ts +++ b/types/bootstrap/bootstrap-tests.ts @@ -1,3 +1,5 @@ +declare let aHtmlElement: HTMLElement; + // -------------------------------------------------------------------------------------- // Alert // -------------------------------------------------------------------------------------- @@ -78,7 +80,7 @@ $("#collapse").collapse({ }); $("#collapse").collapse({ - parent: document.body, + parent: aHtmlElement, }); $("#collapse").collapse({ @@ -122,11 +124,11 @@ $("#dropdown").dropdown({ }); $("#dropdown").dropdown({ - boundary: document.body, + boundary: aHtmlElement, }); $("#dropdown").dropdown({ - reference: document.body, + reference: aHtmlElement, }); // -------------------------------------------------------------------------------------- @@ -340,5 +342,5 @@ $("#tooltip").tooltip({ }); $("#tooltip").tooltip({ - boundary: document.body, + boundary: aHtmlElement, }); diff --git a/types/braft-editor/index.d.ts b/types/braft-editor/index.d.ts index 00d03d81d1..62f339a41b 100644 --- a/types/braft-editor/index.d.ts +++ b/types/braft-editor/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/margox/braft#readme // Definitions by: My Self // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; import { RawDraftContentState } from 'draft-js'; diff --git a/types/bull/bull-tests.tsx b/types/bull/bull-tests.tsx index c2e0d3161f..a8c7f403a7 100644 --- a/types/bull/bull-tests.tsx +++ b/types/bull/bull-tests.tsx @@ -6,7 +6,10 @@ import Redis = require("ioredis"); import Queue = require("bull"); const videoQueue = new Queue('video transcoding', 'redis://127.0.0.1:6379'); -const audioQueue = new Queue('audio transcoding', {redis: {port: 6379, host: '127.0.0.1'}}); // Specify Redis connection using object +const audioQueue = new Queue('audio transcoding', { + redis: {port: 6379, host: '127.0.0.1'}, // Specify Redis connection using object + settings: {}, +}); const imageQueue: Queue.Queue<{ image: string }> = new Queue('image transcoding'); videoQueue.process((job, done) => { diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index c204fea135..a11ae0257a 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -84,6 +84,13 @@ declare namespace Bull { * Delay before processing next job in case of internal error */ retryProcessDelay?: number; + + /** + * Define a custom backoff strategy + */ + backoffStrategies?: { + [key: string]: (attemptsMade: number, err: typeof Error) => number; + }; } type DoneCallback = (error?: Error | null, value?: any) => void; @@ -167,12 +174,12 @@ declare namespace Bull { /** * Backoff type, which can be either `fixed` or `exponential` */ - type: 'fixed' | 'exponential'; + type: string; /** * Backoff delay, in milliseconds */ - delay: number; + delay?: number; } interface RepeatOptions { diff --git a/types/bull/tsconfig.json b/types/bull/tsconfig.json index 3ce6f08792..7dbd4e7b61 100644 --- a/types/bull/tsconfig.json +++ b/types/bull/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/capture-console/capture-console-tests.ts b/types/capture-console/capture-console-tests.ts new file mode 100644 index 0000000000..45dd3a7130 --- /dev/null +++ b/types/capture-console/capture-console-tests.ts @@ -0,0 +1,53 @@ +import * as captureconsole from "capture-console"; + +captureconsole.capture(process.stdout, () => { }); // $ExpectType string[] +captureconsole.capture(process.stdout, {}, () => { }); // $ExpectType string[] +captureconsole.capture(process.stdout, { quiet: true }, () => { }); // $ExpectType string[] + +captureconsole.capture([process.stdout, process.stdin], () => { }); // $ExpectType string[] +captureconsole.capture([process.stdout, process.stdin], {}, () => { }); // $ExpectType string[] +captureconsole.capture([process.stdout, process.stdin], { quiet: true }, () => { }); // $ExpectType string[] + +captureconsole.captureStderr(() => { }); // $ExpectType string +captureconsole.captureStderr({}, () => { }); // $ExpectType string +captureconsole.captureStderr({ quiet: true }, () => { }); // $ExpectType string + +captureconsole.captureStdio(() => { }); // $ExpectType { stdout: string; stderr: string; } +captureconsole.captureStdio({}, () => { }); // $ExpectType { stdout: string; stderr: string; } +captureconsole.captureStdio({ quiet: true }, () => { }); // $ExpectType { stdout: string; stderr: string; } + +captureconsole.captureStdout(() => { }); // $ExpectType string +captureconsole.captureStdout({}, () => { }); // $ExpectType string +captureconsole.captureStdout({ quiet: true }, () => { }); // $ExpectType string + +captureconsole.hook(process.stdout, (string: string, encoding?: string, fd?: (error?: any) => void) => { }); // $ExpectType () => boolean +captureconsole.hook(process.stdout, {}, (string: string, encoding?: string, fd?: (error?: any) => void) => { }); // $ExpectType () => boolean +captureconsole.hook(process.stdout, { quiet: true }, (string: string, encoding?: string, fd?: (error?: any) => void) => { }); // $ExpectType () => boolean + +captureconsole.intercept(process.stdout, () => { }); // $ExpectType string[] +captureconsole.intercept(process.stdout, {}, () => { }); // $ExpectType string[] +captureconsole.intercept(process.stdout, { quiet: true }, () => { }); // $ExpectType string[] + +captureconsole.interceptStderr(() => { }); // $ExpectType string +captureconsole.interceptStderr({}, () => { }); // $ExpectType string +captureconsole.interceptStderr({ quiet: true }, () => { }); // $ExpectType string + +captureconsole.interceptStdio(() => { }); // $ExpectType { stdout: string; stderr: string; } +captureconsole.interceptStdio({}, () => { }); // $ExpectType { stdout: string; stderr: string; } +captureconsole.interceptStdio({ quiet: true }, () => { }); // $ExpectType { stdout: string; stderr: string; } + +captureconsole.interceptStdout(() => { }); // $ExpectType string +captureconsole.interceptStdout({}, () => { }); // $ExpectType string +captureconsole.interceptStdout({ quiet: true }, () => { }); // $ExpectType string + +captureconsole.startCapture(process.stdout, (string: string, encoding?: string, fd?: (error?: any) => void) => { }); // $ExpectType boolean +captureconsole.startCapture(process.stdout, {}, (string: string, encoding?: string, fd?: (error?: any) => void) => { }); // $ExpectType boolean +captureconsole.startCapture(process.stdout, { quiet: true }, (string: string, encoding?: string, fd?: (error?: any) => void) => { }); // $ExpectType boolean + +captureconsole.startIntercept(process.stdout, () => { }); // $ExpectType boolean +captureconsole.startIntercept(process.stdout, {}, () => { }); // $ExpectType boolean +captureconsole.startIntercept(process.stdout, { quiet: true }, () => { }); // $ExpectType boolean + +captureconsole.stopCapture(process.stdout); // $ExpectType boolean + +captureconsole.stopIntercept(process.stdout); // $ExpectType boolean diff --git a/types/capture-console/index.d.ts b/types/capture-console/index.d.ts new file mode 100644 index 0000000000..d3ebd914f9 --- /dev/null +++ b/types/capture-console/index.d.ts @@ -0,0 +1,190 @@ +// Type definitions for capture-console 1.0 +// Project: https://github.com/zackehh/capture-console +// Definitions by: Auston Zahrt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * Options controlling behavior when capturing + */ +export interface CaptureOptions { + /** + * Option to silence the output going to the console + */ + quiet?: boolean; +} + +/** + * Executes the provided function with the output + * on the provided streams. + */ +export function capture( + streams: ReadonlyArray | NodeJS.WritableStream, + exec: () => void +): string[]; + +/** + * Executes the provided function with the output + * on the provided streams. Accepts options to silence + * the output going to the console. + */ +export function capture( + streams: ReadonlyArray | NodeJS.WritableStream, + opts: CaptureOptions, + exec: () => void +): string[]; + +/** + * Captures stderr for the provided execution scope. + */ +export function captureStderr(exec: () => void): string; + +/** + * Captures stderr for the provided execution scope. + */ +export function captureStderr(opts: CaptureOptions, exec: () => void): string; + +/** + * Captures stdout and stderr into an object for + * the provided execution scope. + */ +export function captureStdio(exec: () => void): { stdout: string; stderr: string; }; + +/** + * Captures stdout and stderr into an object for + * the provided execution scope. + */ +export function captureStdio(opts: CaptureOptions, exec: () => void): { stdout: string; stderr: string; }; + +/** + * Captures stdout for the provided execution scope. + */ +export function captureStdout(exec: () => void): string; + +/** + * Captures stdout for the provided execution scope. + */ +export function captureStdout(opts: CaptureOptions, exec: () => void): string; + +/** + * Listens to a provided stream, and executes the provided + * function for every write call. Accepts options to silence + * the output going to the console. + * + * Returns a function to call when you wish to stop listening + * to the call. + */ +export function hook( + stream: NodeJS.WritableStream, + exec: ( + string: string, + encoding?: string, + fd?: (error?: any) => void + ) => void +): () => boolean; + +/** + * Listens to a provided stream, and executes the provided + * function for every write call. Accepts options to silence + * the output going to the console. + * + * Returns a function to call when you wish to stop listening + * to the call. + */ +export function hook( + stream: NodeJS.WritableStream, + opts: CaptureOptions, + exec: ( + string: string, + encoding?: string, + fd?: (error?: any) => void + ) => void +): () => boolean; + +/** + * Delegate to #capture with a quiet passthrough. + */ +export function intercept(stream: NodeJS.WritableStream, exec: () => void): string[]; + +/** + * Delegate to #capture with a quiet passthrough. + */ +export function intercept(stream: NodeJS.WritableStream, opts: CaptureOptions, exec: () => void): string[]; + +/** + * Delegate to #captureStderr with a quiet passthrough. + */ +export function interceptStderr(exec: () => void): string; + +/** + * Delegate to #captureStderr with a quiet passthrough. + */ +export function interceptStderr(opts: CaptureOptions, exec: () => void): string; + +/** + * Delegate to #captureStdio with a quiet passthrough. + */ +export function interceptStdio(exec: () => void): { stdout: string; stderr: string; }; + +/** + * Delegate to #captureStdio with a quiet passthrough. + */ +export function interceptStdio(opts: CaptureOptions, exec: () => void): { stdout: string; stderr: string; }; + +/** + * Delegate to #captureStdout with a quiet passthrough. + */ +export function interceptStdout(exec: () => void): string; + +/** + * Delegate to #captureStdout with a quiet passthrough. + */ +export function interceptStdout(opts: CaptureOptions, exec: () => void): string; + +/** + * Starts a capture on the provided stream using the + * provided options and stream execution. + */ +export function startCapture( + stream: NodeJS.WritableStream, + exec: ( + string: string, + encoding?: string, + fd?: (error?: any) => void + ) => void +): boolean; + +/** + * Starts a capture on the provided stream using the + * provided options and stream execution. + */ +export function startCapture( + stream: NodeJS.WritableStream, + opts: CaptureOptions, + exec: ( + string: string, + encoding?: string, + fd?: (error?: any) => void + ) => void +): boolean; + +/** + * Delegate to #startCapture with a quiet passthrough. + */ +export function startIntercept(stream: NodeJS.WritableStream, exec: () => void): boolean; + +/** + * Delegate to #startCapture with a quiet passthrough. + */ +export function startIntercept(stream: NodeJS.WritableStream, opts: CaptureOptions, exec: () => void): boolean; + +/** + * Stops a capture on the provided stream. + */ +export function stopCapture(stream: NodeJS.WritableStream): boolean; + +/** + * Delegate to #stopCapture with a quiet passthrough. + */ +export function stopIntercept(stream: NodeJS.WritableStream): boolean; diff --git a/types/capture-console/tsconfig.json b/types/capture-console/tsconfig.json new file mode 100644 index 0000000000..01807d6e22 --- /dev/null +++ b/types/capture-console/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", + "capture-console-tests.ts" + ] +} \ No newline at end of file diff --git a/types/react-svg/tslint.json b/types/capture-console/tslint.json similarity index 100% rename from types/react-svg/tslint.json rename to types/capture-console/tslint.json diff --git a/types/catbox-redis/catbox-redis-tests.ts b/types/catbox-redis/catbox-redis-tests.ts new file mode 100644 index 0000000000..d7fb5eb701 --- /dev/null +++ b/types/catbox-redis/catbox-redis-tests.ts @@ -0,0 +1,12 @@ +import * as CatbotRedis from 'catbox-redis'; + +const cache = new CatbotRedis({ + host: 'localhost', + partition: 'test', + port: 2018, +}); + +cache.get({ + segment: 'test', + id: 'test', +}); diff --git a/types/catbox-redis/index.d.ts b/types/catbox-redis/index.d.ts new file mode 100644 index 0000000000..a0d3590953 --- /dev/null +++ b/types/catbox-redis/index.d.ts @@ -0,0 +1,60 @@ +// Type definitions for catbox-redis 4.1 +// Project: https://github.com/hapijs/catbox-redis#readme +// Definitions by: Simon Schick +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +// tslint:disable-next-line +declare module 'catbox-redis' { + import { Redis } from 'ioredis'; + import { EnginePrototype, ClientOptions, Client } from 'catbox'; + namespace CatboxRedis { + interface CatboxRedisOptions extends ClientOptions { + /** + * Raw client. + */ + client?: Redis; + /** + * the Redis server URL (if url is provided, host, port, and socket are ignored) + */ + url?: string; + /** + * the Redis server hostname. + * Defaults to '127.0.0.1'. + */ + host?: string; + /** + * the Redis server port or unix domain socket path. + * Defaults to 6379. + */ + port?: number; + /** + * the unix socket string to connect to (if socket is provided, host and port are ignored) + */ + socket?: string; + /** + * the Redis authentication password when required. + */ + password?: string; + /** + * the Redis database. + */ + database?: string; + /** + * an array of redis sentinel addresses to connect to. + */ + sentinels?: Array<{ + host: string; + }>; + /** + * the name of the sentinel master. + * (Only needed when sentinels is specified) + */ + sentinelName?: string; + } + } + class CatboxRedis extends Client { + constructor(options: CatboxRedis.CatboxRedisOptions); + } + export = CatboxRedis; + } diff --git a/types/meteor-univserse-i18n/tsconfig.json b/types/catbox-redis/tsconfig.json similarity index 91% rename from types/meteor-univserse-i18n/tsconfig.json rename to types/catbox-redis/tsconfig.json index 7beab3bd30..2d31a4bc59 100644 --- a/types/meteor-univserse-i18n/tsconfig.json +++ b/types/catbox-redis/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "meteor-univserse-i18n-tests.ts" + "catbox-redis-tests.ts" ] } diff --git a/types/catbox-redis/tslint.json b/types/catbox-redis/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/catbox-redis/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index 6d51e48696..f6881b1aef 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -112,6 +112,9 @@ export interface CachedObject { export type CacheItem = any; export interface ClientOptions { + /** + * this will store items under keys that start with this value. + */ partition: string; } diff --git a/types/cesium/index.d.ts b/types/cesium/index.d.ts index 967c124bac..3ea9745ebd 100644 --- a/types/cesium/index.d.ts +++ b/types/cesium/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for cesium 1.46 +// Type definitions for cesium 1.47 // Project: http://cesiumjs.org // Definitions by: Aigars Zeiza // Harry Nicholls // Jared Szechy +// Radek Goláň jr. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -1934,15 +1935,15 @@ declare namespace Cesium { semiMinorAxis: Property; rotation: Property; show: Property; - material: MaterialProperty; + material: MaterialProperty | Color; height: Property; extrudedHeight: Property; granularity: Property; stRotation: Property; - fill: Property; - outline: Property; - outlineColor: Property; - outlineWidth: Property; + fill: boolean; + outline: boolean; + outlineColor: Color; + outlineWidth: number; numberOfVerticalLines: Property; constructor(options?: { semiMajorAxis?: number; @@ -1950,11 +1951,11 @@ declare namespace Cesium { height?: Property; extrudedHeight?: Property; show?: Property; - fill?: Property; - material?: MaterialProperty; - outline?: Property; - outlineColor?: Property; - outlineWidth?: Property; + fill?: boolean; + material?: MaterialProperty | Color + outline?: boolean; + outlineColor?: Color; + outlineWidth?: number; numberOfVerticalLines?: Property; rotation?: Property; stRotation?: Property; @@ -2206,11 +2207,11 @@ declare namespace Cesium { class LabelGraphics { definitionChanged: Event; text: Property; - font: Property; + font: string; style: Property; - fillColor: Property; - outlineColor: Property; - outlineWidth: Property; + fillColor: Color; + outlineColor: Color; + outlineWidth: number; horizontalOrigin: Property; verticalOrigin: Property; eyeOffset: Property; @@ -2221,11 +2222,11 @@ declare namespace Cesium { pixelOffsetScaleByDistance: Property; constructor(options?: { text?: Property; - font?: Property; + font?: string; style?: Property; - fillColor?: Property; - outlineColor?: Property; - outlineWidth?: Property; + fillColor?: Color; + outlineColor?: Color; + outlineWidth?: number; show?: Property; scale?: Property; horizontalOrigin?: Property; @@ -2361,16 +2362,16 @@ declare namespace Cesium { class PolygonGraphics { definitionChanged: Event; show: Property; - material: MaterialProperty; + material: MaterialProperty | Color; positions: Property; hierarchy: Property; height: Property; extrudedHeight: Property; granularity: Property; stRotation: Property; - fill: Property; + fill: boolean; outline: Property; - outlineColor: Property; + outlineColor: Color; outlineWidth: Property; perPositionHeight: Property; constructor(options?: { @@ -2378,10 +2379,10 @@ declare namespace Cesium { height?: number; extrudedHeight?: Property; show?: Property; - fill?: Property; - material?: MaterialProperty; + fill?: boolean; + material?: MaterialProperty | Color; outline?: boolean; - outlineColor?: Property; + outlineColor?: Color; outlineWidth?: number; stRotation?: Property; granularity?: Property; @@ -3592,7 +3593,7 @@ declare namespace Cesium { cull?: boolean; asynchronous?: boolean; debugShowBoundingVolume?: boolean; - shadows: ShadowMode + shadows?: ShadowMode }); destroy(): void; getGeometryInstanceAttributes(id: any): any; diff --git a/types/chai-enzyme/index.d.ts b/types/chai-enzyme/index.d.ts index 413f5ec545..783b7fce2f 100644 --- a/types/chai-enzyme/index.d.ts +++ b/types/chai-enzyme/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/producthunt/chai-enzyme // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index d3762d54be..09230f6702 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -584,7 +584,7 @@ declare namespace Chart { position?: string; ticks?: TickOptions; gridLines?: GridLineOptions; - barThickness?: number | string; + barThickness?: number | "flex"; maxBarThickness?: number; scaleLabel?: ScaleTitleOptions; time?: TimeScale; diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index a1713aa6f9..07437c787a 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -1,8 +1,8 @@ // Type definitions for Chrome packaged application development // Project: http://developer.chrome.com/apps/ -// Definitions by: Nikolai Ommundsen , Adam Lay , MIZUNE Pine , MIZUSHIMA Junki , Ingvar Stepanyan , Adam Pyle , Matthew Kimber , otiai10 , couven92 , RReverser , sreimer15 +// Definitions by: Nikolai Ommundsen , Adam Lay , MIZUNE Pine , MIZUSHIMA Junki , Ingconst Stepanyan , Adam Pyle , Matthew Kimber , otiai10 , couven92 , RReverser , sreimer15 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 /// @@ -12,25 +12,55 @@ //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// declare namespace chrome { - //////////////////// - // Accessibility Features - //////////////////// + ////////////// + // INTERNAL // + ////////////// + + /** @deprecated Could be used, if e.g. deprecated recently */ + type deprecatedButUsable = any; + + /** @deprecated Should never be used, used to guide migrations. */ + type deprecated = never; + + // Not proper types, but used to give the programmer a hint // + /** + * Integer + */ + type integer = number; + /** + * Double + */ + type double = number; + + + //////////////////////////// + // Accessibility Features // + //////////////////////////// + /** + * @requires Important: This API works only on Chrome OS. + * @requires Permissions: + * 'accessibilityFeatures.read' (For read access) + * 'accessibilityFeatures.modify' (For modifications) + * Note that accessibilityFeatures.modify does not imply accessibilityFeatures.read permission. + * @since Available since Chrome 37. + * @description * Use the chrome.accessibilityFeatures API to manage Chrome's accessibility features. * This API relies on the ChromeSetting prototype of the type API for getting and setting individual accessibility features. * In order to get feature states the extension must request accessibilityFeatures.read permission. * For modifying feature state, the extension needs accessibilityFeatures.modify permission. * Note that accessibilityFeatures.modify does not imply accessibilityFeatures.read permission. - * Permissions: 'accessibilityFeatures.read' (For read access); 'accessibilityFeatures.modify' (For modifications; Note that accessibilityFeatures.modify does not imply accessibilityFeatures.read permission.) - * Important: This API works only on Chrome OS. - * @since Availability: Since Chrome 37. */ namespace accessibilityFeatures { interface AccessibilityFeaturesGetArg { - /** Optional. Whether to return the value that applies to the incognito session (default false). */ + /** Whether to return the value that applies to the incognito session (default false). */ incognito?: boolean; } + type LevelOfControl = + 'not_controllable' | 'controlled_by_other_extensions' | + 'controllable_by_this_extension' | 'controlled_by_this_extension'; + interface AccessibilityFeaturesCallbackArg { /** The value of the setting. */ value: any; @@ -41,11 +71,13 @@ declare namespace chrome { * • controllable_by_this_extension: can be controlled by this extension * • controlled_by_this_extension: controlled by this extension */ - levelOfControl: 'not_controllable' | 'controlled_by_other_extensions' | 'controllable_by_this_extension' | 'controlled_by_this_extension'; - /** Optional. Whether the effective value is specific to the incognito session. This property will only be present if the incognito property in the details parameter of get() was true. */ + levelOfControl: LevelOfControl; + /** Whether the effective value is specific to the incognito session. This property will only be present if the incognito property in the details parameter of get() was true. */ incognitoSpecific?: boolean; } + type Scope = 'regular' | 'regular_only' | 'incognito_persistent' | 'incognito_session_only'; + interface AccessibilityFeaturesSetArg { /** * The value of the setting. @@ -53,26 +85,24 @@ declare namespace chrome { */ value: any; /** - * Optional. - * The scope of the ChromeSetting. One of + * The scope of the ChromeSetting. One of * • regular: setting for the regular profile (which is inherited by the incognito profile if not overridden elsewhere), * • regular_only: setting for the regular profile only (not inherited by the incognito profile), * • incognito_persistent: setting for the incognito profile that survives browser restarts (overrides regular preferences), * • incognito_session_only: setting for the incognito profile that can only be set during an incognito session and is deleted when the incognito session ends (overrides regular and incognito_persistent preferences). */ - scope?: 'regular' | 'regular_only' | 'incognito_persistent' | 'incognito_session_only'; + scope?: Scope; } interface AccessibilityFeaturesClearArg { /** - * Optional. - * The scope of the ChromeSetting. One of + * The scope of the ChromeSetting. One of * • regular: setting for the regular profile (which is inherited by the incognito profile if not overridden elsewhere), * • regular_only: setting for the regular profile only (not inherited by the incognito profile), * • incognito_persistent: setting for the incognito profile that survives browser restarts (overrides regular preferences), * • incognito_session_only: setting for the incognito profile that can only be set during an incognito session and is deleted when the incognito session ends (overrides regular and incognito_persistent preferences). */ - scope?: 'regular' | 'regular_only' | 'incognito_persistent' | 'incognito_session_only'; + scope?: Scope; } interface AccessibilityFeaturesSetting { @@ -104,83 +134,85 @@ declare namespace chrome { /** * Spoken feedback (text-to-speech). The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. */ - export var spokenFeedback: AccessibilityFeaturesSetting; + const spokenFeedback: AccessibilityFeaturesSetting; /** * Enlarged cursor. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. */ - export var largeCursor: AccessibilityFeaturesSetting; + const largeCursor: AccessibilityFeaturesSetting; /** * Sticky modifier keys (like shift or alt). The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. */ - export var stickyKeys: AccessibilityFeaturesSetting; + const stickyKeys: AccessibilityFeaturesSetting; /** * High contrast rendering mode. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. */ - export var highContrast: AccessibilityFeaturesSetting; + const highContrast: AccessibilityFeaturesSetting; /** * Full screen magnification. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. */ - export var screenMagnifier: AccessibilityFeaturesSetting; + const screenMagnifier: AccessibilityFeaturesSetting; /** * Auto mouse click after mouse stops moving. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. */ - export var autoclick: AccessibilityFeaturesSetting; + const autoclick: AccessibilityFeaturesSetting; /** * Virtual on-screen keyboard. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. */ - export var virtualKeyboard: AccessibilityFeaturesSetting; + const virtualKeyboard: AccessibilityFeaturesSetting; /** * Caret highlighting. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. * @since Since Chrome 51. */ - export var caretHighlight: AccessibilityFeaturesSetting; + const caretHighlight: AccessibilityFeaturesSetting; /** * Cursor highlighting. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. * @since Since Chrome 51. */ - export var cursorHighlight: AccessibilityFeaturesSetting; + const cursorHighlight: AccessibilityFeaturesSetting; /** * Focus highlighting. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. * @since Since Chrome 51. */ - export var focusHighlight: AccessibilityFeaturesSetting; + const focusHighlight: AccessibilityFeaturesSetting; /** * Select-to-speak. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. * @since Since Chrome 51. */ - export var selectToSpeak: AccessibilityFeaturesSetting; + const selectToSpeak: AccessibilityFeaturesSetting; /** * Switch access. The value indicates whether the feature is enabled or not. get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. * @since Since Chrome 51. */ - export var switchAccess: AccessibilityFeaturesSetting; + const switchAccess: AccessibilityFeaturesSetting; /** * get() requires accessibilityFeatures.read permission. set() and clear() require accessibilityFeatures.modify permission. * @since Since Chrome 42. */ - export var animationPolicy: AccessibilityFeaturesSetting; + const animationPolicy: AccessibilityFeaturesSetting; } - //////////////////// - // Alarms - //////////////////// + //////////// + // Alarms // + //////////// /** - * Use the chrome.alarms API to schedule code to run periodically or at a specified time in the future. - * Permissions: 'alarms' + * @requires Permissions: 'alarms' * @since Availability: Since Chrome 22. + * @description + * Use the chrome.alarms API to schedule code to run + * periodically or at a specified time in the future. */ namespace alarms { interface AlarmCreateInfo { - /** Optional. Length of time in minutes after which the onAlarm event should fire. */ + /** Length of time in minutes after which the onAlarm event should fire. */ delayInMinutes?: number; - /** Optional. If set, the onAlarm event should fire every periodInMinutes minutes after the initial event specified by when or delayInMinutes. If not set, the alarm will only fire once. */ + /** If set, the onAlarm event should fire every periodInMinutes minutes after the initial event specified by when or delayInMinutes. If not set, the alarm will only fire once. */ periodInMinutes?: number; - /** Optional. Time at which the alarm should fire, in milliseconds past the epoch (e.g. Date.now() + n). */ + /** Time at which the alarm should fire, in milliseconds past the epoch (e.g. Date.now() + n). */ when?: number; } interface Alarm { - /** Optional. If not null, the alarm is a repeating alarm and will fire again in periodInMinutes minutes. */ + /** If not null, the alarm is a repeating alarm and will fire again in periodInMinutes minutes. */ periodInMinutes?: number; /** Time at which this alarm was scheduled to fire, in milliseconds past the epoch (e.g. Date.now() + n). For performance reasons, the alarm may have been delayed an arbitrary amount beyond this. */ scheduledTime: number; @@ -198,7 +230,7 @@ declare namespace chrome { * To help you debug your app or extension, when you've loaded it unpacked, there's no limit to how often the alarm can fire. * @param alarmInfo Describes when the alarm should fire. The initial time must be specified by either when or delayInMinutes (but not both). If periodInMinutes is set, the alarm will repeat every periodInMinutes minutes after the initial event. If neither when or delayInMinutes is set for a repeating alarm, periodInMinutes is used as the default for delayInMinutes. */ - export function create(alarmInfo: AlarmCreateInfo): void; + function create(alarmInfo: AlarmCreateInfo): void; /** * Creates an alarm. Near the time(s) specified by alarmInfo, the onAlarm event is fired. * If there is another alarm with the same name (or no name if none is specified), it will be cancelled and replaced by this alarm. @@ -209,64 +241,92 @@ declare namespace chrome { * @param name Optional name to identify this alarm. Defaults to the empty string. * @param alarmInfo Describes when the alarm should fire. The initial time must be specified by either when or delayInMinutes (but not both). If periodInMinutes is set, the alarm will repeat every periodInMinutes minutes after the initial event. If neither when or delayInMinutes is set for a repeating alarm, periodInMinutes is used as the default for delayInMinutes. */ - export function create(name: string, alarmInfo: AlarmCreateInfo): void; + function create(name: string, alarmInfo: AlarmCreateInfo): void; /** * Gets an array of all the alarms. * @param callback The callback parameter should be a function that looks like this: * @example function(array of Alarm alarms) {...}; */ - export function getAll(callback: (alarms: Alarm[]) => void): void; + function getAll(callback: (alarms: Alarm[]) => void): void; /** * Clears all alarms. - * @param callback If you specify the callback parameter, it should be a function that looks like this: + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: * @example function(boolean wasCleared) {...}; */ - export function clearAll(callback?: (wasCleared: boolean) => void): void; + function clearAll(callback?: (wasCleared: boolean) => void): void; /** * Clears the alarm with the given name. * @param name The name of the alarm to clear. Defaults to the empty string. - * @param callback If you specify the callback parameter, it should be a function that looks like this: + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: * @example function(boolean wasCleared) {...}; */ - export function clear(name?: string, callback?: (wasCleared: boolean) => void): void; + function clear(name?: string, callback?: (wasCleared: boolean) => void): void; /** * Clears the alarm without a name. - * @param callback If you specify the callback parameter, it should be a function that looks like this: + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: * @example function(boolean wasCleared) {...}; */ - export function clear(callback: (wasCleared: boolean) => void): void; + function clear(callback: (wasCleared: boolean) => void): void; /** * Retrieves details about the specified alarm. * @param callback The callback parameter should be a function that looks like this: * @example function( Alarm alarm) {...}; */ - export function get(callback: (alarm: Alarm) => void): void; + function get(callback: (alarm: Alarm) => void): void; /** * Retrieves details about the specified alarm. * @param name The name of the alarm to get. Defaults to the empty string. * @param callback The callback parameter should be a function that looks like this: * @example function( Alarm alarm) {...}; */ - export function get(name: string, callback: (alarm: Alarm) => void): void; + function get(name: string, callback: (alarm: Alarm) => void): void; /** Fired when an alarm has elapsed. Useful for event pages. */ - export var onAlarm: AlarmEvent; + const onAlarm: AlarmEvent; } - //////////////////// - // App Runtime - //////////////////// - + ///////////////// + // App Runtime // + ///////////////// /** - * Use the chrome.app.runtime API to manage the app lifecycle. - * The app runtime manages app installation, controls the event page, and can shut down the app at anytime. * @since Availability: Since Chrome 24. + * @description + * Use the chrome.app.runtime API to manage the app lifecycle. + * The app runtime manages app installation, controls the event page, + * and can shut down the app at anytime. */ namespace app.runtime { - type LaunchSource = 'untracked' | 'app_launcher' | 'new_tab_page' | 'reload' | 'restart' | - 'load_and_launch' | 'command_line' | 'file_handler' | 'url_handler' | 'system_tray' | - 'about_page' | 'keyboard' | 'extensions_page' | 'management_api' | 'ephemeral_app' | - 'background' | 'kiosk' | 'chrome_internal' | 'test' | 'installed_notification' | 'context_menu'; + /** + * @todo TODO UNDOCUMENTED? + */ + enum PlayStoreStatus { + ENABLED = 'enabled', + AVAILABLE = 'available', + UNKNOWN = 'unknown' + } + enum LaunchSource { + ABOUT_PAGE = "about_page", + APP_LAUNCHER = "app_launcher", + BACKGROUND = "background", + CHROME_INTERNAL = "chrome_internal", + COMMAND_LINE = "command_line", + CONTEXT_MENU = "context_menu", + EPHEMERAL_APP = "ephemeral_app", + EXTENSIONS_PAGE = "extensions_page", + FILE_HANDLER = "file_handler", + INSTALLED_NOTIFICATION = "installed_notification", + KEYBOARD = "keyboard", + KIOSK = "kiosk", + LOAD_AND_LAUNCH = "load_and_launch", + MANAGEMENT_API = "management_api", + NEW_TAB_PAGE = "new_tab_page", + RELOAD = "reload", + RESTART = "restart", + SYSTEM_TRAY = "system_tray", + TEST = "test", + UNTRACKED = "untracked", + URL_HANDLER = "url_handler" + } interface EmbedRequest { /** @@ -285,6 +345,10 @@ declare namespace chrome { type actionType = 'new_note'; + const ActionType: { + NEW_NOTE: actionType + } + interface LaunchData { /** * The ID of the file or URL handler that the app is being invoked with. @@ -319,7 +383,7 @@ declare namespace chrome { /** * Contains data that specifies the ActionType this app was launched with. This is null if the app was not launched with a specific action intent. * ______________________________________________________________________________ - * | enum of 'new_note' | actionType | new_note | + * | type of 'new_note' | actionType | new_note | * | | | The user wants to quickly take a new note. | * |____________________|____________|____________________________________________| * @since Since Chrome 54. @@ -338,41 +402,36 @@ declare namespace chrome { type?: string; } - interface EmbedRequestedEvent extends chrome.events.Event<(request: EmbedRequest) => void> { } - - interface LaunchedEvent extends chrome.events.Event<(launchData: LaunchData) => void> { } - - interface RestartedEvent extends chrome.events.Event<() => void> { } - /** * Fired when an embedding app requests to embed this app. This event is only available on dev channel with the flag --enable-app-view. * @since Since Chrome 38. */ - export var onEmbedRequest: EmbedRequestedEvent; + const onEmbedRequest: chrome.events.Event<(request: EmbedRequest) => void>; /** * Fired when an app is launched from the launcher. */ - export var onLaunched: LaunchedEvent; + const onLaunched: chrome.events.Event<(launchData: LaunchData) => void>; /** * Fired at Chrome startup to apps that were running when Chrome last shut down, * or when apps have been requested to restart from their previous state for other reasons * (e.g. when the user revokes access to an app's retained files the runtime will restart the app). * In these situations if apps do not have an onRestarted handler they will be sent an onLaunched event instead. */ - export var onRestarted: RestartedEvent; + const onRestarted: chrome.events.Event<() => void>; } //////////////////// // App Window //////////////////// /** + * @since Availability: Since Chrome 24. + * @description * Use the chrome.app.window API to create windows. * Windows have an optional frame with title bar and size controls. * They are not associated with any Chrome browser windows. * See the Window State Sample for a demonstration of these options. - * @since Availability: Since Chrome 24. */ - namespace app.window { + namespace app { interface ContentBounds { left?: number; top?: number; @@ -448,7 +507,7 @@ declare namespace chrome { * For none, the -webkit-app-region CSS property can be used to apply draggability to the app's window. * -webkit-app-region: drag can be used to mark regions draggable. no-drag can be used to disable this style on nested elements. */ - type?: 'chrome'; + type: 'chrome'; /** * Allows the frame color to be set. Frame coloring is only available if the frame type is chrome. * @since Frame coloring is new in Chrome 36. @@ -468,6 +527,13 @@ declare namespace chrome { inactiveColor?: string; } + enum State { + NORMAL = 'normal', + FULLSCREEN = 'fullscreen', + MAXIMIZED = 'maximized', + MINIMIZED = 'minimized' + } + interface CreateWindowOptions { /** * Id to identify the window. @@ -545,7 +611,7 @@ declare namespace chrome { /** * The initial state of the window, allowing it to be created already fullscreen, maximized, or minimized. Defaults to 'normal'. */ - state?: 'normal' | 'fullscreen' | 'maximized' | 'minimized'; + state?: State; /** * If true, the window will be created in a hidden state. Call show() on the window to show it once it has been created. Defaults to false. */ @@ -578,7 +644,6 @@ declare namespace chrome { */ visibleOnAllWorkspaces?: boolean; } - interface AppWindow { /** Focus the window. */ focus: () => void; @@ -627,7 +692,7 @@ declare namespace chrome { hide: () => void; /** * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. - * @description Get the window's inner bounds as a ContentBounds object. + * Get the window's inner bounds as a ContentBounds object. */ getBounds: () => ContentBounds; /** @@ -676,52 +741,81 @@ declare namespace chrome { onRestored: WindowEvent; } interface WindowEvent extends chrome.events.Event<() => void> { } - /** - * The size and position of a window can be specified in a number of different ways. The most simple option is not specifying anything at all, in which case a default size and platform dependent position will be used. - * To set the position, size and constraints of the window, use the innerBounds or outerBounds properties. Inner bounds do not include window decorations. Outer bounds include the window's title bar and frame. Note that the padding between the inner and outer bounds is determined by the OS. Therefore setting the same property for both inner and outer bounds is considered an error (for example, setting both innerBounds.left and outerBounds.left). - * To automatically remember the positions of windows you can give them ids. If a window has an id, This id is used to remember the size and position of the window whenever it is moved or resized. This size and position is then used instead of the specified bounds on subsequent opening of a window with the same id. If you need to open a window with an id at a location other than the remembered default, you can create it hidden, move it to the desired location, then show it. - * - * @param url - * @param [options] - * @param [callback] Called in the creating window (parent) before the load event is called in the created window (child). The parent can set fields or functions on the child usable from onload. E.g. background.js: function(createdWindow) { createdWindow.contentWindow.foo = function () { }; }; window.js: window.onload = function () { foo(); } If you specify the callback parameter, it should be a function that looks like this: function(AppWindow createdWindow) {...}; - */ - export function create(url: string, options?: CreateWindowOptions, callback?: (created_window: AppWindow) => void): void; - /** - * Returns an AppWindow object for the current script context (ie JavaScript 'window' object). This can also be called on a handle to a script context for another page, for example: otherWindow.chrome.app.window.current(). - */ - export function current(): AppWindow; - /** - * Gets an AppWindow with the given id. If no window with the given id exists null is returned. This method is new in Chrome 33. - */ - export function get(id: string): AppWindow; - /** - * Gets an array of all currently created app windows. This method is new in Chrome 33. - */ - export function getAll(): AppWindow[]; - /** - * Whether the current platform supports windows being visible on all workspaces. - */ - export function canSetVisibleOnAllWorkspaces(): boolean; - } + interface WindowParams extends AppWindow { + id: string; + frameId?: integer; + existingWindow?: boolean; + [key: string]: any; + } + + interface ChromeAppWindow extends AppWindow { + /** + * The size and position of a window can be specified in a number of different ways. The most simple option is not specifying anything at all, in which case a default size and platform dependent position will be used. + * To set the position, size and constraints of the window, use the innerBounds or outerBounds properties. Inner bounds do not include window decorations. Outer bounds include the window's title bar and frame. Note that the padding between the inner and outer bounds is determined by the OS. Therefore setting the same property for both inner and outer bounds is considered an error (for example, setting both innerBounds.left and outerBounds.left). + * To automatically remember the positions of windows you can give them ids. If a window has an id, This id is used to remember the size and position of the window whenever it is moved or resized. This size and position is then used instead of the specified bounds on subsequent opening of a window with the same id. If you need to open a window with an id at a location other than the remembered default, you can create it hidden, move it to the desired location, then show it. + * + * @param url + * @param [options] + * @param [callback] Called in the creating window (parent) before the load event is called in the created window (child). The parent can set fields or functions on the child usable from onload. E.g. background.js: function(createdWindow) { createdWindow.contentWindow.foo = function () { }; }; window.js: window.onload = function () { foo(); } If you specify the callback parameter, it should be a function that looks like this: function(AppWindow createdWindow) {...}; + */ + create(url: string, options?: CreateWindowOptions, callback?: (created_window: AppWindow) => void): void; + /** + * Returns an AppWindow object for the current script context (ie JavaScript 'window' object). This can also be called on a handle to a script context for another page, for example: otherWindow.chrome.app.window.current(). + */ + current(): AppWindow; + /** + * Gets an AppWindow with the given id. If no window with the given id exists null is returned. This method is new in Chrome 33. + */ + get(id: string): AppWindow; + /** + * Gets an array of all currently created app windows. This method is new in Chrome 33. + */ + getAll(): AppWindow[]; + /** + * Whether the current platform supports windows being visible on all workspaces. + */ + canSetVisibleOnAllWorkspaces(): boolean; + + + /** + * Undocumented + * @todo TODO Find info + * definition app.window.initializeAppWindow(state: object) + * @internal + */ + initializeAppWindow(state: WindowParams): void; + } + const window: ChromeAppWindow; + } //////////////////// // Audio //////////////////// /** - * The chrome.audio API is provided to allow users to get information about and control the audio devices attached to the system. - * This API is currently only implemented for ChromeOS. * @since Since Chrome 59. + * @requires Permissions: 'audio' + * @description + * The chrome.audio API is provided to allow users to get information + * about and control the audio devices attached to the system. + * This API is currently only implemented for ChromeOS. */ namespace audio { - export type StreamType = 'INPUT' | 'OUTPUT'; + type StreamType = 'INPUT' | 'OUTPUT'; + type DeviceType = + 'HEADPHONE' | 'MIC' | 'USB' | + 'BLUETOOTH' | 'HDMI' | 'INTERNAL_SPEAKER' | + 'INTERNAL_MIC' | 'FRONT_MIC' | 'REAR_MIC' | + 'KEYBOARD_MIC' | 'HOTWORD' | 'LINEOUT' | + 'POST_MIX_LOOPBACK' | 'POST_DSP_LOOPBACK' | 'OTHER'; + interface AudioDeviceInfo { /** The unique identifier of the audio device. */ id: string; /** Stream type associated with this device. */ streamType: StreamType; /** Type of the device. */ - deviceType: 'HEADPHONE' | 'MIC' | 'USB' | 'BLUETOOTH' | 'HDMI' | 'INTERNAL_SPEAKER' | 'INTERNAL_MIC' | 'FRONT_MIC' | 'REAR_MIC' | 'KEYBOARD_MIC' | 'HOTWORD' | 'LINEOUT' | 'POST_MIX_LOOPBACK' | 'POST_DSP_LOOPBACK' | 'OTHER'; + deviceType: DeviceType; /** The user-friendly name (e.g. 'USB Microphone'). */ displayName: string; /** Device name. */ @@ -750,35 +844,24 @@ declare namespace chrome { * The audio device's desired sound level. Defaults to the device's current sound level. * If used with audio input device, represents audio device gain. * If used with audio output device, represents audio device volume. - * - * Type: integer */ - level?: number; + level?: integer; } + /** @todo TODO INTEGRATE */ interface OnLevelChangedEvent { - /** - * The callback parameter should be a function that looks like this: - * function(object event) {...}; - * @param {(event: { - * deviceId: string, - * level: number - * }) => void} callback - */ addListener(callback: (event: { deviceId: string, level: number }) => void): void; } + /** @todo TODO INTEGRATE */ interface OnMuteChangedEvent { - /** - * The callback parameter should be a function that looks like this: - * function(object event) {...}; - */ addListener(callback: (event: { streamType: StreamType[], isMuted: boolean }) => void): void; } + /** @todo TODO INTEGRATE */ interface OnDeviceListChangedEvent { /** * The callback parameter should be a function that looks like this: @@ -801,42 +884,44 @@ declare namespace chrome { isActive?: boolean; } /** - * @description Gets a list of audio devices filtered based on |filter|. + * Gets a list of audio devices filtered based on |filter|. */ - export function getDevices(filter: Filter, callback: (devices: AudioDeviceInfo[]) => void): void; - export function getDevices(callback: (devices: AudioDeviceInfo[]) => void): void; + function getDevices(filter: Filter, callback: (devices: AudioDeviceInfo[]) => void): void; + function getDevices(callback: (devices: AudioDeviceInfo[]) => void): void; /** Sets lists of active input and/or output devices. */ - export function setDevices(ids: DeviceIdLists[] | string[], callback: () => void): void; + function setDevices(ids: DeviceIdLists[] | string[], callback: () => void): void; /** Sets the properties for the input or output device. */ - export function setProperties(id: string, properties: SetDeviceProperties, callback: () => void): void; + function setProperties(id: string, properties: SetDeviceProperties, callback: () => void): void; /** - * @description Gets the system-wide mute state for the specified stream type. + * Gets the system-wide mute state for the specified stream type. * @param {StreamType} streamType Stream type for which mute state should be fetched. - * @param {(value: boolean) => {}} callback Callback reporting whether mute is set or not for specified stream type. + * @param {(value: boolean)=> void} callback Callback reporting whether mute is set or not for specified stream type. */ - export function getMute(streamType: StreamType, callback: (value: boolean) => void): void; + function getMute(streamType: StreamType, callback: (value: boolean) => void): void; /** - * @description Sets mute state for a stream type. The mute state will apply to all audio devices with the specified audio stream type. + * Sets mute state for a stream type. The mute state will apply to all audio devices with the specified audio stream type. * @param {StreamType} streamType Stream type for which mute state should be set. * @param {boolean} isMuted New mute value. - * @param {() => {}} [callback] If you specify the callback parameter, it should be a function that looks like this: function() {...}; + * @param {()=> void} [callback] If you specify the callback parameter, it should be a function that looks like this: function() {...}; */ - export function setMute(streamType: StreamType, isMuted: boolean, callback?: () => void): void; + function setMute(streamType: StreamType, isMuted: boolean, callback?: () => void): void; /** Fired when sound level changes for an active audio device. */ - export var onLevelChanged: OnLevelChangedEvent; + const onLevelChanged: OnLevelChangedEvent; /** Fired when the mute state of the audio input or output changes. Note that mute state is system-wide and the new value applies to every audio device with specified stream type. */ - export var onMuteChanged: OnMuteChangedEvent; + const onMuteChanged: OnMuteChangedEvent; /** Fired when audio devices change, either new devices being added, or existing devices being removed. */ - export var onDeviceListChanged: OnDeviceListChangedEvent; + const onDeviceListChanged: OnDeviceListChangedEvent; } - //////////////////// - // Bluetooth - //////////////////// + /////////////// + // Bluetooth // + /////////////// /** - * Use the chrome.bluetooth API to connect to a Bluetooth device. All functions report failures via chrome.runtime.lastError. - * Manifest: 'bluetooth': {...} * @since Chrome 37 + * @requires Manifest: 'bluetooth': {...} + * @description + * Use the chrome.bluetooth API to connect to a Bluetooth device. + * All functions report failures via chrome.runtime.lastError. */ namespace bluetooth { interface AdapterState { @@ -851,6 +936,14 @@ declare namespace chrome { /** Indicates whether or not the adapter is currently discovering. */ discovering: boolean; } + type DeviceType = + 'computer' | 'phone' | 'modem' | + 'audio' | 'carAudio' | 'video' | + 'peripheral' | 'joystick' | 'gamepad' | + 'keyboard' | 'mouse' | 'tablet' | 'keyboardMouseCombo'; + + type DeviceVendorIdSource = 'bluetooth' | 'usb'; + interface Device { /** The address of the device, in the format 'XX:XX:XX:XX:XX:XX'. */ address: string; @@ -859,7 +952,7 @@ declare namespace chrome { /** The class of the device, a bit-field defined by http://www.bluetooth.org/en-us/specification/assigned-numbers/baseband. */ deviceClass?: number; /** The Device ID record of the device, where available. */ - vendorIdSource?: 'bluetooth' | 'usb'; + vendorIdSource?: DeviceVendorIdSource; vendorId?: number; productId?: number; deviceId?: number; @@ -868,7 +961,7 @@ declare namespace chrome { * This is obtained from the |deviceClass| field and only represents a small fraction of the possible device types. * When in doubt you should use the |deviceClass| field directly. */ - type?: 'computer' | 'phone' | 'modem' | 'audio' | 'carAudio' | 'video' | 'peripheral' | 'joystick' | 'gamepad' | 'keyboard' | 'mouse' | 'tablet' | 'keyboardMouseCombo'; + type?: DeviceType; /** Indicates whether or not the device is paired with the system. */ paired?: boolean; /** Indicates whether the device is currently connected to the system. */ @@ -906,47 +999,67 @@ declare namespace chrome { addListener(callback: (event: T) => void): void; } + type DeviceFilterType = 'all' | 'known'; + /** * Some criteria to filter the list of returned bluetooth devices. If the filter is not set or set to {}, returned device list will contain all bluetooth devices. Right now this is only supported in ChromeOS, for other platforms, a full list is returned. */ interface DeviceFilter { /** Type of filter to apply to the device list. Default is all. */ - filterType?: 'all' | 'known'; + filterType?: DeviceFilterType; /** Maximum number of bluetoth devices to return. Default is 0 (no limit) if unspecified. */ limit?: number; } /** Get information about the Bluetooth adapter. */ - export function getAdapterState(callback: (adapterInfo: AdapterState) => void): void; + function getAdapterState(callback: (adapterInfo: AdapterState) => void): void; + /** Get information about a Bluetooth device known to the system. */ - export function getDevice(deviceAddress: string, callback: (deviceInfo: Device) => void): void; + function getDevice(deviceAddress: string, callback: (deviceInfo: Device) => void): void; + + /** + * Get a list of Bluetooth devices known to the system, including paired and recently discovered devices. + * @param callback Called when the search is completed. + */ + function getDevices(callback: (devices: Device[]) => void): void; + /** * Get a list of Bluetooth devices known to the system, including paired and recently discovered devices. * @param filter Since Chrome 67. Some criteria to filter the list of returned bluetooth devices. If the filter is not set or set to {}, returned device list will contain all bluetooth devices. Right now this is only supported in ChromeOS, for other platforms, a full list is returned. * @param callback Called when the search is completed. */ - export function getDevices(filter: DeviceFilter, callback: (deviceInfo: Device) => void): void; + function getDevices(filter: DeviceFilter, callback: (devices: Device[]) => void): void; + /** * Start discovery. Newly discovered devices will be returned via the onDeviceAdded event. Previously discovered devices already known to the adapter must be obtained using getDevices and will only be updated using the |onDeviceChanged| event if information about them changes. * Discovery will fail to start if this application has already called startDiscovery. Discovery can be resource intensive: stopDiscovery should be called as soon as possible. */ - export function startDiscovery(callback: () => void): void; + function startDiscovery(callback: () => void): void; + /** Stop discovery. */ - export function stopDiscovery(callback: () => void): void; + function stopDiscovery(callback: () => void): void; + /** Fired when the state of the Bluetooth adapter changes. */ - export var onAdapterStateChanged: BluetoothEvent; + const onAdapterStateChanged: BluetoothEvent; + /** Fired when information about a new Bluetooth device is available. */ - export var onDeviceAdded: BluetoothEvent; + const onDeviceAdded: BluetoothEvent; + /** Fired when information about a known Bluetooth device has changed. */ - export var onDeviceChanged: BluetoothEvent; + const onDeviceChanged: BluetoothEvent; + /** Fired when a Bluetooth device that was previously discovered has been out of range for long enough to be considered unavailable again, and when a paired device is removed. */ - export var onDeviceRemoved: BluetoothEvent; + const onDeviceRemoved: BluetoothEvent; } + /** - * The chrome.bluetoothLowEnergy API is used to communicate with Bluetooth Smart (Low Energy) devices using the Generic Attribute Profile (GATT). - * Manifest: 'bluetooth': {...} * @since Chrome 37 - * Important: This API works only on Chrome OS. - * Note: With Chrome 56, users can select nearby Bluetooth Low Energy devices to provide to web sites that use the Web Bluetooth API. + * @requires Manifest: 'bluetooth': {...} + * @requires Important: This API works only on Chrome OS. + * @requires Note: With Chrome 56, users can select nearby Bluetooth Low Energy devices to provide to web sites that use the Web Bluetooth API. + * @description + * The chrome.bluetoothLowEnergy API is used to communicate + * with Bluetooth Smart (Low Energy) devices using the + * Generic Attribute Profile (GATT). */ namespace bluetoothLowEnergy { interface Service { @@ -966,22 +1079,21 @@ declare namespace chrome { */ deviceAddress?: string; } - enum CharacteristicProperties { - 'broadcast', - 'read', - 'writeWithoutResponse', - 'write', - 'notify', - 'indicate', - 'authenticatedSignedWrites', - 'extendedProperties', - 'reliableWrite', - 'writableAuxiliaries', - 'encryptRead', - 'encryptWrite', - 'encryptAuthenticatedRead', - 'encryptAuthenticatedWrite' - } + type CharacteristicProperties = + 'broadcast' | + 'read' | + 'writeWithoutResponse' | + 'write' | + 'notify' | + 'indicate' | + 'authenticatedSignedWrites' | + 'extendedProperties' | + 'reliableWrite' | + 'writableAuxiliaries' | + 'encryptRead' | + 'encryptWrite' | + 'encryptAuthenticatedRead' | + 'encryptAuthenticatedWrite'; interface Characteristic { /** The UUID of the characteristic, e.g. 00002a37-0000-1000-8000-00805f9b34fb. */ uuid: string; @@ -994,14 +1106,14 @@ declare namespace chrome { /** The currently cached characteristic value. This value gets updated when the value of the characteristic is read or updated via a notification or indication. */ value?: ArrayBuffer; } - enum DescriptorPermissions { - 'read', - 'write', - 'encryptedRead', - 'encryptedWrite', - 'encryptedAuthenticatedRead', - 'encryptedAuthenticatedWrite' - } + type DescriptorPermissions = + 'read' | + 'write' | + 'encryptedRead' | + 'encryptedWrite' | + 'encryptedAuthenticatedRead' | + 'encryptedAuthenticatedWrite'; + interface Descriptor { /** The UUID of the characteristic descriptor, e.g. 00002902-0000-1000-8000-00805f9b34fb. */ uuid: string; @@ -1049,9 +1161,7 @@ declare namespace chrome { /** Optional flag for sending an indication instead of a notification. */ shouldIndicate: boolean; } - enum AdvertisementType { - 'broadcast', 'peripheral' - } + type AdvertisementType = 'broadcast' | 'peripheral'; interface Advertisement { /** Type of advertisement. */ type: AdvertisementType; @@ -1098,7 +1208,7 @@ declare namespace chrome { */ function getService(serviceId: string, callback: (result: Service) => void): void; /** - * @description Create a locally hosted GATT service. This service can be registered to be available on a local GATT server. This function is only available if the app has both the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. The peripheral permission may not be available to all apps. + * Create a locally hosted GATT service. This service can be registered to be available on a local GATT server. This function is only available if the app has both the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. The peripheral permission may not be available to all apps. * @since Since Chrome 52. * @param service The service to create. * @param callback Called with the created services's unique ID. @@ -1118,7 +1228,7 @@ declare namespace chrome { */ function getCharacteristic(characteristicId: string, callback: (result: Characteristic) => void): void; /** - * @description Create a locally hosted GATT characteristic. This characteristic must be hosted under a valid service. If the service ID is not valid, the lastError will be set. This function is only available if the app has both the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. The peripheral permission may not be available to all apps. + * Create a locally hosted GATT characteristic. This characteristic must be hosted under a valid service. If the service ID is not valid, the lastError will be set. This function is only available if the app has both the bluetooth:low_energy and the bluetooth:peripheral permissions set to true. The peripheral permission may not be available to all apps. * @since Since Chrome 52. * @param characteristic The characteristic to create. * @param serviceId ID of the service to create this characteristic for. @@ -1226,7 +1336,7 @@ declare namespace chrome { * @param serviceId Unique ID of a created service. * @param callback Callback with the result of the register operation. */ - function registerService(serviceId: string, callback: () => void): void; + function registerService(serviceId: string, callback: (result: any) => void): void; /** * Unregister the given service with the local GATT server. * If the service ID is invalid, the lastError will be set. @@ -1237,7 +1347,7 @@ declare namespace chrome { * @param serviceId Unique ID of a current registered service. * @param callback Callback with the result of the register operation. */ - function unregisterService(serviceId: string, callback: () => void): void; + function unregisterService(serviceId: string, callback: (result: any) => void): void; /** * Remove the specified service, unregistering it if it was registered. * If the service ID is invalid, the lastError will be set. @@ -1286,7 +1396,7 @@ declare namespace chrome { /** * Set's the interval betweeen two consecutive advertisements. * Note: This is a best effort. - * The actual interval may vary non-trivially from the requested intervals. + * The actual interval may consty non-trivially from the requested intervals. * On some hardware, there is a minimum interval of 100ms. * The minimum and maximum values cannot exceed the the range allowed by the Bluetooth 4.2 specification. * @since Since Chrome 55. @@ -1302,16 +1412,16 @@ declare namespace chrome { */ function sendRequestResponse(response: IResponse): void; /** Fired whan a new GATT service has been discovered on a remote device. */ - var onServiceAdded: chrome.events.Event<(service: Service) => void>; + const onServiceAdded: chrome.events.Event<(service: Service) => void>; /** * Fired when the state of a remote GATT service changes. * This involves any characteristics and/or descriptors * that get added or removed from the service, as well as - * "ServiceChanged" notifications from the remote device. + * 'ServiceChanged' notifications from the remote device. */ - var onServiceChanged: chrome.events.Event<(service: Service) => void>; + const onServiceChanged: chrome.events.Event<(service: Service) => void>; /** Fired when a GATT service that was previously discovered on a remote device has been removed. */ - var onServiceRemoved: chrome.events.Event<(service: Service) => void>; + const onServiceRemoved: chrome.events.Event<(service: Service) => void>; /** * Fired when the value of a remote GATT characteristic changes, * either as a result of a read request, @@ -1319,14 +1429,14 @@ declare namespace chrome { * This event will only be sent if the app has enabled notifications * by calling startCharacteristicNotifications. */ - var onCharacteristicValueChanged: chrome.events.Event<(characteristic: Characteristic) => void>; + const onCharacteristicValueChanged: chrome.events.Event<(characteristic: Characteristic) => void>; /** * Fired when the value of a remote GATT characteristic descriptor changes, * usually as a result of a read request. * This event exists mostly for convenience and will always be sent after * a successful call to readDescriptorValue. */ - var onDescriptorValueChanged: chrome.events.Event<(descriptor: Descriptor) => void>; + const onDescriptorValueChanged: chrome.events.Event<(descriptor: Descriptor) => void>; /** * Fired when a connected central device requests to read the value of * a characteristic registered on the local GATT server. @@ -1336,7 +1446,7 @@ declare namespace chrome { * The peripheral permission may not be available to all apps. * @since Since Chrome 52. */ - var onCharacteristicReadRequest: chrome.events.Event<(characteristic: Characteristic) => void>; + const onCharacteristicReadRequest: chrome.events.Event<(characteristic: Characteristic) => void>; /** * Fired when a connected central device requests to write the value of * a characteristic registered on the local GATT server. @@ -1346,7 +1456,7 @@ declare namespace chrome { * The peripheral permission may not be available to all apps. * @since Since Chrome 52. */ - var onCharacteristicWriteRequest: chrome.events.Event<(characteristic: Characteristic) => void>; + const onCharacteristicWriteRequest: chrome.events.Event<(characteristic: Characteristic) => void>; /** * Fired when a connected central device requests to read the value of * a descriptor registered on the local GATT server. @@ -1356,7 +1466,7 @@ declare namespace chrome { * The peripheral permission may not be available to all apps. * @since Since Chrome 52. */ - var onDescriptorReadRequest: chrome.events.Event<(descriptor: Descriptor) => void>; + const onDescriptorReadRequest: chrome.events.Event<(descriptor: Descriptor) => void>; /** * Fired when a connected central device requests to write the value of * a descriptor registered on the local GATT server. @@ -1365,22 +1475,341 @@ declare namespace chrome { * and the bluetooth:peripheral permissions set to true. * The peripheral permission may not be available to all apps. */ - var onDescriptorWriteRequest: chrome.events.Event<(descriptor: Descriptor) => void>; - } - /** - * Use the chrome.bluetoothSocket API to send and receive data to Bluetooth devices using RFCOMM and L2CAP connections. - * @since Chrome 37 - * Manifest: 'bluetooth': {...} - * Important: This API works only on OS X, Windows and Chrome OS. - */ - namespace bluetoothSocket { - /* NOT IMPLEMENTED YET */ + const onDescriptorWriteRequest: chrome.events.Event<(descriptor: Descriptor) => void>; } - //////////////////// - // Browser - //////////////////// /** + * @since Chrome 37 + * @requires Manifest: 'bluetooth': {...} + * @requires Important: This API works only on OS X, Windows and Chrome OS. + * Use the chrome.bluetoothSocket API to send and receive data to Bluetooth devices using RFCOMM and L2CAP connections. + */ + namespace bluetoothSocket { + interface SocketProperties { + /** + * Flag indicating whether the socket is left open when + * the event page of the application is unloaded + * (see Manage App Lifecycle). The default value is false. + * When the application is loaded, any sockets previously + * opened with persistent=true can be fetched with $ref:getSockets. + */ + persistent?: boolean; + /** An application-defined string associated with the socket. */ + name?: string; + /** + * @default 4096 + * @description + * The size of the buffer used to receive data. + * */ + bufferSize?: integer; + } + interface ListenOptions { + /** + * The RFCOMM Channel used by listenUsingRfcomm. + * If specified, this channel must not be previously + * in use or the method call will fail. When not specified, + * an unused channel will be automatically allocated. + */ + channel?: integer; + /** + * The L2CAP PSM used by listenUsingL2cap. + * If specified, this PSM must not be previously + * in use or the method call with fail. When not specified, + * an unused PSM will be automatically allocated. + * */ + psm?: integer; + /** + * Length of the socket's listen queue. + * The default value depends on the operating system's host subsystem. + * */ + backlog?: number; + } + interface SocketInfo { + /** + * The socket identifier. + * */ + socketId: integer; + /** + * Flag indicating if the socket remains + * open when the event page of the application + * is unloaded (see SocketProperties.persistent). + * The default value is 'false'. + */ + persistent: boolean; + /** + * Application-defined string associated with the socket. + */ + name?: string; + /** + * The size of the buffer used to receive data. + * If no buffer size has been specified explictly, + * the value is not provided. + */ + bufferSize?: integer; + /** + * Flag indicating whether a connected socket + * blocks its peer from sending more data, or + * whether connection requests on a listening + * socket are dispatched through the onAccept + * event or queued up in the listen queue backlog. + * See setPaused. The default value is 'false'. + */ + paused: boolean; + /** + * Flag indicating whether the socket is connected to a remote peer. + */ + connected: boolean; + /** + * If the underlying socket is connected, + * contains the Bluetooth address of the device it is connected to. + */ + address?: string; + /** + * If the underlying socket is connected, + * contains information about the service + * UUID it is connected to, otherwise if + * the underlying socket is listening, + * contains information about the service + * UUID it is listening on. + */ + uuid?: string; + } + + interface CreateInfo { + /** + * The ID of the newly created socket. + * Note that socket IDs created from this + * API are not compatible with socket IDs + * created from other APIs, such as the + * sockets.tcp API. + */ + socketId: integer; + } + interface OnAcceptInfoData { + /** The server socket identifier. */ + socketId: integer; + /** + * The client socket identifier, i.e. the socket + * identifier of the newly established connection. + * This socket identifier should be used only with + * functions from the chrome.bluetoothSocket namespace. + * Note the client socket is initially paused and must + * be explictly un-paused by the application to start + * receiving data. + */ + clientSocketId: integer; + } + type OnAcceptErrorCode = + 'system_error' | + 'not_listening'; + interface OnAcceptErrorEventData { + /** The server socket identifier. */ + socketId: integer; + /** The error message */ + errorMessage: string; + /** + * An error code indicating what went wrong. + * + * system_error + * > A system error occurred and the connection may be unrecoverable. + * not_listening + * > The socket is not listening. + */ + error: OnAcceptErrorCode; + } + interface OnReceiveEventData { + /** The socket identifier. */ + socketId: integer; + /** The data received, with a maxium size of bufferSize. */ + data: ArrayBuffer; + } + type OnReceiveErrorCode = + 'disconnected' | + 'system_error' | + 'not_connected'; + interface OnReceiveErrorEventData { + /** The server socket identifier. */ + socketId: integer; + /** The error message */ + errorMessage: string; + /** + * An error code indicating what went wrong. + * + * disconnected + * > The connection was disconnected. + * system_error + * > A system error occurred and the connection may be unrecoverable. + * not_connected + * > The socket has not been connected. + */ + error: OnAcceptErrorCode; + } + interface OnAcceptEvent extends chrome.events.Event<(info: OnAcceptInfoData) => void> { } + interface OnAcceptErrorEvent extends chrome.events.Event<(info: OnAcceptErrorEventData) => void> { } + interface OnReceiveEvent extends chrome.events.Event<(info: OnReceiveEventData) => void> { } + interface OnReceiveErrorEvent extends chrome.events.Event<(info: OnReceiveErrorEventData) => void> { } + /** + * Creates a Bluetooth socket. + * @param callback Called when the socket has been created + * */ + function create(callback: (createInfo: CreateInfo) => void): void; + /** + * Creates a Bluetooth socket. + * @param properties The socket properties (optional) + * @param callback Called when the socket has been created + */ + function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + /** + * Updates the socket properties. + * @param socketId The socket identifier. + * @param properties The properties to update. + * @param [callback] Called when the properties are updated. + */ + function update(socketId: integer, properties: SocketProperties, callback?: () => void): void; + /** + * Enables or disables a connected socket from + * receiving messages from its peer, or a listening + * socket from accepting new connections. The default + * value is 'false'. Pausing a connected socket is + * typically used by an application to throttle data + * sent by its peer. When a connected socket is paused, + * no onReceiveevent is raised. When a socket is connected + * and un-paused, onReceive events are raised again when + * messages are received. When a listening socket is paused, + * new connections are accepted until its backlog is full + * then additional connection requests are refused. + * onAccept events are raised only when the socket is un-paused. + * + * @param socketId The socket identifier. + * @param paused Flag indicating whether a connected socket + * blocks its peer from sending more data, or + * whether connection requests on a listening + * socket are dispatched through the onAccept + * event or queued up in the listen queue backlog. + * See setPaused. The default value is 'false'. + * @param [callback] Callback from the setPaused method. + */ + function setPaused(socketId: integer, paused: boolean, callback?: () => void): void; + /** + * Listen for connections using the RFCOMM protocol. + * + * @param socketId The socket identifier. + * @param uuid Service UUID to listen on. + * @param callback Called when listen operation completes. + */ + function listenUsingRfcomm(socketId: integer, uuid: string, callback: () => void): void; + /** + * Listen for connections using the RFCOMM protocol. + * + * @param socketId The socket identifier. + * @param uuid Service UUID to listen on. + * @param options Optional additional options for the service. + * @param callback Called when listen operation completes. + */ + function listenUsingRfcomm(socketId: integer, uuid: string, options: ListenOptions, callback: () => void): void; + /** + * Listen for connections using the L2CAP protocol. + * + * @param socketId The socket identifier. + * @param uuid Service UUID to listen on. + * @param callback Called when listen operation completes. + */ + function listenUsingL2cap(socketId: integer, uuid: string, callback: () => void): void; + /** + * Listen for connections using the L2CAP protocol. + * + * @param socketId The socket identifier. + * @param uuid Service UUID to listen on. + * @param options Optional additional options for the service. + * @param callback Called when listen operation completes. + */ + function listenUsingL2cap(socketId: integer, uuid: string, options: ListenOptions, callback: () => void): void; + /** + * Connects the socket to a remote Bluetooth device. + * When the connect operation completes successfully, + * onReceive events are raised when data is received + * from the peer. If a network error occur while the + * runtime is receiving packets, a onReceiveError + * event is raised, at which point no more onReceive + * event will be raised for this socket until the + * setPaused(false) method is called. + * + * @param socketId The socket identifier. + * @param address The address of the Bluetooth device. + * @param uuid The UUID of the service to connect to. + * @param callback Called when the connect attempt is complete. + */ + function connect(socketId: integer, address: string, uuid: string, callback: () => void): void; + /** + * Disconnects the socket. The socket identifier remains valid. + * @param socketId The socket identifier. + * @param [callback] Called when the disconnect attempt is complete. + */ + function disconnect(socketId: integer, callback?: () => void): void; + /** + * Disconnects and destroys the socket. + * Each socket created should be closed after use. + * The socket id is no longer valid as soon at the + * function is called. However, the socket is guaranteed + * to be closed only when the callback is invoked. + * + * @param socketId The socket identifier. + * @param callback Called when the `close` operation completes + */ + function close(socketId: integer, callback: () => void): void; + /** + * Sends data on the given Bluetooth socket. + * @param socketId The socket identifier. + * @param data The data to send. + * @param [callback] Called with the number of bytes sent. + */ + function send(socketId: integer, data: ArrayBuffer, callback?: (bytesSent: number) => void): void; + /** + * Retrieves the state of the given socket. + * @param socketId The socket identifier. + * @param callback Called when the socket state is available. + * Callback returning object containing the socket information. + */ + function getInfo(socketId: integer, callback: (socketInfo: SocketInfo) => void): void; + /** + * Retrieves the list of currently opened sockets owned by the application. + * @param callback Called when the list of sockets is available. + * Returns an array of socket info. + */ + function getSockets(callback: (sockets: SocketInfo[]) => void): void; + /** + * Event raised when a connection has been established + * for a given socket. + */ + const onAccept: OnAcceptEvent; + /** + * Event raised when a network error occurred while the + * runtime was waiting for new connections on the given + * socket. Once this event is raised, the socket is set + * to paused and no more onAccept events are raised for + * this socket. + */ + const onAcceptError: OnAcceptErrorEvent; + /** + * Event raised when data has been received for a given socket. + */ + const onReceive: OnReceiveEvent; + /** + * Event raised when a network error occured while the runtime + * was waiting for data on the socket. Once this event is raised, + * the socket is set to paused and no more onReceive events are + * raised for this socket. + */ + const onReceiveError: OnReceiveErrorEvent; + } + + ///////////// + // Browser // + ///////////// + /** + * @since Availability: Since Chrome 42. + * @requires Permissions: 'browser' + * @description * Use the chrome.browser API to interact with the Chrome browser associated with * the current application and Chrome profile. */ @@ -1398,7 +1827,7 @@ declare namespace chrome { * @param callback Called when the tab was successfully * created, or failed to be created. If failed, runtime.lastError will be set. */ - export function openTab(options: Options, callback: () => void): void; + function openTab(options: Options, callback: () => void): void; /** * Opens a new tab in a browser window associated with the current application @@ -1406,24 +1835,77 @@ declare namespace chrome { * a new one is opened prior to creating the new tab. Since Chrome 42 only. * @param options Configures how the tab should be opened. */ - export function openTab(options: Options): void; + function openTab(options: Options): void; } - //////////////////// - // Commands - //////////////////// + /////////////// + // Clipboard // + /////////////// /** - * Use the commands API to add keyboard shortcuts that trigger actions in your extension, for example, an action to open the browser action or send a command to the extension. - * Availability: Since Chrome 25. - * Manifest: 'commands': {...} + * @requires(dev) **Dev** channel only. + * @requires Permissions: "clipboard" + * @description + * *This API is* **experimental**. *It is* **only** *available to Chrome users on the* **dev** *channel.* + * The chrome.clipboard API is provided to allow users to access data of the clipboard. + * This is a temporary solution for chromeos platform apps until open-web alternative is available. + * It will be deprecated once open-web solution is available. + * @see[Docs]{@link https://developer.chrome.com/apps/clipboard} + */ + namespace clipboard { + interface AdditionalItems { + /** Type of the additional data item. */ + type: 'textPlain' | 'textHtml'; + /** + * Content of the additional data item. + * Either the plain text string if *type* is "textPlain" or + * markup string if *type* is "textHtml". + * The data can not exceed 2MB. + */ + data: string; + } + /** + * **Dev channel only.** + * Sets image data to clipboard + * @param imageData The encoded image data. *Since Chrome 69. Warning: this is the current Beta channel.* + * @param type The type of image being passed. *Since Chrome 69. Warning: this is the current Beta channel.* + * @param [additionalItems] Additional data items for describing image data. + * The callback is called with chrome.runtime.lastError set to error code if there is an error. + * Requires clipboard and clipboardWrite permissions. + * *Since Chrome 69. Warning: this is the current Beta channel.* + * @param [callback] + */ + function setImageData(imageData: ArrayBuffer, type: 'png' | 'jpeg', additionalItems?: AdditionalItems, callback?: () => void): void; + + /** + * **Dev channel only.** + * Fired when clipboard data changes. + * Requires clipboard and clipboardRead permissions for adding listener to + * chrome.clipboard.onClipboardDataChanged event. After this event fires, the + * clipboard data is available by calling document.execCommand('paste'). + */ + const onClipboardDataChanged: chrome.events.Event<() => void>; + } + + ////////////// + // Commands // + ////////////// + /** + * @since Availability: Since Chrome 35. + * @requires Manifest: 'commands': {...} + * @description + * Use the commands API to add keyboard shortcuts that + * trigger actions in your app, for example, an + * action to open the browser action or send a command + * to the app. + * @see[Usage]{@link https://developer.chrome.com/apps/commands} */ namespace commands { interface Command { - /** Optional. The name of the Extension Command */ + /** The name of the Extension Command */ name?: string; - /** Optional. The Extension Command description */ + /** The Extension Command description */ description?: string; - /** Optional. The shortcut active for this command, or blank if not active. */ + /** The shortcut active for this command, or blank if not active. */ shortcut?: string; } @@ -1432,239 +1914,338 @@ declare namespace chrome { /** * Returns all the registered extension commands for this extension and their shortcut (if active). * @param callback Called to return the registered commands. - * If you specify the callback parameter, it should be a function that looks like this: - * function(array of Command commands) {...}; */ - export function getAll(callback: (commands: Command[]) => void): void; + function getAll(callback: (commands: Command[]) => void): void; /** Fired when a registered command is activated using a keyboard shortcut. */ - export var onCommand: CommandEvent; + const onCommand: CommandEvent; } - //////////////////// - // Context Menus - //////////////////// + /////////////////// + // Context Menus // + /////////////////// /** - * Use the chrome.contextMenus API to add items to Google Chrome's context menu. You can choose what types of objects your context menu additions apply to, such as images, hyperlinks, and pages. - * Availability: Since Chrome 6. - * Permissions: 'contextMenus' + * @since Availability: Since Chrome 24. + * @requires Permissions: 'contextMenus' + * @description + * Use the chrome.contextMenus API to add items to Google Chrome's context menu. + * You can choose what types of objects your context menu additions apply to, + * such as images, hyperlinks, and pages. + * + * Context menu items can appear in any document (or frame within a document), + * even those with file:// or chrome:// URLs. To control which documents your + * items can appear in, specify the documentUrlPatterns field when you call the + * create() or update() method. + * + * You can create as many context menu items as you need, + * but if more than one from your app is visible at once, + * Google Chrome automatically collapses them into a single parent menu. */ namespace contextMenus { + /** + * @since Chrome 38. + * @default 6 + * @description + * The maximum number of top level extension items that + * can be added to an extension action context menu. + * Any items beyond this limit will be ignored. + */ + const ACTION_MENU_TOP_LEVEL_LIMIT: number; /** * The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of all other contexts except for 'launcher'. The 'launcher' context is only supported by apps and is used to add menu items to the context menu that appears when clicking on the app icon in the launcher/taskbar/dock/etc. Different platforms might put limitations on what is actually supported in a launcher context menu. **/ - export type ContextType = 'all' | 'page' | 'frame' | 'selection' | 'link' | 'editable' | 'image' | 'video' | 'audio' | 'launcher' | 'browser_action' | 'page_action'; + type ContextType = + 'all' | + 'page' | + 'frame' | + 'selection' | + 'link' | + 'editable' | + 'image' | + 'video' | + 'audio' | + 'launcher' | + 'browser_action' | + 'page_action'; /** * The type of menu item. **/ - export type ItemType = 'normal' | 'checkbox' | 'radio' | 'separator'; + type ItemType = + 'normal' | + 'checkbox' | + 'radio' | + 'separator'; + type MediaType = + 'image' | + 'video' | + 'audio'; interface OnClickData { /** - * Optional. - * @since Since Chrome 35. - * The text for the context selection, if any. - */ - selectionText?: string; - /** - * Optional. - * @since Since Chrome 35. - * A flag indicating the state of a checkbox or radio item after it is clicked. - */ - checked?: boolean; - /** - * @since Since Chrome 35. * The ID of the menu item that was clicked. - */ - menuItemId: any; - /** - * Optional. * @since Since Chrome 35. - * The URL of the frame of the element where the context menu was clicked, if it was in a frame. */ - frameUrl?: string; + menuItemId: integer | string; + /** + * The parent ID, if any, for the item clicked. * @since Since Chrome 35. - * A flag indicating whether the element is editable (text input, textarea, etc.). */ - editable: boolean; + parentMenuItemId?: integer | string; + /** - * Optional. + * One of 'image', 'video', or 'audio' if the context menu was + * activated on one of these types of elements. * @since Since Chrome 35. - * One of 'image', 'video', or 'audio' if the context menu was activated on one of these types of elements. */ - mediaType?: string; + mediaType?: MediaType; + /** - * Optional. - * @since Since Chrome 35. - * A flag indicating the state of a checkbox or radio item before it was clicked. - */ - wasChecked?: boolean; - /** - * @since Since Chrome 35. - * The URL of the page where the menu item was clicked. This property is not set if the click occured in a context where there is no current page, such as in a launcher context menu. - */ - pageUrl: string; - /** - * Optional. - * @since Since Chrome 35. * If the element is a link, the URL it points to. + * @since Since Chrome 35. */ linkUrl?: string; + /** - * Optional. - * @since Since Chrome 35. - * The parent ID, if any, for the item clicked. - */ - parentMenuItemId?: any; - /** - * Optional. - * @since Since Chrome 35. * Will be present for elements with a 'src' URL. + * @since Since Chrome 35. */ srcUrl?: string; + + /** + * The URL of the page where the menu item was clicked. + * This property is not set if the click occured in a + * context where there is no current page, such as in + * a launcher context menu. + * @since Since Chrome 35. + */ + pageUrl: string; + + /** + * The URL of the frame of the element where the context menu was clicked, + * if it was in a frame. + * @since Since Chrome 35. + */ + frameUrl?: string; + + /** + * The ID of the frame of the element where the context menu was clicked, + * if it was in a frame. + * @since Since Chrome 35. + */ + frameId?: integer; + + /** + * The text for the context selection, if any. + * @since Since Chrome 35. + */ + selectionText?: string; + + /** + * A flag indicating whether the element is editable (text input, textarea, etc.). + * @since Since Chrome 35. + */ + editable: boolean; + + /** + * A flag indicating the state of a checkbox or radio item before it was clicked. + * @since Since Chrome 35. + */ + wasChecked?: boolean; + + /** + * A flag indicating the state of a checkbox or radio item after it is clicked. + * @since Since Chrome 35. + */ + checked?: boolean; } interface CreateProperties { - /** Optional. Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. (This applies to frames as well.) For details on the format of a pattern, see Match Patterns. */ - documentUrlPatterns?: string[]; - /** Optional. The initial state of a checkbox or radio item: true for selected and false for unselected. Only one radio item can be selected at a time in a given group of radio items. */ - checked?: boolean; - /** Optional. The text to be displayed in the item; this is required unless type is 'separator'. When the context is 'selection', you can use %s within the string to show the selected text. For example, if this parameter's value is 'Translate '%s' to Pig Latin' and the user selects the word 'cool', the context menu item for the selection is 'Translate 'cool' to Pig Latin'. */ - title?: string; - /** Optional. List of contexts this menu item will appear in. Defaults to ['page'] if not specified. */ - contexts?: string[]; + /** The type of menu item. Defaults to 'normal' if not specified. */ + type?: ItemType; + /** - * Optional. - * Whether this context menu item is enabled or disabled. Defaults to true. - * @since Since Chrome 20. + * The unique ID to assign to this item. + * Mandatory for event pages. + * Cannot be the same as another ID for this extension. */ - enabled?: boolean; - /** Optional. Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags. */ - targetUrlPatterns?: string[]; + id?: string; + + /** + * The text to be displayed in the item; + * this is required unless type is 'separator'. + * When the context is 'selection', you can use + * %s within the string to show the selected text. + * For example, if this parameter's value is + * 'Translate '%s' to Pig Latin' and the user + * selects the word 'cool', the context menu + * item for the selection is 'Translate 'cool' + * to Pig Latin'. + **/ + title?: string; + + /** + * The initial state of a checkbox or radio item: + * true for selected and false for unselected. + * Only one radio item can be selected at a time + * in a given group of radio items. + **/ + checked?: boolean; + + /** + * List of contexts this menu item will appear in. + * Defaults to ['page'] if not specified. + **/ + contexts?: ContextType[]; + + /** + * Whether the item is visible in the menu. + * @since Since Chrome 62. + */ + visible?: boolean; + /** - * Optional. * A function that will be called back when the menu item is clicked. Event pages cannot use this; instead, they should register a listener for chrome.contextMenus.onClicked. * @param info Information sent when a context menu item is clicked. */ onclick?: (info: OnClickData) => void; - /** Optional. The ID of a parent menu item; this makes the item a child of a previously added item. */ - parentId?: any; - /** Optional. The type of menu item. Defaults to 'normal' if not specified. */ - type?: string; + + /** The ID of a parent menu item; this makes the item a child of a previously added item. */ + parentId?: integer | string; + /** - * Optional. - * @since Since Chrome 21. - * @description The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension. - */ - id?: string; + * Lets you restrict the item to apply only to documents whose URL + * matches one of the given patterns. (This applies to frames as well.) + * For details on the format of a pattern, see Match Patterns. + **/ + documentUrlPatterns?: string[]; + /** - * @description Whether the item is visible in the menu. - * @since Since Chrome 62 + * Similar to documentUrlPatterns, + * but lets you filter based on the src attribute + * of img/audio/video tags and the href of anchor tags. + **/ + targetUrlPatterns?: string[]; + + /** + * Whether this context menu item is enabled or disabled. + * @default true */ - visible?: boolean; + enabled?: boolean; } interface UpdateProperties { - documentUrlPatterns?: string[]; - checked?: boolean; + type?: ItemType; title?: string; - contexts?: string[]; + checked?: boolean; + contexts?: ContextType[]; /** - * @since Chrome 20 - **/ - enabled?: boolean; - targetUrlPatterns?: string[]; - onclick?: (info: OnClickData) => void; - /** Optional. Note: You cannot change an item to be a child of one of its own descendants. */ - parentId?: any; - type?: string; - /** - * @description Whether the item is visible or not. - * @since Since Chrome 62 + * Whether the item is visible in the menu. + * @since Chrome 62. */ visible?: boolean; + /** + * Information sent when a context menu item is clicked. + * @since Chrome 44 + */ + onclick?: (info: OnClickData) => void; + /** Note: You cannot change an item to be a child of one of its own descendants. */ + parentId?: integer | string; + documentUrlPatterns?: string[]; + targetUrlPatterns?: string[]; + enabled?: boolean; } interface MenuClickedEvent extends chrome.events.Event<(info: OnClickData) => void> { } /** - * Since Chrome 38. - * The maximum number of top level extension items that can be added to an extension action context menu. Any items beyond this limit will be ignored. + * Creates a new context menu item. Note that if an error occurs during creation, you may not find out until the creation callback fires (the details will be in chrome.runtime.lastError). + * @param callback Called when the item has been created in the browser. If there were any problems creating the item, details will be available in chrome.runtime.lastError. */ - export var ACTION_MENU_TOP_LEVEL_LIMIT: number; + function create(createProperties: CreateProperties, callback?: () => void): void; + + /** + * Updates a previously created context menu item. + * @param id The ID of the item to update. + * @param updateProperties The properties to update. Accepts the same values as the create function. + * @param callback Called when the context menu has been updated. + */ + function update(id: integer | string, updateProperties: UpdateProperties, callback?: () => void): void; + + /** + * Removes a context menu item. + * @param menuItemId The ID of the context menu item to remove. + * @param callback Called when the context menu has been removed. + */ + function remove(menuItemId: integer | string, callback?: () => void): void; /** * Removes all context menu items added by this extension. * @param callback Called when removal is complete. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; */ - export function removeAll(callback?: () => void): void; - /** - * Creates a new context menu item. Note that if an error occurs during creation, you may not find out until the creation callback fires (the details will be in chrome.runtime.lastError). - * @param callback Called when the item has been created in the browser. If there were any problems creating the item, details will be available in chrome.runtime.lastError. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function create(createProperties: CreateProperties, callback?: () => void): void; - /** - * Updates a previously created context menu item. - * @param id The ID of the item to update. - * @param updateProperties The properties to update. Accepts the same values as the create function. - * @param callback Called when the context menu has been updated. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function update(id: string, updateProperties: UpdateProperties, callback?: () => void): void; - /** - * Updates a previously created context menu item. - * @param id The ID of the item to update. - * @param updateProperties The properties to update. Accepts the same values as the create function. - * @param callback Called when the context menu has been updated. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function update(id: number, updateProperties: UpdateProperties, callback?: () => void): void; - /** - * Removes a context menu item. - * @param menuItemId The ID of the context menu item to remove. - * @param callback Called when the context menu has been removed. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function remove(menuItemId: string, callback?: () => void): void; - /** - * Removes a context menu item. - * @param menuItemId The ID of the context menu item to remove. - * @param callback Called when the context menu has been removed. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; - */ - export function remove(menuItemId: number, callback?: () => void): void; + function removeAll(callback?: () => void): void; - /** - * Since Chrome 21. - * Fired when a context menu item is clicked. - */ - export var onClicked: MenuClickedEvent; + /** Fired when a context menu item is clicked. */ + const onClicked: MenuClickedEvent; } //////////////////// - // Document Scan + // DesktopCapture // //////////////////// /** - * Use the chrome.documentScan API to discover and retrieve images from attached paper document scanners. - * Availability: Since Chrome 44. - * Permissions: 'documentScan' - * Important: This API works only on Chrome OS. + * Desktop Capture API that can be used to capture content of screen, + * individual windows or tabs. + * @since Availability: Since Chrome 34. + * @requires Permissions: "desktopCapture" + */ + namespace desktopCapture { + const DesktopCaptureSourceType: { + SCREEN: "screen", + WINDOW: "window", + TAB: "tab", + AUDIO: "audio" + } + + /** + * Shows desktop media picker UI with the specified set of sources. + * @param sources Set of sources that should be shown to the user. + * @param callback The callback parameter should be a function that looks like this: + * function(string streamId) {...}; + * Parameter streamId: An opaque string that can be passed to getUserMedia() API to generate media stream that corresponds to the source selected by the user. If user didn't select any source (i.e. canceled the prompt) then the callback is called with an empty streamId. The created streamId can be used only once and expires after a few seconds when it is not used. + */ + function chooseDesktopMedia + (sources: Array, callback: (streamId: string) => void): number; + /** + * Hides desktop media picker dialog shown by chooseDesktopMedia(). + * @param desktopMediaRequestId Id returned by chooseDesktopMedia() + */ + function cancelChooseDesktopMedia(desktopMediaRequestId: number): void; + } + + /////////////////// + // Document Scan // + /////////////////// + /** + * Use the chrome.documentScan API to discover and retrieve + * images from attached paper document scanners. + * + * The Document Scan API is designed to allow apps to view + * the content of paper documents on an attached document scanner. + * + * *Note: This API depends on OS features that may not be available* + * *depending on the underlying operating system. As of this writing only* + * *Chrome OS for certain USB-attached devices is known to successfully work.* + * + * @since Availability: Since Chrome 44. + * @requires Permissions: 'documentScan' + * @requires Important: This API works only on Chrome OS. */ namespace documentScan { interface DocumentScanOptions { - /** Optional. The MIME types that are accepted by the caller. */ + /** The MIME types that are accepted by the caller. */ mimeTypes?: string[]; - /** Optional. The number of scanned images allowed (defaults to 1). */ + /** The number of scanned images allowed (defaults to 1). */ maxImages?: number; } @@ -1679,72 +2260,101 @@ declare namespace chrome { * Performs a document scan. On success, the PNG data will be sent to the callback. * @param options Object containing scan parameters. * @param callback Called with the result and data from the scan. - * The callback parameter should be a function that looks like this: - * function(object result) {...}; */ - export function scan(options: DocumentScanOptions, callback: (result: DocumentScanCallbackArg) => void): void; + function scan(options: DocumentScanOptions, callback: (result: DocumentScanCallbackArg) => void): void; } - //////////////////// - // Events - //////////////////// + //////////// + // Events // + //////////// /** - * The chrome.events namespace contains common types used by APIs dispatching events to notify you when something interesting happens. - * Availability: Since Chrome 21. + * The chrome.events namespace contains common types used by APIs + * dispatching events to notify you when something interesting happens. + * + * An Event is an object that allows you to be notified when something interesting happens. + * Here's an example of using the chrome.alarms.onAlarm event to be notified whenever an alarm has elapsed: + * @example + * chrome.alarms.onAlarm.addListener(function(alarm) { + * appendToLog('alarms.onAlarm --' + * + ' name: ' + alarm.name + * + ' scheduledTime: ' + alarm.scheduledTime); + * }); + * @description + * As the example shows, you register for notification using addListener(). + * The argument to addListener() is always a function that you define to + * handle the event, but the parameters to the function depend on which + * event you're handling. Checking the documentation for alarms.onAlarm, + * you can see that the function has a single parameter: an alarms.Alarm + * object that has details about the elapsed alarm. + * @since Availability: Since Chrome 25. */ namespace events { - /** Filters URLs for various criteria. See event filtering. All criteria are case sensitive. */ + /** Filters URLs for constious criteria. See event filtering. All criteria are case sensitive. */ interface UrlFilter { - /** Optional. Matches if the scheme of the URL is equal to any of the schemes specified in the array. */ - schemes?: string[]; /** - * Optional. - * Since Chrome 23. - * Matches if the URL (without fragment identifier) matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax. + * Matches if the host name of the URL contains a specified string. + * To test whether a host name component has a prefix 'foo', + * use hostContains: '.foo'. This matches 'www.foobar.com' and + * 'foo.com', because an implicit dot is added at the beginning of + * the host name. Similarly, hostContains can be used to match + * against component suffix ('foo.') and to exactly match against + * components ('.foo.'). Suffix- and exact-matching for the last + * components need to be done separately using hostSuffix, because + * no implicit dot is added at the end of the host name. + **/ + hostContains?: string; + /** Matches if the host name of the URL is equal to a specified string. */ + hostEquals?: string; + /** Matches if the host name of the URL starts with a specified string. */ + hostPrefix?: string; + /** Matches if the host name of the URL ends with a specified string. */ + hostSuffix?: string; + /** Matches if the path segment of the URL contains a specified string. */ + pathContains?: string; + /** Matches if the path segment of the URL starts with a specified string. */ + pathEquals?: string; + /** Matches if the path segment of the URL ends with a specified string. */ + pathPrefix?: string; + /** Matches if the path segment of the URL is equal to a specified string. */ + pathSuffix?: string; + /** Matches if the query segment of the URL contains a specified string. */ + queryContains?: string; + /** Matches if the query segment of the URL is equal to a specified string. */ + queryEquals?: string; + /** Matches if the query segment of the URL starts with a specified string. */ + queryPrefix?: string; + /** Matches if the query segment of the URL ends with a specified string. */ + querySuffix?: string; + /** Matches if the URL (without fragment identifier) contains a specified string. Port numbers are stripped from the URL if they match the default port number. */ + urlContains?: string; + /** Matches if the URL (without fragment identifier) is equal to a specified string. Port numbers are stripped from the URL if they match the default port number. */ + urlEquals?: string; + /** Matches if the URL (without fragment identifier) matches a specified regular expression. + * Port numbers are stripped from the URL if they match the default port number. + * The regular expressions use the RE2 syntax. + * @see[RE2 syntax docs]{@link https://github.com/google/re2/blob/master/doc/syntax.txt} */ urlMatches?: string; - /** Optional. Matches if the path segment of the URL contains a specified string. */ - pathContains?: string; - /** Optional. Matches if the host name of the URL ends with a specified string. */ - hostSuffix?: string; - /** Optional. Matches if the host name of the URL starts with a specified string. */ - hostPrefix?: string; - /** Optional. Matches if the host name of the URL contains a specified string. To test whether a host name component has a prefix 'foo', use hostContains: '.foo'. This matches 'www.foobar.com' and 'foo.com', because an implicit dot is added at the beginning of the host name. Similarly, hostContains can be used to match against component suffix ('foo.') and to exactly match against components ('.foo.'). Suffix- and exact-matching for the last components need to be done separately using hostSuffix, because no implicit dot is added at the end of the host name. */ - hostContains?: string; - /** Optional. Matches if the URL (without fragment identifier) contains a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlContains?: string; - /** Optional. Matches if the query segment of the URL ends with a specified string. */ - querySuffix?: string; - /** Optional. Matches if the URL (without fragment identifier) starts with a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlPrefix?: string; - /** Optional. Matches if the host name of the URL is equal to a specified string. */ - hostEquals?: string; - /** Optional. Matches if the URL (without fragment identifier) is equal to a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlEquals?: string; - /** Optional. Matches if the query segment of the URL contains a specified string. */ - queryContains?: string; - /** Optional. Matches if the path segment of the URL starts with a specified string. */ - pathPrefix?: string; - /** Optional. Matches if the path segment of the URL is equal to a specified string. */ - pathEquals?: string; - /** Optional. Matches if the path segment of the URL ends with a specified string. */ - pathSuffix?: string; - /** Optional. Matches if the query segment of the URL is equal to a specified string. */ - queryEquals?: string; - /** Optional. Matches if the query segment of the URL starts with a specified string. */ - queryPrefix?: string; - /** Optional. Matches if the URL (without fragment identifier) ends with a specified string. Port numbers are stripped from the URL if they match the default port number. */ - urlSuffix?: string; - /** Optional. Matches if the port of the URL is contained in any of the specified port lists. For example [80, 443, [1000, 1200]] matches all requests on port 80, 443 and in the range 1000-1200. */ - ports?: any[]; /** - * Optional. - * Since Chrome 28. - * Matches if the URL without query segment and fragment identifier matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use the RE2 syntax. + * Matches if the URL without query segment and fragment identifier matches a specified regular expression. + * Port numbers are stripped from the URL if they match the default port number. + * The regular expressions use the RE2 syntax. + * @see[RE2 syntax docs]{@link https://github.com/google/re2/blob/master/doc/syntax.txt} + * @since Since Chrome 28. */ originAndPathMatches?: string; + /** Matches if the URL (without fragment identifier) starts with a specified string. Port numbers are stripped from the URL if they match the default port number. */ + urlPrefix?: string; + /** Matches if the URL (without fragment identifier) ends with a specified string. Port numbers are stripped from the URL if they match the default port number. */ + urlSuffix?: string; + /** Matches if the scheme of the URL is equal to any of the schemes specified in the array. */ + schemes?: string[]; + /** + * Matches if the port of the URL is contained in any of the specified port lists. + * For example [80, 443, [1000, 1200]] matches all requests on port 80, 443 and in the range 1000-1200. + */ + ports?: Array; } - /** An object which allows the addition and removal of listeners for a Chrome event. */ interface Event { /** @@ -1772,9 +2382,11 @@ declare namespace chrome { */ getRules(ruleIdentifiers: string[], callback: (rules: Rule[]) => void): void; /** - * @param callback Listener whose registration status shall be tested. + * Has this event this provided listener? + * @param listener Listener whose registration status shall be tested. + * @return If it has the provided listener */ - hasListener(callback: T): boolean; + hasListener(callback: T | Function): boolean; /** * Unregisters currently registered rules. * @param ruleIdentifiers If an array is passed, only rules with identifiers contained in this array are unregistered. @@ -1786,151 +2398,183 @@ declare namespace chrome { /** * Unregisters currently registered rules. * @param callback Called when rules were unregistered. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; */ removeRules(callback?: () => void): void; /** * Registers rules to handle events. * @param rules Rules to be registered. These do not replace previously registered rules. * @param callback Called with registered rules. - * If you specify the callback parameter, it should be a function that looks like this: - * function(array of Rule rules) {...}; * Parameter rules: Rules that were registered, the optional parameters are filled with values. */ addRules(rules: Rule[], callback?: (rules: Rule[]) => void): void; /** * Deregisters an event listener callback from an event. * @param callback Listener that shall be unregistered. - * The callback parameter should be a function that looks like this: - * function() {...}; */ removeListener(callback: T): void; + /** + * Has this event listeners? + */ hasListeners(): boolean; } /** Description of a declarative rule for handling events. */ interface Rule { - /** Optional. Optional priority of this rule. Defaults to 100. */ - priority?: number; - /** List of conditions that can trigger the actions. */ - conditions: any[]; - /** Optional. Optional identifier that allows referencing this rule. */ + /** Identifier that allows referencing this rule. */ id?: string; - /** List of actions that are triggered if one of the condtions is fulfilled. */ - actions: any[]; + /** - * Optional. - * Since Chrome 28. * Tags can be used to annotate rules and perform operations on sets of rules. + * @since Since Chrome 28. */ tags?: string[]; + + /** List of conditions that can trigger the actions. */ + conditions: any[]; + + /** List of actions that are triggered if one of the condtions is fulfilled. */ + actions: any[]; + + /** + * Optional priority of this rule. + * @default 100 + */ + priority?: integer; } } - //////////////////// - // Extension Types - //////////////////// + ///////////////////// + // Extension Types // + ///////////////////// /** * Primary for extensions, but also used in apps. * https://developer.chrome.com/extensions/extensionTypes#type-ImageDetails + * @since Chrome 39. **/ namespace extensionTypes { /** * The format of an image. **/ - export type ImageFormat = 'jpeg' | 'png'; + type ImageFormat = + 'jpeg' | + 'png'; /** * Details about the format and quality of an image. */ interface ImageDetails { - /** - * @description The format of the resulting image. Default is 'jpeg'. - * @type {ImageFormat} - * @memberof ImageDetails - */ + /** The format of the resulting image. Default is 'jpeg'. */ format?: ImageFormat; + /** - * @description When format is 'jpeg', controls the quality of the resulting image. This value is ignored for PNG images. As quality is decreased, the resulting image will have more visual artifacts, and the number of bytes needed to store it will decrease. - * @type {number} - * @memberof ImageDetails + * When format is 'jpeg', controls the quality of the resulting image. + * This value is ignored for PNG images. As quality is decreased, + * the resulting image will have more visual artifacts, + * and the number of bytes needed to store it will decrease. */ quality?: number; } /** * The soonest that the JavaScript or CSS will be injected into the tab. **/ - export type RunAt = 'document_start' | 'document_end' | 'document_idle'; + type RunAt = + 'document_start' | + 'document_end' | + 'document_idle'; /** * The origin of injected CSS. **/ - export type CSSOrigin = 'author' | 'user'; + type CSSOrigin = + 'author' | + 'user'; /** - * @description Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. - * @interface InjectDetails + * Internal interfaces, not to be used directly + * @private + * @internal */ - interface InjectDetails { + namespace _internal_ { + /** + * Partial, use these interfaces instead: + * @see InjectCodeDetails + * @see InjectFileDetails + */ + interface InjectDetailsBase { + /** + * If allFrames is true, implies that the JavaScript or CSS should be + * injected into all frames of current page. By default, it's false + * and is only injected into the top frame. If true and frameId is set, + * then the code is inserted in the selected frame and all of its child frames. + */ + allFrames?: boolean; + /** + * The frame where the script or CSS should be injected. Defaults to 0 (the top-level frame). + * @see[frame ref]{@link https://developer.chrome.com/apps/webNavigation#frame_ids} + * @since Since Chrome 50. + */ + frameId?: number; + /** + * If matchAboutBlank is true, then the code is also injected in about:blank + * and about:srcdoc frames if your extension has access to its parent document. + * Code cannot be inserted in top-level about:-frames. By default it is false. + */ + matchAboutBlank?: boolean; + /** + * The soonest that the JavaScript or CSS will be injected into the tab. + * @default 'document_idle' + */ + runAt: RunAt; + /** + * The origin of the CSS to inject. + * This may only be specified for CSS, not JavaScript. + * @default 'author' + * @since Since Chrome 66. + */ + cssOrigin: CSSOrigin; + } + } + + interface InjectFileDetails extends _internal_.InjectDetailsBase { + /** JavaScript or CSS file to inject. */ + file: string; + } + + interface InjectCodeDetails extends _internal_.InjectDetailsBase { /** * JavaScript or CSS code to inject. - * Warning: - * Be careful using the code parameter. Incorrect use of it may open your extension to cross site scripting attacks. - * @type {string} - * @memberof InjectDetails + * **Warning** + * Be careful using the code parameter. + * Incorrect use of it may open your app + * to cross site scripting attacks. + * @see[More information]{https://en.wikipedia.org/wiki/Cross-site_scripting} */ - code?: string; - /** - * @description JavaScript or CSS file to inject. - * @type {string} - * @memberof InjectDetails - */ - file?: string; - /** - * @description If allFrames is true, implies that the JavaScript or CSS should be injected into all frames of current page. By default, it's false and is only injected into the top frame. If true and frameId is set, then the code is inserted in the selected frame and all of its child frames. - * @type {boolean} - * @memberof InjectDetails - */ - allFrames?: boolean; - /** - * @description The frame where the script or CSS should be injected. Defaults to 0 (the top-level frame). - * @since Since Chrome 50. - * @type {number} - * @memberof InjectDetails - */ - frameId?: number; - /** - * @description If matchAboutBlank is true, then the code is also injected in about:blank and about:srcdoc frames if your extension has access to its parent document. Code cannot be inserted in top-level about:-frames. By default it is false. - * @type {boolean} - * @memberof InjectDetails - */ - matchAboutBlank?: boolean; - /** - * @description The soonest that the JavaScript or CSS will be injected into the tab. Defaults to 'document_idle'. - * @type {RunAt} - * @memberof InjectDetails - */ - runAt: RunAt; - /** - * @description The origin of the CSS to inject. This may only be specified for CSS, not JavaScript. Defaults to 'author'. - * @since Since Chrome 66. - * @type {CSSOrigin} - * @memberof InjectDetails - */ - cssOrigin: CSSOrigin; + code: string; } } - //////////////////// - // FileSystem - //////////////////// + //////////////// + // FileSystem // + //////////////// /** * Use the chrome.fileSystem API to create, read, navigate, and write to the user's local file system. * With this API, Chrome Apps can read and write to a user-selected location. * For example, a text editor app can use the API to read and write local documents. * All failures are notified via chrome.runtime.lastError. + * @since Availability: Since Chrome 24. + * @requires Permissions: + * 'fileSystem' + * {'fileSystem': ['write']} + * {'fileSystem': ['write', 'retainEntries', 'directory']} */ namespace fileSystem { - + type ChildChangeType = + 'created' | + 'removed' | + 'changed'; + type ChooseEntryOptionsTypes = + 'openFile' | + 'openWritableFile' | + 'saveFile' | + 'openDirectory'; interface AcceptOptions { /** * This is the optional text description for this option. @@ -1943,7 +2587,7 @@ declare namespace chrome { */ mimeTypes?: string[]; /** - * Extensions to accept, e.g. 'jpg' | 'gif' | 'crx'. + * Extensions to accept, e.g. 'jpg', 'gif', 'crx'. */ extensions?: string[]; } @@ -1952,16 +2596,26 @@ declare namespace chrome { /** * Type of the prompt to show. The default is 'openFile'. * openFile - * - Prompts the user to open an existing file and returns a FileEntry on success. From Chrome 31 onwards, the FileEntry will be writable if the application has the 'write' permission under 'fileSystem'; otherwise, the FileEntry will be read-only. + * - Prompts the user to open an existing file and returns a FileEntry on success. + * From Chrome 31 onwards, the FileEntry will be writable if the application has + * the 'write' permission under 'fileSystem'; otherwise, the FileEntry will be read-only. * openWritableFile - * - Prompts the user to open an existing file and returns a writable FileEntry on success. Calls using this type will fail with a runtime error if the application doesn't have the 'write' permission under 'fileSystem'. + * - Prompts the user to open an existing file and returns a writable FileEntry on success. + * Calls using this type will fail with a runtime error if the application doesn't have the + * 'write' permission under 'fileSystem'. * saveFile - * - Prompts the user to open an existing file or a new file and returns a writable FileEntry on success. Calls using this type will fail with a runtime error if the application doesn't have the 'write' permission under 'fileSystem'. + * - Prompts the user to open an existing file or a new file and returns a writable FileEntry + * on success. Calls using this type will fail with a runtime error if the application doesn't + * have the 'write' permission under 'fileSystem'. * openDirectory - * - Prompts the user to open a directory and returns a DirectoryEntry on success. Calls using this type will fail with a runtime error if the application doesn't have the 'directory' permission under 'fileSystem'. If the application has the 'write' permission under 'fileSystem', the returned DirectoryEntry will be writable; otherwise it will be read-only. New in Chrome 31. + * - Prompts the user to open a directory and returns a DirectoryEntry on success. Calls using + * this type will fail with a runtime error if the application doesn't have the 'directory' + * permission under 'fileSystem'. If the application has the 'write' permission under + * 'fileSystem', the returned DirectoryEntry will be writable; otherwise it will be read-only. + * New in Chrome 31. */ - type?: 'openFile' | 'openWritableFile' | 'saveFile' | 'openDirectory'; - /** The suggested file name that will be presented to the user as the default name to read or write. This is optional. */ + type?: ChooseEntryOptionsTypes; + /** The suggested file name that will be presented to the user as the default name to read or write. */ suggestedName?: string; /** The optional list of accept options for this file opener. Each option will be presented as a unique group to the end-user. */ accepts?: AcceptOptions[]; @@ -1972,17 +2626,23 @@ declare namespace chrome { acceptsAllTypes?: boolean; /** * Whether to accept multiple files. This is only supported for openFile and openWritableFile. - * The callback to chooseEntry will be called with a list of entries if this is set to true. Otherwise it will be called with a single Entry. + * The callback to chooseEntry will be called with a list of entries if this is set to true. + * Otherwise it will be called with a single Entry. + * @since Chrome 30. */ acceptsMultiple?: boolean; } - type ChildChangeType = 'created' | 'removed' | 'changed'; - + /** + * @since Chrome 44. + */ interface Volume { /** The ID of the requested volume. */ volumeId: string; - /** Whether the requested file system should be writable. The default is read-only. */ + /** + * Whether the requested file system should be writable. The default is read-only. + * @default false + **/ writable?: boolean; } @@ -1990,33 +2650,37 @@ declare namespace chrome { * Get the display path of an Entry object. * The display path is based on the full path of the file or directory on the local file system, but may be made more readable for display purposes. */ - export function getDisplayPath(entry: Entry, callback: (displayPath: string) => void): void; + function getDisplayPath(entry: Entry, callback: (displayPath: string) => void): void; /** * Get a writable Entry from another Entry. This call will fail with a runtime error if the application does not have the 'write' permission under 'fileSystem'. * If entry is a DirectoryEntry, this call will fail if the application does not have the 'directory' permission under 'fileSystem'. */ - export function getWritableEntry(entry: Entry, callback: (entry: Entry) => void): void; + function getWritableEntry(entry: Entry, callback: (entry: Entry) => void): void; /** Gets whether this Entry is writable or not. */ - export function isWritableEntry(entry: Entry, callback: (isWritable: boolean) => void): void; + function isWritableEntry(entry: Entry, callback: (isWritable: boolean) => void): void; /** Ask the user to choose a file or directory. */ - export function chooseEntry(callback: (entry: Entry) => void): void; + function chooseEntry(callback: (entry: Entry) => void): void; /** Ask the user to choose a file or directory. */ - export function chooseEntry(callback: (fileEntries: FileEntry[]) => void): void; + function chooseEntry(callback: (fileEntries: FileEntry[]) => void): void; /** Ask the user to choose a file or directory. */ - export function chooseEntry(options: ChooseEntryOptions, callback: (entry: Entry) => void): void; + function chooseEntry(options: ChooseEntryOptions, callback: (entry: Entry) => void): void; /** Ask the user to choose a file or directory. */ - export function chooseEntry(options: ChooseEntryOptions, callback: (fileEntries: FileEntry[]) => void): void; + function chooseEntry(options: ChooseEntryOptions, callback: (fileEntries: FileEntry[]) => void): void; /** Returns the file entry with the given id if it can be restored. This call will fail with a runtime error otherwise. */ - export function restoreEntry(id: string, callback: (entry: Entry) => void): void; - /** Returns whether the app has permission to restore the entry with the given id. */ - export function isRestorable(id: string, callback: (isRestorable: boolean) => void): void; + function restoreEntry(id: string, callback: (entry: Entry) => void): void; + /** + * Returns whether the app has permission to restore the entry with the given id. + * @since Chrome 29. + **/ + function isRestorable(id: string, callback: (isRestorable: boolean) => void): void; /** * Returns an id that can be passed to restoreEntry to regain access to a given file entry. * Only the 500 most recently used entries are retained, where calls to retainEntry and restoreEntry count as use. * If the app has the 'retainEntries' permission under 'fileSystem', entries are retained indefinitely. * Otherwise, entries are retained only while the app is running and across restarts. + * @since Chrome 29. * */ - export function retainEntry(entry: Entry): string; + function retainEntry(entry: Entry): string; /** * Requests access to a file system for a volume represented by options.volumeId. * If options.writable is set to true, then the file system will be writable. @@ -2025,16 +2689,22 @@ declare namespace chrome { * Available to kiosk apps running in kiosk session only. * For manual-launch kiosk mode, a confirmation dialog will be shown on top of the active app window. * In case of an error, fileSystem will be undefined, and chrome.runtime.lastError will be set. + * @since Chrome 44. */ - export function requestFileSystem(options: Volume, callback: (fileSystem: FileSystem) => void): void; + function requestFileSystem(options: Volume, callback: (fileSystem: FileSystem) => void): void; /** * Returns a list of volumes available for requestFileSystem(). * The 'fileSystem': {'requestFileSystem'} manifest permission is required. * Available to kiosk apps running in the kiosk session only. * In case of an error, volumes will be undefined, and chrome.runtime.lastError will be set. + * @since Chrome 44. */ - export function getVolumeList(callback: (volumes: Volume[]) => void): void; - export var onVolumeListChanged: chrome.events.Event<(object: Volume[]) => void>; + function getVolumeList(callback: (volumes: Volume[]) => void): void; + /** + * Called when a list of available volumes is changed. + * @since Chrome 44. + */ + const onVolumeListChanged: chrome.events.Event<(object: Volume[]) => void>; } @@ -2042,76 +2712,161 @@ declare namespace chrome { // File System Provider //////////////////// /** - * Use the chrome.fileSystemProvider API to create file systems, that can be accessible from the file manager on Chrome OS. - * Availability: Since Chrome 40. - * Permissions: 'fileSystemProvider' - * Important: This API works only on Chrome OS. + * Use the chrome.fileSystemProvider API to create file systems, + * that can be accessible from the file manager on Chrome OS. + * @since Availability: Since Chrome 40. + * @requires Permissions: 'fileSystemProvider' + * @requires Important: This API works only on Chrome OS. + * @requires Manifest: + * Requires an section in addition to the permission. + * The file_system_provider section must be declared as follows: + * **configurable (boolean)** - optional + * Whether configuring via onConfigureRequested is supported. By default: false. + * **multiple_mounts (boolean)** - optional + * Whether multiple (more than one) mounted file systems are supported. By default: false. + * **watchable (boolean)** - optional + * Whether setting watchers and notifying about changes is supported. By default: false. + * **source (type of 'file', 'device', or 'network') - required** + * Source of data for mounted file systems. + * @description + * Files app uses above information in order to render related UI elements approprietly. + * For example, if configurable is set to true, then a menu item for configuring volumes + * will be rendered. Similarly, if multiple_mounts is set to true, then Files app will + * allow to add more than one mount points from the UI. If watchable is false, then a + * refresh button will be rendered. Note, that if possible you should add support for + * watchers, so changes on the file system can be reflected immediately and automatically. + * @see[More information]{@link https://developer.chrome.com/apps/fileSystemProvider} */ namespace fileSystemProvider { - interface OpenedFileInfo { - /** A request ID to be be used by consecutive read/write and close requests. */ - openRequestId: number; - /** The path of the opened file. */ - filePath: string; - /** Whether the file was opened for reading or writing. */ - mode: string; - } - - interface FileWatchersInfo { - /** The path of the entry being observed. */ - entryPath: string; - /** Whether watching should include all child entries recursively. It can be true for directories only. */ - recursive: boolean; - /** Optional. Tag used by the last notification for the watcher. */ - lastTag?: string; - } + /** + * Error codes used by providing extensions in response to requests + * as well as in case of errors when calling methods of the API. + * For success, 'OK' must be used. + * */ + type ProviderError = + 'OK' | + 'FAILED' | + 'IN_USE' | + 'EXISTS' | + 'NOT_FOUND' | + 'ACCESS_DENIED' | + 'TOO_MANY_OPENED' | + 'NO_MEMORY' | + 'NO_SPACE' | + 'NOT_A_DIRECTORY' | + 'INVALID_OPERATION' | + 'SECURITY' | + 'ABORT' | + 'NOT_A_FILE' | + 'NOT_EMPTY' | + 'INVALID_URL' | + 'IO'; + /** Mode of opening a file. Used by onOpenFileRequested. */ + type OpenFileMode = + 'READ' | + 'WRITE'; + /** Type of a change detected on the observed directory. */ + type ChangeType = + 'CHANGED' | + 'DELETED'; + /** + * List of common actions. 'SHARE' is for sharing files with others. + * 'SAVE_FOR_OFFLINE' for pinning (saving for offline access). + * 'OFFLINE_NOT_NECESSARY' for notifying that the file doesn't + * need to be stored for offline access anymore. + * Used by onGetActionsRequested and onExecuteActionRequested. + */ + type CommonActionId = + 'SAVE_FOR_OFFLINE' | + 'OFFLINE_NOT_NECESSARY' | + 'SHARE'; interface EntryMetadata { - /** True if it is a directory. */ - isDirectory: boolean; - /** Name of this entry (not full path name). Must not contain '/'. For root it must be empty. */ - name: string; - /** File size in bytes. */ - size: number; + /** True if it is a directory. Must be provided if requested in options */ + isDirectory?: boolean; + /** + * Name of this entry (not full path name). + * Must not contain '/'. + * For root it must be empty. + * Must be provided if requested in options. + **/ + name?: string; + /** File size in bytes. Must be provided if requested in options. */ + size?: double; /** The last modified time of this entry. */ - modificationTime: any; - /** Optional. Mime type for the entry. */ + modificationTime?: Date; + /** Mime type for the entry. */ mimeType?: string; - /** Optional. Thumbnail image as a data URI in either PNG, JPEG or WEBP format, at most 32 KB in size. Optional, but can be provided only when explicitly requested by the onGetMetadataRequested event. */ + /** + * Thumbnail image as a data URI in either PNG, JPEG or WEBP format, at most 32 KB in size. + * Optional, but can be provided only when explicitly requested + * by the onGetMetadataRequested event. + */ thumbnail?: string; } interface FileSystemInfo { /** The identifier of the file system. */ fileSystemId: string; + /** A human-readable name for the file system. */ displayName: string; - /** Whether the file system supports operations which may change contents of the file system (such as creating, deleting or writing to files). */ + + /** + * Whether the file system supports operations which may + * change contents of the file system (such as creating, deleting or writing to files). + */ writable: boolean; + /** * The maximum number of files that can be opened at once. If 0, then not limited. * @since Since Chrome 42. */ - openedFilesLimit: number; + openedFilesLimit: integer; + /** * List of currently opened files. * @since Since Chrome 42. */ openedFiles: OpenedFileInfo[]; + /** - * Optional. - * Whether the file system supports the tag field for observing directories. - * @since Since Chrome 45. Warning: this is the current Beta channel. + * Whether the file system supports the tag field for observing directories. + * @since Since Chrome 45. */ supportsNotifyTag?: boolean; + /** * List of watchers. - * @since Since Chrome 45. Warning: this is the current Beta channel. + * @since Since Chrome 45. */ watchers: FileWatchersInfo[]; } - /** @since Since Chrome 45. Warning: this is the current Beta channel. */ + interface OpenedFileInfo { + /** A request ID to be be used by consecutive read/write and close requests. */ + openRequestId: integer; + /** The path of the opened file. */ + filePath: string; + /** Whether the file was opened for reading or writing. */ + mode: OpenFileMode; + } + + interface FileWatchersInfo { + /** The path of the entry being observed. */ + entryPath: string; + + /** + * Whether watching should include all child entries recursively. + * It can be true for directories only. + */ + recursive: boolean; + + /** Tag used by the last notification for the watcher. */ + lastTag?: string; + } + + /** @since Since Chrome 45. */ interface GetActionsRequestedOptions { /** The identifier of the file system related to this operation. */ fileSystemId: string; @@ -2121,15 +2876,14 @@ declare namespace chrome { entryPath: string; } - /** @since Since Chrome 45. Warning: this is the current Beta channel. */ interface Action { /** The identifier of the action. Any string or CommonActionId for common actions. */ - id: string; - /** Optional. The title of the action. It may be ignored for common actions. */ + id: CommonActionId | string; + /** The title of the action. It may be ignored for common actions. */ title?: string; } - /** @since Since Chrome 45. Warning: this is the current Beta channel. */ + /** @since Since Chrome 45. */ interface ExecuteActionRequestedOptions { /** The identifier of the file system related to this operation. */ fileSystemId: string; @@ -2146,20 +2900,27 @@ declare namespace chrome { fileSystemId: string; /** A human-readable name for the file system. */ displayName: string; - /** Optional. Whether the file system supports operations which may change contents of the file system (such as creating, deleting or writing to files). */ + /** + * Whether the file system supports operations which may change contents + * of the file system (such as creating, deleting or writing to files). + */ writable?: boolean; /** - * Optional. - * The maximum number of files that can be opened at once. If not specified, or 0, then not limited. + * The maximum number of files that can be opened at once. If not specified, or 0, then not limited. * @since Since Chrome 41. */ - openedFilesLimit?: number; + openedFilesLimit?: integer; /** - * Optional. - * Whether the file system supports the tag field for observed directories. - * @since Since Chrome 45. Warning: this is the current Beta channel. + * Whether the file system supports the tag field for observed directories. + * @since Since Chrome 45. */ supportsNotifyTag?: boolean; + /** + * Whether the framework should resume the file system at the next sign-in session. + * @default true + * @since Since Chrome 64. + */ + persistent?: boolean; } interface UnmountOptions { @@ -2171,7 +2932,7 @@ declare namespace chrome { /** The path of the changed entry. */ entryPath: string; /** The type of the change which happened to the entry. */ - changeType: string; + changeType: ChangeType; } interface NotificationOptions { @@ -2181,241 +2942,543 @@ declare namespace chrome { observedPath: string; /** Mode of the observed entry. */ recursive: boolean; - /** The type of the change which happened to the observed entry. If it is DELETED, then the observed entry will be automatically removed from the list of observed entries. */ - changeType: string; - /** Optional. List of changes to entries within the observed directory (including the entry itself) */ + /** + * The type of the change which happened to the observed entry. + * If it is DELETED, then the observed entry will be automatically + * removed from the list of observed entries. + */ + changeType: ChangeType; + /** List of changes to entries within the observed directory (including the entry itself) */ changes?: NotificationChange[]; - /** Optional. Tag for the notification. Required if the file system was mounted with the supportsNotifyTag option. Note, that this flag is necessary to provide notifications about changes which changed even when the system was shutdown. */ + /** + * Tag for the notification. + * Required if the file system was mounted with the supportsNotifyTag option. + * Note, that this flag is necessary to provide notifications about changes + * which changed even when the system was shutdown. + */ tag?: string; } + /** + * Internal interfaces, not for use + * @private + * @internal + */ + namespace _internal_ { + /** + * @private + * @internal + */ + interface RequestedEventOptions { + /** The identifier of the file system related to this operation. */ + fileSystemId: string; + /** The unique identifier of this request. */ + requestId: integer; + } - interface RequestedEventOptions { - /** The identifier of the file system related to this operation. */ - fileSystemId: string; - /** The unique identifier of this request. */ - requestId: number; + /** + * @private + * @internal + */ + interface EntryPathRequestedEventOptions extends RequestedEventOptions { + /** The path of the entry to which this operation is related to. */ + entryPath: string; + } + + /** + * @private + * @internal + */ + interface FilePathRequestedEventOptions extends RequestedEventOptions { + /** The path of the entry for the operation */ + filePath: string; + } } - - interface EntryPathRequestedEventOptions extends RequestedEventOptions { - /** The path of the entry to which this operation is related to. */ - entryPath: string; + interface UnmountRequestedEventOptions extends _internal_.RequestedEventOptions { } - - interface MetadataRequestedEventOptions extends EntryPathRequestedEventOptions { - /** Set to true if the thumbnail is requested. */ + interface MetadataRequestedEventOptions extends _internal_.EntryPathRequestedEventOptions { + /** + * Set to true if is_directory value is requested + * @since Chrome 49. + */ + isDirectory: boolean; + /** + * Set to true if is_directory value is requested. + * @since Chrome 49. + */ + name: boolean; + /** + * Set to true if size value is requested. + * @since Chrome 49. + */ + size: boolean; + /** + * Set to true if modificationTime value is requested + * @since Chrome 49. + */ + modificationTime: boolean; + /** + * Set to true if mimeType value is requested. + * @since Chrome 49. + */ + mimeType: boolean; + /** + * Set to true if the thumbnail is requested. + */ thumbnail: boolean; } - - interface DirectoryPathRequestedEventOptions extends RequestedEventOptions { + interface GetActionsRequestedEventOptions extends _internal_.RequestedEventOptions { + /** The path of the entry to which this operation is related to. */ + entryPaths: string[]; + } + interface ReadDirectoryRequestedEventOptions extends _internal_.RequestedEventOptions { /** The path of the directory which is to be operated on. */ directoryPath: string; + /** + * Set to true if is_directory value is requested + * @since Chrome 49. + */ + isDirectory: boolean; + /** + * Set to true if is_directory value is requested. + * @since Chrome 49. + */ + name: boolean; + /** + * Set to true if size value is requested. + * @since Chrome 49. + */ + size: boolean; + /** + * Set to true if modificationTime value is requested + * @since Chrome 49. + */ + modificationTime: boolean; + /** + * Set to true if mimeType value is requested. + * @since Chrome 49. + */ + mimeType: boolean; + /** + * Set to true if the thumbnail is requested. + */ + thumbnail: boolean; } - - interface FilePathRequestedEventOptions extends RequestedEventOptions { - /** The path of the entry for the operation */ - filePath: string; - } - - interface OpenFileRequestedEventOptions extends FilePathRequestedEventOptions { + interface OpenFileRequestedEventOptions extends _internal_.FilePathRequestedEventOptions { /** Whether the file will be used for reading or writing. */ - mode: string; + mode: OpenFileMode; } - - interface OpenedFileRequestedEventOptions extends RequestedEventOptions { + interface CloseFileRequestedEventOptions extends _internal_.RequestedEventOptions { /** A request ID used to open the file. */ - openRequestId: number; + openRequestId: integer; } - - interface OpenedFileOffsetRequestedEventOptions extends OpenedFileRequestedEventOptions { + interface ReadFileRequestedEventOptions extends _internal_.RequestedEventOptions { + /** A request ID used to open the file. */ + openRequestId: integer; /** Position in the file (in bytes) to start reading from. */ - offset: number; + offset: double; /** Number of bytes to be returned. */ - length: number; + length: double; } - - interface DirectoryPathRecursiveRequestedEventOptions extends DirectoryPathRequestedEventOptions { + interface CreateDirectoryRequestedEventOptions extends _internal_.RequestedEventOptions { + /** The path of the directory which is to be operated on. */ + directoryPath: string; /** Whether the operation is recursive (for directories only). */ recursive: boolean; } - - interface EntryPathRecursiveRequestedEventOptions extends EntryPathRequestedEventOptions { + interface DeleteEntryRequestedEventOptions extends _internal_.EntryPathRequestedEventOptions { /** Whether the operation is recursive (for directories only). */ recursive: boolean; } - - interface SourceTargetPathRequestedEventOptions extends RequestedEventOptions { + interface CreateFileRequestedEventOptions extends _internal_.FilePathRequestedEventOptions { + } + interface CopyEntryRequestedEventOptions extends _internal_.RequestedEventOptions { /** The source path for the operation. */ sourcePath: string; /** The destination path for the operation. */ targetPath: string; } - - interface FilePathLengthRequestedEventOptions extends FilePathRequestedEventOptions { - /** Number of bytes to be retained after the operation completes. */ - length: number; + interface MoveEntryRequestedEventOptions extends CopyEntryRequestedEventOptions { } - - interface OpenedFileIoRequestedEventOptions extends OpenedFileRequestedEventOptions { + interface TruncateRequestedEventOptions extends _internal_.FilePathRequestedEventOptions { + /** Number of bytes to be retained after the operation completes. */ + length: double; + } + interface WriteFileRequestedEventOptions extends _internal_.RequestedEventOptions { + /** A request ID used to open the file. */ + openRequestId: integer; /** Position in the file (in bytes) to start operating from. */ offset: number; /** Buffer of bytes to be operated on the file. */ data: ArrayBuffer; } - - interface OperationRequestedEventOptions extends RequestedEventOptions { + interface AbortRequestedEventOptions extends _internal_.RequestedEventOptions { /** An ID of the request to which this operation is related. */ - operationRequestId: number; + operationRequestId: integer; + } + interface ConfigureRequestedEventOptions extends _internal_.RequestedEventOptions { + } + interface WatcherRequestedEventOptions extends _internal_.EntryPathRequestedEventOptions { + /** + * Mode of the watcher. + * Whether observing should include all child entries recursively. + * It can be true for directories only. + */ + recursive: boolean; + } + interface ExecuteActionRequestedEventOptions extends GetActionsRequestedEventOptions { + /** The identifier of the action to be executed. */ + actionId: string; } - interface RequestedEvent extends chrome.events.Event<(options: RequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - interface MetadataRequestedEvent extends chrome.events.Event<(options: MetadataRequestedEventOptions, successCallback: (metadata: EntryMetadata) => void, errorCallback: (error: string) => void) => void> { } - - interface DirectoryPathRequestedEvent extends chrome.events.Event<(options: DirectoryPathRequestedEventOptions, successCallback: (entries: EntryMetadata[], hasMore: boolean) => void, errorCallback: (error: string) => void) => void> { } - - interface OpenFileRequestedEvent extends chrome.events.Event<(options: OpenFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface OpenedFileRequestedEvent extends chrome.events.Event<(options: OpenedFileRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface OpenedFileOffsetRequestedEvent extends chrome.events.Event<(options: OpenedFileOffsetRequestedEventOptions, successCallback: (data: ArrayBuffer, hasMore: boolean) => void, errorCallback: (error: string) => void) => void> { } - - interface DirectoryPathRecursiveRequestedEvent extends chrome.events.Event<(options: DirectoryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface EntryPathRecursiveRequestedEvent extends chrome.events.Event<(options: EntryPathRecursiveRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface FilePathRequestedEvent extends chrome.events.Event<(options: FilePathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface SourceTargetPathRequestedEvent extends chrome.events.Event<(options: SourceTargetPathRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface FilePathLengthRequestedEvent extends chrome.events.Event<(options: FilePathLengthRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface OpenedFileIoRequestedEvent extends chrome.events.Event<(options: OpenedFileIoRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface OperationRequestedEvent extends chrome.events.Event<(options: OperationRequestedEventOptions, successCallback: Function, errorCallback: (error: string) => void) => void> { } - - interface OptionlessRequestedEvent extends chrome.events.Event<(successCallback: Function, errorCallback: (error: string) => void) => void> { } + ///\/\/|\/\/\\\ + /// METHODS \\\ + ///\/\/|\/\/\\\ /** - * Mounts a file system with the given fileSystemId and displayName. displayName will be shown in the left panel of Files.app. displayName can contain any characters including '/', but cannot be an empty string. displayName must be descriptive but doesn't have to be unique. The fileSystemId must not be an empty string. + * Mounts a file system with the given fileSystemId and displayName. + * displayName will be shown in the left panel of the Files app. + * displayName can contain any characters including '/', but cannot be an empty string. + * displayName must be descriptive but doesn't have to be unique. + * The fileSystemId must not be an empty string. + * * Depending on the type of the file system being mounted, the source option must be set appropriately. + * * In case of an error, runtime.lastError will be set with a corresponding error code. + * * @param callback A generic result callback to indicate success or failure. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; */ - export function mount(options: MountOptions, callback?: () => void): void; + function mount(options: MountOptions, callback?: () => void): void; + /** - * Unmounts a file system with the given fileSystemId. It must be called after onUnmountRequested is invoked. Also, the providing extension can decide to perform unmounting if not requested (eg. in case of lost connection, or a file error). + * Unmounts a file system with the given fileSystemId. + * It must be called after onUnmountRequested is invoked. + * Also, the providing extension can decide to perform unmounting if not requested + * (eg. in case of lost connection, or a file error). + * * In case of an error, runtime.lastError will be set with a corresponding error code. + * * @param callback A generic result callback to indicate success or failure. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; */ - export function unmount(options: UnmountOptions, callback?: () => void): void; + function unmount(options: UnmountOptions, callback?: () => void): void; + /** * Returns all file systems mounted by the extension. * @param callback Callback to receive the result of getAll function. - * The callback parameter should be a function that looks like this: - * function(array of FileSystemInfo fileSystems) {...}; */ - export function getAll(callback: (fileSystems: FileSystemInfo[]) => void): void; + function getAll(callback: (fileSystems: FileSystemInfo[]) => void): void; + /** * Returns information about a file system with the passed fileSystemId. * @since Since Chrome 42. * @param callback Callback to receive the result of get function. - * The callback parameter should be a function that looks like this: - * function(FileSystemInfo fileSystem) {...}; */ - export function get(fileSystemId: string, callback: (fileSystem: FileSystemInfo) => void): void; + function get(fileSystemId: string, callback: (fileSystem: FileSystemInfo) => void): void; + /** - * Notifies about changes in the watched directory at observedPath in recursive mode. If the file system is mounted with supportsNofityTag, then tag must be provided, and all changes since the last notification always reported, even if the system was shutdown. The last tag can be obtained with getAll. + * Notifies about changes in the watched directory at observedPath in recursive mode. + * If the file system is mounted with supportsNofityTag, then tag must be provided, + * and all changes since the last notification always reported, even if the system was shutdown. + * The last tag can be obtained with getAll. + * * To use, the file_system_provider.notify manifest option must be set to true. - * Value of tag can be any string which is unique per call, so it's possible to identify the last registered notification. Eg. if the providing extension starts after a reboot, and the last registered notification's tag is equal to '123', then it should call notify for all changes which happened since the change tagged as '123'. It cannot be an empty string. - * Not all providers are able to provide a tag, but if the file system has a changelog, then the tag can be eg. a change number, or a revision number. - * Note that if a parent directory is removed, then all descendant entries are also removed, and if they are watched, then the API must be notified about the fact. Also, if a directory is renamed, then all descendant entries are in fact removed, as there is no entry under their original paths anymore. + * + * Value of tag can be any string which is unique per call, + * so it's possible to identify the last registered notification. + * Eg. if the providing extension starts after a reboot, + * and the last registered notification's tag is equal to '123', + * then it should call notify for all changes which happened since + * the change tagged as '123'. It cannot be an empty string. + * + * Not all providers are able to provide a tag, but if the file system has a changelog, + * then the tag can be eg. a change number, or a revision number. + * + * Note that if a parent directory is removed, then all descendant entries are also removed, + * and if they are watched, then the API must be notified about the fact. + * Also, if a directory is renamed, then all descendant entries are in fact removed, + * as there is no entry under their original paths anymore. + * * In case of an error, runtime.lastError will be set will a corresponding error code. + * * @param callback A generic result callback to indicate success or failure. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; + * @since Since Chrome 45. */ - export function notify(options: NotificationOptions, callback: () => void): void; + function notify(options: NotificationOptions, callback: () => void): void; + + ///\/\/\/\/\\\ + /// EVENTS \\\ + ///\/\/\/\/\\\ + + /** + * Raised when unmounting for the file system with the fileSystemId identifier is requested. + * In the response, the unmount API method must be called together with successCallback. + * If unmounting is not possible (eg. due to a pending operation), then errorCallback must be called. + */ + const onUnmountRequested: chrome.events.Event<( + options: UnmountRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when metadata of a file or a directory at entryPath is requested. + * The metadata must be returned with the successCallback call. + * In case of an error, errorCallback must be called. + */ + const onGetMetadataRequested: chrome.events.Event<( + options: MetadataRequestedEventOptions, + successCallback: (metadata: EntryMetadata) => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when a list of actions for a set of files or directories at entryPaths is requested. + * All of the returned actions must be applicable to each entry. + * If there are no such actions, an empty array should be returned. + * The actions must be returned with the successCallback call. + * In case of an error, errorCallback must be called. + * @since Since Chrome 48. + **/ + const onGetActionsRequested: chrome.events.Event<( + options: GetActionsRequestedEventOptions, + successCallback: (actions: Action[]) => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when contents of a directory at directoryPath are requested. + * The results must be returned in chunks by calling the successCallback several times. + * In case of an error, errorCallback must be called. + */ + const onReadDirectoryRequested: chrome.events.Event<( + options: ReadDirectoryRequestedEventOptions, + successCallback: (entries: EntryMetadata[], hasMore: boolean) => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when opening a file at filePath is requested. + * If the file does not exist, then the operation must fail. + * Maximum number of files opened at once can be specified with MountOptions. + */ + const onOpenFileRequested: chrome.events.Event<( + options: OpenFileRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when opening a file previously opened + * with openRequestId is requested to be closed. + */ + const onCloseFileRequested: chrome.events.Event<( + options: CloseFileRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void> + + /** + * Raised when reading contents of a file opened previously with openRequestId is requested. + * The results must be returned in chunks by calling successCallback several times. + * In case of an error, errorCallback must be called. + */ + const onReadFileRequested: chrome.events.Event<( + options: ReadFileRequestedEventOptions, + successCallback: (data: ArrayBuffer, hasMore: boolean) => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when creating a directory is requested. + * The operation must fail with the EXISTS error if the target directory already exists. + * If recursive is true, then all of the missing directories on the directory path must be created. + */ + const onCreateDirectoryRequested: chrome.events.Event<( + options: CreateDirectoryRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when deleting an entry is requested. + * If recursive is true, and the entry is a directory, + * then all of the entries inside must be recursively deleted as well. + */ + const onDeleteEntryRequested: chrome.events.Event<( + options: DeleteEntryRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when creating a file is requested. + * If the file already exists, then errorCallback must be called with the 'EXISTS' error code. + */ + const onCreateFileRequested: chrome.events.Event<( + options: CreateFileRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when copying an entry (recursively if a directory) is requested. + * If an error occurs, then errorCallback must be called. + */ + const onCopyEntryRequested: chrome.events.Event<( + options: CopyEntryRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when moving an entry (recursively if a directory) is requested. + * If an error occurs, then errorCallback must be called. + */ + const onMoveEntryRequested: chrome.events.Event<( + options: MoveEntryRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when truncating a file to a desired length is requested. + * If an error occurs, then errorCallback must be called. + */ + const onTruncateRequested: chrome.events.Event<( + options: TruncateRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; - /** Raised when unmounting for the file system with the fileSystemId identifier is requested. In the response, the unmount API method must be called together with successCallback. If unmounting is not possible (eg. due to a pending operation), then errorCallback must be called. */ - export var onUnmountRequested: RequestedEvent; - /** Raised when metadata of a file or a directory at entryPath is requested. The metadata must be returned with the successCallback call. In case of an error, errorCallback must be called. */ - export var onGetMetadataRequested: MetadataRequestedEvent; - /** Raised when contents of a directory at directoryPath are requested. The results must be returned in chunks by calling the successCallback several times. In case of an error, errorCallback must be called. */ - export var onReadDirectoryRequested: DirectoryPathRequestedEvent; - /** Raised when opening a file at filePath is requested. If the file does not exist, then the operation must fail. Maximum number of files opened at once can be specified with MountOptions. */ - export var onOpenFileRequested: OpenFileRequestedEvent; - /** Raised when opening a file previously opened with openRequestId is requested to be closed. */ - export var onCloseFileRequested: OpenedFileRequestedEvent; - /** Raised when reading contents of a file opened previously with openRequestId is requested. The results must be returned in chunks by calling successCallback several times. In case of an error, errorCallback must be called. */ - export var onReadFileRequested: OpenedFileOffsetRequestedEvent; - /** Raised when creating a directory is requested. The operation must fail with the EXISTS error if the target directory already exists. If recursive is true, then all of the missing directories on the directory path must be created. */ - export var onCreateDirectoryRequested: DirectoryPathRecursiveRequestedEvent; - /** Raised when deleting an entry is requested. If recursive is true, and the entry is a directory, then all of the entries inside must be recursively deleted as well. */ - export var onDeleteEntryRequested: EntryPathRecursiveRequestedEvent; - /** Raised when creating a file is requested. If the file already exists, then errorCallback must be called with the 'EXISTS' error code. */ - export var onCreateFileRequested: FilePathRequestedEvent; - /** Raised when copying an entry (recursively if a directory) is requested. If an error occurs, then errorCallback must be called. */ - export var onCopyEntryRequested: SourceTargetPathRequestedEvent; - /** Raised when moving an entry (recursively if a directory) is requested. If an error occurs, then errorCallback must be called. */ - export var onMoveEntryRequested: SourceTargetPathRequestedEvent; - /** Raised when truncating a file to a desired length is requested. If an error occurs, then errorCallback must be called. */ - export var onTruncateRequested: FilePathLengthRequestedEvent; /** Raised when writing contents to a file opened previously with openRequestId is requested. */ - export var onWriteFileRequested: OpenedFileIoRequestedEvent; - /** Raised when aborting an operation with operationRequestId is requested. The operation executed with operationRequestId must be immediately stopped and successCallback of this abort request executed. If aborting fails, then errorCallback must be called. Note, that callbacks of the aborted operation must not be called, as they will be ignored. Despite calling errorCallback, the request may be forcibly aborted. */ - export var onAbortRequested: OperationRequestedEvent; + const onWriteFileRequested: chrome.events.Event<( + options: WriteFileRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + /** - * Raised when showing a configuration dialog for fileSystemId is requested. If it's handled, the file_system_provider.configurable manfiest option must be set to true. + * Raised when aborting an operation with operationRequestId is requested. + * The operation executed with operationRequestId must be immediately stopped + * and successCallback of this abort request executed. If aborting fails, + * then errorCallback must be called. Note, that callbacks of the aborted + * operation must not be called, as they will be ignored. Despite calling + * errorCallback, the request may be forcibly aborted. + */ + const onAbortRequested: chrome.events.Event<( + options: AbortRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when showing a configuration dialog for fileSystemId is requested. + * If it's handled, the file_system_provider.configurable manfiest option must be set to true. * @since Since Chrome 44. */ - export var onConfigureRequested: RequestedEvent; + const onConfigureRequested: chrome.events.Event<( + options: ConfigureRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + /** - * Raised when showing a dialog for mounting a new file system is requested. If the extension/app is a file handler, then this event shouldn't be handled. Instead app.runtime.onLaunched should be handled in order to mount new file systems when a file is opened. For multiple mounts, the file_system_provider.multiple_mounts manifest option must be set to true. + * Raised when showing a dialog for mounting a new file system is requested. + * If the extension/app is a file handler, then this event shouldn't be handled. + * Instead app.runtime.onLaunched should be handled in order to mount new file systems when a file is opened. + * For multiple mounts, the file_system_provider.multiple_mounts manifest option must be set to true. * @since Since Chrome 44. */ - export var onMountRequested: OptionlessRequestedEvent; + const onMountRequested: chrome.events.Event<( + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + /** - * Raised when setting a new directory watcher is requested. If an error occurs, then errorCallback must be called. - * @since Since Chrome 45. Warning: this is the current Beta channel. + * Raised when setting a new directory watcher is requested. + * If an error occurs, then errorCallback must be called. + * @since Since Chrome 45. */ - export var onAddWatcherRequested: EntryPathRecursiveRequestedEvent; + const onAddWatcherRequested: chrome.events.Event<( + options: WatcherRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + /** - * Raised when the watcher should be removed. If an error occurs, then errorCallback must be called. - * @since Since Chrome 45. Warning: this is the current Beta channel. + * Raised when the watcher should be removed. + * If an error occurs, then errorCallback must be called. + * @since Since Chrome 45. */ - export var onRemoveWatcherRequested: EntryPathRecursiveRequestedEvent; + const onRemoveWatcherRequested: chrome.events.Event<( + options: WatcherRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; + + /** + * Raised when executing an action for a set of files or directories is\ requested. + * After the action is completed, successCallback must be called. + * On error, errorCallback must be called. + * @since Since Chrome 48. + */ + const onExecuteActionRequested: chrome.events.Event<( + options: ExecuteActionRequestedEventOptions, + successCallback: () => void, + errorCallback: (error: ProviderError) => void + ) => void>; } - //////////////////// - // Google Cloud Messaging - //////////////////// + //////////////////////////// + // Google Cloud Messaging // + //////////////////////////// /** - * Use chrome.gcm to enable apps and extensions to send and receive messages through the Google Cloud Messaging Service. - * Availability: Since Chrome 35. - * Permissions: 'gcm' + * Use chrome.gcm to enable apps and extensions to send and receive + * messages through the Google Cloud Messaging Service. + * @deprecated + * As of April 10, 2018, Google has deprecated GCM. + * The GCM server and client APIs are deprecated and will be removed as soon as April 11, 2019. + * Migrate GCM apps to Firebase Cloud Messaging (FCM), + * which inherits the reliable and scalable GCM infrastructure, + * plus many new features. See the migration guide to learn more. + * @see[Migration guide]{@link https://developers.google.com/cloud-messaging/android/android-migrate-fcm} + * @see[GCM Imlementation guide]{@link https://developers.google.com/cloud-messaging/chrome/client} + * @since Availability: Since Chrome 35. + * @requires Permissions: 'gcm' */ namespace gcm { + /** + * The maximum size (in bytes) of all key/value pairs in a message. + * @default 4096 + */ + const MAX_MESSAGE_SIZE: integer; + interface IGCMData { 'collapse_key'?: never; 'goog'?: never; 'goog.'?: never; + 'GOOG'?: never; + 'GOOG.'?: never; 'google'?: never; 'GOOGLE'?: never; [key: string]: any; } + interface OutgoingMessage { /** The ID of the server to send the message to as assigned by Google API Console. */ destinationId: string; /** The ID of the message. It must be unique for each message in scope of the applications. See the Cloud Messaging documentation for advice for picking and handling an ID. */ messageId: string; - /** Optional. Time-to-live of the message in seconds. If it is not possible to send the message within that time, an onSendError event will be raised. A time-to-live of 0 indicates that the message should be sent immediately or fail if it's not possible. The maximum and a default value of time-to-live is 86400 seconds (1 day). */ - timeToLive?: number; + /** Time-to-live of the message in seconds. If it is not possible to send the message within that time, an onSendError event will be raised. A time-to-live of 0 indicates that the message should be sent immediately or fail if it's not possible. The maximum and a default value of time-to-live is 86400 seconds (1 day). */ + timeToLive?: integer; /** - * @description Message data to send to the server. Case-insensitive goog. and google, as well as case-sensitive collapse_key are disallowed as key prefixes. Sum of all key/value pairs should not exceed gcm.MAX_MESSAGE_SIZE. + * Message data to send to the server. + * + * Case-insensitive goog. and google, + * as well as case-sensitive collapse_key + * are disallowed as key prefixes. + * + * Sum of all key/value pairs should not exceed gcm.MAX_MESSAGE_SIZE. **/ data: IGCMData; } @@ -2439,21 +3502,12 @@ declare namespace chrome { interface GcmError { /** The error message describing the problem. */ errorMessage: string; - /** Optional. The ID of the message with this error, if error is related to a specific message. */ + /** The ID of the message with this error, if error is related to a specific message. */ messageId?: string; /** Additional details related to the error, when available. */ detail: Object; } - interface MessageReceptionEvent extends chrome.events.Event<(message: IncomingMessage) => void> { } - - interface MessageDeletionEvent extends chrome.events.Event<() => void> { } - - interface GcmErrorEvent extends chrome.events.Event<(error: GcmError) => void> { } - - /** The maximum size (in bytes) of all key/value pairs in a message. Default: 4096 */ - export var MAX_MESSAGE_SIZE: number; - /** * Registers the application with GCM. The registration ID will be returned by the callback. If register is called again with the same list of senderIds, the same registration ID will be returned. * @param senderIds A list of server IDs that are allowed to send messages to the application. It should contain at least one and no more than 100 sender IDs. @@ -2462,14 +3516,14 @@ declare namespace chrome { * function(string registrationId) {...}; * Parameter registrationId: A registration ID assigned to the application by the GCM. */ - export function register(senderIds: string[], callback: (registrationId: string) => void): void; + function register(senderIds: string[], callback: (registrationId: string) => void): void; /** * Unregisters the application from GCM. * @param callback A function called after the unregistration completes. Unregistration was successful if runtime.lastError is not set. * The callback parameter should be a function that looks like this: * function() {...}; */ - export function unregister(callback: () => void): void; + function unregister(callback: () => void): void; /** * Sends a message according to its contents. * @param message A message to send to the other party via GCM. @@ -2478,46 +3532,440 @@ declare namespace chrome { * function(string messageId) {...}; * Parameter messageId: The ID of the message that the callback was issued for. */ - export function send(message: OutgoingMessage, callback: (messageId: string) => void): void; + function send(message: OutgoingMessage, callback: (messageId: string) => void): void; /** Fired when a message is received through GCM. */ - export var onMessage: MessageReceptionEvent; + const onMessage: chrome.events.Event<(message: IncomingMessage) => void>; /** Fired when a GCM server had to delete messages sent by an app server to the application. See Messages deleted event section of Cloud Messaging documentation for details on handling this event. */ - export var onMessagesDeleted: MessageDeletionEvent; + const onMessagesDeleted: chrome.events.Event<() => void>; /** Fired when it was not possible to send a message to the GCM server. */ - export var onSendError: GcmErrorEvent; + const onSendError: chrome.events.Event<(error: GcmError) => void>; } - //////////////////// - // HID - //////////////////// + ///////// + // HID // + ///////// /** - * Use the chrome.hid API to interact with connected HID devices. This API provides access to HID operations from within the context of an app. Using this API, apps can function as drivers for hardware devices. Errors generated by this API are reported by setting runtime.lastError and executing the function's regular callback. The callback's regular parameters will be undefined in this case. - * @since Chrome 38 + * Use the chrome.hid API to interact with connected HID devices. + * This API provides access to HID operations from within the context of an app. + * Using this API, apps can function as drivers for hardware devices. + * Errors generated by this API are reported by setting runtime.lastError + * and executing the function's regular callback. The callback's regular + * parameters will be undefined in this case. + * + * @requires Permissions: 'hid' + * @since Available since Chrome 38. */ namespace hid { - /** NOT YET IMPLEMENTED */ + interface Collection { + /** HID usage page identifier. */ + usagePage: integer; + /** Page-defined usage identifier. */ + usage: integer; + /** Report IDs which belong to the collection and to its children. */ + reportIds: integer[]; + } + interface HidDeviceInfo { + /** Opaque device ID. */ + deviceId: integer; + /** Vendor ID. */ + vendorId: integer; + /** Product ID. */ + productId: integer; + /** + * The product name read from the device, if available. + * @since Chrome 46 + * */ + productName: string; + /** + * The serial number read from the device, if available. + * @since Chrome 46 + */ + serialNumber: string; + /** + * Top-level collections from this device's report descriptors. + */ + collections: Collection[]; + /** Top-level collection's maximum input report size. */ + maxInputReportSize: integer; + /** Top-level collection's maximum output report size. */ + maxOutputReportSize: integer; + /** Top-level collection's maximum feature report size. */ + maxFeatureReportSize: integer; + /** + * Raw device report descriptor (not available on Windows). + * @since Chrome 42 + * */ + reportDescriptor: ArrayBuffer; + } + /** @since Chrome 39. */ + interface DeviceFilter { + /** Device vendor ID. */ + vendorId?: integer; + /** Device product ID, only checked only if the vendor ID matches. */ + productId?: integer; + /** HID usage page identifier. */ + usagePage?: integer; + /** HID usage identifier, checked only if the HID usage page matches. */ + usage?: integer; + } + interface DeviceOptions { + /** + * Equivalent to setting DeviceFilter.vendorId. + * @deprecated Deprecated since Chrome 39 + */ + vendorId?: chrome.deprecated; + /** + * Equivalent to setting DeviceFilter.productId. + * @deprecated Deprecated since Chrome 39. + */ + productId?: chrome.deprecated; + /** + * A device matching any given filter will be returned. + * An empty filter list will return all devices the app has permission for. + * @since Chrome 39 + */ + filters?: DeviceFilter[]; + } + interface UserSelectedDevicePickerOptions { + /** + * Allow the user to select multiple devices. + */ + multiple?: boolean; + /** + * Filter the list of devices presented to the user. + * If multiple filters are provided devices matching any filter will be displayed. + */ + filters?: DeviceFilter[]; + } + + /** + * Enumerate connected HID devices. + * @param options The properties to search for on target devices. + * @param callback + */ + function getDevices(options: DeviceOptions, callback: (devices: HidDeviceInfo[]) => void): void; + + /** + * @requires(dev) **Dev channel only!** + * @see[Learn more]{@link https://developer.chrome.com/apps/api_index#dev_apis} + * @description + * Presents a device picker to the user and returns + * HidDeviceInfo objects for the devices selected. If the user + * cancels the picker devices will be empty. A user gesture is + * required for the dialog to display. Without a user gesture, + * the callback will run as though the user cancelled. If multiple + * filters are provided devices matching any filter will be displayed. + * @param callback Invoked with a list of chosen Devices. + */ + function getUserSelectedDevices(callback: (devices: HidDeviceInfo) => void): void; + + /** + * @since Since Chrome 45. + * @requires(dev) **Dev channel only!** + * @see[Learn more]{@link https://developer.chrome.com/apps/api_index#dev_apis} + * Presents a device picker to the user and returns + * HidDeviceInfo objects for the devices selected. If the user + * cancels the picker devices will be empty. A user gesture is + * required for the dialog to display. Without a user gesture, + * the callback will run as though the user cancelled. If multiple + * filters are provided devices matching any filter will be displayed. + * @param options Configuration of the device picker dialog box. + * @param callback Invoked with a list of chosen Devices. + */ + function getUserSelectedDevices(options: UserSelectedDevicePickerOptions, callback: (devices: HidDeviceInfo) => void): void; + + /** + * Open a connection to an HID device for communication. + * @param deviceId The HidDeviceInfo.deviceId of the device to open. + * @param callback The callback function returns an object, containing the connectionId. + * The connectionId is the opaque ID used to identify this connection in all other functions. + */ + function connect(deviceId: number, callback: (connection: { connectionId: number }) => void): void; + + /** + * Disconnect from a device. + * Invoking operations on a device after calling this is safe but has no effect. + * @param connectionId The connectionId returned by connect. + * @param [callback] + */ + function disconnect(connectionId: integer, callback?: () => void): void; + + /** + * Receive the next input report from the device. + * @param connectionId The connectionId returned by connect. + * @param callback The callback will return these parameters: + * * reportId - The report ID or 0 if none. + * * data - The report data, the report ID prefix (if present) is removed. + */ + function receive(connectionId: integer, callback: (reportId: integer, data: ArrayBuffer) => void): void; + + /** + * Send an output report to the device. + * Note: Do not include a report ID prefix in data. It will be added if necessary. + * @param connectionId The connectionId returned by connect. + * @param reportId reportId - The report ID or 0 if none. + * @param data The report data. + * @param callback + */ + function send(connectionId: integer, reportId: integer, data: ArrayBuffer, callback: () => void): void; + + /** + * Request a feature report from the device. + * @param connectionId The connectionId returned by connect. + * @param reportId The report ID, or 0 if none. + * @param callback Will provide `data` which contain the report data, including a report ID prefix if one is sent by the device. + */ + function receiveFeatureReport(connectionId: integer, reportId: integer, callback: (data: ArrayBuffer) => void): void; + + /** + * Send a feature report to the device. + * Note: Do not include a report ID prefix in data. It will be added if necessary. + * @param connectionId The connectionId returned by connect. + * @param reportId The report ID to use, or 0 if none. + * @param data The report data. + * @param callback + */ + function sendFeatureReport(connectionId: integer, reportId: integer, data: ArrayBuffer, callback: () => void): void; + + /** + * Event generated when a device is added to the system. + * Events are only broadcast to apps and extensions that + * have permission to access the device. Permission may + * have been granted at install time or when the user + * accepted an optional permission. + * @since Chrome 41. + * @see[permissions.request]{@link https://developer.chrome.com/apps/permissions#method-request} + */ + const onDeviceAdded: chrome.events.Event<(device: HidDeviceInfo) => void>; + + /** + * Event generated when a device is removed from the system. + * The callback will contain the deviceId property of the device passed to onDeviceAdded. + * @since Chrome 41. + * @see[See onDeviceAdded for which events are delivered]{@link https://developer.chrome.com/apps/hid#event-onDeviceAdded}. + */ + const onDeviceRemoved: chrome.events.Event<(deviceId: integer) => void>; } - //////////////////// - // i18n - //////////////////// + ///////////////////////////////// + // i18n - Internationalization // + ///////////////////////////////// /** - * Use the chrome.i18n infrastructure to implement internationalization across your whole app or extension. - * @since Chrome 5. + * Use the chrome.i18n infrastructure to implement internationalization across your whole app. + * Content scripts: Fully supported. + * @see[Docs]{@link https://developer.chrome.com/apps/i18n} + * @since Chrome 25. */ namespace i18n { + /** + * An ISO language code such as en or fr. + * For a complete list of languages supported by this method, see kLanguageInfoTable. + * For an unknown language, und will be returned, + * which means that [percentage] of the text is unknown to CLD + * @since Chrome 47. + */ + type LanguageCode = kLanguageInfoTable | 'und'; + /** + * @see[Source]{@link https://github.com/chromium/chromium/blob/master/ui/base/l10n/l10n_util.cc} + */ + type kLanguageInfoTable = + 'af' | // Afrikaans + 'am' | // Amharic + 'an' | // Aragonese + 'ar' | // Arabic + 'ast' | // Asturian + 'az' | // Azerbaijani + 'be' | // Belarusian + 'bg' | // Bulgarian + 'bh' | // Bihari + 'bn' | // Bengali + 'br' | // Breton + 'bs' | // Bosnian + 'ca' | // Catalan + 'ceb' | // Cebuano + 'ckb' | // Kurdish (Arabci), Sorani + 'co' | // Corsican + 'cs' | // Czech + 'cy' | // Welsh + 'da' | // Danish + 'de' | // German + 'de-AT' | // German (Austria) + 'de-CH' | // German (Switzerland) + 'de-DE' | // German (Germany) + 'de-LI' | // German (Liechtenstein) + 'el' | // Greek + 'en' | // English + 'en-AU' | // English (Australia) + 'en-CA' | // English (Canada) + 'en-GB' | // English (UK) + 'en-IN' | // English (India) + 'en-NZ' | // English (New Zealand) + 'en-US' | // English (US) + 'en-ZA' | // English (South Africa) + 'eo' | // Esperanto + // TODO(jungshik) : Do we want to list all es-Foo for Latin-American + // Spanish speaking countries? + 'es' | // Spanish + 'es-419' | // Spanish (Latin America) + 'es-AR' | // Spanish (Argentina) + 'es-CL' | // Spanish (Chile) + 'es-CO' | // Spanish (Colombia) + 'es-CR' | // Spanish (Costa Rica) + 'es-ES' | // Spanish (Spain) + 'es-HN' | // Spanish (Honduras) + 'es-MX' | // Spanish (Mexico) + 'es-PE' | // Spanish (Peru) + 'es-US' | // Spanish (US) + 'es-UY' | // Spanish (Uruguay) + 'es-VE' | // Spanish (Venezuela) + 'et' | // Estonian + 'eu' | // Basque + 'fa' | // Persian + 'fi' | // Finnish + 'fil' | // Filipino + 'fo' | // Faroese + 'fr' | // French + 'fr-CA' | // French (Canada) + 'fr-CH' | // French (Switzerland) + 'fr-FR' | // French (France) + 'fy' | // Frisian + 'ga' | // Irish + 'gd' | // Scots Gaelic + 'gl' | // Galician + 'gn' | // Guarani + 'gu' | // Gujarati + 'ha' | // Hausa + 'haw' | // Hawaiian + 'he' | // Hebrew + 'hi' | // Hindi + 'hmn' | // Hmong + 'hr' | // Croatian + 'ht' | // Haitian Creole + 'hu' | // Hungarian + 'hy' | // Armenian + 'ia' | // Interlingua + 'id' | // Indonesian + 'ig' | // Igbo + 'is' | // Icelandic + 'it' | // Italian + 'it-CH' | // Italian (Switzerland) + 'it-IT' | // Italian (Italy) + 'ja' | // Japanese + 'jv' | // Javanese + 'ka' | // Georgian + 'kk' | // Kazakh + 'km' | // Cambodian + 'kn' | // Kannada + 'ko' | // Korean + 'ku' | // Kurdish + 'ky' | // Kyrgyz + 'la' | // Latin + 'lb' | // Luxembourgish + 'ln' | // Lingala + 'lo' | // Laothian + 'lt' | // Lithuanian + 'lv' | // Latvian + 'mg' | // Malagasy + 'mi' | // Maori + 'mk' | // Macedonian + 'ml' | // Malayalam + 'mn' | // Mongolian + 'mo' | // Moldavian + 'mr' | // Marathi + 'ms' | // Malay + 'mt' | // Maltese + 'my' | // Burmese + 'nb' | // Norwegian (Bokmal) + 'ne' | // Nepali + 'nl' | // Dutch + 'nn' | // Norwegian (Nynorsk) + 'no' | // Norwegian + 'ny' | // Nyanja + 'oc' | // Occitan + 'om' | // Oromo + 'or' | // Oriya + 'pa' | // Punjabi + 'pl' | // Polish + 'ps' | // Pashto + 'pt' | // Portuguese (pt-BR and pt-PT are used) + 'pt-BR' | // Portuguese (Brazil) + 'pt-PT' | // Portuguese (Portugal) + 'qu' | // Quechua + 'rm' | // Romansh + 'ro' | // Romanian + 'ru' | // Russian + 'sd' | // Sindhi + 'sh' | // Serbo-Croatian + 'si' | // Sinhalese + 'sk' | // Slovak + 'sl' | // Slovenian + 'sm' | // Samoan + 'sn' | // Shona + 'so' | // Somali + 'sq' | // Albanian + 'sr' | // Serbian + 'st' | // Sesotho + 'su' | // Sundanese + 'sv' | // Swedish + 'sw' | // Swahili + 'ta' | // Tamil + 'te' | // Telugu + 'tg' | // Tajik + 'th' | // Thai + 'ti' | // Tigrinya + 'tk' | // Turkmen + 'to' | // Tonga + 'tr' | // Turkish + 'tt' | // Tatar + 'tw' | // Twi + 'ug' | // Uighur + 'uk' | // Ukrainian + 'ur' | // Urdu + 'uz' | // Uzbek + 'vi' | // Vietnamese + 'wa' | // Walloon + 'xh' | // Xhosa + 'yi' | // Yiddish + 'yo' | // Yoruba + 'zh' | // Chinese + 'zh-CN' | // Chinese (China) + 'zh-HK' | // Chinese (Hong Kong) + 'zh-TW' | // Chinese (Taiwan) + 'zu' | // Zulu + // Aliases: + 'ar_001' | + 'en_001' | + 'en_150' | + 'zh_hans_cn' | + 'zh_hant_hk' | + 'zh_hant_mo' | + 'zh_hans_sg' | + 'zh_hant_tw'; + + /** Allow array of strings with length 1 to 9 */ + type StringSubstitutions = + [string] | + [string, string] | + [string, string, string] | + [string, string, string, string] | + [string, string, string, string, string] | + [string, string, string, string, string, string] | + [string, string, string, string, string, string, string] | + [string, string, string, string, string, string, string, string] | + [string, string, string, string, string, string, string, string, string]; + /** Holds detected ISO language code and its percentage in the input string */ interface DetectedLanguage { /** - * @description An ISO language code such as 'en' or 'fr'. - * @description For a complete list of languages supported by this method: + * An ISO language code such as 'en' or 'fr'. + * For a complete list of languages supported by this method: * @see [kLanguageInfoTable]{@link https://src.chromium.org/viewvc/chrome/trunk/src/third_party/cld/languages/internal/languages.cc}. - * @description For an unknown language, 'und' will be returned, which means that [percentage] of the text is unknown to CLD */ - language: string; + * For an unknown language, 'und' will be returned, which means that [percentage] of the text is unknown to CLD */ + language: kLanguageInfoTable; /** The percentage of the detected language */ - percentage: number; + percentage: integer; } /** Holds detected language reliability and array of DetectedLanguage */ @@ -2525,60 +3973,75 @@ declare namespace chrome { /** CLD detected language reliability */ isReliable: boolean; - /** Array of detectedLanguage */ + /** Array of DetectedLanguage */ languages: DetectedLanguage[]; } /** - * Gets the accept-languages of the browser. This is different from the locale used by the browser; to get the locale, use i18n.getUILanguage. - * @param callback The callback parameter should be a function that looks like this: - * function(array of string languages) {...}; - * Parameter languages: Array of the accept languages of the browser, such as en-US,en,zh-CN + * Gets the accept-languages of the browser. + * This is different from the locale used by the browser; + * to get the locale, use i18n.getUILanguage. */ - export function getAcceptLanguages(callback: (languages: string[]) => void): void; + function getAcceptLanguages(callback: (languages: LanguageCode[]) => void): void; /** - * Gets the localized string for the specified message. If the message is missing, this method returns an empty string (''). If the format of the getMessage() call is wrong — for example, messageName is not a string or the substitutions array has more than 9 elements — this method returns undefined. + * Gets the localized string for the specified message. + * If the message is missing, this method returns an empty string (''). + * If the format of the getMessage() call is wrong — for example, + * messageName is not a string or the substitutions array has + * more than 9 elements — this method returns undefined. + * * @param messageName The name of the message, as specified in the messages.json file. - * @param substitutions Optional. Up to 9 substitution strings, if the message requires any. + * @param substitutions Up to 9 substitution strings, if the message requires any. */ - export function getMessage(messageName: string, substitutions?: any): string | undefined; + function getMessage(messageName: string, substitutions?: StringSubstitutions): string | undefined; /** - * Gets the browser UI language of the browser. This is different from i18n.getAcceptLanguages which returns the preferred user languages. + * Gets the browser UI language of the browser. + * This is different from i18n.getAcceptLanguages which returns the preferred user languages. * @since Chrome 35. */ - export function getUILanguage(): string; + function getUILanguage(): string; - /** Detects the language of the provided text using CLD. + /** + * Detects the language of the provided text using CLD. * @param text User input string to be translated. - * @param callback The callback parameter should be a function that looks like this: function(object result) {...}; + * @param callback + * @since Chrome 47. */ - export function detectLanguage(text: string, callback: (result: LanguageDetectionResult) => void): void; + function detectLanguage(text: string, callback: (result: LanguageDetectionResult) => void): void; } - //////////////////// - // Identity - //////////////////// + ////////////// + // Identity // + ////////////// /** * Use the chrome.identity API to get OAuth2 access tokens. - * Permissions: 'identity' + * @requires Permissions: 'identity' + * @see[Identity User]{@link https://developer.chrome.com/apps/app_identity} * @since Chrome 29. */ namespace identity { /** @since Chrome 32. */ interface AccountInfo { - /** A unique identifier for the account. This ID will not change for the lifetime of the account. */ + /** + * A unique identifier for the account. + * This ID will not change for the lifetime of the account. + */ id: string; } interface TokenDetails { /** - * Optional. - * Fetching a token may require the user to sign-in to Chrome, or approve the application's requested scopes. If the interactive flag is true, getAuthToken will prompt the user as necessary. When the flag is false or omitted, getAuthToken will return failure any time a prompt would be required. + * Fetching a token may require the user to sign-in to Chrome, + * or approve the application's requested scopes. + * If the interactive flag is true, getAuthToken will prompt the user as necessary. + * When the flag is false or omitted, getAuthToken will return failure any time + * a prompt would be required. */ interactive?: boolean; /** * Optional. - * The account ID whose token should be returned. If not specified, the primary account for the profile will be used. + * The account ID whose token should be returned. + * If not specified, the primary account for the profile will be used. * account is only supported when the 'enable-new-profile-management' flag is set. * @since Chrome 37. */ @@ -2593,9 +4056,17 @@ declare namespace chrome { } interface UserInfo { - /** An email address for the user account signed into the current profile. Empty if the user is not signed in or the identity.email manifest permission is not specified. */ + /** + * An email address for the user account signed into the current profile. + * Empty if the user is not signed in or the identity.email manifest permission is not specified. + */ email: string; - /** A unique identifier for the account. This ID will not change for the lifetime of the account. Empty if the user is not signed in or (in M41+) the identity.email manifest permission is not specified. */ + /** + * A unique identifier for the account. + * This ID will not change for the lifetime of the account. + * Empty if the user is not signed in or (in M41+) the identity.email + * manifest permission is not specified. + */ id: string; } @@ -2605,7 +4076,9 @@ declare namespace chrome { } interface WebAuthFlowOptions { - /** The URL that initiates the auth flow. */ + /** + * The URL that initiates the auth flow. + */ url: string; /** * Optional. @@ -2616,75 +4089,97 @@ declare namespace chrome { interactive?: boolean; } - interface SignInChangeEvent extends chrome.events.Event<(account: AccountInfo, signedIn: boolean) => void> { } - /** + * @requires(dev) **Dev channel only.** + * @description * Retrieves a list of AccountInfo objects describing the accounts present on the profile. * getAccounts is only supported on dev channel. - * Dev channel only. */ - export function getAccounts(callback: (accounts: AccountInfo[]) => void): void; + function getAccounts(callback: (accounts: AccountInfo[]) => void): void; + /** - * Gets an OAuth2 access token using the client ID and scopes specified in the oauth2 section of manifest.json. - * The Identity API caches access tokens in memory, so it's ok to call getAuthToken non-interactively any time a token is required. The token cache automatically handles expiration. - * For a good user experience it is important interactive token requests are initiated by UI in your app explaining what the authorization is for. Failing to do this will cause your users to get authorization requests, or Chrome sign in screens if they are not signed in, with with no context. In particular, do not use getAuthToken interactively when your app is first launched. + * Gets an OAuth2 access token using the client ID and + * scopes specified in the oauth2 section of manifest.json. + * + * The Identity API caches access tokens in memory, + * so it's ok to call getAuthToken non-interactively any time a token is required. + * The token cache automatically handles expiration. + * + * For a good user experience it is important interactive token requests are initiated by + * UI in your app explaining what the authorization is for. Failing to do this will cause + * your users to get authorization requests, or Chrome sign in screens if they are not + * signed in, with with no context. In particular, do not use getAuthToken interactively + * when your app is first launched. + * * @param details Token options. - * @param callback Called with an OAuth2 access token as specified by the manifest, or undefined if there was an error. - * If you specify the callback parameter, it should be a function that looks like this: - * function(string token) {...}; + * @param [callback] Called with an OAuth2 access token as specified by the manifest, + * or undefined if there was an error. */ - export function getAuthToken(details: TokenDetails, callback?: (token: string) => void): void; + function getAuthToken(details: TokenDetails, callback?: (token: string) => void): void; + /** * Retrieves email address and obfuscated gaia id of the user signed into a profile. - * This API is different from identity.getAccounts in two ways. The information returned is available offline, and it only applies to the primary account for the profile. + * This API is different from identity.getAccounts in two ways. + * The information returned is available offline, and it only applies to the primary account for the profile. * @since Chrome 37. */ - export function getProfileUserInfo(callback: (userInfo: UserInfo) => void): void; + function getProfileUserInfo(callback: (userInfo: UserInfo) => void): void; + /** * Removes an OAuth2 access token from the Identity API's token cache. - * If an access token is discovered to be invalid, it should be passed to removeCachedAuthToken to remove it from the cache. The app may then retrieve a fresh token with getAuthToken. + * If an access token is discovered to be invalid, + * it should be passed to removeCachedAuthToken to remove it from the cache. + * The app may then retrieve a fresh token with getAuthToken. * @param details Token information. * @param callback Called when the token has been removed from the cache. - * If you specify the callback parameter, it should be a function that looks like this: - * function() {...}; */ - export function removeCachedAuthToken(details: TokenInformation, callback?: () => void): void; + function removeCachedAuthToken(details: TokenInformation, callback?: () => void): void; + /** * Starts an auth flow at the specified URL. - * This method enables auth flows with non-Google identity providers by launching a web view and navigating it to the first URL in the provider's auth flow. When the provider redirects to a URL matching the pattern https://.chromiumapp.org/*, the window will close, and the final redirect URL will be passed to the callback function. - * For a good user experience it is important interactive auth flows are initiated by UI in your app explaining what the authorization is for. Failing to do this will cause your users to get authorization requests with no context. In particular, do not launch an interactive auth flow when your app is first launched. + * This method enables auth flows with non-Google identity providers by launching + * a web view and navigating it to the first URL in the provider's auth flow. + * When the provider redirects to a URL matching the pattern https://.chromiumapp.org/*, + * the window will close, and the final redirect URL will be passed to the callback function. + * For a good user experience it is important interactive auth flows are initiated by UI in + * your app explaining what the authorization is for. Failing to do this will cause your + * users to get authorization requests with no context. + * In particular, do not launch an interactive auth flow when your app is first launched. * @param details WebAuth flow options. * @param callback Called with the URL redirected back to your application. * The callback parameter should be a function that looks like this: * function(string responseUrl) {...}; */ - export function launchWebAuthFlow(details: WebAuthFlowOptions, callback: (responseUrl?: string) => void): void; + function launchWebAuthFlow(details: WebAuthFlowOptions, callback: (responseUrl?: string) => void): void; + /** * Generates a redirect URL to be used in launchWebAuthFlow. * The generated URLs match the pattern https://.chromiumapp.org/*. * @since Chrome 33. - * @param path Optional. The path appended to the end of the generated URL. + * @param path The path appended to the end of the generated URL. */ - export function getRedirectURL(path?: string): string; + function getRedirectURL(path?: string): string; /** * Fired when signin state changes for an account on the user's profile. * @since Chrome 33. */ - export var onSignInChanged: SignInChangeEvent; + const onSignInChanged: chrome.events.Event<(account: AccountInfo, signedIn: boolean) => void>; } - //////////////////// - // Idle - //////////////////// + ////////// + // Idle // + ////////// /** * Use the chrome.idle API to detect when the machine's idle state changes. - * Permissions: 'idle' - * @since Chrome 6. + * @requires Permissions: 'idle' + * @since Chrome 25. */ namespace idle { - interface IdleStateChangedEvent extends chrome.events.Event<(newState: string) => void> { } - + type IdleState = + 'active' | + 'idle' | + 'locked'; /** * Returns 'locked' if the system is locked, 'idle' if the user has not generated any input for a specified number of seconds, or 'active' otherwise. * @param detectionIntervalInSeconds The system is considered idle if detectionIntervalInSeconds seconds have elapsed since the last user input detected. @@ -2692,88 +4187,481 @@ declare namespace chrome { * @param callback The callback parameter should be a function that looks like this: * function( IdleState newState) {...}; */ - export function queryState(detectionIntervalInSeconds: number, callback: (newState: string) => void): void; + function queryState(detectionIntervalInSeconds: integer, callback: (newState: IdleState) => void): void; /** - * Sets the interval, in seconds, used to determine when the system is in an idle state for onStateChanged events. The default interval is 60 seconds. + * Sets the interval, in seconds, used to determine when the system is in an idle state for + * onStateChanged events. + * The default interval is 60 seconds. * @since Chrome 25. * @param intervalInSeconds Threshold, in seconds, used to determine when the system is in an idle state. */ - export function setDetectionInterval(intervalInSeconds: number): void; + function setDetectionInterval(intervalInSeconds: integer): void; - /** Fired when the system changes to an active, idle or locked state. The event fires with 'locked' if the screen is locked or the screensaver activates, 'idle' if the system is unlocked and the user has not generated any input for a specified number of seconds, and 'active' when the user generates input on an idle system. */ - export var onStateChanged: IdleStateChangedEvent; + /** + * Fired when the system changes to an active, idle or locked state. + * The event fires with 'locked' if the screen is locked or the screensaver activates, + * 'idle' if the system is unlocked and the user has not generated any input for a + * specified number of seconds, and 'active' when the user generates input on an idle system. + */ + const onStateChanged: chrome.events.Event<(newState: IdleState) => void>; } - //////////////////// - // InstanceID - //////////////////// + //////////////// + // InstanceID // + //////////////// /** * Use chrome.instanceID to access the Instance ID service. + * @requires Permissions: 'gcm' * @since Chrome 46 */ namespace instanceID { - /** NOT YET IMPLEMENTED */ + interface TokenParams { + /** + * Identifies the entity that is authorized to access resources associated with this Instance ID. + * It can be a project ID from Google developer console. + */ + authorizedEntity: string; + /** + * Identifies authorized actions that the authorized entity can take. + * E.g. for sending GCM messages, GCM scope should be used. + */ + scope: string; + /** + * Allows including a small number of string key/value pairs that will + * be associated with the token and may be used in processing the request. + */ + options?: { [key: string]: string }; + } + interface DeleteTokenParams { + /** + * The authorized entity that is used to obtain the token. + */ + authorizedEntity: string; + /** + * The scope that is used to obtain the token. + */ + scope: string; + } + /** + * Retrieves an identifier for the app instance. + * The instance ID will be returned by the callback. + * The same ID will be returned as long as the application + * identity has not been revoked or expired. + * @param callback Function called when the retrieval completes. + * It should check runtime.lastError for error when instanceID is empty. + * Will be provided with instanceID: An Instance ID assigned to the app instance. + */ + function getID(callback: (instanceId: string) => void): void; + /** + * Retrieves the time when the InstanceID has been generated. + * The creation time will be returned by the callback. + * @param callback Function called when the retrieval completes. + * It should check runtime.lastError for error when creationTime is zero. + * Provides `creationTime` (double) + * > The time when the Instance ID has been generated, represented in milliseconds since the epoch. + */ + function getCreationTime(callback: (creationTime: number) => void): void; + /** + * Return a token that allows the authorized entity to access the service defined by scope. + * @param getTokenParams Parameters for getToken. + * @param callback Function called when the retrieval completes. It should check runtime.lastError for error when token is empty. + */ + function getToken(getTokenParams: TokenParams, callback: (token: string) => void): void; + /** + * Revokes a granted token. + * @param deleteTokenParams Parameters for deleteToken. + * @param callback Function called when the token deletion completes. + * The token was revoked successfully if runtime.lastError is not set. + */ + function deleteToken(deleteTokenParams: DeleteTokenParams, callback: () => void): void; + /** + * Fired when all the granted tokens need to be refreshed. + * @param callback Function called when the deletion completes. + * The instance identifier was revoked successfully if runtime.lastError is not set. + */ + function deleteID(callback: () => void): void; + /** Fired when all the granted tokens need to be refreshed. */ + const onTokenRefresh: chrome.events.Event<() => void>; + } + + //////////////// + // Management // + //////////////// + /** + * The chrome.management API provides ways to manage the list of extensions/apps + * that are installed and running. It is particularly useful for extensions that + * override the built-in New Tab page. + * @requires Permissions: "management" + */ + namespace management { + /** Information about an installed extension, app, or theme. */ + interface ExtensionInfo { + /** + * Optional. + * A reason the item is disabled. + * @since Chrome 17. + */ + disabledReason?: string; + /** Optional. The launch url (only present for apps). */ + appLaunchUrl?: string; + /** + * The description of this extension, app, or theme. + * @since Chrome 9. + */ + description: string; + /** + * Returns a list of API based permissions. + * @since Chrome 9. + */ + permissions: string[]; + /** + * Optional. + * A list of icon information. Note that this just reflects what was declared in the manifest, and the actual image at that url may be larger or smaller than what was declared, so you might consider using explicit width and height attributes on img tags referencing these images. See the manifest documentation on icons for more details. + */ + icons?: IconInfo[]; + /** + * Returns a list of host based permissions. + * @since Chrome 9. + */ + hostPermissions: string[]; + /** Whether it is currently enabled or disabled. */ + enabled: boolean; + /** + * Optional. + * The URL of the homepage of this extension, app, or theme. + * @since Chrome 11. + */ + homepageUrl?: string; + /** + * Whether this extension can be disabled or uninstalled by the user. + * @since Chrome 12. + */ + mayDisable: boolean; + /** + * How the extension was installed. + * @since Chrome 22. + */ + installType: string; + /** The version of this extension, app, or theme. */ + version: string; + /** The extension's unique identifier. */ + id: string; + /** + * Whether the extension, app, or theme declares that it supports offline. + * @since Chrome 15. + */ + offlineEnabled: boolean; + /** + * Optional. + * The update URL of this extension, app, or theme. + * @since Chrome 16. + */ + updateUrl?: string; + /** + * The type of this extension, app, or theme. + * @since Chrome 23. + */ + type: 'packaged_app' | string; + /** The url for the item's options page, if it has one. */ + optionsUrl: string; + /** The name of this extension, app, or theme. */ + name: string; + /** + * A short version of the name of this extension, app, or theme. + * @since Chrome 31. + */ + shortName: string; + /** + * True if this is an app. + * @deprecated since Chrome 33. Please use management.ExtensionInfo.type. + */ + isApp: boolean; + /** + * Optional. + * The app launch type (only present for apps). + * @since Chrome 37. + */ + launchType?: string; + /** + * Optional. + * The currently available launch types (only present for apps). + * @since Chrome 37. + */ + availableLaunchTypes?: string[]; + } + + /** Information about an icon belonging to an extension, app, or theme. */ + interface IconInfo { + /** The URL for this icon image. To display a grayscale version of the icon (to indicate that an extension is disabled, for example), append ?grayscale=true to the URL. */ + url: string; + /** A number representing the width and height of the icon. Likely values include (but are not limited to) 128, 48, 24, and 16. */ + size: number; + } + + interface UninstallOptions { + /** + * Optional. + * Whether or not a confirm-uninstall dialog should prompt the user. Defaults to false for self uninstalls. If an extension uninstalls another extension, this parameter is ignored and the dialog is always shown. + */ + showConfirmDialog?: boolean; + } + + interface ManagementDisabledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> { } + + interface ManagementUninstalledEvent extends chrome.events.Event<(id: string) => void> { } + + interface ManagementInstalledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> { } + + interface ManagementEnabledEvent extends chrome.events.Event<(info: ExtensionInfo) => void> { } + + /** + * Enables or disables an app or extension. + * @param id This should be the id from an item of management.ExtensionInfo. + * @param enabled Whether this item should be enabled or disabled. + * @param [callback] + */ + function setEnabled(id: string, enabled: boolean, callback?: () => void): void; + /** + * Returns a list of permission warnings for the given extension id. + * @since Chrome 15. + * @param id The ID of an already installed extension. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function(array of string permissionWarnings) {...}; + */ + function getPermissionWarningsById(id: string, callback?: (permissionWarnings: string[]) => void): void; + /** + * Returns information about the installed extension, app, or theme that has the given ID. + * @param id The ID from an item of management.ExtensionInfo. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function( ExtensionInfo result) {...}; + */ + function get(id: string, callback?: (result: ExtensionInfo) => void): void; + /** + * Returns a list of information about installed extensions and apps. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function(array of ExtensionInfo result) {...}; + */ + function getAll(callback?: (result: ExtensionInfo[]) => void): void; + /** + * Returns a list of permission warnings for the given extension manifest string. + * Note: This function can be used without requesting the 'management' permission in the manifest. + * @param manifestStr Extension manifest JSON string. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function(array of string permissionWarnings) {...}; + */ + function getPermissionWarningsByManifest(manifestStr: string, callback?: (permissionWarnings: string[]) => void): void; + /** + * Launches an application. + * @param id The extension id of the application. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function() {...}; + */ + function launchApp(id: string, callback?: () => void): void; + /** + * Uninstalls a currently installed app or extension. + * @since Chrome 21. + * @param id This should be the id from an item of management.ExtensionInfo. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function() {...}; + */ + function uninstall(id: string, options?: UninstallOptions, callback?: () => void): void; + /** + * Uninstalls a currently installed app or extension. + * @deprecated since Chrome 21. The options parameter was added to this function. + * @param id This should be the id from an item of management.ExtensionInfo. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function() {...}; + */ + function uninstall(id: string, callback?: () => void): void; + /** + * Returns information about the calling extension, app, or theme. Note: This function can be used without requesting the 'management' permission in the manifest. + * @since Chrome 39. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function( ExtensionInfo result) {...}; + */ + function getSelf(callback?: (result: ExtensionInfo) => void): void; + /** + * Uninstalls the calling extension. + * Note: This function can be used without requesting the 'management' permission in the manifest. + * @since Chrome 26. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function() {...}; + */ + function uninstallSelf(options?: UninstallOptions, callback?: () => void): void; + /** + * Uninstalls the calling extension. + * Note: This function can be used without requesting the 'management' permission in the manifest. + * @since Chrome 26. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function() {...}; + */ + function uninstallSelf(callback?: () => void): void; + /** + * Display options to create shortcuts for an app. On Mac, only packaged app shortcuts can be created. + * @since Chrome 37. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function() {...}; + */ + function createAppShortcut(id: string, callback?: () => void): void; + /** + * Set the launch type of an app. + * @since Chrome 37. + * @param id This should be the id from an app item of management.ExtensionInfo. + * @param launchType The target launch type. Always check and make sure this launch type is in ExtensionInfo.availableLaunchTypes, because the available launch types vary on different platforms and configurations. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function() {...}; + */ + function setLaunchType(id: string, launchType: string, callback?: () => void): void; + /** + * Generate an app for a URL. Returns the generated bookmark app. + * @since Chrome 37. + * @param url The URL of a web page. The scheme of the URL can only be "http" or "https". + * @param title The title of the generated app. + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: + * function( ExtensionInfo result) {...}; + */ + function generateAppForLink(url: string, title: string, callback?: (result: ExtensionInfo) => void): void; + + /** Fired when an app or extension has been disabled. */ + var onDisabled: ManagementDisabledEvent; + /** Fired when an app or extension has been uninstalled. */ + var onUninstalled: ManagementUninstalledEvent; + /** Fired when an app or extension has been installed. */ + var onInstalled: ManagementInstalledEvent; + /** Fired when an app or extension has been enabled. */ + var onEnabled: ManagementEnabledEvent; } //////////////////// // mDNS //////////////////// /** - * Use the chrome.mdns API to discover services over mDNS. This comprises a subset of the features of the NSD spec: http://www.w3.org/TR/discovery-api/ + * Use the chrome.mdns API to discover services over mDNS. + * This comprises a subset of the features of the NSD spec: + * @see[NSD Spec]{@link http://www.w3.org/TR/discovery-api/} + * @requires Permissions: 'mdns' * @since Chrome 31 */ namespace mdns { - /** NOT YET IMPLEMENTED */ + interface Service { + /** The service name of an mDNS advertised service, .. */ + serviceName: string; + /** The host:port pair of an mDNS advertised service. */ + serviceHostPort: string; + /** The IP address of an mDNS advertised service. */ + ipAddress: string; + /** Metadata for an mDNS advertised service. */ + serviceData: string[]; + } + /** + * The maximum number of service instances that will be + * included in onServiceList events. If more instances + * are available, they may be truncated from the + * onServiceList event. + * @default 2048 + * @since Chrome 44. + */ + const MAX_SERVICE_INSTANCES_PER_EVENT: number; + /** + * Immediately issues a multicast DNS query for all service types. + * |callback| is invoked immediately. + * At a later time, queries will be sent, + * and any service events will be fired. + * @since Chrome 45. + * @param callback Callback invoked after ForceDiscovery() has started. + */ + function forceDiscovery(callback: () => void): void; + /** + * Event fired to inform clients of the current complete + * set of known available services. Clients should only + * need to store the list from the most recent event. + * The service type that the extension is interested in + * discovering should be specified as the event filter + * with the 'serviceType' key. Not specifying an event + * filter will not start any discovery listeners. + */ + const onServiceList: chrome.events.Event<(services: Service[]) => void>; + } //////////////////// // Media Galleries //////////////////// + /** + * Use the chrome.mediaGalleries API to access media files (audio, images, video) + * from the user's local disks (with the user's consent). + * @since Available since Chrome 24. + * @requires Permissions: {'mediaGalleries': ['accessType1' | 'accessType2', ...]} + * {'mediaGalleries': ['accessType1' | 'accessType2', ..., 'allAutoDetected']} + * @see[More information]{@link https://developer.chrome.com/apps/mediaGalleries} + */ namespace mediaGalleries { + type Interactive = + 'no' | + 'yes' | + 'if_needed'; interface MediaFileSystemsOptions { - interactive?: 'no' | 'yes' | 'if_needed'; + /** + * Whether to prompt the user for permission to additional media galleries before returning + * the permitted set. Default is silent. If the value 'yes' is passed, or if the application + * has not been granted access to any media galleries and the value 'if_needed' is passed, + * then the media gallery configuration dialog will be displayed. + * + * **no** + * Do not act interactively. + * **yes** + * Ask the user to manage permitted media galleries. + * **if_needed** + * Ask the user to manage permitted galleries only if the return set would otherwise be empty. + */ + interactive?: Interactive; } - interface MediaFileSystemMetadata { + /** The name of the file system. */ name: string; + /** A unique and persistent id for the media gallery. */ galleryId: string; + /** If the media gallery is on a removable device, a unique id for the device while the device is online. */ deviceId?: string; + /** True if the media gallery is on a removable device. */ isRemovable: boolean; + /** True if the device the media gallery is on was detected as a media device. i.e. a PTP or MTP device, or a DCIM directory is present. */ isMediaDevice: boolean; + /** True if the device is currently available. */ isAvailable: boolean; } + type MetadataOptionsType = + 'all' | + 'mimeTypeAndTags' | + 'mimeTypeOnly'; + interface MetadataOptions { - metadataType: 'all' | 'mimeTypeAndTags' | 'mimeTypeOnly'; + metadataType: MetadataOptionsType; } interface RawTag { + /** + * Describes format of container or codec of stream, i.e. 'mp3' | 'h264'. + */ type: string; + /** + * An unfiltered string->string dictionary of tags for the stream. + */ tags: { [name: string]: string; }; } interface Metadata { - // The browser sniffed mime type. + /** The browser sniffed mime type. */ mimeType: string; - // Defined for images and video. In pixels. - height?: number; - width?: number; - // Defined for images only. - xResolution?: number; - yResolution?: number; - // Defined for audio and video. In seconds. - duration?: number; - // Defined for images and video. In degrees. - rotation?: number; - // Defined for images only. - cameraMake?: string; - cameraModel?: string; - exposureTimeSeconds?: number; - flashFired?: boolean; - fNumber?: number; - focalLengthMm?: number; - isoEquivalent?: number; - // Defined for audio and video only. + /** Defined for images and video. In pixels. */ + height?: integer; + width?: integer; + /** Defined for audio and video. In seconds. */ + duration?: integer; + /** Defined for images and video. In degrees. */ + rotation?: integer; + /** Defined for audio and video only. */ album?: string; artist?: string; comment?: string; @@ -2783,9 +4671,16 @@ declare namespace chrome { language?: string; title?: string; track?: number; - // All the metadata in the media file. For formats with multiple streams, stream order will be preserved. Container metadata is the first element. + /** + * All the metadata in the media file. + * For formats with multiple streams, stream order will be preserved. + * Container metadata is the first element. + */ rawTags: RawTag[]; - // The images embedded in the media file's metadata. This is most often used for album art or video thumbnails. + /** + * The images embedded in the media file's metadata. + * This is most often used for album art or video thumbnails. + */ attachedImages: Blob[]; } @@ -2794,167 +4689,793 @@ declare namespace chrome { success: boolean; } + type GalleryChangedType = + 'contents_changed' | + 'watch_dropped'; + interface GalleryChangedEventArgs { - type: 'contents_changed' | 'watch_dropped'; + type: GalleryChangedType; galleryId: string; } + type ScanProgressType = + 'start' | + 'cancel' | + 'finish' | + 'error'; + interface ScanProgressEventArgs { - // The type of progress event, i.e. start, finish, etc. - type: 'start' | 'cancel' | 'finish' | 'error'; - // The number of Galleries found. - galleryCount?: number; - // Appoximate number of media files found; some file types can be either audio or video and are included in both counts. - audioCount?: number; - imageCount?: number; - videoCount?: number; + /** The type of progress event, i.e. start, finish, etc. */ + type: ScanProgressType; + /** The number of Galleries found. */ + galleryCount?: integer; + /** + * Appoximate number of media files found; + * some file types can be either audio or video + * and are included in both counts. + */ + audioCount?: integer; + imageCount?: integer; + videoCount?: integer; } - export function getMediaFileSystems(callback: (mediaFileSystems: FileSystem[]) => void): void; - export function getMediaFileSystems(options: MediaFileSystemsOptions, callback: (mediaFileSystems: FileSystem[]) => void): void; - export function addUserSelectedFolder(callback: (mediaFileSystems: FileSystem[], selectedFileSystemName: string) => void): void; - export function dropPermissionForMediaFileSystem(galleryId: string, callback?: () => void): void; - export function startMediaScan(): void; - export function cancelMediaScan(): void; - export function addScanResults(callback: (mediaFileSystems: FileSystem[]) => void): void; - export function getMediaFileSystemMetadata(mediaFileSystem: FileSystem): MediaFileSystemMetadata; - export function getAllMediaFileSystemMetadata(callback: (metadatas: MediaFileSystemMetadata[]) => void): void; - export function getMetadata(mediaFile: Blob, callback: (metadata: Metadata) => void): void; - export function getMetadata(mediaFile: Blob, options: MetadataOptions, callback: (metadata: Metadata) => void): void; - export function addGalleryWatch(galleryId: string, callback: (result: GalleryWatchResult) => void): void; - export function removeGalleryWatch(galleryId: string): void; - export function getAllGalleryWatch(callback: (galleryIds: string[]) => void): void; - export function removeAllGalleryWatch(): void; - - export var onGalleryChanged: chrome.events.Event<(args: GalleryChangedEventArgs) => void>; - export var onScanProgress: chrome.events.Event<(args: ScanProgressEventArgs) => void>; + /** + * Get the media galleries configured in this user agent. + * If none are configured or available, the callback will receive an empty array. + */ + function getMediaFileSystems(callback: (mediaFileSystems: FileSystem[]) => void): void; + /** + * Get the media galleries configured in this user agent. + * If none are configured or available, the callback will receive an empty array. + */ + function getMediaFileSystems(options: MediaFileSystemsOptions, callback: (mediaFileSystems: FileSystem[]) => void): void; + /** + * Present a directory picker to the user and add the selected directory as a gallery. + * If the user cancels the picker, selectedFileSystemName will be empty. + * A user gesture is required for the dialog to display. + * Without a user gesture, the callback will run as though the user canceled. + * @since Since Chrome 34. + */ + function addUserSelectedFolder(callback: (mediaFileSystems: FileSystem[], selectedFileSystemName: string) => void): void; + /** + * @deprecated Deprecated since Chrome 51. The user can manually drop access to galleries via the permissions dialog. + * @description Give up access to a given media gallery. + */ + function dropPermissionForMediaFileSystem(galleryId: string, callback?: () => void): void; + /** + * @deprecated Deprecated since Chrome 51. The mediaGalleries API no longer supports scanning. + * @description + * Start a scan of the user's hard disks for directories containing media. + * The scan may take a long time so progress and completion is communicated by events. + * No permission is granted as a result of the scan, see addScanResults. + */ + function startMediaScan(): void; + /** + * @deprecated Deprecated since Chrome 51. The mediaGalleries API no longer supports scanning. + * @description + * Cancel any pending media scan. + * Well behaved apps should provide a way for the user to cancel scans they start. + */ + function cancelMediaScan(): void; + /** + * @deprecated Deprecated since Chrome 51. The mediaGalleries API no longer supports scanning. + * @description + * Show the user the scan results and let them add any or all of them as galleries. + * This should be used after the 'finish' onScanProgress() event has happened. + * All galleries the app has access to are returned, not just the newly added galleries. + */ + function addScanResults(callback: (mediaFileSystems: FileSystem[]) => void): void; + /** + * Get metadata about a specific media file system + * @since Since Chrome 26. + */ + function getMediaFileSystemMetadata(mediaFileSystem: FileSystem): MediaFileSystemMetadata; + /** + * @deprecated Deprecated since Chrome 51. Use getMediaFileSystemMetadata instead + * Get metadata for all available media galleries. + */ + function getAllMediaFileSystemMetadata(callback: (metadatas: MediaFileSystemMetadata[]) => void): void; + /** + * Gets the media-specific metadata for a media file. + * This should work for files in media galleries as well as other DOM filesystems. + * @since Chrome 38. + */ + function getMetadata(mediaFile: Blob, callback: (metadata: Metadata) => void): void; + /** + * Gets the media-specific metadata for a media file. + * This should work for files in media galleries as well as other DOM filesystems. + * @since Chrome 38. + */ + function getMetadata(mediaFile: Blob, options: MetadataOptions, callback: (metadata: Metadata) => void): void; + /** + * Adds a gallery watch for the gallery with the specified gallery ID. + * The given callback is then fired with a success or failure result. + * @since Chrome 39. + */ + function addGalleryWatch(galleryId: string, callback: (result: GalleryWatchResult) => void): void; + /** + * Removes a gallery watch for the gallery with the specified gallery ID. + * @since Chrome 39. + */ + function removeGalleryWatch(galleryId: string): void; + /** + * @deprecated Deprecated since Chrome 51. Applications should store their own gallery watches as they are added. + * Notifies which galleries are being watched via the given callback. + */ + function getAllGalleryWatch(callback: (galleryIds: string[]) => void): void; + /** + * @deprecated Deprecated since Chrome 51. Use removeGalleryWatch instead. + * Removes all gallery watches. + */ + function removeAllGalleryWatch(): void; + /** + * Fired when a media gallery is changed or a gallery watch is dropped + * @since Since Chrome 38. + */ + const onGalleryChanged: chrome.events.Event<(args: GalleryChangedEventArgs) => void>; + /** + * @deprecated Deprecated since Chrome 51. The mediaGalleries API no longer supports scanning. + * The pending media scan has changed state. See details for more information. + */ + const onScanProgress: chrome.events.Event<(args: ScanProgressEventArgs) => void>; } //////////////////////////////////// // Open Network Configuration (ONC) //////////////////////////////////// /** - * The chrome.networking.onc API is used for configuring network connections (Cellular, Ethernet, VPN, WiFi or WiMAX). This API is available in Chrome OS kiosk sessions. - * Network connection configurations are specified following Open Network Configuration (ONC) specification. - * NOTE: Most dictionary properties and enum values use UpperCamelCase to match the ONC specification instead of the JavaScript lowerCamelCase convention. + * @requires(CrOS kiosk mode) This API is available in Chrome OS kiosk sessions. + * @requires Permissions: 'networking.onc' + * @since Since Chrome 59 + * @description + * The chrome.networking.onc API is used for configuring network connections + * (Cellular, Ethernet, VPN, WiFi or WiMAX). + * Network connection configurations are specified following + * @see[Open Network Configuration (ONC) specification.]{@link https://chromium.googlesource.com/chromium/src/+/master/components/onc/docs/onc_spec.md} + * @description + * **NOTE** + * Most dictionary properties and type values use UpperCamelCase to match + * the ONC specification instead of the JavaScript lowerCamelCase convention. */ namespace networking.onc { - export type ActivationStateType = 'Activated' | 'Activating' | 'NotActivated' | 'PartiallyActivated'; - export type CaptivePortalStatus = 'Unknown' | 'Offline' | 'Online' | 'Portal' | 'ProxyAuthRequired'; - export type ConnectionStateType = 'Connected' | 'Connecting' | 'NotConnected'; - export type IPConfigType = 'DHCP' | 'Static'; - export type NetworkType = 'All' | 'Cellular' | 'Ethernet' | 'VPN' | 'Wireless' | 'WiFi' | 'WiMAX'; - export type ProxySettingsType = 'Direct' | 'Manual' | 'PAC' | 'WPAD'; - interface ManagedBoolean { - /** - * @description The active value currently used by the network configuration manager (e.g. Shill). - * @type {boolean} - * @memberof ManagedBoolean - */ - Active?: boolean, - /** - * @description The source from which the effective property value was determined. - * @type {string} - * @memberof ManagedBoolean - */ - Effective?: string, - /** - * @description The property value provided by the user policy. - * @type {boolean} - * @memberof ManagedBoolean - */ - UserPolicy?: boolean, - /** - * @description The property value provided by the device policy. - * @type {boolean} - * @memberof ManagedBoolean - */ - DevicePolicy?: boolean, - /** - * @description The property value set by the logged in user. Only provided if |UserEditable| is true. - * @type {boolean} - * @memberof ManagedBoolean - */ - UserSettings?: boolean, - /** - * @description The value set for all users of the device. Only provided if |DeviceEditiable| is true. - * @type {boolean} - * @memberof ManagedBoolean - */ - SharedSettings?: boolean, - /** - * @description Whether a UserPolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). Defaults to false. - * @type {boolean} - * @memberof ManagedBoolean - */ - UserEditable?: boolean, - /** - * @description Whether a DevicePolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). Defaults to false. - * @type {boolean} - * @memberof ManagedBoolean - */ - DeviceEditable?: boolean + type ActivationStateType = 'Activated' | 'Activating' | 'NotActivated' | 'PartiallyActivated'; + type CaptivePortalStatus = 'Unknown' | 'Offline' | 'Online' | 'Portal' | 'ProxyAuthRequired'; + type ConnectionStateType = 'Connected' | 'Connecting' | 'NotConnected' + type IPConfigType = 'DHCP' | 'Static' + type NetworkType = 'All' | 'Cellular' | 'Ethernet' | 'VPN' | 'Wireless' | 'WiFi' | 'WiMAX' + type ProxySettingsType = 'Direct' | 'Manual' | 'PAC' | 'WPAD'; + /** + * Partial classes for internal use + * @internal + * @private + */ + namespace _internal_ { + type ObjectFunction = 'unknown' | 'getter' | 'setter'; + interface NetworkConfigBase< + M extends ManagedObject = 'unmanaged', + IF extends InterfaceType = 'full', + OF extends ObjectFunction = 'unknown'> { + /** For cellular networks, cellular network properties. */ + Cellular?: IF extends 'partial' ? CellularBase : CellularProperties; + /** For Ethernet networks, the Ethernet network properties. */ + Ethernet?: IF extends 'partial' ? { Authentication: string; } : EthernetProperties; + /** The network GUID. */ + GUID?: string; + /** The network's IP address configuration type. */ + IPAddressConfigType?: M extends 'managed' ? ManagedIPConfigType : IPConfigType; + /** A user friendly network name. */ + Name?: M extends 'managed' ? ManagedDOMString : string; + /** The IP configuration type for the name servers used by the network. */ + NameServersConfigType?: M extends 'managed' ? ManagedIPConfigType : IPConfigType; + /** The network priority. */ + Priority?: M extends 'managed' ? ManagedLong : integer; + /** The network type. */ + Type?: NetworkType; + /** For VPN networks, the network VPN properties. */ + VPN?: IF extends 'partial' ? { Type: string; } : VPNProperties; + /** For WiFi networks, the network WiFi properties. */ + WiFi?: IF extends 'partial' ? WiFiPropertiesBase : WiFiProperties; + /** For WiMAX networks, the network WiMAX properties. */ + WiMAX?: IF extends 'partial' ? { SignalStrength?: integer } : WiMAXProperties; + } } - interface ManagedLong { + interface ManagedType { + /** The active value currently used by the network configuration manager (e.g. Shill). */ + Active?: T; + /** The source from which the effective property value was determined. */ + Effective?: string; + /** The property value provided by the user policy. */ + UserPolicy?: T; + /** The property value provided by the device policy. */ + DevicePolicy?: T; + /** The property value set by the logged in user. Only provided if *UserEditable* is true. */ + UserSetting?: T; + /** The value set for all users of the device. Only provided if *DeviceEditiable* is true. */ + SharedSetting?: T; /** - * @description The active value currently used by the network configuration manager (e.g. Shill). - * @type {number} - * @memberof ManagedLong + * Whether a UserPolicy for the property exists and allows the property + * to be edited (i.e. the policy set recommended property value). + * @default false */ - Active?: number, + UserEditable?: boolean; /** - * @description The source from which the effective property value was determined. - * @type {string} - * @memberof ManagedLong + * Whether a DevicePolicy for the property exists and allows the property + * to be edited (i.e. the policy set recommended property value). + * @default false */ - Effective?: string, - /** - * @description The property value provided by the user policy. - * @type {number} - * @memberof ManagedLong - */ - UserPolicy?: number, - /** - * @description The property value provided by the device policy. - * @type {number} - * @memberof ManagedLong - */ - DevicePolicy?: number, - /** - * @description The property value set by the logged in user. Only provided if |UserEditable| is true. - * @type {number} - * @memberof ManagedLong - */ - UserSettings?: number, - /** - * @description The value set for all users of the device. Only provided if |DeviceEditiable| is true. - * @type {number} - * @memberof ManagedLong - */ - SharedSettings?: number, - /** - * @description Whether a UserPolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). Defaults to false. - * @type {boolean} - * @memberof ManagedLong - */ - UserEditable?: boolean, - /** - * @description Whether a DevicePolicy for the property exists and allows the property to be edited (i.e. the policy set recommended property value). Defaults to false. - * @type {boolean} - * @memberof ManagedLong - */ - DeviceEditable?: boolean + DeviceEditable?: boolean; } + interface ManagedBoolean extends ManagedType { } + interface ManagedLong extends ManagedType { } + interface ManagedDOMString extends ManagedType { } + interface ManagedDOMStringList extends ManagedType { } + interface ManagedIPConfigType extends ManagedType { } + + interface CellularProviderProperties { + /** The operator name. */ + Name: string; + /** Cellular network ID as a simple concatenation of the network's MCC (Mobile Country Code) and MNC (Mobile Network Code). */ + Code: string; + /** The two-letter country code. */ + Country?: string; + } + interface IssuerSubjectPattern { + /** If set, the value against which to match the certificate subject's common name. */ + CommonName?: string; + /** If set, the value against which to match the certificate subject's common location. */ + Locality?: string; + /** + * If set, the value against which to match the certificate subject's organizations. + * At least one organization should match the value. + */ + Organization?: string; + /** + * If set, the value against which to match the certificate subject's organizational units. + * At least one organizational unit should match the value. + */ + OrganizationalUnit?: string; + } + interface CertPattern { + /** + * List of URIs to which the user can be directed in case + * no certificates that match this pattern are found. + */ + EnrollmentURI?: string[]; + /** + * If set, pattern against which X.509 issuer settings should be matched. + */ + Issuer?: IssuerSubjectPattern; + /** + * List of certificate issuer CA certificates. + * A certificate must be signed by one of them in order to match this pattern. + */ + IssuerCARef?: string[]; + /** + * If set, pattern against which X.509 subject settings should be matched. + */ + IssuerSubjectPattern?: IssuerSubjectPattern; + } + type ClientCertType = 'Ref' | 'Pattern'; + interface EAPProperties { + AnonymousIdentity?: string; + ClientCertPattern?: CertPattern; + /** @since Chrome 60. */ + ClientCertPKCS11Id?: string; + ClientCertRef?: string; + ClientCertType?: ClientCertType; + Identity?: string; + Inner?: string; + /** The outer EAP type. Required by ONC, but may not be provided when translating from Shill. */ + Outer?: string; + Password?: string; + SaveCredentials?: boolean; + ServerCAPEMs?: string[]; + ServerCARefs?: string[]; + /** @since Chrome 60. */ + SubjectMatch?: ManagedDOMString; + UseProactiveKeyCaching?: boolean; + UseSytemCAs?: boolean; + } + interface FoundNetworkProperties { + /** Network availability. */ + Status: string; + /** Network ID. */ + NetworkId: string; + /** Access technology used by the network. */ + Technology: string; + /** The network operator's short-format name. */ + ShortName?: string; + /** The network operator's long-format name. */ + LongName?: string; + } + type IPConfigurationType = 'IPv4' | 'IPv6'; + interface IPConfigProperties { + /** Gateway address used for the IP configuration. */ + Gateway?: S; + /** The IP address for a connection. Can be IPv4 or IPv6 address, depending on value of Type. */ + IPAddress?: S; + /** Array of addresses used for name servers. */ + NameServers?: SL; + /** The routing prefix. */ + RoutingPrefix?: L; + /** The IP configuration type. Can be IPv4 or IPv6. */ + Type?: M extends 'managed' ? ManagedType : IPConfigurationType; + /** The URL for WEb Proxy Auto-Discovery, as reported over DHCP. */ + WebProxyAutoDiscoveryUrl?: S; + } + interface PaymentPortalPost { + /** The HTTP method to use for the payment portal. */ + Method: 'POST'; + /** The post data to send to the payment portal. */ + PostData?: string; + /** The payment portal URL. */ + Url?: string; + } + interface PaymentPortal { + /** The HTTP method to use for the payment portal. */ + Method: string; + /** The payment portal URL. */ + Url?: string; + } + interface ProxyLocation { + /** The proxy IP address host. */ + Host?: string; + /** The port to use for the proxy */ + Port?: integer; + } + interface ManagedProxyLocation { + /** The proxy IP address host. */ + Host?: ManagedDOMString; + /** The port to use for the proxy */ + Port?: ManagedLong; + } + interface ManualProxySettings { + /** Settings for HTTP proxy. */ + HTTPProxy?: P; + /** Settings for secure HTTP proxy. */ + SecureHTTPProxy?: P; + /** Settings for FTP proxy. */ + FTPProxy?: P; + /** Settings for SOCKS proxy. */ + SOCKS?: P; + } + interface ProxySettings { + /** The type of proxy settings. */ + Type: M extends 'managed' ? ManagedType : ProxySettingsType; + /** Manual proxy settings - used only for *Manual* proxy settings. */ + Manual?: ManualProxySettings; + /** Domains and hosts for which manual proxy settings are excluded. */ + ExcludeDomains?: SL; + /** URL for proxy auto-configuration file. */ + PAC?: S; + } + interface SIMLockStatus { + /** The status of SIM lock - possible values are 'sim-pin', 'sim-puk' and ''. */ + LockType: 'sim-pin' | 'sim-puk' | ''; + /** Whether SIM lock is enabled. */ + LockEnabled: boolean; + /** Number of PIN lock tries allowed before PUK is required to unlock the SIM. */ + RetriesLeft?: integer; + } + interface ThirdPartyVPNProperties { + /** ID of the third-party VPN provider extension. */ + ExtensionID: string; + /** The VPN provider name. */ + ProviderName?: string; + } + interface ManagedThirdPartyVPNProperties { + /** ID of the third-party VPN provider extension. */ + ExtensionID: ManagedDOMString; + /** The VPN provider name. */ + ProviderName?: string; + } + interface CellularBase { + /** Carrier account activation state. */ + ActivationState?: ActivationStateType; + /** If the modem is registered on a network, the network technology currently in use. */ + NetworkTechnology?: string; + /** The roaming state of the cellular modem on the current network. */ + RoamingState?: string; + /** Whether a SIM card is present. */ + SIMPresent?: boolean; + /** The current network signal strength. */ + SignalStrength?: integer; + } + interface CellularProperties extends CellularBase { + /** Whether the cellular network should be connected automatically (when in range). */ + AutoConnect?: M extends 'managed' ? ManagedBoolean : boolean; + /** The cellular network activation type. */ + ActivationType?: string; + /** Whether roaming is allowed for the network. */ + AllowRoaming?: boolean; + /** The name of the carrier for which the cellular device is configured. */ + Carrier?: M extends 'managed' ? ManagedDOMString : string; + /** Cellular device technology family - CDMA or GSM. */ + Family?: 'CDMA' | 'GSM'; + /** The firmware revision loaded in the cellular modem. */ + FirmwareRevision?: string; + /** The list of networks found during the most recent network scan. */ + FoundNetworks?: FoundNetworkProperties[]; + /** The cellular modem hardware revision. */ + HardwareRevision?: string; + /** Information about the operator that issued the SIM card currently installed in the modem. */ + HomeProvider?: CellularProviderProperties; + /** The cellular modem manufacturer. */ + MAnufacturer?: string; + /** The cellular modem model ID. */ + ModelID?: string; + /** Online payment portal a user can use to sign-up for or modify a mobile data plan. */ + PaymentPortal?: PaymentPortal | PaymentPortalPost; + /** The revision of the Preferred Roaming List loaded in the modem. */ + PRLVersion?: integer; + /** + * @since Chrome 63. + * True when a cellular network scan is in progress. + */ + Scanning?: boolean; + /** Information about the operator on whose network the modem is currently registered. */ + ServingOperator?: CellularProviderProperties; + /** The state of SIM lock for GSM family networks. */ + SIMLockStatus?: SIMLockStatus; + /** Whether the cellular network supports scanning. */ + SupportNetworkScan?: boolean; + /** A list of supported carriers. */ + SupportedCarriers?: string[]; + } + type EthernetAuthenticationType = 'None' | '8021X'; + interface EthernetProperties { + /** Whether the Ethernet network should be connected automatically. */ + AutoConnect?: M extends 'managed' ? ManagedBoolean : boolean; + /** The authentication used by the Ethernet network. Possible values are None and 8021X. */ + Authentication?: M extends 'managed' ? ManagedType : EthernetAuthenticationType; + /** Network's EAP settings. Required for 8021X authentication. */ + EAP?: EAPProperties; + } + interface VPNProperties { + /** Whether the VPN network should be connected automatically. */ + AutoConnect?: B; + /** The VPN host. */ + Host?: S; + /** + * The VPN type. + * This cannot be an enum because of 'L2TP-IPSec'. + * This is optional for NetworkConfigProperties which is passed to + * *setProperties* which may be used to set only specific properties. + */ + Type?: S; + } + interface WiFiPropertiesBase { + /** The BSSID of the associated access point.. */ + BSSID?: string; + /** + * The WiFi service operating frequency in MHz. + * For connected networks, the current frequency on which the network is connected. + * Otherwise, the frequency of the best available BSS. + */ + Frequency?: integer; + /** HEX-encoded copy of the network SSID. */ + HexSSID?: S; + /** The network security type. */ + Security?: S; + /** The network SSID. */ + SSID?: S; + /** The network signal strength. */ + SignalStrength?: integer; + } + interface WiFiProperties + extends WiFiPropertiesBase { + /** + * Whether ARP polling of default gateway is allowed. + * @default true + */ + AllowGatewayARPPolling?: B; + /** Whether the WiFi network should be connected automatically when in range. */ + AutoConnect?: B; + /** The network EAP properties. Required for WEP-8021X and WPA-EAP networks. */ + EAP?: EAPProperties; + /** Contains all operating frequency recently seen for the WiFi network. */ + FrequencyList?: integer[]; + /** Whether the network SSID will be broadcast. */ + HiddenSSID?: B; + /** Signal-to-noise value (in dB) below which roaming to a new network should be attempted. */ + RoamTreshold?: L; + /** + * @since Chrome 66. + * The passphrase for WEP/WPA/WPA2 connections. + * *This property can only be set!* + */ + Passphrase?: OF extends 'setter' ? string : never; + } + interface WiMAXProperties { + /** Whether the network should be connected automatically. */ + AutoConnect?: B; + /** The network EAP properties. */ + EAP?: EAPProperties; + /** The network signal strength. */ + SignalStrength?: integer; + } + type ManagedObject = 'managed' | 'unmanaged'; + type InterfaceType = 'partial' | 'full'; + + interface NetworkConfigProperties + extends _internal_.NetworkConfigBase<'unmanaged', 'full', OF> { } + + interface NetworkProperties< + M extends ManagedObject = 'unmanaged', + IF extends InterfaceType = 'full'> extends _internal_.NetworkConfigBase { + /** Whether the network is connectable. */ + Connectable?: boolean; + /** The network's current connection state. */ + ConnectionState?: ConnectionStateType; + /** The last recorded network error state. */ + ErrorState?: string; + /** The network's IP configuration. */ + IPConfigs?: IPConfigProperties[]; + /** The network's MAC address. */ + MacAddress?: string; + /** The network's proxy settings. */ + ProxySettings?: ProxySettings; + /** + * For a connected network, whether the network connectivity to the Internet is limited, + * e.g. if the network is behind a portal, or a cellular network is not activated. + */ + RestrictedConnectivity?: boolean; + /** The network's static IP configuration. */ + StaticIPConfig?: IPConfigProperties; + /** IP configuration that was received from the DHCP server before applying static IP configuration. */ + SavedIPConfig?: IPConfigProperties; + /** + * Indicates whether and how the network is configured. + * 'None' conflicts with extension code generation, + * so we must use a string for 'Source' instead of a SourceType enum. + */ + Source?: 'Device' | 'DevicePolicy' | 'User' | 'UserPolicy' | 'None'; + } + interface ManagedProperties extends NetworkProperties<'managed'> { } + interface NetworkStateProperties extends NetworkProperties<'unmanaged', 'partial'> { } + + /** Describes which networks to return. */ + interface Filter { + /** The type of networks to return. */ + networkType: NetworkType; + /** + * If true, only include visible (physically connected or in-range) networks. + * @default false + */ + visible?: boolean; + /** + * If true, only include configured (saved) networks. + * @default false + */ + configured?: boolean; + /** + * Maximum number of networks to return. + * Use 0 for no limit + * @default 1000 if unspecified. + * */ + limit?: integer; + } + + /* The current state of the device. */ + type DeviceState = 'Uninitialized' | 'Disabled' | 'Enabling' | 'Enabled' | 'Prohibited'; + + /** A list of devices and their state. */ + interface DeviceStates { + /** Set if the device is enabled. True if the device is currently scanning. */ + Scanning?: boolean; + /** The SIM lock status if Type = Cellular and SIMPresent = True. */ + SIMLockStatus?: SIMLockStatus; + /** Set to the SIM present state if the device type is Cellular. */ + SIMPresent?: boolean; + /** + * The current state of the device. + * + * **Uninitialized** + * - Device is available but not initialized. + * **Disabled** + * - Device is initialized but not enabled. + * **Enabling** + * - Enabled state has been requested but has not completed. + * **Enabled** + * - Device is enabled. + * **Prohibited** + * - Device is prohibited. + */ + State: DeviceState; + /** The network type associated with the device (Cellular, Ethernet, WiFi, or WiMAX). */ + Type: NetworkType; + } + + interface GlobalPolicy { + /** + * If true, only policy networks may auto connect. + * @default false + */ + AllowOnlyPolicyNetworksToAutoconnect?: boolean; + /** + * If true, only policy networks may be connected to + * and no new networks may be added or configured. + * @default false + */ + AllowOnlyPolicyNetworksToConnect?: boolean; + /** + * List of blacklisted networks. + * Connections to blacklisted networks are prohibited. + * Networks can be whitelisted again by specifying an explicit network configuration. + * @default [] + */ + BlacklistedHexSSIDs?: string[]; + } + + /** + * Gets all the properties of the network with id *networkGuid*. + * Includes all properties of the network (read-only and read/write values). + * @param networkGuid The GUID of the network to get properties for. + * @param callback Called with the network properties when received. + */ + function getProperties(networkGuid: string, callback: (result: NetworkProperties) => void): void; + /** + * Gets the merged properties of the network with id networkGuid from the sources: + * User settings, shared settings, user policy, device policy and the currently active settings. + * @param networkGuid The GUID of the network to get properties for. + * @param callback Called with the managed network properties when received. + */ + function getManagedProperties(networkGuid: string, callback: (result: ManagedProperties) => void): void; + /** + * Gets the cached read-only properties of the network with id *networkGuid*. + * This is meant to be a higher performance function than *getProperties*, + * which requires a round trip to query the networking subsystem. + * The following properties are returned for all networks: + * GUID, Type, Name, WiFi.Security. + * Additional properties are provided for visible networks: + * ConnectionState, ErrorState, WiFi.SignalStrength, + * Cellular.NetworkTechnology, Cellular.ActivationState, Cellular.RoamingState. + * @param networkGuid The GUID of the network to get properties for. + * @param callback Called immediately with the network state properties. + */ + function getState(networkGuid: string, callback: (result: NetworkStateProperties) => void): void; + /** + * Sets the properties of the network with id *networkGuid*. + * This is only valid for configured networks (Source != None). + * Unconfigured visible networks should use **createNetwork** instead. + * **In kiosk sessions, calling this method on a shared network will fail.** + * @param networkGuid The GUID of the network to set properties for. + * @param properties The properties to set. + * @param [callback] Called when the operation has completed. + */ + function setProperties(networkGuid: string, properties: NetworkConfigProperties<'setter'>, callback?: () => void): void; + /** + * Creates a new network configuration from properties. + * If a matching configured network already exists, this will fail. + * Otherwise returns the GUID of the new network. + * @param shared If true, share this network configuration with other users. + * Note: This option is exposed only to Chrome's Web UI. + * When called by apps, false is the only allowed value. + * @param properties The properties to configure the new network with. + * @param [callback] Called with the GUID for the new network configuration once the network has been created. + */ + function createNetwork(shared: false, properties: NetworkConfigProperties<'setter'>, callback?: () => void): void; + /** + * Forgets a network configuration by clearing any configured properties for the network with GUID networkGuid. + * This may also include any other networks with matching identifiers (e.g. WiFi SSID and Security). + * If no such configuration exists, an error will be set and the operation will fail. + * **In kiosk sessions, this method will not be able to forget shared network configurations.** + * @param networkGuid The GUID of the network to forget. + * @param [callback] Called when the operation has completed. + */ + function forgetNetwork(networkGuid: string, callback?: () => void): void; + /** + * Returns a list of network objects with the same properties provided by *getState*. + * A filter is provided to specify the type of networks returned and to limit the number of networks. + * Networks are ordered by the system based on their priority, with connected or connecting networks listed first. + * @param callback Called with a dictionary of networks and their state properties when received. + */ + function getNetworks(filter: Filter, callback: (result: NetworkStateProperties[]) => void): void; + /** + * Returns states of available networking devices. + * @param callback Called with a list of devices and their state. + */ + function getDeviceStates(callback: (result: DeviceStates[]) => void): void; + /** + * Enables any devices matching the specified network type. + * Note, the type might represent multiple network types (e.g. 'Wireless'). + * @param networkType The type of network to enable. + */ + function enableNetworkType(networkType: NetworkType): void; + /** + * Disables any devices matching the specified network type. + * Note, the type might represent multiple network types (e.g. 'Wireless'). + * @param networkType The type of network to disable. + */ + function disableNetworkType(networkType: NetworkType): void; + /** + * Requests that the networking subsystem scan for new networks and update the list returned by *getVisibleNetworks*. + * This is only a request: the network subsystem can choose to ignore it. + * If the list is updated, then the *onNetworkListChanged* event will be fired. + */ + function requestNetworkScan(): void; + /** + * Requests that the networking subsystem scan for new networks and update the list returned by *getVisibleNetworks*. + * This is only a request: the network subsystem can choose to ignore it. + * If the list is updated, then the *onNetworkListChanged* event will be fired. + * @param networkType If provided, requests a scan specific to the type. For Cellular a mobile network scan will be requested if supported. + * @since Chrome 63. + */ + function requestNetworkScan(networkType: NetworkType): void; + /** + * @description Starts a connection to the network with networkGuid. + * @param networkGuid The GUID of the network to connect to. + * @param [callback] Creates a new network configuration from properties. + * If a matching configured network already exists, this will fail. + * Otherwise returns the GUID of the new network. + */ + function startConnect(networkGuid: string, callback?: () => void): void; + /** + * @description Starts a disconnect from the network with networkGuid. + * @param networkGuid The GUID of the network to connect to. + * @param [callback] Called when the disconnect request has been sent. See note for *startConnect*. + */ + function startDisconnect(networkGuid: string, callback?: () => void): void; + /** + * Returns captive portal status for the network matching 'networkGuid'. + * @param networkGuid The GUID of the network to get captive portal status for. + * @param callback A callback function that returns the results of the query for network captive portal status. + */ + function getCaptivePortalStatus(networkGuid: string, callback: (result: CaptivePortalStatus) => void): void; + /** + * Gets the global policy properties. + * These properties are not expected to change during a session. + */ + function getGlobalPolicy(callback: (result: GlobalPolicy) => void): void; + + // + // EVENTS + // + + /** + * Fired when the properties change on any of the networks. + * Sends a list of GUIDs for networks whose properties have changed. + */ + const onNetworksChanged: chrome.events.Event<(changes: string[]) => void>; + /** + * Fired when the list of networks has changed. Sends a complete list of GUIDs for all the current networks. + */ + const onNetworkListChanged: chrome.events.Event<(changes: string[]) => void>; + /** + * Fired when the list of devices has changed or any device state properties have changed. + */ + const onDeviceStateListChanged: chrome.events.Event<() => void>; + /** + * Fired when a portal detection for a network completes. + * Sends the GUID of the network and the corresponding captive portal status. + */ + const onPortalDetectionCompleted: chrome.events.Event<(networkGuid: string, status: CaptivePortalStatus) => void>; } - //////////////////// - // Notifications - // https://developer.chrome.com/extensions/notifications - //////////////////// + /////////////////// + // Notifications // + /////////////////// /** - * Use the chrome.notifications API to create rich notifications using templates and show these notifications to users in the system tray. - * Permissions: 'notifications' + * Use the chrome.notifications API to create rich notifications using + * templates and show these notifications to users in the system tray. + * @requires Permissions: 'notifications' * @since Chrome 28. + * @see[Docs]{@link https://developer.chrome.com/extensions/notifications} */ namespace notifications { interface ButtonOptions { @@ -2970,7 +5491,7 @@ declare namespace chrome { } interface NotificationOptions { - /** Optional. Which type of notification to display. Required for notifications.create method. */ + /** Which type of notification to display. Required for notifications.create method. */ type?: string; /** * Optional. @@ -2978,9 +5499,9 @@ declare namespace chrome { * URLs can be a data URL, a blob URL, or a URL relative to a resource within this extension's .crx file Required for notifications.create method. */ iconUrl?: string; - /** Optional. Title of the notification (e.g. sender name for email). Required for notifications.create method. */ + /** Title of the notification (e.g. sender name for email). Required for notifications.create method. */ title?: string; - /** Optional. Main notification content. Required for notifications.create method. */ + /** Main notification content. Required for notifications.create method. */ message?: string; /** * Optional. @@ -2988,13 +5509,13 @@ declare namespace chrome { * @since Chrome 31. */ contextMessage?: string; - /** Optional. Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default. */ + /** Priority ranges from -2 to 2. -2 is lowest priority. 2 is highest. Zero is default. */ priority?: number; - /** Optional. A timestamp associated with the notification, in milliseconds past the epoch (e.g. Date.now() + n). */ + /** A timestamp associated with the notification, in milliseconds past the epoch (e.g. Date.now() + n). */ eventTime?: number; - /** Optional. Text and icons for up to two notification action buttons. */ + /** Text and icons for up to two notification action buttons. */ buttons?: ButtonOptions[]; - /** Optional. Items for multi-item notifications. */ + /** Items for multi-item notifications. */ items?: ItemOptions[]; /** * Optional. @@ -3014,7 +5535,7 @@ declare namespace chrome { * @since Chrome 38. */ appIconMaskUrl?: string; - /** Optional. A URL to the image thumbnail for image-type notifications. URLs have the same restrictions as iconUrl. */ + /** A URL to the image thumbnail for image-type notifications. URLs have the same restrictions as iconUrl. */ imageUrl?: string; /** * Indicates that the notification should remain visible on screen until the user activates or dismisses the notification. @@ -3035,21 +5556,21 @@ declare namespace chrome { interface NotificationShowSettingsEvent extends chrome.events.Event<() => void> { } /** The notification closed, either by the system or by user action. */ - export var onClosed: NotificationClosedEvent; + const onClosed: NotificationClosedEvent; /** The user clicked in a non-button area of the notification. */ - export var onClicked: NotificationClickedEvent; + const onClicked: NotificationClickedEvent; /** The user pressed a button in the notification. */ - export var onButtonClicked: NotificationButtonClickedEvent; + const onButtonClicked: NotificationButtonClickedEvent; /** * The user changes the permission level. * @since Chrome 32. */ - export var onPermissionLevelChanged: NotificationPermissionLevelChangedEvent; + const onPermissionLevelChanged: NotificationPermissionLevelChangedEvent; /** * The user clicked on a link for the app's notification settings. * @since Chrome 32. */ - export var onShowSettings: NotificationShowSettingsEvent; + const onShowSettings: NotificationShowSettingsEvent; /** * Creates and displays a notification. @@ -3061,7 +5582,7 @@ declare namespace chrome { * If you specify the callback parameter, it should be a function that looks like this: * function(string notificationId) {...}; */ - export function create(notificationId: string, options: NotificationOptions, callback?: (notificationId: string) => void): void; + function create(notificationId: string, options: NotificationOptions, callback?: (notificationId: string) => void): void; /** * Creates and displays a notification. * @param notificationId Identifier of the notification. If not set or empty, an ID will automatically be generated. If it matches an existing notification, this method first clears that notification before proceeding with the create operation. @@ -3072,7 +5593,7 @@ declare namespace chrome { * If you specify the callback parameter, it should be a function that looks like this: * function(string notificationId) {...}; */ - export function create(options: NotificationOptions, callback?: (notificationId: string) => void): void; + function create(options: NotificationOptions, callback?: (notificationId: string) => void): void; /** * Updates an existing notification. * @param notificationId The id of the notification to be updated. This is returned by notifications.create method. @@ -3082,7 +5603,7 @@ declare namespace chrome { * If you specify the callback parameter, it should be a function that looks like this: * function(boolean wasUpdated) {...}; */ - export function update(notificationId: string, options: NotificationOptions, callback?: (wasUpdated: boolean) => void): void; + function update(notificationId: string, options: NotificationOptions, callback?: (wasUpdated: boolean) => void): void; /** * Clears the specified notification. * @param notificationId The id of the notification to be cleared. This is returned by notifications.create method. @@ -3091,7 +5612,7 @@ declare namespace chrome { * If you specify the callback parameter, it should be a function that looks like this: * function(boolean wasCleared) {...}; */ - export function clear(notificationId: string, callback?: (wasCleared: boolean) => void): void; + function clear(notificationId: string, callback?: (wasCleared: boolean) => void): void; /** * Retrieves all the notifications. * @since Chrome 29. @@ -3099,7 +5620,7 @@ declare namespace chrome { * The callback parameter should be a function that looks like this: * function(object notifications) {...}; */ - export function getAll(callback: (notifications: Object) => void): void; + function getAll(callback: (notifications: Object) => void): void; /** * Retrieves whether the user has enabled notifications from this app or extension. * @since Chrome 32. @@ -3107,7 +5628,7 @@ declare namespace chrome { * The callback parameter should be a function that looks like this: * function( PermissionLevel level) {...}; */ - export function getPermissionLevel(callback: (level: string) => void): void; + function getPermissionLevel(callback: (level: string) => void): void; } //////////////////// @@ -3155,33 +5676,33 @@ declare namespace chrome { * function(boolean result) {...}; * Parameter result: True if the extension has the specified permissions. */ - export function contains(permissions: Permissions, callback: (result: boolean) => void): void; + function contains(permissions: Permissions, callback: (result: boolean) => void): void; /** * Gets the extension's current set of permissions. * @param callback The callback parameter should be a function that looks like this: * function( Permissions permissions) {...}; * Parameter permissions: The extension's active permissions. */ - export function getAll(callback: (permissions: Permissions) => void): void; + function getAll(callback: (permissions: Permissions) => void): void; /** * Requests access to the specified permissions. These permissions must be defined in the optional_permissions field of the manifest. If there are any problems requesting the permissions, runtime.lastError will be set. - * @param callback If you specify the callback parameter, it should be a function that looks like this: + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: * function(boolean granted) {...}; * Parameter granted: True if the user granted the specified permissions. */ - export function request(permissions: Permissions, callback?: (granted: boolean) => void): void; + function request(permissions: Permissions, callback?: (granted: boolean) => void): void; /** * Removes access to the specified permissions. If there are any problems removing the permissions, runtime.lastError will be set. - * @param callback If you specify the callback parameter, it should be a function that looks like this: + * @param [callback] If you specify the callback parameter, it should be a function that looks like this: * function(boolean removed) {...}; * Parameter removed: True if the permissions were removed. */ - export function remove(permissions: Permissions, callback?: (removed: boolean) => void): void; + function remove(permissions: Permissions, callback?: (removed: boolean) => void): void; /** Fired when access to permissions has been removed from the extension. */ - export var onRemoved: PermissionsRemovedEvent; + const onRemoved: PermissionsRemovedEvent; /** Fired when the extension acquires new permissions. */ - export var onAdded: PermissionsAddedEvent; + const onAdded: PermissionsAddedEvent; } //////////////////// @@ -3194,9 +5715,9 @@ declare namespace chrome { */ namespace power { /** Requests that power management be temporarily disabled. |level| describes the degree to which power management should be disabled. If a request previously made by the same app is still active, it will be replaced by the new request. */ - export function requestKeepAwake(level: string): void; + function requestKeepAwake(level: string): void; /** Releases a request previously made via requestKeepAwake(). */ - export function releaseKeepAwake(): void; + function releaseKeepAwake(): void; } //////////////////// @@ -3213,7 +5734,7 @@ declare namespace chrome { id: string; /** Printer's human readable name. */ name: string; - /** Optional. Printer's human readable description. */ + /** Printer's human readable description. */ description?: string; } @@ -3235,26 +5756,18 @@ declare namespace chrome { document: Blob; } - interface PrinterRequestedEvent extends chrome.events.Event<(resultCallback: (printerInfo: PrinterInfo[]) => void) => void> { } - - interface PrinterInfoRequestedEvent extends chrome.events.Event<(device: any, resultCallback: (printerInfo?: PrinterInfo) => void) => void> { } - - interface CapabilityRequestedEvent extends chrome.events.Event<(printerId: string, resultCallback: (capabilities: PrinterCapabilities) => void) => void> { } - - interface PrintRequestedEvent extends chrome.events.Event<(printJob: PrintJob, resultCallback: (result: string) => void) => void> { } - /** Event fired when print manager requests printers provided by extensions. */ - export var onGetPrintersRequested: PrinterRequestedEvent; + const onGetPrintersRequested: chrome.events.Event<(resultCallback: (printerInfo: PrinterInfo[]) => void) => void>; /** * Event fired when print manager requests information about a USB device that may be a printer. * Note: An application should not rely on this event being fired more than once per device. If a connected device is supported it should be returned in the onGetPrintersRequested event. * @since Chrome 45. */ - export var onGetUsbPrinterInfoRequested: PrinterInfoRequestedEvent; + const onGetUsbPrinterInfoRequested: chrome.events.Event<(device: any, resultCallback: (printerInfo?: PrinterInfo) => void) => void>; /** Event fired when print manager requests printer capabilities. */ - export var onGetCapabilityRequested: CapabilityRequestedEvent; + const onGetCapabilityRequested: chrome.events.Event<(printerId: string, resultCallback: (capabilities: PrinterCapabilities) => void) => void>; /** Event fired when print manager requests printing. */ - export var onPrintRequested: PrintRequestedEvent; + const onPrintRequested: chrome.events.Event<(printJob: PrintJob, resultCallback: (result: string) => void) => void>; } //////////////////// @@ -3266,12 +5779,12 @@ declare namespace chrome { */ namespace runtime { /** This will be defined during an API method callback if there was an error */ - export var lastError: LastError | undefined; + const lastError: LastError | undefined; /** The ID of the extension/app. */ - export var id: string; + const id: string; interface LastError { - /** Optional. Details about the error which occurred. */ + /** Details about the error which occurred. */ message?: string; } @@ -3362,9 +5875,9 @@ declare namespace chrome { */ sender?: MessageSender; /** An object which allows the addition and removal of listeners for a Chrome event. */ - onDisconnect: PortDisconnectEvent; + onDisconnect: chrome.events.Event<(port: Port) => void>; /** An object which allows the addition and removal of listeners for a Chrome event. */ - onMessage: PortMessageEvent; + onMessage: chrome.events.Event<(message: any, port: Port) => void>; name: string; } @@ -3378,22 +5891,6 @@ declare namespace chrome { version: string; } - interface PortDisconnectEvent extends chrome.events.Event<(port: Port) => void> { } - - interface PortMessageEvent extends chrome.events.Event<(message: any, port: Port) => void> { } - - interface ExtensionMessageEvent extends chrome.events.Event<(message: any, sender: MessageSender, sendResponse: (response: any) => void) => void> { } - - interface ExtensionConnectEvent extends chrome.events.Event<(port: Port) => void> { } - - interface RuntimeInstalledEvent extends chrome.events.Event<(details: InstalledDetails) => void> { } - - interface RuntimeEvent extends chrome.events.Event<() => void> { } - - interface RuntimeRestartRequiredEvent extends chrome.events.Event<(reason: string) => void> { } - - interface RuntimeUpdateAvailableEvent extends chrome.events.Event<(details: UpdateAvailableDetails) => void> { } - interface ManifestIcons { [size: number]: string; } @@ -3422,6 +5919,63 @@ declare namespace chrome { is_default?: boolean; } + type Permissions = + 'alarms' | + 'audio' | + 'audioCapture' | + 'background' | + 'browser' | + 'certificateProvider' | + 'clipboard' | + 'clipboardRead' | + 'clipboardWrite' | + 'contextMenus' | + 'desktopCapture' | + 'diagnostics' | + 'displaySource' | + 'dns' | + 'documentScan' | + 'enterprise.deviceAttributes' | + 'enterprise.platformKeys' | + 'experimental' | + 'fileBrowserHandler' | + 'fileSystem' | + 'gcm' | + 'geolocation' | + 'hid' | + 'identity' | + 'idle' | + 'mdns' | + 'mediaGalleries' | + 'nativeMessaging' | + 'networking.config' | + 'networking.onc' | + 'notifications' | + 'platformKeys' | + 'pointerLock' | + 'power' | + 'printerProvider' | + 'proxy' | + 'serial' | + 'signedInDevices' | + 'socket' | + 'storage' | + 'syncFileSystem' | + 'system.cpu' | + 'system.display' | + 'system.memory' | + 'system.network' | + 'system.powerSource' | + 'system.storage' | + 'tts' | + 'unlimitedStorage' | + 'usb' | + 'videoCapture' | + 'virtualKeyboard' | + 'vpnProvider' | + 'wallpaper' | + 'webview'; + interface Manifest { /** Required */ app: { @@ -3546,6 +6100,15 @@ declare namespace chrome { pages: string[]; content_security_policy?: string; }; + /** + * The short_name (maximum of 12 characters recommended) is + * a short version of the app's name. It is an optional field + * and if not specified, the name will be used, though it will + * likely be truncated. The short name is typically used where + * there is insufficient space to display the full name, such as: + * - App launcher + * - New Tab page + */ short_name?: string; signature?: any; sockets?: { @@ -3560,7 +6123,7 @@ declare namespace chrome { managed_schema: string }; system_indicator?: any; - update_url?: string; + // update_url?: string; // Listed but deprecated since Chrome 33 - leaving it here so it's not added again url_handlers?: { [name: string]: { matches: string[]; @@ -3590,48 +6153,60 @@ declare namespace chrome { * Attempts to connect to connect listeners within an extension/app (such as the background page), or other extensions/apps. This is useful for content scripts connecting to their extension processes, inter-app/extension communication, and web messaging. Note that this does not connect to any listeners in a content script. Extensions may connect to content scripts embedded in tabs via tabs.connect. * @since Chrome 26. */ - export function connect(connectInfo?: ConnectInfo): Port; + function connect(connectInfo?: ConnectInfo): Port; /** * Attempts to connect to connect listeners within an extension/app (such as the background page), or other extensions/apps. This is useful for content scripts connecting to their extension processes, inter-app/extension communication, and web messaging. Note that this does not connect to any listeners in a content script. Extensions may connect to content scripts embedded in tabs via tabs.connect. * @since Chrome 26. * @param extensionId Optional. * The ID of the extension or app to connect to. If omitted, a connection will be attempted with your own extension. Required if sending messages from a web page for web messaging. */ - export function connect(extensionId: string, connectInfo?: ConnectInfo): Port; + function connect(extensionId: string, connectInfo?: ConnectInfo): Port; /** * Connects to a native application in the host machine. * @since Chrome 28. * @param application The name of the registered application to connect to. */ - export function connectNative(application: string): Port; - /** Retrieves the JavaScript 'window' object for the background page running inside the current extension/app. If the background page is an event page, the system will ensure it is loaded before calling the callback. If there is no background page, an error is set. */ - export function getBackgroundPage(callback: (backgroundPage?: Window) => void): void; + function connectNative(application: string): Port; + /** - * Returns details about the app or extension from the manifest. The object returned is a serialization of the full manifest file. + * Retrieves the JavaScript 'window' object for the background page running inside the current extension/app. + * If the background page is an event page, the system will ensure it is loaded before calling the callback. + * If there is no background page, an error is set. + */ + function getBackgroundPage(callback: (backgroundPage?: Window) => void): void; + + /** + * Returns details about the app or extension from the manifest. + * The object returned is a serialization of the full manifest file. * @returns The manifest details. */ - export function getManifest(): Manifest; + function getManifest(): Manifest; + /** * Returns a DirectoryEntry for the package directory. * @since Chrome 29. */ - export function getPackageDirectoryEntry(callback: (directoryEntry: DirectoryEntry) => void): void; + function getPackageDirectoryEntry(callback: (directoryEntry: DirectoryEntry) => void): void; + /** * Returns information about the current platform. * @since Chrome 29. * @param callback Called with results */ - export function getPlatformInfo(callback: (platformInfo: PlatformInfo) => void): void; + function getPlatformInfo(callback: (platformInfo: PlatformInfo) => void): void; + /** * Converts a relative path within an app/extension install directory to a fully-qualified URL. * @param path A path to a resource within an app/extension expressed relative to its install directory. */ - export function getURL(path: string): string; + function getURL(path: string): string; + /** * Reloads the app or extension. * @since Chrome 25. */ - export function reload(): void; + function reload(): void; + /** * Requests an update check for this app/extension. * @since Chrome 25. @@ -3639,26 +6214,30 @@ declare namespace chrome { * Parameter status: Result of the update check. One of: 'throttled', 'no_update', or 'update_available' * Optional parameter details: If an update is available, this contains more information about the available update. */ - export function requestUpdateCheck(callback: (status: string, details?: UpdateCheckDetails) => void): void; + function requestUpdateCheck(callback: (status: string, details?: UpdateCheckDetails) => void): void; + /** * Restart the ChromeOS device when the app runs in kiosk mode. Otherwise, it's no-op. * @since Chrome 32. */ - export function restart(): void; + function restart(): void; + /** * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. * @since Chrome 26. * @param responseCallback Optional * Parameter response: The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. */ - export function sendMessage(message: any, responseCallback?: (response: any) => void): void; + function sendMessage(message: any, responseCallback?: (response: any) => void): void; + /** * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. * @since Chrome 32. * @param responseCallback Optional * Parameter response: The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. */ - export function sendMessage(message: any, options: MessageOptions, responseCallback?: (response: any) => void): void; + function sendMessage(message: any, options: MessageOptions, responseCallback?: (response: any) => void): void; + /** * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. * @since Chrome 26. @@ -3666,7 +6245,8 @@ declare namespace chrome { * @param responseCallback Optional * Parameter response: The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. */ - export function sendMessage(extensionId: string, message: any, responseCallback?: (response: any) => void): void; + function sendMessage(extensionId: string, message: any, responseCallback?: (response: any) => void): void; + /** * Sends a single message to event listeners within your extension/app or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in each page, or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage. * @since Chrome 32. @@ -3674,7 +6254,8 @@ declare namespace chrome { * @param responseCallback Optional * Parameter response: The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message. */ - export function sendMessage(extensionId: string, message: any, options: MessageOptions, responseCallback?: (response: any) => void): void; + function sendMessage(extensionId: string, message: any, options: MessageOptions, responseCallback?: (response: any) => void): void; + /** * Send a single message to a native application. * @since Chrome 28. @@ -3683,7 +6264,8 @@ declare namespace chrome { * @param responseCallback Optional. * Parameter response: The response message sent by the native messaging host. If an error occurs while connecting to the native messaging host, the callback will be called with no arguments and runtime.lastError will be set to the error message. */ - export function sendNativeMessage(application: string, message: Object, responseCallback?: (response: any) => void): void; + function sendNativeMessage(application: string, message: Object, responseCallback?: (response: any) => void): void; + /** * Sets the URL to be visited upon uninstallation. This may be used to clean up server-side data, do analytics, and implement surveys. Maximum 255 characters. * @since Chrome 41. @@ -3691,73 +6273,82 @@ declare namespace chrome { * URL to be opened after the extension is uninstalled. This URL must have an http: or https: scheme. Set an empty string to not open a new tab upon uninstallation. * @param callback Called when the uninstall URL is set. If the given URL is invalid, runtime.lastError will be set. */ - export function setUninstallURL(url: string, callback?: () => void): void; + function setUninstallURL(url: string, callback?: () => void): void; + /** * Open your Extension's options page, if possible. * The precise behavior may depend on your manifest's options_ui or options_page key, or what Chrome happens to support at the time. For example, the page may be opened in a new tab, within chrome://extensions, within an App, or it may just focus an open options page. It will never cause the caller page to reload. * If your Extension does not declare an options page, or Chrome failed to create one for some other reason, the callback will set lastError. * @since Chrome 42. */ - export function openOptionsPage(callback?: () => void): void; + function openOptionsPage(callback?: () => void): void; + + + interface ExtensionMessageEvent extends chrome.events.Event<(message: any, sender: MessageSender, sendResponse: (response: any) => void) => void> { } + + interface ExtensionConnectEvent extends chrome.events.Event<(port: Port) => void> { } + + interface RuntimeEvent extends chrome.events.Event<() => void> { } /** * Fired when a connection is made from either an extension process or a content script. * @since Chrome 26. */ - export var onConnect: ExtensionConnectEvent; + const onConnect: ExtensionConnectEvent; /** * Fired when a connection is made from another extension. * @since Chrome 26. */ - export var onConnectExternal: ExtensionConnectEvent; + const onConnectExternal: ExtensionConnectEvent; /** Sent to the event page just before it is unloaded. This gives the extension opportunity to do some clean up. Note that since the page is unloading, any asynchronous operations started while handling this event are not guaranteed to complete. If more activity for the event page occurs before it gets unloaded the onSuspendCanceled event will be sent and the page won't be unloaded. */ - export var onSuspend: RuntimeEvent; + const onSuspend: RuntimeEvent; /** * Fired when a profile that has this extension installed first starts up. This event is not fired when an incognito profile is started, even if this extension is operating in 'split' incognito mode. * @since Chrome 23. */ - export var onStartup: RuntimeEvent; + const onStartup: RuntimeEvent; /** Fired when the extension is first installed, when the extension is updated to a new version, and when Chrome is updated to a new version. */ - export var onInstalled: RuntimeInstalledEvent; + const onInstalled: chrome.events.Event<(details: InstalledDetails) => void>; /** Sent after onSuspend to indicate that the app won't be unloaded after all. */ - export var onSuspendCanceled: RuntimeEvent; + const onSuspendCanceled: RuntimeEvent; /** * Fired when a message is sent from either an extension process or a content script. * @since Chrome 26. */ - export var onMessage: ExtensionMessageEvent; + const onMessage: ExtensionMessageEvent; /** * Fired when a message is sent from another extension/app. Cannot be used in a content script. * @since Chrome 26. */ - export var onMessageExternal: ExtensionMessageEvent; + const onMessageExternal: ExtensionMessageEvent; /** * Fired when an app or the device that it runs on needs to be restarted. The app should close all its windows at its earliest convenient time to let the restart to happen. If the app does nothing, a restart will be enforced after a 24-hour grace period has passed. Currently, this event is only fired for Chrome OS kiosk apps. * @since Chrome 29. */ - export var onRestartRequired: RuntimeRestartRequiredEvent; + const onRestartRequired: chrome.events.Event<(reason: string) => void>; /** * Fired when an update is available, but isn't installed immediately because the app is currently running. If you do nothing, the update will be installed the next time the background page gets unloaded, if you want it to be installed sooner you can explicitly call chrome.runtime.reload(). If your extension is using a persistent background page, the background page of course never gets unloaded, so unless you call chrome.runtime.reload() manually in response to this event the update will not get installed until the next time chrome itself restarts. If no handlers are listening for this event, and your extension has a persistent background page, it behaves as if chrome.runtime.reload() is called in response to this event. * @since Chrome 25. */ - export var onUpdateAvailable: RuntimeUpdateAvailableEvent; + const onUpdateAvailable: chrome.events.Event<(details: UpdateAvailableDetails) => void>; /** * @deprecated since Chrome 33. Please use chrome.runtime.onRestartRequired. * Fired when a Chrome update is available, but isn't installed immediately because a browser restart is required. */ - export var onBrowserUpdateAvailable: RuntimeEvent; + const onBrowserUpdateAvailable: RuntimeEvent; } //////////////////// // Serial //////////////////// /** - * Use the chrome.serial API to read from and write to a device connected to a serial port. + * Use the chrome.socket API to send and receive data over the network using TCP and UDP connections. + * @deprecated Note: Starting with Chrome 33, + * this API is deprecated in favor of the + * sockets.udp, sockets.tcp and sockets.tcpServer APIs. * @since Chrome 23 */ - namespace serial { - /** NOT YET IMPLEMENTED */ - } + const serial: chrome.deprecated; //////////////////// // Socket @@ -3802,21 +6393,21 @@ declare namespace chrome { address: string; } - export function create(type: string, options?: Object, callback?: (createInfo: CreateInfo) => void): void; - export function destroy(socketId: number): void; - export function connect(socketId: number, hostname: string, port: number, callback: (result: number) => void): void; - export function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void; - export function disconnect(socketId: number): void; - export function read(socketId: number, bufferSize?: number, callback?: (readInfo: ReadInfo) => void): void; - export function write(socketId: number, data: ArrayBuffer, callback?: (writeInfo: WriteInfo) => void): void; - export function recvFrom(socketId: number, bufferSize?: number, callback?: (recvFromInfo: RecvFromInfo) => void): void; - export function sendTo(socketId: number, data: ArrayBuffer, address: string, port: number, callback?: (writeInfo: WriteInfo) => void): void; - export function listen(socketId: number, address: string, port: number, backlog?: number, callback?: (result: number) => void): void; - export function accept(socketId: number, callback?: (acceptInfo: AcceptInfo) => void): void; - export function setKeepAlive(socketId: number, enable: boolean, delay?: number, callback?: (result: boolean) => void): void; - export function setNoDelay(socketId: number, noDelay: boolean, callback?: (result: boolean) => void): void; - export function getInfo(socketId: number, callback: (result: SocketInfo) => void): void; - export function getNetworkList(callback: (result: NetworkInterface[]) => void): void; + function create(type: string, options?: Object, callback?: (createInfo: CreateInfo) => void): void; + function destroy(socketId: number): void; + function connect(socketId: number, hostname: string, port: number, callback: (result: number) => void): void; + function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void; + function disconnect(socketId: number): void; + function read(socketId: number, bufferSize?: number, callback?: (readInfo: ReadInfo) => void): void; + function write(socketId: number, data: ArrayBuffer, callback?: (writeInfo: WriteInfo) => void): void; + function recvFrom(socketId: number, bufferSize?: number, callback?: (recvFromInfo: RecvFromInfo) => void): void; + function sendTo(socketId: number, data: ArrayBuffer, address: string, port: number, callback?: (writeInfo: WriteInfo) => void): void; + function listen(socketId: number, address: string, port: number, backlog?: number, callback?: (result: number) => void): void; + function accept(socketId: number, callback?: (acceptInfo: AcceptInfo) => void): void; + function setKeepAlive(socketId: number, enable: boolean, delay?: number, callback?: (result: boolean) => void): void; + function setNoDelay(socketId: number, noDelay: boolean, callback?: (result: boolean) => void): void; + function getInfo(socketId: number, callback: (result: SocketInfo) => void): void; + function getNetworkList(callback: (result: NetworkInterface[]) => void): void; } namespace sockets.tcp { @@ -3858,28 +6449,28 @@ declare namespace chrome { peerPort?: number; } - export function create(callback: (createInfo: CreateInfo) => void): void; - export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + function create(callback: (createInfo: CreateInfo) => void): void; + function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; - export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; - export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + function setPaused(socketId: number, paused: boolean, callback?: () => void): void; - export function setKeepAlive(socketId: number, + function setKeepAlive(socketId: number, enable: boolean, callback: (result: number) => void): void; - export function setKeepAlive(socketId: number, + function setKeepAlive(socketId: number, enable: boolean, delay: number, callback: (result: number) => void): void; - export function setNoDelay(socketId: number, noDelay: boolean, callback: (result: number) => void): void; - export function connect(socketId: number, + function setNoDelay(socketId: number, noDelay: boolean, callback: (result: number) => void): void; + function connect(socketId: number, peerAddress: string, peerPort: number, callback: (result: number) => void): void; - export function disconnect(socketId: number, callback?: () => void): void; - export function send(socketId: number, data: ArrayBuffer, callback: (sendInfo: SendInfo) => void): void; - export function close(socketId: number, callback?: () => void): void; - export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; - export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; + function disconnect(socketId: number, callback?: () => void): void; + function send(socketId: number, data: ArrayBuffer, callback: (sendInfo: SendInfo) => void): void; + function close(socketId: number, callback?: () => void): void; + function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; - export var onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; - export var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; + const onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; + const onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; } /** @@ -3960,7 +6551,7 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_tcpServer#method-create * @param callback Called when the socket has been created. */ - export function create(callback: (createInfo: CreateInfo) => void): void; + function create(callback: (createInfo: CreateInfo) => void): void; /** * Creates a TCP server socket. @@ -3969,7 +6560,7 @@ declare namespace chrome { * @param properties The socket properties. * @param callback Called when the socket has been created. */ - export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; /** * Updates the socket properties. @@ -3979,7 +6570,7 @@ declare namespace chrome { * @param properties The properties to update. * @param callback Called when the properties are updated. */ - export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + function update(socketId: number, properties: SocketProperties, callback?: () => void): void; /** * Enables or disables a listening socket from accepting new connections. @@ -3990,7 +6581,7 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_tcpServer#method-setPaused * @param callback Callback from the setPaused method. */ - export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + function setPaused(socketId: number, paused: boolean, callback?: () => void): void; /** * Listens for connections on the specified port and address. If the @@ -4007,7 +6598,7 @@ declare namespace chrome { * ensures a reasonable queue length for most applications. * @param callback Called when listen operation completes. */ - export function listen(socketId: number, address: string, port: number, backlog: number, callback: (result: number) => void): void; + function listen(socketId: number, address: string, port: number, backlog: number, callback: (result: number) => void): void; /** * Listens for connections on the specified port and address. If the @@ -4021,7 +6612,7 @@ declare namespace chrome { * be found by calling getInfo. * @param callback Called when listen operation completes. */ - export function listen(socketId: number, address: string, port: number, callback: (result: number) => void): void; + function listen(socketId: number, address: string, port: number, callback: (result: number) => void): void; /** * Disconnects the listening socket, i.e. stops accepting new connections @@ -4033,7 +6624,7 @@ declare namespace chrome { * @param socketId The socket identifier. * @param callback Called when the disconnect attempt is complete. */ - export function disconnect(socketId: number, callback?: () => void): void; + function disconnect(socketId: number, callback?: () => void): void; /** * Disconnects and destroys the socket. Each socket created should be closed @@ -4045,7 +6636,7 @@ declare namespace chrome { * @param socketId The socket identifier. * @param callback Called when the close operation completes. */ - export function close(socketId: number, callback?: () => void): void; + function close(socketId: number, callback?: () => void): void; /** * Retrieves the state of the given socket. @@ -4054,7 +6645,7 @@ declare namespace chrome { * @param socketId The socket identifier. * @param callback Called when the socket state is available. */ - export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; /** * Retrieves the list of currently opened sockets owned by the application. @@ -4062,14 +6653,14 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_tcpServer#method-getSockets * @param callback Called when the list of sockets is available. */ - export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; + function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; /** * Event raised when a connection has been made to the server socket. * * @see https://developer.chrome.com/apps/sockets_tcpServer#event-onAccept */ - export var onAccept: chrome.events.Event<(args: AcceptEventArgs) => void>; + const onAccept: chrome.events.Event<(args: AcceptEventArgs) => void>; /** * Event raised when a network error occured while the runtime was waiting @@ -4079,7 +6670,7 @@ declare namespace chrome { * * @see https://developer.chrome.com/apps/sockets_tcpServer#event-onAcceptError */ - export var onAcceptError: chrome.events.Event<(args: AcceptErrorEventArgs) => void>; + const onAcceptError: chrome.events.Event<(args: AcceptErrorEventArgs) => void>; } /** @@ -4129,7 +6720,7 @@ declare namespace chrome { name?: string; /** - * The size of the buffer used to receive data. If the buffer is too + * The size of the buffer used to Receive data. If the buffer is too * small to receive the UDP packet, data is lost. The default value is * 4096. */ @@ -4181,7 +6772,7 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_udp#method-create * @param createInfo.socketId The ID of the newly created socket. */ - export function create(callback: (createInfo: CreateInfo) => void): void; + function create(callback: (createInfo: CreateInfo) => void): void; /** * Creates a UDP socket with the given properties. @@ -4190,7 +6781,7 @@ declare namespace chrome { * @param properties The socket properties. * @param createInfo.socketId The ID of the newly created socket. */ - export function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; + function create(properties: SocketProperties, callback: (createInfo: CreateInfo) => void): void; /** * Updates the socket properties. @@ -4200,7 +6791,7 @@ declare namespace chrome { * @param properties The properties to update. * @param callback Called when the properties are updated. */ - export function update(socketId: number, properties: SocketProperties, callback?: () => void): void; + function update(socketId: number, properties: SocketProperties, callback?: () => void): void; /** * Pauses or unpauses a socket. A paused socket is blocked from firing @@ -4212,7 +6803,7 @@ declare namespace chrome { * @param callback Called when the socket has been successfully paused or * unpaused. */ - export function setPaused(socketId: number, paused: boolean, callback?: () => void): void; + function setPaused(socketId: number, paused: boolean, callback?: () => void): void; /** * Binds the local address and port for the socket. For a client socket, it @@ -4231,7 +6822,7 @@ declare namespace chrome { * port. * @param callback Called when the bind operation completes. */ - export function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void; + function bind(socketId: number, address: string, port: number, callback: (result: number) => void): void; /** * Sends data on the given socket to the given address and port. The socket @@ -4244,7 +6835,7 @@ declare namespace chrome { * @param port The port of the remote machine. * @param callback Called when the send operation completes. */ - export function send(socketId: number, data: ArrayBuffer, address: string, port: number, callback: (sendInfo: SendInfo) => void): void; + function send(socketId: number, data: ArrayBuffer, address: string, port: number, callback: (sendInfo: SendInfo) => void): void; /** * Closes the socket and releases the address/port the socket is bound to. @@ -4256,7 +6847,7 @@ declare namespace chrome { * @param socketId The socket ID. * @param callback Called when the close operation completes. */ - export function close(socketId: number, callback?: () => void): void; + function close(socketId: number, callback?: () => void): void; /** * Retrieves the state of the given socket. @@ -4265,7 +6856,7 @@ declare namespace chrome { * @param socketId The socket ID. * @param callback Called when the socket state is available. */ - export function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; + function getInfo(socketId: number, callback: (socketInfo: SocketInfo) => void): void; /** * Retrieves the list of currently opened sockets owned by the application. @@ -4273,7 +6864,7 @@ declare namespace chrome { * @see https://developer.chrome.com/apps/sockets_udp#method-getSockets * @param callback Called when the list of sockets is available. */ - export function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; + function getSockets(callback: (socketInfos: SocketInfo[]) => void): void; /** * Joins the multicast group and starts to receive packets from that group. @@ -4284,7 +6875,7 @@ declare namespace chrome { * @param address The group address to join. Domain names are not supported. * @param callback Called when the joinGroup operation completes. */ - export function joinGroup(socketId: number, address: string, callback: (result: number) => void): void; + function joinGroup(socketId: number, address: string, callback: (result: number) => void): void; /** * Leaves the multicast group previously joined using joinGroup. This is @@ -4301,7 +6892,7 @@ declare namespace chrome { * supported. * @param callback Called when the leaveGroup operation completes. */ - export function leaveGroup(socketId: number, address: string, callback: (result: number) => void): void; + function leaveGroup(socketId: number, address: string, callback: (result: number) => void): void; /** * Sets the time-to-live of multicast packets sent to the multicast group. @@ -4313,7 +6904,7 @@ declare namespace chrome { * @param ttl The time-to-live value. * @param callback Called when the configuration operation completes. */ - export function setMulticastTimeToLive(socketId: number, ttl: number, callback: (result: number) => void): void; + function setMulticastTimeToLive(socketId: number, ttl: number, callback: (result: number) => void): void; /** * Sets whether multicast packets sent from the host to the multicast group @@ -4324,7 +6915,7 @@ declare namespace chrome { * when there is more than one application on the same host joined to the * same multicast group while having different settings on multicast * loopback mode. On Windows, the applications with loopback off will not - * RECEIVE the loopback packets; while on Unix-like systems, the + * receive the loopback packets; while on Unix-like systems, the * applications with loopback off will not SEND the loopback packets to * other applications on the same host. * @see MSDN: http://goo.gl/6vqbj @@ -4336,7 +6927,7 @@ declare namespace chrome { * @param enabled Indicate whether to enable loopback mode. * @param callback Called when the configuration operation completes. */ - export function setMulticastLoopbackMode(socketId: number, enabled: boolean, callback: (result: number) => void): void; + function setMulticastLoopbackMode(socketId: number, enabled: boolean, callback: (result: number) => void): void; /** * Gets the multicast group addresses the socket is currently joined to. @@ -4345,7 +6936,7 @@ declare namespace chrome { * @param socketId The socket ID. * @param callback Called with an array of strings of the result. */ - export function getJoinedGroups(socketId: number, callback: (groups: string[]) => void): void; + function getJoinedGroups(socketId: number, callback: (groups: string[]) => void): void; /** * Enables or disables broadcast packets on this socket. @@ -4356,14 +6947,14 @@ declare namespace chrome { * @param enabled true to enable broadcast packets, false to disable them. * @param callback Callback from the setBroadcast method. */ - export function setBroadcast(socketId: number, enabled: boolean, callback?: (result: number) => void): void; + function setBroadcast(socketId: number, enabled: boolean, callback?: (result: number) => void): void; /** * Event raised when a UDP packet has been received for the given socket. * * @see https://developer.chrome.com/apps/sockets_udp#event-onReceive */ - export var onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; + const onReceive: chrome.events.Event<(args: ReceiveEventArgs) => void>; /** * Event raised when a network error occured while the runtime was waiting @@ -4373,7 +6964,7 @@ declare namespace chrome { * * @see https://developer.chrome.com/apps/sockets_udp#event-onReceiveError */ - export var onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; + const onReceiveError: chrome.events.Event<(args: ReceiveErrorEventArgs) => void>; } //////////////////// @@ -4437,9 +7028,9 @@ declare namespace chrome { } interface StorageChange { - /** Optional. The new value of the item, if there is a new value. */ + /** The new value of the item, if there is a new value. */ newValue?: any; - /** Optional. The old value of the item, if there was an old value. */ + /** The old value of the item, if there was an old value. */ oldValue?: any; } @@ -4473,29 +7064,163 @@ declare namespace chrome { interface StorageChangedEvent extends chrome.events.Event<(changes: { [key: string]: StorageChange }, areaName: string) => void> { } /** Items in the local storage area are local to each machine. */ - export var local: LocalStorageArea; + const local: LocalStorageArea; /** Items in the sync storage area are synced using Chrome Sync. */ - export var sync: SyncStorageArea; + const sync: SyncStorageArea; /** * Items in the managed storage area are set by the domain administrator, and are read-only for the extension; trying to modify this namespace results in an error. * @since Chrome 33. */ - export var managed: StorageArea; + const managed: StorageArea; /** Fired when one or more items change. */ - export var onChanged: StorageChangedEvent; + const onChanged: StorageChangedEvent; } //////////////////// // SyncFileSystem //////////////////// /** - * Use the chrome.syncFileSystem API to save and synchronize data on Google Drive. This API is NOT for accessing arbitrary user docs stored in Google Drive. It provides app-specific syncable storage for offline and caching usage so that the same data can be available across different clients. Read Manage Data for more on using this API. + * Use the chrome.syncFileSystem API to save and synchronize data on Google Drive. + * This API is NOT for accessing arbitrary user docs stored in Google Drive. + * It provides app-specific syncable storage for offline and caching usage so that + * the same data can be available across different clients. Read Manage Data for + * more on using this API. + * + * @requires[Permissions: 'syncFileSystem'] + * @see[Learn more: Manage Data]{@link https://developer.chrome.com/apps/app_storage} * @since Chrome 27 */ namespace syncFileSystem { - /** NOT YET IMPLEMENTED */ + /** + * 'initializing' + * - The sync service is being initialized (e.g. restoring data from the database, checking connectivity and authenticating to the service etc). + * 'running' + * - The sync service is up and running. + * 'authentication_required' + * - The sync service is not synchronizing files because the remote service needs to be authenticated by the user to proceed. + * 'temporary_unavailable' + * - The sync service is not synchronizing files because the remote service is (temporarily) unavailable due to some recoverable errors, e.g. network is offline, the remote service is down or not reachable etc. More details should be given by |description| parameter in OnServiceInfoUpdated (which could contain service-specific details). + * 'disabled' + * - The sync service is disabled and the content will never sync. (E.g. this could happen when the user has no account on the remote service or the sync service has had an unrecoverable error.) + */ + type ServiceStatus = + 'initializing' | + 'running' | + 'authentication_required' | + 'temporary_unavailable' | + 'disabled'; + /** + * 'synced' + * - Not conflicting and has no pending local changes. + * 'pending' + * - Has one or more pending local changes that haven't been synchronized. + * 'conflicting' + * - File conflicts with remote version and must be resolved manually. + */ + type FileStatus = + 'synced' | + 'pending' | + 'conflicting'; + type ConflictResolutionPolicy = + 'last_write_win' | + 'manual' + + type Action = + 'added' | + 'updated' | + 'deleted' + + type Direction = + 'local_to_remote' | + 'remote_to_local'; + + interface FileStatusInfo { + /** One of the Entry's originally given to getFileStatuses. */ + fileEntry: Entry; + /** Status value */ + status: FileStatus; + /** Optional error that is only returned if there was a problem retrieving the FileStatus for the given file. */ + error?: string; + } + interface FileStatusChangedDetail { + /** + * fileEntry for the target file whose status has changed. + * Contains name and path information of synchronized file. + * On file deletion, fileEntry information will still be + * available but file will no longer exist. + */ + fileEntry: Entry; + /** + * Resulting file status after onFileStatusChanged event. + * The status value can be 'synced', 'pending' or 'conflicting'. + */ + status: FileStatus; + /** + * Sync action taken to fire onFileStatusChanged event. + * The action value can be 'added', 'updated' or 'deleted'. + * Only applies if status is 'synced'. + */ + action?: Action; + /** + * Sync direction for the onFileStatusChanged event. + * Sync direction value can be 'local_to_remote' or + * 'remote_to_local'. Only applies if status is 'synced'. + */ + direction?: Direction; + } + /** + * Returns a syncable filesystem backed by Google Drive. + * The returned DOMFileSystem instance can be operated on + * in the same way as the Temporary and Persistant file systems + * @see[More information]{@link http://dev.w3.org/2009/dap/file-system/file-dir-sys.html} + * @description + * Calling this multiple times from the same app will return the same handle to the same file system. + * Note this call can fail. + * For example, if the user is not signed in to Chrome + * or if there is no network operation. To handle these + * errors it is important chrome.runtime.lastError is + * checked in the callback. + * @param callback A callback type for requestFileSystem. + */ + function requestFileSystem(callback: (fileSystem: FileSystem) => void): void; + /** + * Sets the default conflict resolution policy for the 'syncable' file storage + * for the app. By default it is set to 'last_write_win'. When conflict resolution + * policy is set to 'last_write_win' conflicts for existing files are automatically + * resolved next time the file is updated. |callback| can be optionally given to + * know if the request has succeeded or not. + * @param policy Policy + * @param [callback] A generic result callback to indicate success or failure. + */ + function setConflictResolutionPolicy(policy: ConflictResolutionPolicy, callback?: () => void): void; + /** Gets the current conflict resolution policy. */ + function getConflictResolutionPolicy(callback: (policy: ConflictResolutionPolicy) => void): void; + /** + * Returns the current usage and quota in bytes for the 'syncable' file storage for the app. + * @param fileSystem + * @param callback + */ + function getUsageAndQuota(fileSystem: FileSystem, callback: (info: { usageBytes: number, quotaBytes: number }) => void): void; + /** + * Returns the FileStatus for the given fileEntry. + * Note that 'conflicting' state only happens when + * the service's conflict resolution policy is set to 'manual'. + * */ + function getFileStatus(fileEntry: Entry, callback: (status: FileStatus) => void): void; + /** Returns each FileStatus for the given fileEntry array. Typically called with the result from dirReader.readEntries(). */ + function getFileStatuses(fileEntries: Entry[], callback: (status: FileStatusInfo[]) => void): void; + /** + * Returns the current sync backend status. + * @since Chrome 31. + * @param callback + */ + function getServiceStatus(callback: (status: ServiceStatus) => void): void; + /** Fired when an error or other status change has happened in the sync backend (for example, when the sync is temporarily disabled due to network or authentication error). */ + const onServiceStatusChanged: chrome.events.Event<(detail: { state: ServiceStatus, description: string }) => void>; + /** Fired when a file has been updated by the background sync service. */ + const onFileStatusChanged: chrome.events.Event<(detail: FileStatusChangedDetail) => void>; } @@ -4541,7 +7266,7 @@ declare namespace chrome { } /** Queries basic CPU information of the system. */ - export function getInfo(callback: (info: CpuInfo) => void): void; + function getInfo(callback: (info: CpuInfo) => void): void; } //////////////////// @@ -4589,7 +7314,7 @@ declare namespace chrome { * @since Chrome 57 */ interface TouchCalibrationPair { - /** The coordinates of the display point. */ + /** The coordinates of the display point. */ displayPoint: Point; /** The coordinates of the touch point corresponding to the display point. */ touchPoint: Point; @@ -4624,6 +7349,8 @@ declare namespace chrome { isSelected: boolean; } + type DisplayPosition = 'top' | 'right' | 'bottom' | 'left'; + /** * @since Chrome 53 */ @@ -4633,13 +7360,13 @@ declare namespace chrome { /** The unique identifier of the parent display. Empty if this is the root. */ parentId: string; /** The layout position of this display relative to the parent. This will be ignored for the root. */ - position: 'top' | 'right' | 'bottom' | 'left'; + position: DisplayPosition; /** The offset of the display along the connected edge. 0 indicates that the topmost or leftmost corners are aligned. */ offset: number; } /** - * @description The pairs of point used to calibrate the display. + * The pairs of point used to calibrate the display. * @export * @interface TouchCalibrationPairs */ @@ -4655,13 +7382,13 @@ declare namespace chrome { } /** - * @description Representation of info data to be used in chrome.system.display.setDisplayProperties() + * Representation of info data to be used in chrome.system.display.setDisplayProperties() * @export * @interface DisplayPropertiesInfo */ interface DisplayPropertiesInfo { /** - * @description Chrome OS only. If set to true, changes the display mode to unified desktop (see enableUnifiedDesktop for details). If set to false, unified desktop mode will be disabled. This is only valid for the primary display. If provided, mirroringSourceId must not be provided and other properties may not apply. This is has no effect if not provided. + * Chrome OS only. If set to true, changes the display mode to unified desktop (see enableUnifiedDesktop for details). If set to false, unified desktop mode will be disabled. This is only valid for the primary display. If provided, mirroringSourceId must not be provided and other properties may not apply. This is has no effect if not provided. * @since Chrome 59 * */ isUnified?: boolean; @@ -4688,20 +7415,20 @@ declare namespace chrome { /** * @since Chrome 52 - * @description If set, updates the display mode to the mode matching this value. + * If set, updates the display mode to the mode matching this value. */ displayMode?: DisplayMode; } /** - * @description Options affecting how the information is returned. + * Options affecting how the information is returned. * @since Chrome 59 * @export * @interface DisplayInfoFlags */ interface DisplayInfoFlags { /** - * @description If set to true, only a single DisplayUnitInfo will be returned by getInfo when in unified desktop mode (see enableUnifiedDesktop). Defaults to false. + * If set to true, only a single DisplayUnitInfo will be returned by getInfo when in unified desktop mode (see enableUnifiedDesktop). Defaults to false. * @type {boolean} * @memberof DisplayInfoFlags */ @@ -4753,7 +7480,7 @@ declare namespace chrome { } /** - * @description Fired when anything changes to the display configuration. + * Fired when anything changes to the display configuration. * @export * @interface DisplayChangedEvent * @extends {chrome.events.Event<() => void>} @@ -4761,123 +7488,123 @@ declare namespace chrome { interface DisplayChangedEvent extends chrome.events.Event<() => void> { } /** - * @description Requests the information for all attached display devices. + * Requests the information for all attached display devices. * @export * @param {(info: DisplayInfo[]) => void} callback The callback to invoke with the results. */ - export function getInfo(callback: (info: DisplayInfo[]) => void): void; + function getInfo(callback: (info: DisplayInfo[]) => void): void; /** - * @description Requests the information for all attached display devices. + * Requests the information for all attached display devices. * @export * @since Chrome 59 * @param {DisplayInfoFlags} [flags] Options affecting how the information is returned. * @param {(info: DisplayInfo[]) => void} callback The callback to invoke with the results. */ - export function getInfo(flags: DisplayInfoFlags, callback: (info: DisplayInfo[]) => void): void; + function getInfo(flags: DisplayInfoFlags, callback: (info: DisplayInfo[]) => void): void; /** - * @description Requests the layout info for all displays. NOTE: This is only available to Chrome OS Kiosk apps and Web UI. + * Requests the layout info for all displays. NOTE: This is only available to Chrome OS Kiosk apps and Web UI. * @since Chrome 53 * @export * @param {(layouts: DisplayLayout[]) => void} callback The callback to invoke with the results. */ - export function getDisplayLayout(callback: (layouts: DisplayLayout[]) => void): void; + function getDisplayLayout(callback: (layouts: DisplayLayout[]) => void): void; /** - * @description Updates the properties for the display specified by |id|, according to the information provided in |info|. On failure, runtime.lastError will be set. NOTE: This is only available to Chrome OS Kiosk apps and Web UI. + * Updates the properties for the display specified by |id|, according to the information provided in |info|. On failure, runtime.lastError will be set. NOTE: This is only available to Chrome OS Kiosk apps and Web UI. * @export * @param {string} id The display's unique identifier. * @param {DisplayPropertiesInfo} info The information about display properties that should be changed. A property will be changed only if a new value for it is specified in |info|. * @param {() => void} [callback] Empty function called when the function finishes. To find out whether the function succeeded, runtime.lastError should be queried. */ - export function setDisplayProperties(id: string, info: DisplayPropertiesInfo, callback?: () => void): void; + function setDisplayProperties(id: string, info: DisplayPropertiesInfo, callback?: () => void): void; /** - * @description Set the layout for all displays. Any display not included will use the default layout. If a layout would overlap or be otherwise invalid it will be adjusted to a valid layout. After layout is resolved, an onDisplayChanged event will be triggered. NOTE: This is only available to Chrome OS Kiosk apps and Web UI. + * Set the layout for all displays. Any display not included will use the default layout. If a layout would overlap or be otherwise invalid it will be adjusted to a valid layout. After layout is resolved, an onDisplayChanged event will be triggered. NOTE: This is only available to Chrome OS Kiosk apps and Web UI. * @since Chrome 53 * @export * @param {DisplayLayout[]} layouts The layout information, required for all displays except the primary display. * @param {() => void} callback Empty function called when the function finishes. To find out whether the function succeeded, runtime.lastError should be queried. */ - export function setDisplayLayout(layouts: DisplayLayout[], callback?: () => void): void; + function setDisplayLayout(layouts: DisplayLayout[], callback?: () => void): void; /** - * @description Enables/disables the unified desktop feature. Note that this simply enables the feature, but will not change the actual desktop mode. (That is, if the desktop is in mirror mode, it will stay in mirror mode) NOTE: This is only available to Chrome OS Kiosk apps and Web UI. + * Enables/disables the unified desktop feature. Note that this simply enables the feature, but will not change the actual desktop mode. (That is, if the desktop is in mirror mode, it will stay in mirror mode) NOTE: This is only available to Chrome OS Kiosk apps and Web UI. * @since Chrome 46 * @export * @param {boolean} enabled True if unified desktop should be enabled. */ - export function enableUnifiedDesktop(enabled: boolean): void; + function enableUnifiedDesktop(enabled: boolean): void; /** - * @description Starts overscan calibration for a display. This will show an overlay on the screen indicating the current overscan insets. If overscan calibration for display |id| is in progress this will reset calibration. + * Starts overscan calibration for a display. This will show an overlay on the screen indicating the current overscan insets. If overscan calibration for display |id| is in progress this will reset calibration. * @since Chrome 53 * @export * @param {string} id The display's unique identifier. */ - export function overscanCalibrationStart(id: string): void; + function overscanCalibrationStart(id: string): void; /** - * @description Adjusts the current overscan insets for a display. Typically this should etiher move the display along an axis (e.g. left+right have the same value) or scale it along an axis (e.g. top+bottom have opposite values). Each Adjust call is cumulative with previous calls since Start. + * Adjusts the current overscan insets for a display. Typically this should etiher move the display along an axis (e.g. left+right have the same value) or scale it along an axis (e.g. top+bottom have opposite values). Each Adjust call is cumulative with previous calls since Start. * @since Chrome 53 * @export * @param {string} id The display's unique identifier. * @param {Insets} delta The amount to change the overscan insets. */ - export function overscanCalibrationAdjust(id: string, delta: Insets): void; + function overscanCalibrationAdjust(id: string, delta: Insets): void; /** - * @description Resets the overscan insets for a display to the last saved value (i.e before Start was called). + * Resets the overscan insets for a display to the last saved value (i.e before Start was called). * @since Chrome 53 * @export * @param {string} id The display's unique identifier. */ - export function overscanCalibrationReset(id: string): void; + function overscanCalibrationReset(id: string): void; /** - * @description Complete overscan adjustments for a display by saving the current values and hiding the overlay. + * Complete overscan adjustments for a display by saving the current values and hiding the overlay. * @since Chrome 53 * @export * @param {string} id The display's unique identifier. */ - export function overscanCalibrationComplete(id: string): void; + function overscanCalibrationComplete(id: string): void; /** - * @description Displays the native touch calibration UX for the display with |id| as display id. This will show an overlay on the screen with required instructions on how to proceed. The callback will be invoked in case of successful calibraion only. If the calibration fails, this will throw an error. + * Displays the native touch calibration UX for the display with |id| as display id. This will show an overlay on the screen with required instructions on how to proceed. The callback will be invoked in case of successful calibraion only. If the calibration fails, this will throw an error. * @since Chrome 57 * @export * @param {string} id The display's unique identifier. * @param {(success) => void} callback Optional callback to inform the caller that the touch calibration has ended. The argument of the callback informs if the calibration was a success or not. */ - export function showNativeTouchCalibration(id: string, callback: (success: boolean) => void): void; + function showNativeTouchCalibration(id: string, callback: (success: boolean) => void): void; /** - * @description Starts custom touch calibration for a display. This should be called when using a custom UX for collecting calibration data. If another touch calibration is already in progress this will throw an error. + * Starts custom touch calibration for a display. This should be called when using a custom UX for collecting calibration data. If another touch calibration is already in progress this will throw an error. * @since Chrome 57 * @export * @param {string} id The display's unique identifier. */ - export function startCustomTouchCalibration(id: string): void; + function startCustomTouchCalibration(id: string): void; /** - * @description Sets the touch calibration pairs for a display. These |pairs| would be used to calibrate the touch screen for display with |id| called in startCustomTouchCalibration(). Always call |startCustomTouchCalibration| before calling this method. If another touch calibration is already in progress this will throw an error. + * Sets the touch calibration pairs for a display. These |pairs| would be used to calibrate the touch screen for display with |id| called in startCustomTouchCalibration(). Always call |startCustomTouchCalibration| before calling this method. If another touch calibration is already in progress this will throw an error. * @since Chrome 57 * @export * @param {TouchCalibrationPairs} pairs The pairs of point used to calibrate the display. * @param {Bounds} bounds Bounds of the display when the touch calibration was performed. |bounds.left| and |bounds.top| values are ignored. */ - export function completeCustomTouchCalibration(pairs: TouchCalibrationPairs, bounds: Bounds): void; + function completeCustomTouchCalibration(pairs: TouchCalibrationPairs, bounds: Bounds): void; /** - * @description Resets the touch calibration for the display and brings it back to its default state by clearing any touch calibration data associated with the display. + * Resets the touch calibration for the display and brings it back to its default state by clearing any touch calibration data associated with the display. * @since Chrome 57 * @export * @param {string} id The display's unique identifier. */ - export function clearTouchCalibration(id: string): void; + function clearTouchCalibration(id: string): void; /** - * @description Fired when anything changes to the display configuration. + * Fired when anything changes to the display configuration. * @export */ - export var onDisplayChanged: DisplayChangedEvent; + const onDisplayChanged: DisplayChangedEvent; } //////////////////// @@ -4897,7 +7624,7 @@ declare namespace chrome { } /** Get physical memory information. */ - export function getInfo(callback: (info: MemoryInfo) => void): void; + function getInfo(callback: (info: MemoryInfo) => void): void; } //////////////////// @@ -4910,7 +7637,7 @@ declare namespace chrome { prefixLength: number; } - export function getNetworkInterfaces(callback: (networkInterfaces: NetworkInterface[]) => void): void; + function getNetworkInterfaces(callback: (networkInterfaces: NetworkInterface[]) => void): void; } //////////////////// @@ -4950,23 +7677,23 @@ declare namespace chrome { interface SystemStorageDetachedEvent extends chrome.events.Event<(id: string) => void> { } /** Get the storage information from the system. The argument passed to the callback is an array of StorageUnitInfo objects. */ - export function getInfo(callback: (info: StorageUnitInfo[]) => void): void; + function getInfo(callback: (info: StorageUnitInfo[]) => void): void; /** * Ejects a removable storage device. * @param callback * Parameter result: success: The ejection command is successful -- the application can prompt the user to remove the device; in_use: The device is in use by another application. The ejection did not succeed; the user should not remove the device until the other application is done with the device; no_such_device: There is no such device known. failure: The ejection command failed. */ - export function ejectDevice(id: string, callback: (result: string) => void): void; + function ejectDevice(id: string, callback: (result: string) => void): void; /** * Get the available capacity of a specified |id| storage device. The |id| is the transient device ID from StorageUnitInfo. * @since Dev channel only. */ - export function getAvailableCapacity(id: string, callback: (info: StorageCapacityInfo) => void): void; + function getAvailableCapacity(id: string, callback: (info: StorageCapacityInfo) => void): void; /** Fired when a new removable storage is attached to the system. */ - export var onAttached: SystemStorageAttachedEvent; + const onAttached: SystemStorageAttachedEvent; /** Fired when a removable storage is detached from the system. */ - export var onDetached: SystemStorageDetachedEvent; + const onDetached: SystemStorageDetachedEvent; } //////////////////// @@ -4980,9 +7707,9 @@ declare namespace chrome { namespace tts { /** An event from the TTS engine to communicate the status of an utterance. */ interface TtsEvent { - /** Optional. The index of the current character in the utterance. */ + /** The index of the current character in the utterance. */ charIndex?: number; - /** Optional. The error description, if the event type is 'error'. */ + /** The error description, if the event type is 'error'. */ errorMessage?: string; /** * The type can be 'start' as soon as speech has started, 'word' when a word boundary is reached, 'sentence' when a sentence boundary is reached, 'marker' when an SSML mark element is reached, 'end' when the end of the utterance is reached, 'interrupted' when the utterance is stopped or interrupted before reaching the end, 'cancelled' when it's removed from the queue before ever being synthesized, or 'error' when any other error occurs. When pausing speech, a 'pause' event is fired if a particular utterance is paused in the middle, and 'resume' if an utterance resumes speech. Note that pause and resume events may not fire if speech is paused in-between utterances. @@ -4993,14 +7720,14 @@ declare namespace chrome { /** A description of a voice available for speech synthesis. */ interface TtsVoice { - /** Optional. The language that this voice supports, in the form language-region. Examples: 'en', 'en-US', 'en-GB', 'zh-CN'. */ + /** The language that this voice supports, in the form language-region. Examples: 'en', 'en-US', 'en-GB', 'zh-CN'. */ lang?: string; /** - * Optional. This voice's gender. + * This voice's gender. * One of: 'male', or 'female' */ gender?: string; - /** Optional. The name of the voice. */ + /** The name of the voice. */ voiceName?: string; /** The ID of the extension providing this voice. */ extensionsId?: string; @@ -5014,7 +7741,7 @@ declare namespace chrome { } interface SpeakOptions { - /** Optional. Speaking volume between 0 and 1 inclusive, with 0 being lowest and 1 being highest, with a default of 1.0. */ + /** Speaking volume between 0 and 1 inclusive, with 0 being lowest and 1 being highest, with a default of 1.0. */ volume?: number; /** * Optional. @@ -5027,7 +7754,7 @@ declare namespace chrome { */ rate?: number; /** - * Optional. This function is called with events that occur in the process of speaking the utterance. + * This function is called with events that occur in the process of speaking the utterance. * @param event The update event from the text-to-speech engine indicating the status of this utterance. */ onEvent?: (event: TtsEvent) => void; @@ -5036,52 +7763,52 @@ declare namespace chrome { * Speaking pitch between 0 and 2 inclusive, with 0 being lowest and 2 being highest. 1.0 corresponds to a voice's default pitch. */ pitch?: number; - /** Optional. The language to be used for synthesis, in the form language-region. Examples: 'en', 'en-US', 'en-GB', 'zh-CN'. */ + /** The language to be used for synthesis, in the form language-region. Examples: 'en', 'en-US', 'en-GB', 'zh-CN'. */ lang?: string; - /** Optional. The name of the voice to use for synthesis. If empty, uses any available voice. */ + /** The name of the voice to use for synthesis. If empty, uses any available voice. */ voiceName?: string; - /** Optional. The extension ID of the speech engine to use, if known. */ + /** The extension ID of the speech engine to use, if known. */ extensionId?: string; /** - * Optional. Gender of voice for synthesized speech. + * Gender of voice for synthesized speech. * One of: 'male', or 'female' */ gender?: string; - /** Optional. The TTS event types the voice must support. */ + /** The TTS event types the voice must support. */ requiredEventTypes?: string[]; - /** Optional. The TTS event types that you are interested in listening to. If missing, all event types may be sent. */ + /** The TTS event types that you are interested in listening to. If missing, all event types may be sent. */ desiredEventTypes?: string[]; } /** Checks whether the engine is currently speaking. On Mac OS X, the result is true whenever the system speech engine is speaking, even if the speech wasn't initiated by Chrome. */ - export function isSpeaking(callback?: (speaking: boolean) => void): void; + function isSpeaking(callback?: (speaking: boolean) => void): void; /** Stops any current speech and flushes the queue of any pending utterances. In addition, if speech was paused, it will now be un-paused for the next call to speak. */ - export function stop(): void; + function stop(): void; /** Gets an array of all available voices. */ - export function getVoices(callback?: (voices: TtsVoice[]) => void): void; + function getVoices(callback?: (voices: TtsVoice[]) => void): void; /** * Speaks text using a text-to-speech engine. * @param utterance The text to speak, either plain text or a complete, well-formed SSML document. Speech engines that do not support SSML will strip away the tags and speak the text. The maximum length of the text is 32,768 characters. - * @param callback Optional. Called right away, before speech finishes. Check chrome.runtime.lastError to make sure there were no errors. Use options.onEvent to get more detailed feedback. + * @param callback Called right away, before speech finishes. Check chrome.runtime.lastError to make sure there were no errors. Use options.onEvent to get more detailed feedback. */ - export function speak(utterance: string, callback?: Function): void; + function speak(utterance: string, callback?: Function): void; /** * Speaks text using a text-to-speech engine. * @param utterance The text to speak, either plain text or a complete, well-formed SSML document. Speech engines that do not support SSML will strip away the tags and speak the text. The maximum length of the text is 32,768 characters. - * @param options Optional. The speech options. - * @param callback Optional. Called right away, before speech finishes. Check chrome.runtime.lastError to make sure there were no errors. Use options.onEvent to get more detailed feedback. + * @param options The speech options. + * @param callback Called right away, before speech finishes. Check chrome.runtime.lastError to make sure there were no errors. Use options.onEvent to get more detailed feedback. */ - export function speak(utterance: string, options: SpeakOptions, callback?: Function): void; + function speak(utterance: string, options: SpeakOptions, callback?: Function): void; /** * Pauses speech synthesis, potentially in the middle of an utterance. A call to resume or stop will un-pause speech. * @since Chrome 29. */ - export function pause(): void; + function pause(): void; /** * If speech was paused, resumes speaking where it left off. * @since Chrome 29. */ - export function resume(): void; + function resume(): void; } //////////////////// @@ -5122,14 +7849,14 @@ declare namespace chrome { } interface ChromeSettingGetDetails { - /** Optional. Whether to return the value that applies to the incognito session (default false). */ + /** Whether to return the value that applies to the incognito session (default false). */ incognito?: boolean; } /** * @param details Details of the currently effective value. */ - export type DetailsCallback = (details: ChromeSettingGetResultDetails) => void; + type DetailsCallback = (details: ChromeSettingGetResultDetails) => void; interface ChromeSettingGetResultDetails { /** @@ -5157,7 +7884,7 @@ declare namespace chrome { /** * Sets the value of a setting. * @param details Which setting to change. - * @param callback Optional. Called at the completion of the set operation. + * @param callback Called at the completion of the set operation. */ set(details: ChromeSettingSetDetails, callback?: Function): void; /** @@ -5168,7 +7895,7 @@ declare namespace chrome { /** * Clears the setting, restoring any default value. * @param details Which setting to clear. - * @param callback Optional. Called at the completion of the clear operation. + * @param callback Called at the completion of the clear operation. */ clear(details: ChromeSettingClearDetails, callback?: Function): void; /** Fired after the setting changes. */ @@ -5197,13 +7924,17 @@ declare namespace chrome { productId: number } + type EndpointType = 'control' | 'interrupt' | 'isochronous' | 'bulk'; + type EndpointSyncType = 'asynchronous' | 'adaptive' | 'synchronous'; + type EndpointUsage = 'data' | 'feedback' | 'explicitFeedback'; + interface EndpointDescriptor { address: number, - type: 'control' | 'interrupt' | 'isochronous' | 'bulk', + type: EndpointType, direction: Direction, maximumPacketSize: number, - synchronization?: 'asynchronous' | 'adaptive' | 'synchronous', - usage?: 'data' | 'feedback' | 'explicitFeedback', + synchronization?: EndpointSyncType, + usage?: EndpointUsage, pollingInterval?: number, extra_data: ArrayBuffer } @@ -5251,10 +7982,14 @@ declare namespace chrome { interfaceProtocol?: number } + type TransferRecipient = 'device' | 'interface' | 'endpoint' | 'other'; + + type TransferRequestType = 'standard' | 'class' | 'vendor' | 'reserved'; + interface TransferInfo { direction: Direction; - recipient: 'device' | 'interface' | 'endpoint' | 'other'; - requestType: 'standard' | 'class' | 'vendor' | 'reserved'; + recipient: TransferRecipient; + requestType: TransferRequestType; request: number; value: number; index: number; @@ -5265,27 +8000,27 @@ declare namespace chrome { interface DeviceEvent extends chrome.events.Event<(device: Device) => void> { } - export var onDeviceAdded: DeviceEvent; - export var onDeviceRemoved: DeviceEvent; + const onDeviceAdded: DeviceEvent; + const onDeviceRemoved: DeviceEvent; - export function getDevices(options: { vendorId?: number, productId?: number, filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void; - export function getUserSelectedDevices(options: { multiple?: boolean, filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void; - export function getConfigurations(device: Device, callback: (configs: ConfigDescriptor[]) => void): void; - export function requestAccess(device: Device, interfaceId: number, callback: (success: boolean) => void): void; - export function openDevice(device: Device, callback: (handle: ConnectionHandle) => void): void; - export function findDevices(options: { vendorId: number, productId: number, interfaceId?: number }, callback: (handles: ConnectionHandle[]) => void): void; - export function closeDevice(handle: ConnectionHandle, callback?: () => void): void; - export function setConfiguration(handle: ConnectionHandle, configurationValue: number, callback: () => void): void; - export function getConfiguration(handle: ConnectionHandle, callback: (config: ConfigDescriptor) => void): void; - export function listInterfaces(handle: ConnectionHandle, callback: (descriptors: InterfaceDescriptor[]) => void): void; - export function claimInterface(handle: ConnectionHandle, interfaceNumber: number, callback: () => void): void; - export function releaseInterface(handle: ConnectionHandle, interfaceNumber: number, callback: () => void): void; - export function setInterfaceAlternateSetting(handle: ConnectionHandle, interfaceNumber: number, alternateSetting: number, callback: () => void): void; - export function controlTransfer(handle: ConnectionHandle, transferInfo: TransferInfo, callback: (info: TransferResultInfo) => void): void; - export function bulkTransfer(handle: ConnectionHandle, transferInfo: GenericTransferInfo, callback: (info: TransferResultInfo) => void): void; - export function interruptTransfer(handle: ConnectionHandle, transferInfo: GenericTransferInfo, callback: (info: TransferResultInfo) => void): void; - export function isochronousTransfer(handle: ConnectionHandle, transferInfo: { transferInfo: GenericTransferInfo, packets: number, packetLength: number }, callback: (info: TransferResultInfo) => void): void; - export function resetDevice(handle: ConnectionHandle, callback: (success: boolean) => void): void; + function getDevices(options: { vendorId?: number, productId?: number, filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void; + function getUserSelectedDevices(options: { multiple?: boolean, filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void; + function getConfigurations(device: Device, callback: (configs: ConfigDescriptor[]) => void): void; + function requestAccess(device: Device, interfaceId: number, callback: (success: boolean) => void): void; + function openDevice(device: Device, callback: (handle: ConnectionHandle) => void): void; + function findDevices(options: { vendorId: number, productId: number, interfaceId?: number }, callback: (handles: ConnectionHandle[]) => void): void; + function closeDevice(handle: ConnectionHandle, callback?: () => void): void; + function setConfiguration(handle: ConnectionHandle, configurationValue: number, callback: () => void): void; + function getConfiguration(handle: ConnectionHandle, callback: (config: ConfigDescriptor) => void): void; + function listInterfaces(handle: ConnectionHandle, callback: (descriptors: InterfaceDescriptor[]) => void): void; + function claimInterface(handle: ConnectionHandle, interfaceNumber: number, callback: () => void): void; + function releaseInterface(handle: ConnectionHandle, interfaceNumber: number, callback: () => void): void; + function setInterfaceAlternateSetting(handle: ConnectionHandle, interfaceNumber: number, alternateSetting: number, callback: () => void): void; + function controlTransfer(handle: ConnectionHandle, transferInfo: TransferInfo, callback: (info: TransferResultInfo) => void): void; + function bulkTransfer(handle: ConnectionHandle, transferInfo: GenericTransferInfo, callback: (info: TransferResultInfo) => void): void; + function interruptTransfer(handle: ConnectionHandle, transferInfo: GenericTransferInfo, callback: (info: TransferResultInfo) => void): void; + function isochronousTransfer(handle: ConnectionHandle, transferInfo: { transferInfo: GenericTransferInfo, packets: number, packetLength: number }, callback: (info: TransferResultInfo) => void): void; + function resetDevice(handle: ConnectionHandle, callback: (success: boolean) => void): void; } @@ -5302,9 +8037,9 @@ declare namespace chrome { interface VpnSessionParameters { /** IP address for the VPN interface in CIDR notation. IPv4 is currently the only supported mode. */ address: string; - /** Optional. Broadcast address for the VPN interface. (default: deduced from IP address and mask) */ + /** Broadcast address for the VPN interface. (default: deduced from IP address and mask) */ broadcastAddress?: string; - /** Optional. MTU setting for the VPN interface. (default: 1500 bytes) */ + /** MTU setting for the VPN interface. (default: 1500 bytes) */ mtu?: string; /** * Exclude network traffic to the list of IP blocks in CIDR notation from the tunnel. This can be used to bypass traffic to and from the VPN server. When many rules match a destination, the rule with the longest matching prefix wins. Entries that correspond to the same CIDR block are treated as duplicates. Such duplicates in the collated (exclusionList + inclusionList) list are eliminated and the exact duplicate entry that will be eliminated is undefined. @@ -5314,7 +8049,7 @@ declare namespace chrome { * Include network traffic to the list of IP blocks in CIDR notation to the tunnel. This parameter can be used to set up a split tunnel. By default no traffic is directed to the tunnel. Adding the entry '0.0.0.0/0' to this list gets all the user traffic redirected to the tunnel. When many rules match a destination, the rule with the longest matching prefix wins. Entries that correspond to the same CIDR block are treated as duplicates. Such duplicates in the collated (exclusionList + inclusionList) list are eliminated and the exact duplicate entry that will be eliminated is undefined. */ inclusionList: string[]; - /** Optional. A list of search domains. (default: no search domain) */ + /** A list of search domains. (default: no search domain) */ domainSearch?: string[]; /** A list of IPs for the DNS servers. */ dnsServer: string[]; @@ -5336,135 +8071,123 @@ declare namespace chrome { * @param callback Called when the configuration is created or if there is an error. * Parameter id: A unique ID for the created configuration, empty string on failure. */ - export function createConfig(name: string, callback: (id: string) => void): void; + function createConfig(name: string, callback: (id: string) => void): void; /** * Destroys a VPN configuration created by the extension. * @param id ID of the VPN configuration to destroy. - * @param callback Optional. Called when the configuration is destroyed or if there is an error. + * @param callback Called when the configuration is destroyed or if there is an error. */ - export function destroyConfig(id: string, callback?: Function): void; + function destroyConfig(id: string, callback?: Function): void; /** * Sets the parameters for the VPN session. This should be called immediately after 'connected' is received from the platform. This will succeed only when the VPN session is owned by the extension. * @param parameters The parameters for the VPN session. * @param callback Called when the parameters are set or if there is an error. */ - export function setParameters(parameters: VpnSessionParameters, callback: Function): void; + function setParameters(parameters: VpnSessionParameters, callback: Function): void; /** * Sends an IP packet through the tunnel created for the VPN session. This will succeed only when the VPN session is owned by the extension. * @param data The IP packet to be sent to the platform. - * @param callback Optional. Called when the packet is sent or if there is an error. + * @param callback Called when the packet is sent or if there is an error. */ - export function sendPacket(data: ArrayBuffer, callback?: Function): void; + function sendPacket(data: ArrayBuffer, callback?: Function): void; /** * Notifies the VPN session state to the platform. This will succeed only when the VPN session is owned by the extension. * @param state The VPN session state of the VPN client. * connected: VPN connection was successful. * failure: VPN connection failed. - * @param callback Optional. Called when the notification is complete or if there is an error. + * @param callback Called when the notification is complete or if there is an error. */ - export function notifyConnectionStateChanged(state: string, callback?: Function): void; + function notifyConnectionStateChanged(state: string, callback?: Function): void; /** Triggered when a message is received from the platform for a VPN configuration owned by the extension. */ - export var onPlatformMessage: VpnPlatformMessageEvent; + const onPlatformMessage: VpnPlatformMessageEvent; /** Triggered when an IP packet is received via the tunnel for the VPN session owned by the extension. */ - export var onPacketReceived: VpnPacketReceptionEvent; + const onPacketReceived: VpnPacketReceptionEvent; /** Triggered when a configuration created by the extension is removed by the platform. */ - export var onConfigRemoved: VpnConfigRemovalEvent; + const onConfigRemoved: VpnConfigRemovalEvent; /** Triggered when a configuration is created by the platform for the extension. */ - export var onConfigCreated: VpnConfigCreationEvent; + const onConfigCreated: VpnConfigCreationEvent; /** Triggered when there is a UI event for the extension. UI events are signals from the platform that indicate to the app that a UI dialog needs to be shown to the user. */ - export var onUIEvent: VpnUiEvent; + const onUIEvent: VpnUiEvent; } - //////////////////// - // Wallpaper - //////////////////// + /////////////// + // Wallpaper // + /////////////// /** * Use the chrome.wallpaper API to change the ChromeOS wallpaper. - * Permissions: 'wallpaper' - * Important: This API works only on Chrome OS. + * @requires Permissions: 'wallpaper' + * @requires Important: This API works only on Chrome OS. * @since Chrome 43. */ namespace wallpaper { + type WallpaperLayout = + 'STRETCH' | + 'CENTER' | + 'CENTER_CROPPED'; interface WallpaperDetails { - /** Optional. The jpeg or png encoded wallpaper image. */ + /** The jpeg or png encoded wallpaper image. */ data?: any; - /** Optional. The URL of the wallpaper to be set. */ + /** The URL of the wallpaper to be set. */ url?: string; - /** - * The supported wallpaper layouts. - * One of: 'STRETCH', 'CENTER', or 'CENTER_CROPPED' - */ - layout: string; + /** The supported wallpaper layouts. */ + layout: WallpaperLayout; /** The file name of the saved wallpaper. */ filename: string; - /** Optional. True if a 128x60 thumbnail should be generated. */ + /** True if a 128x60 thumbnail should be generated. */ thumbnail?: boolean; } /** * Sets wallpaper to the image at url or wallpaperData with the specified layout - * @param callback - * Optional parameter thumbnail: The jpeg encoded wallpaper thumbnail. It is generated by resizing the wallpaper to 128x60. + * @param callback Contains the optional parameter thumbnail: The jpeg encoded wallpaper thumbnail. It is generated by resizing the wallpaper to 128x60. */ - export function setWallpaper(details: WallpaperDetails, callback: (thumbnail: any) => void): void; + function setWallpaper(details: WallpaperDetails, callback: (thumbnail?: string) => void): void; } - /////////////////// - // Webview Tag - /////////////////// + ///////////////// + // Webview Tag // + ///////////////// /** - * Use the webview tag to actively load live content from the web over the network and embed it in your Chrome App. Your app can control the appearance of the webview and interact with the web content, initiate navigations in an embedded web page, react to error events that happen within it, and more (see Usage). + * Use the webview tag to actively load live content from the web over the network and embed it in your Chrome App. + * Your app can control the appearance of the *webview* and interact with the web content, initiate navigations in + * an embedded web page, react to error events that happen within it. */ namespace webview { - /** Options that determine what data should be cleared by `clearData`. */ + /** Options that determine what data should be cleared by *clearData`* */ interface ClearDataOptions { - /** Clear data accumulated on or after this date, represented in milliseconds since the epoch (accessible via the getTime method of the JavaScript Date object). If absent, defaults to 0 (which would remove all browsing data). */ + /** + * Clear data accumulated on or after this date, + * represented in milliseconds since the epoch + * (accessible via the getTime method of the JavaScript *Date* object). + * If absent, defaults to *0* (which would remove all browsing data). + **/ since?: number; } interface WindowEvent extends chrome.events.Event<() => void> { } interface ConsoleEvent extends Event { - /** - * @description The severity level of the log message. Ranges from 0 to 4. - * @type {number} - * @memberof ConsoleEvent - */ + /** The severity level of the log message. Ranges from 0 to 4. */ level: number; - /** - * @description The logged message contents. - * @type {string} - * @memberof ConsoleEvent - */ + /** The logged message contents.*/ message: string; - /** - * @description The line number of the message source. - * @type {number} - * @memberof ConsoleEvent - */ + /** The line number of the message source.*/ line: number; - /** - * @description A string identifying the resource which logged the message. - * @type {string} - * @memberof ConsoleEvent - */ + /** A string identifying the resource which logged the message. */ sourceId: string; } + type ExitEventReason = + 'normal' | + 'abnormal' | + 'crash' | + 'kill'; interface ExitEvent extends Event { - /** - * @description Chrome's internal ID of the process that exited. - * @type {number} - * @memberof ExitEvent - */ + /** Chrome's internal ID of the process that exited. */ processID: number; - /** - * @description String indicating the reason for the exit. - * @type {string} - * @memberof ExitEvent - */ - reason: 'normal' | 'abnormal' | 'crash' | 'kill'; + /** String indicating the reason for the exit. */ + reason: ExitEventReason; } /** Description of a declarative rule for handling events. */ @@ -5473,47 +8196,44 @@ declare namespace chrome { priority?: number; /** List of conditions that can trigger the actions. */ conditions: any[]; - /** Optional. Optional identifier that allows referencing this rule. */ + /** Optional identifier that allows referencing this rule. */ id?: string; /** List of actions that are triggered if one of the condtions is fulfilled. */ actions: any[]; /** - * @description Tags can be used to annotate rules and perform operations on sets of rules.¨ + * Tags can be used to annotate rules and perform operations on sets of rules.¨ * @since Chrome 28 - * @type {string[]} - * @memberof Rule */ tags?: string[]; } /** - * @description Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. - * @export - * @interface InjectDetails + * Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. */ interface InjectDetails { /** - * @description JavaScript or CSS code to inject.

Warning:
Be careful using the code parameter. Incorrect use of it may open your app to cross site scripting attacks. - * @type {string} - * @memberof InjectDetails + * JavaScript or CSS code to inject. + * + * **Warning** + * Be careful using the *code* parameter. + * Incorrect use of it may open your app to + * cross site scripting attacks. + * @see[More information]{@link https://en.wikipedia.org/wiki/Cross-site_scripting} */ code?: string, /** - * @description JavaScript or CSS file to inject. - * @type {string} - * @memberof InjectDetails + * JavaScript or CSS file to inject. */ file?: string } /** - * @description WebView element from html + * WebView element from html */ - interface HTMLWebViewElement extends Element { - /** - * This sets the guest content's window.name object. - */ + interface HTMLWebViewElement extends HTMLElement { + /** This sets the guest content's window.name object.**/ name: string; + /** * Returns the visible URL. Mirrors the logic in the browser's omnibox: either returning a pending new navigation if initiated by the embedder page, or the last committed navigation. Writing to this attribute initiates top-level navigation. * Assigning src its own value will reload the current page. @@ -5521,28 +8241,45 @@ declare namespace chrome { * The src attribute can also accept data URLs, such as 'data:text/plain,Hello, world!'. */ src: string; + /** - * Storage partition ID used by the webview tag. If the storage partition ID starts with persist: (partition='persist:googlepluswidgets'), the webview will use a persistent storage partition available to all guests in the app with the same storage partition ID. If the ID is unset or if there is no 'persist': prefix, the webview will use an in-memory storage partition. This value can only be modified before the first navigation, since the storage partition of an active renderer process cannot change. Subsequent attempts to modify the value will fail with a DOM exception. By assigning the same partition ID, multiple webviews can share the same storage partition. + * Storage partition ID used by the webview tag. + * If the storage partition ID starts with persist: (partition='persist:googlepluswidgets'), + * the webview will use a persistent storage partition available to all guests in the app with the same storage partition ID. + * If the ID is unset or if there is no 'persist': prefix, the webview will use an in-memory storage partition. + * his value can only be modified before the first navigation, since the storage partition of an active renderer process cannot change. + * Subsequent attempts to modify the value will fail with a DOM exception. + * By assigning the same partition ID, multiple webviews can share the same storage partition. */ partition?: string; + /** - * If present, portions of the embedder could be visible through the webview, where the contents are transparent. Without allowtransparency enabled, no part of the embedder will be shown through the webview, even if elements exist that are specified as transparent. + * If present, portions of the embedder could be visible through the webview, + * where the contents are transparent. Without allowtransparency enabled, + * no part of the embedder will be shown through the webview, + * even if elements exist that are specified as transparent. * This does not affect transparency within the contents of the webview itself. */ allowtransparency?: boolean; + /** * If 'on', the webview container will automatically resize within the bounds specified by the attributes minwidth, minheight, maxwidth, and maxheight. * These constraints do not impact the webview UNLESS autosize is enabled. * When autosize is enabled, the webview container size cannot be less than the minimum values or greater than the maximum. */ autosize?: 'on'; + /** * Object reference which can be used to post messages into the guest page. */ contentWindow: ContentWindow; + /** Interface which provides access to webRequest events on the guest page. */ request: WebRequestEventInterface; - /** Similar to chrome's ContextMenus API, but applies to webview instead of browser. Use the webview.contextMenus API to add items to webview's context menu. You can choose what types of objects your context menu additions apply to, such as images, hyperlinks, and pages. */ + + /** Similar to chrome's ContextMenus API, but applies to webview instead of browser. + * Use the webview.contextMenus API to add items to webview's context menu. + * You can choose what types of objects your context menu additions apply to, such as images, hyperlinks, and pages. */ contextMenus: webview.ContextMenus; /** * Fired when the guest window attempts to close itself. @@ -5553,7 +8290,7 @@ declare namespace chrome { * Fired when the guest window logs a console message. * The following example code forwards all log messages to the embedder's console without regard for log level or other properties. */ - addEventListener(type: 'consolemessage', listener: (this: HTMLWebViewElement, ev: IConsoleMessage) => void, useCapture?: boolean): void; + addEventListener(type: 'consolemessage', listener: (this: HTMLWebViewElement, ev: ConsoleMessage) => void, useCapture?: boolean): void; /** * Fired when the guest window fires a load event, i.e., when a new document is loaded. This does not include page navigation within the current document or asynchronous resource loads. * The following example code modifies the default font size of the guest's body element after the page loads: @@ -5568,33 +8305,33 @@ declare namespace chrome { * Handling this event will block the guest process until each event listener returns or the dialog object becomes unreachable (if preventDefault() was called.) * The default behavior is to cancel the dialog. */ - addEventListener(type: 'dialog', listener: (this: HTMLWebViewElement, ev: IDialog) => void, useCapture?: boolean): void; + addEventListener(type: 'dialog', listener: (this: HTMLWebViewElement, ev: Dialog) => void, useCapture?: boolean): void; /** * Fired when the process rendering the guest web content has exited. */ - addEventListener(type: 'exit', listener: (this: HTMLWebViewElement, ev: IExit) => void, useCapture?: boolean): void; + addEventListener(type: 'exit', listener: (this: HTMLWebViewElement, ev: Exit) => void, useCapture?: boolean): void; /** * Fired when new find results are available for an active find request. This might happen multiple times for a single find request as matches are found. */ - addEventListener(type: 'findupdate', listener: (this: HTMLWebViewElement, ev: IFindupdate) => void, useCapture?: boolean): void; + addEventListener(type: 'findupdate', listener: (this: HTMLWebViewElement, ev: FindUpdate) => void, useCapture?: boolean): void; /** * Fired when a top-level load has aborted without committing. An error message will be printed to the console unless the event is default-prevented. * Note: When a resource load is aborted, a loadabort event will eventually be followed by a loadstop event, even if all committed loads since the last loadstop event (if any) were aborted. * Note: When the load of either an about URL or a JavaScript URL is aborted, loadabort will be fired and then the webview will be navigated to 'about:blank'. */ - addEventListener(type: 'loadabort', listener: (this: HTMLWebViewElement, ev: ILoadabort) => void, useCapture?: boolean): void; + addEventListener(type: 'loadabort', listener: (this: HTMLWebViewElement, ev: LoadAbort) => void, useCapture?: boolean): void; /** * Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. */ - addEventListener(type: 'loadcommit', listener: (this: HTMLWebViewElement, ev: ILoadcommit) => void, useCapture?: boolean): void; + addEventListener(type: 'loadcommit', listener: (this: HTMLWebViewElement, ev: LoadCommit) => void, useCapture?: boolean): void; /** * Fired when a top-level load request has redirected to a different URL. */ - addEventListener(type: 'loadredirect', listener: (this: HTMLWebViewElement, ev: ILoadredirect) => void, useCapture?: boolean): void; + addEventListener(type: 'loadredirect', listener: (this: HTMLWebViewElement, ev: LoadRedirect) => void, useCapture?: boolean): void; /** * Fired when a load has begun. */ - addEventListener(type: 'loadstart', listener: (this: HTMLWebViewElement, ev: ILoadstart) => void, useCapture?: boolean): void; + addEventListener(type: 'loadstart', listener: (this: HTMLWebViewElement, ev: LoadStart) => void, useCapture?: boolean): void; /** * Fired when all frame-level loads in a guest page (including all its subframes) have completed. * This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. @@ -5608,12 +8345,12 @@ declare namespace chrome { * The following example code will create and navigate a new webview in the embedder for each requested new window: * @example * webview.addEventListener('newwindow', function(e) { - * var newWebview = document.createElement('webview'); + * const newWebview = document.createElement('webview'); * document.body.appendChild(newWebview); * e.window.attach(newWebview); * }); */ - addEventListener(type: 'newwindow', listener: (this: HTMLWebViewElement, ev: INewwindow) => void, useCapture?: boolean): void; + addEventListener(type: 'newwindow', listener: (this: HTMLWebViewElement, ev: NewWindow) => void, useCapture?: boolean): void; /** * Fired when the guest page needs to request special permission from the embedder. * The following example code will grant the guest page access to the webkitGetUserMedia API. @@ -5625,40 +8362,40 @@ declare namespace chrome { * } * }); */ - addEventListener(type: 'permissionrequest', listener: (this: HTMLWebViewElement, ev: IPermissionrequest) => void, useCapture?: boolean): void; + addEventListener(type: 'permissionrequest', listener: (this: HTMLWebViewElement, ev: PermissionRequest) => void, useCapture?: boolean): void; /** Fired when the process rendering the guest web content has become responsive again after being unresponsive. */ - addEventListener(type: 'response', listener: (this: HTMLWebViewElement, ev: IResponsive) => void, useCapture?: boolean): void; + addEventListener(type: 'response', listener: (this: HTMLWebViewElement, ev: ProcessResponsive) => void, useCapture?: boolean): void; /** Fired when the embedded web content has been resized via autosize. Only fires if autosize is enabled. */ - addEventListener(type: 'sizechanged', listener: (this: HTMLWebViewElement, ev: ISizechanged) => void, useCapture?: boolean): void; + addEventListener(type: 'sizechanged', listener: (this: HTMLWebViewElement, ev: SizeChanged) => void, useCapture?: boolean): void; /** Fired when the process rendering the guest web content has become unresponsive. This event will be generated once with a matching responsive event if the guest begins to respond again. */ - addEventListener(type: 'unresponsive', listener: (this: HTMLWebViewElement, ev: IUnresponsive) => void, useCapture?: boolean): void; + addEventListener(type: 'unresponsive', listener: (this: HTMLWebViewElement, ev: ProcessUnresponsive) => void, useCapture?: boolean): void; /** Fired when the page's zoom changes. */ - addEventListener(type: 'zoomchange', listener: (this: HTMLWebViewElement, ev: IZoomchange) => void, useCapture?: boolean): void; + addEventListener(type: 'zoomchange', listener: (this: HTMLWebViewElement, ev: ZoomChange) => void, useCapture?: boolean): void; /** - * @description Queries audio state. - */ + * Queries audio state. + **/ getAudioState(callback: (audible: boolean) => void): void; /** - * @description Sets audio mute state of the webview. - * @param {boolean} mute Mute audio value + * Sets audio mute state of the webview. + * @param mute Mute audio value */ setAudioMuted(mute: boolean): void; /** - * @description Queries whether audio is muted. + * Queries whether audio is muted. */ isAudioMuted(callback: (muted: boolean) => void): void; /** - * @description Captures the visible region of the webview. - * @param {(dataUrl: string) => void} callback A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. + * Captures the visible region of the webview. + * @param callback A data URL which encodes an image of the visible area of the captured tab. May be assigned to the 'src' property of an HTML Image element for display. */ captureVisibleRegion(callback: (dataUrl: string) => void): void; /** - * @description Captures the visible region of the webview. - * @param {*} options - * @param {(dataUrl: string) => void} callback + * Captures the visible region of the webview. + * @param options + * @param callback */ captureVisibleRegion(options: chrome.extensionTypes.ImageDetails, callback: (dataUrl: string) => void): void; @@ -5713,1059 +8450,975 @@ declare namespace chrome { addContentScripts(contentScriptList: ContentScriptDetails[]): void; /** - * @description Navigates backward one history entry if possible. Equivalent to go(-1). - * @param {(success: boolean) => void} [callback] Called after the navigation has either failed or completed successfully. Success parameter indicates whether the navigation was successful. + * Navigates backward one history entry if possible. Equivalent to go(-1). + * @param [callback] Called after the navigation has either failed or completed successfully. Success parameter indicates whether the navigation was successful. */ back(callback?: (success: boolean) => void): void; /** - * @description Indicates whether or not it is possible to navigate backward through history. The state of this function is cached, and updated before each loadcommit, so the best place to call it is on loadcommit. + * Indicates whether or not it is possible to navigate backward through history. + * The state of this function is cached, and updated before each loadcommit, + * so the best place to call it is on loadcommit. */ canGoBack(): void; /** - * @description Indicates whether or not it is possible to navigate forward through history. The state of this function is cached, and updated before each loadcommit, so the best place to call it is on loadcommit. + * Indicates whether or not it is possible to navigate forward through history. + * The state of this function is cached, and updated before each loadcommit, + * so the best place to call it is on loadcommit. */ canGoForward(): void; /** - * @description

Clears browsing data for the webview partition.

- * @param options Options determining which data to clear. - * @param types The types of data to be cleared. + * Clears browsing data for the webview partition. + * @param options Options determining which data to clear. + * @param types The types of data to be cleared. * @param callback */ clearData(options: ClearDataOptions, types: ClearDataTypeSet, callback?: () => void): void; /** - * @description

Injects JavaScript code into the guest page.

The following sample code uses script injection to set the guest page's background color to red:

webview.executeScript({ code: 'document.body.style.backgroundColor = 'red'' });
- * @param details Details of the script to run. + * Injects JavaScript code into the guest page. + * The following sample code uses script injection + * to set the guest page's background color to red: + * @example webview.executeScript({ code: 'document.body.style.backgroundColor = 'red'' }); + * @param details Details of the script to run. * @param callback */ executeScript(details: InjectDetails, callback?: (result?: any[]) => void): void; /** - * @description Initiates a find-in-page request. - * @param {string} searchText The string to find in the page. - * @param options Options for the find request. + * Initiates a find-in-page request. + * @param {string} searchText The string to find in the page. + * @param options Options for the find request. * @param callback */ find(searchText: string, options?: FindOptions, callback?: (results?: any) => void): void; /** - * @description Navigates forward one history entry if possible. Equivalent to go(1). + * Navigates forward one history entry if possible. Equivalent to go(1). * @param callback */ forward(callback?: (success: boolean) => void): void; /** - * @description Returns Chrome's internal process ID for the guest web page's current process, allowing embedders to know how many guests would be affected by terminating the process. Two guests will share a process only if they belong to the same app and have the same storage partition ID. The call is synchronous and returns the embedder's cached notion of the current process ID. The process ID isn't the same as the operating system's process ID. + * Returns Chrome's internal process ID for the guest web page's current process, allowing embedders to know how many guests would be affected by terminating the process. Two guests will share a process only if they belong to the same app and have the same storage partition ID. The call is synchronous and returns the embedder's cached notion of the current process ID. The process ID isn't the same as the operating system's process ID. */ getProcessId(): void; /** - * @description Returns the user agent string used by the webview for guest page requests. + * Returns the user agent string used by the webview for guest page requests. */ getUserAgent(): void; /** - * @description Gets the current zoom factor. + * Gets the current zoom factor. * @param callback */ getZoom(callback: (zoomFactor: number) => void): void; /** - * @description Gets the current zoom mode. + * Gets the current zoom mode. * @param callback */ getZoomMode(callback: (ZoomMode: any) => void): void; /** - * @description Navigates to a history entry using a history index relative to the current navigation. If the requested navigation is impossible, this method has no effect. - * @param {number} relativeIndex Relative history index to which the webview should be navigated. For example, a value of 2 will navigate forward 2 history entries if possible; a value of -3 will navigate backward 3 entries. + * Navigates to a history entry using a history index relative to the current navigation. + * If the requested navigation is impossible, this method has no effect. + * @param relativeIndex Relative history index to which the webview should be navigated. + * For example, a value of 2 will navigate forward 2 history entries if possible; + * a value of -3 will navigate backward 3 entries. * @param callback */ go(relativeIndex: number, callback?: (success: boolean) => void): void; /** - * @description Injects CSS into the guest page. - * @param details Details of the CSS to insert. + * Injects CSS into the guest page. + * @param details Details of the CSS to insert. * @param callback */ insertCSS(details: InjectDetails, callback?: () => void): void; - /** - * @description Indicates whether or not the webview's user agent string has been overridden by $(ref:webviewTag.setUserAgentOverride). - */ + /** Indicates whether or not the webview's user agent string has been overridden by *setUserAgentOverride*. */ isUserAgentOverridden(): void; - /** - * @description Prints the contents of the webview. This is equivalent to calling scripted print function from the webview itself. - */ + /** Prints the contents of the webview. This is equivalent to calling scripted print function from the webview itself. */ print(): void; - /** - * @description Reloads the current top-level page. - */ + /** Reloads the current top-level page. */ reload(): void; /** - * @description Removes content scripts from a webview. - * @description The following example removes 'myRule' which was added before. - * @example webview.removeContentScripts(['myRule']); - * @description You can remove all the rules by calling: - * @example webview.removeContentScripts(); - * @param {any[]} scriptNameList A list of names of content scripts that will be removed. If the list is empty, all the content scripts added to the webview will be removed. + * Removes content scripts from a webview. + * The following example removes 'myRule' which was added before. + * @example webview.removeContentScripts(['myRule']); + * @description You can remove all the rules by calling: + * @example webview.removeContentScripts(); + * @todo TODO LIST FIX + * @param {any[]} scriptNameList A list of names of content scripts that will be removed. If the list is empty, all the content scripts added to the webview will be removed. */ removeContentScripts(scriptNameList?: any[]): void; /** - * @description Override the user agent string used by the webview for guest page requests. - * @param {string} userAgent The user agent string to use. + * Override the user agent string used by the webview for guest page requests. + * @param userAgent The user agent string to use. */ setUserAgentOverride(userAgent: string): void; /** - * @description Changes the zoom factor of the page. The scope and persistence of this change are determined by the webview's current zoom mode (see $(ref:webviewTag.ZoomMode)). - * @param {number} zoomFactor The new zoom factor. - * @param callback + * Changes the zoom factor of the page. + * The scope and persistence of this change + * are determined by the webview's current zoom mode. + * @param zoomFactor The new zoom factor. + * @param [callback] */ setZoom(zoomFactor: number, callback?: () => void): void; /** - * @description Sets the zoom mode of the webview. - * @param ZoomMode Defines how zooming is handled in the webview. - * @param callback + * Sets the zoom mode of the webview. + * @param ZoomMode Defines how zooming is handled in the webview. + * @param [callback] */ setZoomMode(ZoomMode: ZoomMode, callback?: () => void): void; - /** - * @description Stops loading the current webview navigation if in progress. - */ + /** Stops loading the current webview navigation if in progress. */ stop(): void; /** - * @description Ends the current find session (clearing all highlighting) and cancels all find requests in progress. - * @param {string} action Determines what to do with the active match after the find session has ended. clear will clear the highlighting over the active match; keep will keep the active match highlighted; activate will keep the active match highlighted and simulate a user click on that match. The default action is keep. + * @todo TODO Fix action param + * Ends the current find session (clearing all highlighting) + * and cancels all find requests in progress. + * @param {string} action Determines what to do with the active match after the find session has ended. clear will clear the highlighting over the active match; keep will keep the active match highlighted; activate will keep the active match highlighted and simulate a user click on that match. The default action is keep. */ stopFinding(action?: string): void; /** - * @description Loads a data URL with a specified base URL used for relative links. Optionally, a virtual URL can be provided to be shown to the user instead of the data URL. - * @param {string} dataUrl The data URL to load. - * @param {string} baseUrl The base URL that will be used for relative links. - * @param {string} virtualUrl The URL that will be displayed to the user (in the address bar). + * Loads a data URL with a specified base URL used for relative links. + * Optionally, a virtual URL can be provided to be shown to the user instead of the data URL. + * @param {string} dataUrl The data URL to load. + * @param {string} baseUrl The base URL that will be used for relative links. + * @param {string} virtualUrl The URL that will be displayed to the user (in the address bar). */ loadDataWithBaseUrl(dataUrl: string, baseUrl: string, virtualUrl?: string): void; /** - * @description Forcibly kills the guest web page's renderer process. This may affect multiple webview tags in the current app if they share the same process, but it will not affect webview tags in other apps. + * Forcibly kills the guest web page's renderer process. + * This may affect multiple webview tags in the current app if they share the same process, + * but it will not affect webview tags in other apps. */ terminate(): void; /** - * @description Fired when the guest window attempts to close itself.

The following example code navigates the webview to about:blank when the guest attempts to close itself.

webview.addEventListener('close', function() {
-              webview.src = 'about:blank';
-            });
+ * Fired when the guest window attempts to close itself. + * The following example code navigates the webview to + * about:blank when the guest attempts to close itself. + * @example + * webview.addEventListener('close', function() { + * webview.src = 'about:blank'; + * }); */ - close(event: chrome.events.Event): void; /** - * @description Fired when the guest window logs a console message.

The following example code forwards all log messages to the embedder's console without regard for log level or other properties.

webview.addEventListener('consolemessage', function(e) {
-              console.log('Guest page logged a message: ', e.message);
-            });
- * @param callback + * Fired when the guest window logs a console message. + * The following example code forwards all log messages + * to the embedder's console without regard for log level + * or other properties. + * @example + * webview.addEventListener('consolemessage', function(e) { + * console.log('Guest page logged a message: ', e.message); + * }); */ - - consolemessage: chrome.events.Event; + consolemessage: chrome.events.Event; /** - * @description Fired when the guest window fires a load event, i.e., when a new document is loaded. This does not include page navigation within the current document or asynchronous resource loads.

The following example code modifies the default font size of the guest's body element after the page loads:

webview.addEventListener('contentload', function() {
-              webview.executeScript({ code: 'document.body.style.fontSize = '42px'' });
-            });
+ * Fired when the guest window fires a load event, i.e., when a new document is loaded. + * This does *not* include page navigation within the current document or asynchronous + * resource loads. The following example code modifies the default font size of the + * guest's body element after the page loads: + * @example + * webview.addEventListener('contentload', function() { + * webview.executeScript({ code: 'document.body.style.fontSize = '42px'' }); + * }); */ - contentload: (event: chrome.events.Event) => void; /** - * @description Fired when the guest window attempts to open a modal dialog via window.alert, window.confirm, or window.prompt.

Handling this event will block the guest process until each event listener returns or the dialog object becomes unreachable (if preventDefault() was called.)

The default behavior is to cancel the dialog.

+ * Fired when the guest window attempts to open a modal dialog via window.alert, window.confirm, or window.prompt.

Handling this event will block the guest process until each event listener returns or the dialog object becomes unreachable (if preventDefault() was called.)

The default behavior is to cancel the dialog.

* @param callback */ - dialog: chrome.events.Event; + dialog: chrome.events.Event; /** - * @description Fired when the process rendering the guest web content has exited.

The following example code will show a farewell message whenever the guest page crashes:

webview.addEventListener('exit', function(e) {
-              if (e.reason === 'crash') {
-                webview.src = 'data:text/plain,Goodbye, world!';
-              }
-            });
+ * Fired when the process rendering the guest web content has exited. + * The following example code will show a farewell message whenever + * the guest page crashes: + * @example + * webview.addEventListener('exit', function(e) { + * if (e.reason === 'crash') { + * webview.src = 'data:text/plain,Goodbye, world!'; + * } + * }); * @param callback */ - exit: chrome.events.Event; + exit: chrome.events.Event; /** - * @description Fired when new find results are available for an active find request. This might happen multiple times for a single find request as matches are found. + * Fired when new find results are available for an active find request. + * This might happen multiple times for a single find request as matches are found. + */ + + findupdate: chrome.events.Event; + + /** + * Fired when a top-level load has aborted without committing. + * An error message will be printed to the console unless the event is default-prevented. + * @requires Note: When a resource load is aborted, + * a loadabort event will eventually be followed by a loadstop event, + * even if all committed loads since the last loadstop event (if any) + * were aborted. + * @requires Note: When the load of either an about URL + * or a JavaScript URL is aborted, loadabort will be fired + * and then the webview will be navigated to 'about:blank'. + */ + + loadabort: chrome.events.Event; + + /** + * Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. * @param callback */ - findupdate: chrome.events.Event; + loadcommit: chrome.events.Event; /** - * @description Fired when a top-level load has aborted without committing. An error message will be printed to the console unless the event is default-prevented.

Note: When a resource load is aborted, a loadabort event will eventually be followed by a loadstop event, even if all committed loads since the last loadstop event (if any) were aborted.

Note: When the load of either an about URL or a JavaScript URL is aborted, loadabort will be fired and then the webview will be navigated to 'about:blank'.

+ * Fired when a top-level load request has redirected to a different URL. * @param callback */ - loadabort: chrome.events.Event; + loadredirect: chrome.events.Event; /** - * @description Fired when a load has committed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. + * Fired when a load has begun. * @param callback */ - loadcommit: chrome.events.Event; + loadstart: chrome.events.Event; /** - * @description Fired when a top-level load request has redirected to a different URL. - * @param callback + * Fired when all frame-level loads in a guest page (including all its subframes) + * have completed. This includes navigation within the current document as well + * as subframe document-level loads, but does not(!) include asynchronousresource + * loads. This event fires every time the number of document-level loads transitions + * from one (or more) to zero. For example, if a page that has already finished loading + * (i.e., loadstop already fired once) creates a new iframe which loads a page, + * then a second loadstop will fire when the iframe page load completes. This pattern + * is commonly observed on pages that load ads. + * @requires Note: When a committed load is aborted, + * a loadstop event will eventually follow a loadabort event, + * even if all committed loads since the last loadstop event (if any) were aborted. */ - - loadredirect: chrome.events.Event; - - /** - * @description Fired when a load has begun. - * @param callback - */ - - loadstart: chrome.events.Event; - - /** - * @description Fired when all frame-level loads in a guest page (including all its subframes) have completed. This includes navigation within the current document as well as subframe document-level loads, but does not include asynchronous resource loads. This event fires every time the number of document-level loads transitions from one (or more) to zero. For example, if a page that has already finished loading (i.e., loadstop already fired once) creates a new iframe which loads a page, then a second loadstop will fire when the iframe page load completes. This pattern is commonly observed on pages that load ads.

Note: When a committed load is aborted, a loadstop event will eventually follow a loadabort event, even if all committed loads since the last loadstop event (if any) were aborted.

- */ - loadstop(event: chrome.events.Event): void; /** - * @description Fired when the guest page attempts to open a new browser window.

The following example code will create and navigate a new webview in the embedder for each requested new window:

webview.addEventListener('newwindow', function(e) {
-              var newWebview = document.createElement('webview');
-              document.body.appendChild(newWebview);
-              e.window.attach(newWebview);
-            });
- * @param callback + * Fired when the guest page attempts to open a new browser window. + * The following example code will create and navigate a new webview + * in the embedder for each requested new window: + * @example + * webview.addEventListener('newwindow', function(e) { + * const newWebview = document.createElement('webview'); + * document.body.appendChild(newWebview); + * e.window.attach(newWebview); + * }); */ - newwindow: chrome.events.Event; + newwindow: chrome.events.Event; /** - * @description Fired when the guest page needs to request special permission from the embedder.

The following example code will grant the guest page access to the webkitGetUserMedia API. Note that an app using this example code must itself specify audioCapture and/or videoCapture manifest permissions:

webview.addEventListener('permissionrequest', function(e) {
-              if (e.permission === 'media') {
-                e.request.allow();
-              }
-            });
- * @param callback + * Fired when the guest page needs to request special permission from the embedder. + * The following example code will grant the guest page access to the webkitGetUserMedia API. + * Note that an app using this example code must itself specify audioCapture and / or + * videoCapture manifest permissions: + * @example + * webview.addEventListener('permissionrequest', function(e) { + * if (e.permission === 'media') { + * e.request.allow(); + * } + * }); */ - permissionrequest: chrome.events.Event; + permissionrequest: chrome.events.Event; /** - * @description Fired when the process rendering the guest web content has become responsive again after being unresponsive.

The following example code will fade the webview element in or out as it becomes responsive or unresponsive:

webview.style.webkitTransition = 'opacity 250ms';
-            webview.addEventListener('unresponsive', function() {
-              webview.style.opacity = '0.5';
-            });
-            webview.addEventListener('responsive', function() {
-              webview.style.opacity = '1';
-            });
- * @param callback + * Fired when the process rendering the guest web content has become + * responsive again after being unresponsive. + * + * The following example code will fade the webview element + * in or out as it becomes responsive or unresponsive: + * + * @example + * webview.style.webkitTransition = 'opacity 250ms'; + * webview.addEventListener('unresponsive', function() { + * webview.style.opacity = '0.5'; + * }); + * webview.addEventListener('responsive', function() { + * webview.style.opacity = '1'; + * }); */ - - responsive: chrome.events.Event; - + responsive: chrome.events.Event; /** - * @description Fired when the embedded web content has been resized via autosize. Only fires if autosize is enabled. - * @param callback + * Fired when the embedded web content has been resized via autosize. + * @requires Note: Only fires if autosize is enabled. */ - - sizechanged: chrome.events.Event; - + sizechanged: chrome.events.Event; /** - * @description Fired when the process rendering the guest web content has become unresponsive. This event will be generated once with a matching responsive event if the guest begins to respond again. - * @param callback + * Fired when the process rendering the guest web content has become unresponsive. + * This event will be generated once with a matching responsive event if the guest begins to respond again. */ - - unresponsive: chrome.events.Event; - + unresponsive: chrome.events.Event; /** - * @description Fired when the page's zoom changes. - * @param callback + * Fired when the page's zoom changes. */ - - zoomchange: chrome.events.Event; + zoomchange: chrome.events.Event; } - /**Options that determine what data should be cleared by clearData. */ + /** Options that determine what data should be cleared by clearData. */ interface ClearDataOptions { - /** - * @description Clear data accumulated on or after this date, represented in milliseconds since the epoch (accessible via the getTime method of the JavaScript Date object). If absent, defaults to 0 (which would remove all browsing data). + * Clear data accumulated on or after this date, + * represented in milliseconds since the epoch + * (accessible via the getTime method of the JavaScript Date object). + * If absent, defaults to 0 (which would remove all browsing data). + * @default 0 */ - since?: number; + since?: integer; } - /**A set of data types. Missing properties are interpreted as false. */ + /** A set of data types. Missing properties are interpreted as false. */ interface ClearDataTypeSet { - + /** Websites' appcaches. */ + appcache?: boolean; /** - * @description Websites' appcaches. + * The browser's cache. Note: when removing data, this clears the entire cache; it is not limited to the range you specify. + * @since Available since Chrome 43. */ - appcache?: boolean - - /** - * @description Since Chrome 43. The browser's cache. Note: when removing data, this clears the entire cache; it is not limited to the range you specify. - */ - cache?: boolean - - /** - * @description The partition's cookies. - */ - cookies?: boolean - - /** - * @description The partition's session cookies. - */ - sessionCookies?: boolean - - /** - * @description The partition's persistent cookies. - */ - persistentCookies?: boolean - - /** - * @description Websites' filesystems. - */ - fileSystems?: boolean - - /** - * @description Websites' IndexedDB data. - */ - indexedDB?: boolean - - /** - * @description Websites' local storage data. - */ - localStorage?: boolean - - /** - * @description Websites' WebSQL data. - */ - webSQL?: boolean + cache?: boolean; + /** The partition's cookies. */ + cookies?: boolean; + /** The partition's session cookies. */ + sessionCookies?: boolean; + /** The partition's persistent cookies. */ + persistentCookies?: boolean; + /** Websites' filesystems. */ + fileSystems?: boolean; + /** Websites' IndexedDB data. */ + indexedDB?: boolean; + /** Websites' local storage data. */ + localStorage?: boolean; + /** Websites' WebSQL data. */ + webSQL?: boolean; } /** - * The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of all other contexts. - * Enum values: - * 'all' - * 'page' - * 'frame' - * 'selection' - * 'link' - * 'editable' - * 'image' - * 'video' - * 'audio' */ - export type ContextType = 'all' | 'page' | 'frame' | 'selection' | 'link' | 'editable' | 'image' | 'video' | 'audio'; - /**Details of the script or CSS to inject. Either the code or the file property must be set, but both may not be set at the same time. */ + * The different contexts a menu can appear in. + * Specifying 'all' is equivalent to the combination of all other contexts. + **/ + type ContextType = + 'all' | + 'page' | + 'frame' | + 'selection' | + 'link' | + 'editable' | + 'image' | + 'video' | + 'audio'; + /** + * Details of the script or CSS to inject. + * Either the code or the file property must be set, + * but both may not be set at the same time. + **/ interface InjectDetails { - /** - * @description JavaScript or CSS code to inject. Warning: Be careful using the code parameter. Incorrect use of it may open your app to cross site scripting attacks. + * JavaScript or CSS code to inject. + * Warning: Be careful using the code parameter. + * Incorrect use of it may open your app to xss attacks. */ - code?: string + code?: string; - /** - * @description JavaScript or CSS file to inject. - */ + /** JavaScript or CSS file to inject. */ file?: string } - /**The type of injection item: code or a set of files. */ + /** The type of injection item: code or a set of files. */ interface InjectionItems { - - /** - * @description JavaScript code or CSS to be injected into matching pages. - */ + /** JavaScript code or CSS to be injected into matching pages. */ code?: string - /** - * @description The list of JavaScript or CSS files to be injected into matching pages. These are injected in the order they appear in this array. + * The list of JavaScript or CSS files to be injected into matching pages. + * These are injected in the order they appear in this array. */ files?: any[] } - /**Details of the content script to inject. Refer to the content scripts documentation for more details. */ + /** Details of the content script to inject. **/ interface ContentScriptDetails { - - /** - * @description The name of the content script to inject. - */ + /** The name of the content script to inject. */ name: string - /** - * @description Specifies which pages this content script will be injected into. - */ + /** Specifies which pages this content script will be injected into. */ matches: any[] - /** - * @description Excludes pages that this content script would otherwise be injected into. - */ + /** Excludes pages that this content script would otherwise be injected into. */ exclude_matches?: any[] /** - * @description Whether to insert the content script on about:blank and about:srcdoc. Content scripts will only be injected on pages when their inherit URL is matched by one of the declared patterns in the matches field. The inherit URL is the URL of the document that created the frame or window. Content scripts cannot be inserted in sandboxed frames. + * Whether to insert the content script on about:blank and about:srcdoc. + * Content scripts will only be injected on pages when their inherit URL + * is matched by one of the declared patterns in the matches field. + * The inherit URL is the URL of the document that created the frame or window. + * Content scripts cannot be inserted in sandboxed frames. */ - match_about_blank?: boolean + match_about_blank?: boolean; /** - * @description The CSS code or a list of CSS files to be injected into matching pages. These are injected in the order they appear, before any DOM is constructed or displayed for the page. + * The CSS code or a list of CSS files to be injected into matching pages. + * These are injected in the order they appear, + * before any DOM is constructed or displayed for the page. */ - css?: InjectionItems + css?: InjectionItems; /** - * @description The JavaScript code or a list of JavaScript files to be injected into matching pages. These are injected in the order they appear. + * The JavaScript code or a list of JavaScript files to be injected into matching pages. + * These are injected in the order they appear. */ - js?: InjectionItems + js?: InjectionItems; /** - * @description The soonest that the JavaScript or CSS will be injected into the tab. Defaults to 'document_idle'. + * The soonest that the JavaScript or CSS will be injected into the tab. + * Defaults to 'document_idle'. */ run_at?: chrome.extensionTypes.RunAt; /** - * @description If all_frames is true, this implies that the JavaScript or CSS should be injected into all frames of current page. By default, all_frames is false and the JavaScript or CSS is only injected into the top frame. + * If all_frames is true, this implies that the JavaScript or CSS should be injected into all frames of current page. + * By default, all_frames is false and the JavaScript or CSS is only injected into the top frame. + * @default false */ all_frames?: boolean; /** - * @description Applied after matches to include only those URLs that also match this glob. Intended to emulate the @include Greasemonkey keyword. + * Applied after matches to include only those URLs that also match this glob. + * Intended to emulate the @include Greasemonkey keyword. */ include_globs?: string[]; /** - * @description Applied after matches to exclude URLs that match this glob. Intended to emulate the @exclude Greasemonkey keyword. + * Applied after matches to exclude URLs that match this glob. + * Intended to emulate the @exclude Greasemonkey keyword. */ exclude_globs?: string[]; } - /**@todo Add documentation */ + /** @todo TODO Add documentation */ interface ContextMenuCreateProperties { /** - * @description The type of menu item. Defaults to 'normal' if not specified. + * The type of menu item. Defaults to 'normal' if not specified. */ - type?: chrome.contextMenus.ItemType + type?: chrome.contextMenus.ItemType; /** - * @description The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension. + * The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension. */ - id?: string + id?: string; /** - * @description The text to be displayed in the item; this is required unless type is 'separator'. When the context is 'selection', you can use %s within the string to show the selected text. For example, if this parameter's value is 'Translate '%s' to Pig Latin' and the user selects the word 'cool', the context menu item for the selection is 'Translate 'cool' to Pig Latin'. + * The text to be displayed in the item; this is -required- unless type is 'separator'. + * When the context is 'selection', you can use %s within the string to show the selected text. + * For example, if this parameter's value is 'Translate '%s' to Pig Latin' and the user selects + * the word 'cool', the context menu item for the selection is 'Translate 'cool' to Pig Latin'. */ - title?: string + title?: string; /** - * @description The initial state of a checkbox or radio item: true for selected and false for unselected. Only one radio item can be selected at a time in a given group of radio items. + * The initial state of a checkbox or radio item: + * true for selected and false for unselected. + * Only one radio item can be selected at a time in a given group of radio items. */ checked?: boolean /** - * @description List of contexts this menu item will appear in. Defaults to ['page'] if not specified. + * List of contexts this menu item will appear in. + * Defaults to ['page'] if not specified. */ - contexts?: any[] + contexts?: any[]; /** - * @description A function that will be called back when the menu item is clicked. - * @param callback + * A function that will be called back when the menu item is clicked. */ onclick?: (info: any) => void /** - * @description The ID of a parent menu item; this makes the item a child of a previously added item. + * The ID of a parent menu item; this makes the item a child of a previously added item. */ - parentId?: number | string + parentId?: number | string; /** - * @description Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. (This applies to frames as well.) For details on the format of a pattern, see Match Patterns. + * Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. (This applies to frames as well.) For details on the format of a pattern, see Match Patterns. */ - documentUrlPatterns?: any[] + documentUrlPatterns?: any[]; /** - * @description Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags. + * Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags. */ - targetUrlPatterns?: any[] + targetUrlPatterns?: any[]; /** - * @description Whether this context menu item is enabled or disabled. Defaults to true. + * Whether this context menu item is enabled or disabled. Defaults to true. */ - enabled?: boolean + enabled?: boolean; } /**@todo Add documentation */ interface ContextMenuUpdateProperties { - - /** - * @description The type of menu item. - */ + /** The type of menu item. */ type?: chrome.webview.ContextType; - /** - * @description The text to be displayed in the item - */ - title?: string + /** The text to be displayed in the item */ + title?: string; /** - * @description The state of a checkbox or radio item: true for selected and false for unselected. Only one radio item can be selected at a time in a given group of radio items. + * The state of a checkbox or radio item: true for selected and false for unselected. + * Only one radio item can be selected at a time in a given group of radio items. */ - checked?: boolean + checked?: boolean; /** - * @description List of contexts this menu item will appear in. + * List of contexts this menu item will appear in. */ - contexts?: any[] + contexts?: any[]; /** - * @description A function that will be called back when the menu item is clicked. + * A function that will be called back when the menu item is clicked. * @param callback */ - onclick?: (info: any) => void + onclick?: (info: any) => void; /** - * @description The ID of a parent menu item; this makes the item a child of a previously added item. Note: You cannot change an item to be a child of one of its own descendants. + * The ID of a parent menu item; this makes the item a child of a previously added item. Note: You cannot change an item to be a child of one of its own descendants. */ - parentId?: number | string + parentId?: number | string; /** - * @description Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. (This applies to frames as well.) For details on the format of a pattern, see Match Patterns. + * Lets you restrict the item to apply only to documents whose URL matches one of the given patterns. + * (This applies to frames as well.) */ - documentUrlPatterns?: any[] + documentUrlPatterns?: any[]; /** - * @description Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags. + * Similar to documentUrlPatterns, but lets you filter based on the src attribute of img/audio/video tags and the href of anchor tags. */ - targetUrlPatterns?: any[] + targetUrlPatterns?: any[]; /** - * @description Whether this context menu item is enabled or disabled. + * Whether this context menu item is enabled or disabled. */ - enabled?: boolean + enabled?: boolean; } interface ContextMenus { - /** - * @description Creates a new context menu item. Note that if an error occurs during creation, you may not find out until the creation callback fires (the details will be in chrome.runtime.lastError). - * @param {object} createProperties The properties used to create the item - * @param callback + * Creates a new context menu item. Note that if an error occurs during creation, + * you may not find out until the creation callback fires + * (the details will be in chrome.runtime.lastError). + * @param createProperties The properties used to create the item + * @param [callback] */ create(createProperties: object, callback?: () => void): void; /** - * @description Updates a previously created context menu item. - * @param id The ID of the item to update. - * @param {object} updateProperties The properties to update. Accepts the same values as the create function. - * @param callback + * Updates a previously created context menu item. + * @param id The ID of the item to update. + * @param updateProperties The properties to update. Accepts the same values as the create function. + * @param [callback] */ - update(id: number | string, updateProperties: object, callback?: () => void): void; + update(id: integer | string, updateProperties: object, callback?: () => void): void; /** - * @description Removes a context menu item. - * @param menuItemId The ID of the context menu item to remove. - * @param callback + * Removes a context menu item. + * @param menuItemId The ID of the context menu item to remove. + * @param [callback] */ - remove(menuItemId: number | string, callback?: () => void): void; + remove(menuItemId: integer | string, callback?: () => void): void; /** - * @description Removes all context menu items added to this webview. - * @param callback + * Removes all context menu items added to this webview. + * @param [callback] */ removeAll(callback?: () => void): void; - /** - * @description Fired before showing a context menu on this webview. Can be used to disable this context menu by calling event.preventDefault(). + * Fired before showing a context menu on this webview. + * Can be used to disable this context menu by calling event.preventDefault(). */ - onShow: chrome.events.Event; - + onShow: chrome.events.Event; } - interface IOnShowEvent { - /** - * @description Call this to prevent showing the context menu. - * @memberof IOnShowEvent - */ + interface OnShowEvent { + /** Call this to prevent showing the context menu. */ preventDefault: () => void; } interface ContentWindow { - /** - * @description

Posts a message to the embedded web content as long as the embedded content is displaying a page from the target origin. This method is available once the page has completed loading. Listen for the contentload event and then call the method.

The guest will be able to send replies to the embedder by posting message to event.source on the message event it receives.

This API is identical to the HTML5 postMessage API for communication between web pages. The embedder may listen for replies by adding a message event listener to its own frame.

- * @param message Message object to send to the guest. - * @param {string} targetOrigin Specifies what the origin of the guest window must be for the event to be dispatched. + * Posts a message to the embedded web content as long as the embedded + * content is displaying a page from the target origin. This method is + * available once the page has completed loading. Listen for the + * contentload event and then call the method. + * + * The guest will be able to send replies to the embedder by posting message + * to event.source on the message event it receives. + * + * This API is identical to the HTML5 postMessage API for communication + * between web pages. The embedder may listen for replies by adding + * a message event listener to its own frame. + * + * @param message Message object to send to the guest. + * @param targetOrigin Specifies what the origin of the guest window must be for the event to be dispatched. */ postMessage(message: any, targetOrigin: string): void; - } interface DialogController { - /** - * @description Accept the dialog. Equivalent to clicking OK in an alert, confirm, or prompt dialog. - * @param {string} response The response string to provide to the guest when accepting a prompt dialog. + * Accept the dialog. Equivalent to clicking OK in an alert, confirm, or prompt dialog. + * @param response The response string to provide to the guest when accepting a prompt dialog. */ ok(response?: string): void; - - /** - * @description Reject the dialog. Equivalent to clicking Cancel in a confirm or prompt dialog. - */ + /** Reject the dialog. Equivalent to clicking Cancel in a confirm or prompt dialog. */ cancel(): void; - } - /**Contains all of the results of the find request. */ + /** Contains all of the results of the find request. */ interface FindCallbackResults { - - /** - * @description The number of times searchText was matched on the page. - */ - numberOfMatches: number - - /** - * @description The ordinal number of the current match. - */ - activeMatchOrdinal: number - - /** - * @description Describes a rectangle around the active match in screen coordinates. - */ - selectionRect: SelectionRect - - /** - * @description Indicates whether this find request was canceled. - */ - canceled: boolean + /** The number of times searchText was matched on the page. */ + numberOfMatches: number; + /** The ordinal number of the current match. */ + activeMatchOrdinal: number; + /** Describes a rectangle around the active match in screen coordinates. */ + selectionRect: SelectionRect; + /** Indicates whether this find request was canceled. */ + canceled: boolean; } - /**Options for the find request. */ interface FindOptions { - /** - * @description Flag to find matches in reverse order. The default value is false. + * Flag to find matches in reverse order. + * @default false */ - backward?: boolean - + backward?: boolean; /** - * @description Flag to match with case-sensitivity. The default value is false. + * Flag to match with case-sensitivity. + * @default false */ - matchCase?: boolean + matchCase?: boolean; } interface NewWindow { - /** - * @description Attach the requested target page to an existing webview element. - * @param {object} webview The webview element to which the target page should be attached. + * Attach the requested target page to an existing webview element. + * @param webview The webview element to which the target page should be attached. */ - attach(webview: object): void; - + attach(webview: HTMLWebViewElement): void; /** - * @description Cancel the new window request. + * Cancel the new window request. */ discard(): void; - } - interface MediaPermissionRequest { - - /** - * @description Allow the permission request. - */ + interface PermissionRequestHandler { + /** Allow the permission request. */ allow(): void; - - /** - * @description Deny the permission request. This is the default behavior if allow is not called. - */ + /** Deny the permission request. This is the default behavior if allow is not called. */ deny(): void; - - } - interface GeolocationPermissionRequest { - - /** - * @description Allow the permission request. - */ - allow(): void; - - /** - * @description Deny the permission request. This is the default behavior if allow is not called. - */ - deny(): void; - - } - interface PointerLockPermissionRequest { - - /** - * @description Allow the permission request. - */ - allow(): void; - - /** - * @description Deny the permission request. This is the default behavior if allow is not called. - */ - deny(): void; - - } - interface DownloadPermissionRequest { - - /** - * @description Allow the permission request. - */ - allow(): void; - - /** - * @description Deny the permission request. This is the default behavior if allow is not called. - */ - deny(): void; - - } - interface FileSystemPermissionRequest { - - /** - * @description Allow the permission request. - */ - allow(): void; - - /** - * @description Deny the permission request. - */ - deny(): void; - - } - interface FullscreenPermissionRequest { - - /** - * @description Allow the permission request. - */ - allow(): void; - - /** - * @description Deny the permission request. - */ - deny(): void; - - } - interface LoadPluginPermissionRequest { - - /** - * @description Allow the permission request. This is the default behavior if deny is not called.. - */ - allow(): void; - - /** - * @description Deny the permission request. - */ - deny(): void; - } /** - * Fescribes a rectangle in screen coordinates. + * Describes a rectangle in screen coordinates. * The containment semantics are array-like; that is, the coordinate (left, top) is considered to be contained by the rectangle, * but the coordinate (left + width, top) is not. **/ interface SelectionRect { - - /** - * @description Distance from the left edge of the screen to the left edge of the rectangle. - */ - left: number - - /** - * @description Distance from the top edge of the screen to the top edge of the rectangle. - */ - top: number - - /** - * @description Width of the rectangle. - */ - width: number - - /** - * @description Height of the rectangle. - */ - height: number + /** Distance from the left edge of the screen to the left edge of the rectangle. */ + left: number; + /** Distance from the top edge of the screen to the top edge of the rectangle. */ + top: number; + /** Width of the rectangle. */ + width: number; + /** Height of the rectangle. */ + height: number; } /** - * @description Interface which provides access to webRequest events on the guest page. See the chrome.webRequest extensions API for details on webRequest life cycle and related concepts.

To illustrate how usage differs from the extensions webRequest API, consider the following example code which blocks any guest requests for URLs which match *://www.evil.com/*:

webview.request.onBeforeRequest.addListener(
-         * @example function(details) { return {cancel: true}; }, {urls: ['*://www.evil.com/*']}, ['blocking']);
-         * @description Additionally, this interface supports declarative webRequest rules through onRequest and onMessage events.
-         * @see http://developer.chrome.com/extensions/declarativeWebRequest.htmldeclarativeWebRequest
-         * @description Note that conditions and actions for declarative webview webRequests should be instantiated from their chrome.webViewRequest.* counterparts. The following example code declaratively blocks all requests to 'example.com' on the webview myWebview:
-         * @example var rule = { conditions: [ new chrome.webViewRequest.RequestMatcher({ url: { hostSuffix: 'example.com' } }) ], actions: [ new chrome.webViewRequest.CancelRequest() ] }; myWebview.request.onRequest.addRules([rule]);
+         * Interface which provides access to webRequest events on the guest page.
+         * @see[chrome.webRequest]{@link http://developer.chrome.com/extensions/webRequest}
+         * extensions API for details on webRequest life cycle and related concepts.
+         *
+         * To illustrate how usage differs from the extensions webRequest API,
+         * consider the following example code which blocks any guest requests
+         * for URLs which match *://www.evil.com/*:
+         * @example
+         * webview.request.onBeforeRequest.addListener(
+         *   function(details) { return {cancel: true}; }, {urls: ['*://www.evil.com/*']}, ['blocking']);
+         * @description
+         * Additionally, this interface supports declarative webRequest rules through onRequest and onMessage events.
+         * @see[Docs]{@link http://developer.chrome.com/extensions/declarativeWebRequest.htmldeclarativeWebRequest}
+         * @description
+         * Note that conditions and actions for declarative webview webRequests should be instantiated
+         * from their chrome.webViewRequest.* counterparts. The following example code declaratively
+         * blocks all requests to 'example.com' on the webview myWebview:
+         * @example const rule = { conditions: [ new chrome.webViewRequest.RequestMatcher({ url: { hostSuffix: 'example.com' } }) ], actions: [ new chrome.webViewRequest.CancelRequest() ] }; myWebview.request.onRequest.addRules([rule]);
          **/
         interface WebRequestEventInterface {
+            /** @todo TODO */
         }
         /**
         * Defines the how zooming is handled in the webview.
         * Enum values:
         * 'per-origin'
-        * * Zoom changes will persist in the zoomed page's origin, i.e. all other webviews in the same partition that are navigated to that same origin will be zoomed as well. Moreover, per-origin zoom changes are saved with the origin, meaning that when navigating to other pages in the same origin, they will all be zoomed to the same zoom factor.
+        *   > Zoom changes will persist in the zoomed page's origin,
+        *     i.e. all other webviews in the same partition that are
+        *     navigated to that same origin will be zoomed as well.
+        *     Moreover, per-origin zoom changes are saved with the origin,
+        *     meaning that when navigating to other pages in the same origin,
+        *     they will all be zoomed to the same zoom factor.
         * 'per-view'
-        * * Zoom changes only take effect in this webview, and zoom changes in other webviews will not affect the zooming of this webview. Also, per-view zoom changes are reset on navigation; navigating a webview will always load pages with their per-origin zoom factors (within the scope of the partition).
+        *   > Zoom changes only take effect in this webview,
+        *     and zoom changes in other webviews will not affect
+        *     the zooming of this webview. Also, per-view zoom
+        *     changes are reset on navigation; navigating a webview
+        *     will always load pages with their per-origin zoom factors
+        *     (within the scope of the partition).
         * 'disabled'
-        * * Disables all zooming in the webview. The content will revert to the default zoom level, and all attempted zoom changes will be ignored. */
-        export type ZoomMode = 'per-origin' | 'per-view' | 'disabled';
-
-        export enum ConsoleMessageLevel {
-            LOG_VERBOSE = -1,
-            LOG_INFO = 0,
-            LOG_WARNING = 1,
-            LOG_ERROR = 2
-        }
-        interface IConsoleMessage {
-
+        *   > Disables all zooming in the webview.
+        *     The content will revert to the default zoom level,
+        *     and all attempted zoom changes will be ignored.
+        **/
+        type ZoomMode =
+            'per-origin' |
+            'per-view' |
+            'disabled';
+        type ConsoleMessageLevel = -1 | 0 | 1 | 2;
+        type LoadAbortReason =
+            'ERR_ABORTED' |
+            'ERR_INVALID_URL' |
+            'ERR_DISALLOWED_URL_SCHEME' |
+            'ERR_BLOCKED_BY_CLIENT' |
+            'ERR_ADDRESS_UNREACHABLE' |
+            'ERR_EMPTY_RESPONSE' |
+            'ERR_FILE_NOT_FOUND' |
+            'ERR_UNKNOWN_URL_SCHEME';
+        interface ConsoleMessage {
             /**
-            * @description The severity level of the log message. Ranges from -1 to 2. LOG_VERBOSE (console.debug) = -1, LOG_INFO (console.log, console.info) = 0, LOG_WARNING (console.warn) = 1, LOG_ERROR (console.error) = 2.
+             * The severity level of the log message.
+             * Ranges from -1 to 2.
+             * LOG_VERBOSE (console.debug) = -1
+             * LOG_INFO (console.log, console.info) = 0
+             * LOG_WARNING (console.warn) = 1
+             * LOG_ERROR (console.error) = 2
              */
             level: ConsoleMessageLevel;
-
-            /**
-            * @description The logged message contents.
-             */
-            message: string
-
-            /**
-            * @description The line number of the message source.
-             */
-            line: number
-
-            /**
-            * @description A string identifying the resource which logged the message.
-             */
-            sourceId: string
+            /** The logged message contents. */
+            message: string;
+            /** The line number of the message source. */
+            line: number;
+            /** A string identifying the resource which logged the message. */
+            sourceId: string;
         }
-        interface IDialog {
+        type DialogMessageType =
+            'alert' |
+            'confirm' |
+            'prompt';
 
+        interface Dialog {
             /**
-            * @description The type of modal dialog requested by the guest.
+             * The type of modal dialog requested by the guest.
              */
-            messageType: 'alert' | 'confirm' | 'prompt'
-
+            messageType: DialogMessageType;
             /**
-            * @description The text the guest attempted to display in the modal dialog.
+             * The text the guest attempted to display in the modal dialog.
              */
-            messageText: string
-
+            messageText: string;
             /**
-            * @description An interface that can be used to respond to the guest's modal request.
+             * An interface that can be used to respond to the guest's modal request.
              */
-            dialog: DialogController
+            dialog: DialogController;
         }
-        interface IExit {
-
-            /**
-            * @description Chrome's internal ID of the process that exited.
-             */
-            processID: number
-
-            /**
-            * @description String indicating the reason for the exit.
-             */
-            reason: 'normal' | 'abnormal' | 'crash' | 'kill'
+        type ExitReason =
+            'normal' |
+            'abnormal' |
+            'crash' |
+            'kill';
+        interface Exit {
+            /** Chrome's internal ID of the process that exited. */
+            processID: number;
+            /** String indicating the reason for the exit. */
+            reason: ExitReason;
         }
-        interface IFindupdate {
-
+        interface FindUpdate {
             /**
-            * @description The string that is being searched for in the page.
+             * The string that is being searched for in the page.
              */
-            searchText: string
-
+            searchText: string;
             /**
-            * @description The number of matches found for searchText on the page so far.
+             * The number of matches found for searchText on the page so far.
              */
-            numberOfMatches: number
-
+            numberOfMatches: number;
             /**
-            * @description The ordinal number of the current active match, if it has been found. This will be 0 until then.
+             * The ordinal number of the current active match,
+             * if it has been found. This will be 0 until then.
              */
-            activeMatchOrdinal: number
-
+            activeMatchOrdinal: number;
             /**
-            * @description Describes a rectangle around the active match, if it has been found, in screen coordinates.
+             * Describes a rectangle around the active match,
+             * if it has been found, in screen coordinates.
              */
-            selectionRect: SelectionRect
-
+            selectionRect: SelectionRect;
             /**
-            * @description Indicates whether the find request was canceled.
+             * Indicates whether the find request was canceled.
              */
-            canceled: boolean
-
+            canceled: boolean;
             /**
-            * @description Indicates that all find requests have completed and that no more findupdate events will be fired until more find requests are made.
+             * Indicates that all find requests have completed
+             * and that no more findupdate events will be fired
+             * until more find requests are made.
              */
-            finalUpdate: string
+            finalUpdate: string;
         }
-        interface ILoadabort {
-
+        interface LoadAbort {
+            /** Requested URL. */
+            url: string;
+            /** Whether the load was top-level or in a subframe. */
+            isTopLevel: boolean;
             /**
-            * @description Requested URL.
+             * Unique integer ID for the type of abort.
+             * Note that this ID is `not` guaranteed to
+             * remain backwards compatible between releases.
+             * You must not act based upon this specific integer.
              */
-            url: string
-
+            code: integer;
             /**
-            * @description Whether the load was top-level or in a subframe.
+             * String indicating what type of abort occurred.
+             * This string is `not` guaranteed to remain
+             * backwards compatible between releases.
+             * You must not parse and act based upon its content.
+             * It is also possible that, in some cases,
+             * an error not listed here could be reported.
              */
-            isTopLevel: boolean
-
-            /**
-            * @description Unique integer ID for the type of abort. Note that this ID is not guaranteed to remain backwards compatible between releases. You must not act based upon this specific integer.
-             */
-            code: number
-
-            /**
-            * @description String indicating what type of abort occurred. This string is not guaranteed to remain backwards compatible between releases. You must not parse and act based upon its content. It is also possible that, in some cases, an error not listed here could be reported.
-             */
-            reason: 'ERR_ABORTED' | 'ERR_INVALID_URL' | 'ERR_DISALLOWED_URL_SCHEME' | 'ERR_BLOCKED_BY_CLIENT' | 'ERR_ADDRESS_UNREACHABLE' | 'ERR_EMPTY_RESPONSE' | 'ERR_FILE_NOT_FOUND' | 'ERR_UNKNOWN_URL_SCHEME'
+            reason: LoadAbortReason;
         }
-        interface ILoadcommit {
-
-            /**
-            * @description The URL that committed.
-             */
-            url: string
-
-            /**
-            * @description Whether the load is top-level or in a subframe.
-             */
-            isTopLevel: boolean
+        interface LoadCommit {
+            /** The URL that committed. */
+            url: string;
+            /** Whether the load is top-level or in a subframe. */
+            isTopLevel: boolean;
         }
-        /**ILoadredirect (Auto generated interface) */
-        interface ILoadredirect {
-
-            /**
-            * @description The requested URL before the redirect.
-             */
-            oldUrl: string
-
-            /**
-            * @description The new URL after the redirect.
-             */
-            newUrl: string
-
-            /**
-            * @description Whether or not the redirect happened at top-level or in a subframe.
-             */
-            isTopLevel: boolean
+        interface LoadRedirect {
+            /** The requested URL before the redirect. */
+            oldUrl: string;
+            /** The new URL after the redirect. */
+            newUrl: string;
+            /** Whether or not the redirect happened at top-level or in a subframe. */
+            isTopLevel: boolean;
         }
-        /**ILoadstart (Auto generated interface) */
-        interface ILoadstart {
-
-            /**
-            * @description Requested URL.
-             */
-            url: string
-
-            /**
-            * @description Whether the load is top-level or in a subframe.
-             */
-            isTopLevel: boolean
+        interface LoadStart {
+            /** Requested URL. */
+            url: string;
+            /** Whether the load is top-level or in a subframe. */
+            isTopLevel: boolean;
         }
-        /**INewwindow (Auto generated interface) */
-        interface INewwindow {
-
+        type WindowOpenDisposition =
+            'ignore' |
+            'save_to_disk' |
+            'current_tab' |
+            'new_background_tab' |
+            'new_foreground_tab' |
+            'new_window' |
+            'new_popup';
+        interface NewWindow {
             /**
-            * @description An interface that can be used to either attach the requested target page to an existing webview element or explicitly discard the request.
-             */
-            window: NewWindow
+             * An interface that can be used to either attach the requested
+             * target page to an existing webview element or explicitly
+             * discard the request.
+             **/
+            window: NewWindow;
 
-            /**
-            * @description The target URL requested for the new window.
-             */
-            targetUrl: string
+            /** The target URL requested for the new window. */
+            targetUrl: string;
 
-            /**
-            * @description The initial width requested for the new window.
-             */
-            initialWidth: number
+            /** The initial width requested for the new window. */
+            initialWidth: number;
 
-            /**
-            * @description The initial height requested for the new window.
-             */
-            initialHeight: number
+            /** The initial height requested for the new window. */
+            initialHeight: number;
 
-            /**
-            * @description The requested name of the new window.
-             */
-            name: string
+            /** The requested name of the new window. */
+            name: string;
 
-            /**
-            * @description The requested disposition of the new window.
-             */
-            windowOpenDisposition: 'ignore' | 'save_to_disk' | 'current_tab' | 'new_background_tab' | 'new_foreground_tab' | 'new_window' | 'new_popup'
+            /** The requested disposition of the new window. */
+            windowOpenDisposition: WindowOpenDisposition;
         }
-        interface IPermissionrequest {
-
-            /**
-            * @description The type of permission being requested.
-             */
-            permission: 'media' | 'geolocation' | 'pointerLock' | 'download' | 'loadplugin' | 'filesystem' | 'fullscreen'
-
-            /**
-            * @description An object which holds details of the requested permission. Depending on the type of permission requested, this may be a $(ref:webviewTag.MediaPermissionRequest), $(ref:webviewTag.GeolocationPermissionRequest), $(ref:webviewTag.PointerLockPermissionRequest), $(ref:webviewTag.DownloadPermissionRequest), $(ref:webviewTag.LoadPluginPermissionRequest), or $(ref:webviewTag.FullscreenPermissionRequest).
-             */
-            request: GeolocationPermissionRequest | PointerLockPermissionRequest | DownloadPermissionRequest | LoadPluginPermissionRequest | FullscreenPermissionRequest;
+        type RequestedPermission =
+            'media' |
+            'geolocation' |
+            'pointerLock' |
+            'download' |
+            'loadplugin' |
+            'filesystem' |
+            'fullscreen';
+        interface PermissionRequest {
+            /** The type of permission being requested. */
+            permission: RequestedPermission;
+            /** An object which holds details of the requested permission.*/
+            request: PermissionRequestHandler;
         }
-
-        /**IResponsive (Auto generated interface) */
-        interface IResponsive {
-
-            /**
-            * @description Chrome's internal ID of the process that became responsive.
-             */
-            processID: number
+        interface ProcessResponsive {
+            /** Chrome's internal ID of the process that became responsive. */
+            processID: number;
         }
-        /**ISizechanged (Auto generated interface) */
-        interface ISizechanged {
-
-            /**
-            * @description Old width of embedded web content.
-             */
-            oldWidth: number
-
-            /**
-            * @description Old height of embedded web content.
-             */
-            oldHeight: number
-
-            /**
-            * @description New width of embedded web content.
-             */
-            newWidth: number
-
-            /**
-            * @description New height of embedded web content.
-             */
-            newHeight: number
+        interface SizeChanged {
+            /** Old width of embedded web content. */
+            oldWidth: number;
+            /** Old height of embedded web content. */
+            oldHeight: number;
+            /** New width of embedded web content. */
+            newWidth: number;
+            /** New height of embedded web content. */
+            newHeight: number;
         }
-        /**IUnresponsive (Auto generated interface) */
-        interface IUnresponsive {
-
-            /**
-            * @description Chrome's internal ID of the process that has become unresponsive.
-             */
-            processID: number
+        interface ProcessUnresponsive {
+            /** Chrome's internal ID of the process that has become unresponsive. */
+            processID: number;
         }
-        /**IZoomchange (Auto generated interface) */
-        interface IZoomchange {
-
-            /**
-            * @description The page's previous zoom factor.
-             */
-            oldZoomFactor: number
-
-            /**
-            * @description The new zoom factor that the page was zoomed to.
-             */
-            newZoomFactor: number
+        interface ZoomChange {
+            /** The page's previous zoom factor. */
+            oldZoomFactor: number;
+            /** The new zoom factor that the page was zoomed to. */
+            newZoomFactor: number;
         }
-
     }
 
+    /////////////
+    // METHODS //
+    /////////////
+
+    /**
+     * Different page speed and load metrics
+     */
+    function csi(): {
+        onloadT: number;
+        pageT: number;
+        startE: number;
+        tran: number;
+    }
+
+    /**
+     * @deprecated Deprecated in Chrome 64.
+     * chrome.loadTimes() is a non-standard API that exposes loading metrics
+     * and network information to developers in order to help them better
+     * understand their site's performance in the real world.
+     * @see[Use this instead]{@link https://www.w3.org/TR/navigation-timing-2/}
+     * @see[Deprecation article]{@link https://developers.google.com/web/updates/2017/12/chrome-loadtimes-deprecated}
+     */
+    function loadTimes(): chrome.deprecatedButUsable;
 }
 
 /////////////////////
diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts
index c0dc6402a6..3babb0b80e 100644
--- a/types/chrome-apps/test/index.ts
+++ b/types/chrome-apps/test/index.ts
@@ -1,8 +1,8 @@
 import runtime = chrome.app.runtime;
-import cwindow = chrome.app.window;
+const cwindow = chrome.app.window;
 
-const createOptions: cwindow.CreateWindowOptions = {
-    id: "My Window",
+const createOptions: chrome.app.CreateWindowOptions = {
+    id: 'My Window',
     bounds: {
         left: 0,
         top: 0,
@@ -14,7 +14,7 @@ const createOptions: cwindow.CreateWindowOptions = {
 
 //Create new window on app launch
 chrome.app.runtime.onLaunched.addListener(function (launchData: runtime.LaunchData) {
-    chrome.app.window.create('app/url', createOptions, function (created_window: cwindow.AppWindow) {
+    chrome.app.window.create('app/url', createOptions, function (created_window: chrome.app.AppWindow) {
         return;
     });
 });
@@ -22,9 +22,9 @@ chrome.app.runtime.onLaunched.addListener(function (launchData: runtime.LaunchDa
 chrome.app.runtime.onRestarted.addListener(function () { return; });
 
 // retrieving windows
-var currentWindow: cwindow.AppWindow = chrome.app.window.current();
-var otherWindow: cwindow.AppWindow = chrome.app.window.get('some-string');
-var allWindows: cwindow.AppWindow[] = chrome.app.window.getAll();
+var currentWindow: chrome.app.AppWindow = chrome.app.window.current();
+var otherWindow: chrome.app.AppWindow = chrome.app.window.get('some-string');
+var allWindows: chrome.app.AppWindow[] = chrome.app.window.getAll();
 
 // listening to window events
 currentWindow.onBoundsChanged.addListener(function () { return; });
@@ -42,11 +42,11 @@ var visibleEverywhere: boolean = chrome.app.window.canSetVisibleOnAllWorkspaces(
 
 function test_fileSystem(): void {
     var accepts: chrome.fileSystem.AcceptOptions[] = [
-        { mimeTypes: ["text/*"], extensions: ['js', 'css', 'txt', 'html', 'xml', 'tsv', 'csv', 'rtf'] }
+        { mimeTypes: ['text/*'], extensions: ['js', 'css', 'txt', 'html', 'xml', 'tsv', 'csv', 'rtf'] }
     ];
     var chooseOption: chrome.fileSystem.ChooseEntryOptions = {
-        type: "openFile",
-        suggestedName: "foo.txt",
+        type: 'openFile',
+        suggestedName: 'foo.txt',
         accepts: accepts,
         acceptsAllTypes: false,
         acceptsMultiple: false
@@ -98,7 +98,7 @@ function test_socketsTcp(): void {
     chrome.sockets.tcp.setNoDelay(socketId, true, (result: number) => { });
 
     // connect
-    chrome.sockets.tcp.connect(socketId, "192.168.0.1", 8080, (result: number) => { });
+    chrome.sockets.tcp.connect(socketId, '192.168.0.1', 8080, (result: number) => { });
 
     // disconnect
     chrome.sockets.tcp.disconnect(socketId);
@@ -132,7 +132,7 @@ function testSocketsTcpTypes(): void {
 
     properties = {
         persistent: true,
-        name: "test",
+        name: 'test',
         bufferSize: 1024
     };
 
@@ -146,11 +146,11 @@ function testSocketsTcpTypes(): void {
         connected: false
     };
 
-    socketInfo.name = "test";
+    socketInfo.name = 'test';
     socketInfo.bufferSize = 1024;
-    socketInfo.localAddress = "192.168.0.2";
+    socketInfo.localAddress = '192.168.0.2';
     socketInfo.localPort = 8000;
-    socketInfo.peerAddress = "192.168.0.3";
+    socketInfo.peerAddress = '192.168.0.3';
     socketInfo.peerPort = 1000;
 }
 
@@ -178,10 +178,10 @@ function test_socketsUdp(): void {
     chrome.sockets.udp.setPaused(socketId, true, () => { });
 
     // bind
-    chrome.sockets.udp.bind(socketId, "0.0.0.0", 8080, (result: number) => { });
+    chrome.sockets.udp.bind(socketId, '0.0.0.0', 8080, (result: number) => { });
 
     // send
-    chrome.sockets.udp.send(socketId, buffer, "172.21.0.1", 10080, (info: chrome.sockets.udp.SendInfo) => { });
+    chrome.sockets.udp.send(socketId, buffer, '172.21.0.1', 10080, (info: chrome.sockets.udp.SendInfo) => { });
 
     // close
     chrome.sockets.udp.close(socketId);
@@ -194,10 +194,10 @@ function test_socketsUdp(): void {
     chrome.sockets.udp.getSockets((infos: chrome.sockets.udp.SocketInfo[]) => { });
 
     // joinGroup
-    chrome.sockets.udp.joinGroup(socketId, "224.0.0.1", (result: number) => { });
+    chrome.sockets.udp.joinGroup(socketId, '224.0.0.1', (result: number) => { });
 
     // leaveGroup
-    chrome.sockets.udp.leaveGroup(socketId, "224.0.0.1", (result: number) => { });
+    chrome.sockets.udp.leaveGroup(socketId, '224.0.0.1', (result: number) => { });
 
     // setMulticastTimeToLive
     chrome.sockets.udp.setMulticastTimeToLive(socketId, 100, (result: number) => { });
@@ -223,7 +223,7 @@ function testSocketsUdpTypes(): void {
 
     properties = {
         persistent: true,
-        name: "test",
+        name: 'test',
         bufferSize: 1024
     };
 
@@ -236,9 +236,9 @@ function testSocketsUdpTypes(): void {
         paused: true
     };
 
-    socketInfo.name = "test";
+    socketInfo.name = 'test';
     socketInfo.bufferSize = 1024;
-    socketInfo.localAddress = "192.168.0.2";
+    socketInfo.localAddress = '192.168.0.2';
     socketInfo.localPort = 8000;
 }
 
@@ -266,8 +266,8 @@ function test_socketsTcpServer(): void {
     chrome.sockets.tcpServer.setPaused(socketId, true, () => { });
 
     // listen
-    chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, (result: number) => { });
-    chrome.sockets.tcpServer.listen(socketId, "0.0.0.0", 80, 128, (result: number) => { });
+    chrome.sockets.tcpServer.listen(socketId, '0.0.0.0', 80, (result: number) => { });
+    chrome.sockets.tcpServer.listen(socketId, '0.0.0.0', 80, 128, (result: number) => { });
 
     // disconnect
     chrome.sockets.tcp.disconnect(socketId);
@@ -298,7 +298,7 @@ function testSocketsTcpServerTypes(): void {
 
     properties = {
         persistent: true,
-        name: "test"
+        name: 'test'
     };
 
     // SocketInfo
@@ -310,8 +310,8 @@ function testSocketsTcpServerTypes(): void {
         paused: true
     };
 
-    socketInfo.name = "test";
-    socketInfo.localAddress = "192.168.0.2";
+    socketInfo.name = 'test';
+    socketInfo.localAddress = '192.168.0.2';
     socketInfo.localPort = 8000;
 }
 
@@ -340,7 +340,7 @@ wve.addEventListener('close', () => {
     return;
 });
 wve.addEventListener('consolemessage', (ev) => {
-    if (ev.level === chrome.webview.ConsoleMessageLevel.LOG_ERROR) {
+    if (ev.level === 2) {
         const msg = ev.message;
     }
 });
@@ -360,4 +360,177 @@ wve.addEventListener('loadredirect', (ev) => {
     return ev.newUrl || ev.oldUrl;
 });
 
-chrome.bluetoothLowEnergy.connect('1111111', () => { });
+chrome.bluetooth.getAdapterState((adapter) => {
+    console.log('Adapter ' + adapter.address + ': ' + adapter.name);
+});
+
+chrome.bluetooth.getDevices((devices) => {
+    for (const device of devices) {
+        console.log(device.address);
+    }
+});
+
+chrome.bluetooth.onDeviceAdded.addListener((device) => {
+    let uuid = '0000180d-0000-1000-8000-00805f9b34fb';
+    if (!device.uuids || device.uuids.indexOf(uuid) < 0)
+        return;
+
+    // The device has a service with the desired UUID.
+    chrome.bluetoothLowEnergy.connect(device.address, () => {
+        if (chrome.runtime.lastError) {
+            console.log('Failed to connect: ' + chrome.runtime.lastError.message);
+            return;
+        }
+        // Connected! Do stuff...
+    });
+});
+
+const uuid = '1105';
+
+chrome.bluetooth.getDevices((devices) => {
+    chrome.bluetoothSocket.create((createInfo) => {
+        chrome.bluetoothSocket.connect(createInfo.socketId,
+            devices[0].address, uuid, () => {
+                if (chrome.runtime.lastError) {
+                    console.log('Connection failed: ' + chrome.runtime.lastError.message);
+                } else {
+                    chrome.bluetoothSocket.send(createInfo.socketId, new ArrayBuffer(4096), (bytes_sent) => {
+                        if (chrome.runtime.lastError) {
+                            console.log('Send failed: ' + chrome.runtime.lastError.message);
+                        } else {
+                            console.log('Sent ' + bytes_sent + ' bytes')
+                        }
+                    });
+                }
+            });
+        chrome.bluetoothSocket.onReceive.addListener((receiveInfo) => {
+            if (receiveInfo.socketId != createInfo.socketId)
+                return;
+            // receiveInfo.data is an ArrayBuffer.
+        });
+    });
+});
+
+chrome.hid.getDevices({
+    filters: [
+        { vendorId: 5 }
+    ]
+}, (devices) => {
+    const productId = devices[0].productId;
+    chrome.hid.getUserSelectedDevices((selectedDevices) => {
+        const hmm = selectedDevices.productId == productId ? selectedDevices.vendorId : selectedDevices.maxFeatureReportSize;
+    });
+});
+
+chrome.syncFileSystem.getConflictResolutionPolicy((policy) => {
+    if (policy === 'manual') {
+        chrome.syncFileSystem.requestFileSystem((fs) => {
+            if (fs.root.isFile) {
+                throw new Error('It was a file!');
+            }
+        });
+    }
+})
+chrome.contextMenus.ACTION_MENU_TOP_LEVEL_LIMIT;
+
+chrome.i18n.getMessage('click_here', ['string1', 'string2']);
+
+const TLSFormatExample = {
+    NetworkConfigurations: 
+        {
+            GUID: '{00f79111-51e0-e6e0-76b3b55450d80a1b}',
+            Name: 'MyTTLSNetwork',
+            Type: 'WiFi',
+            WiFi: {
+                AutoConnect: false,
+                EAP: {
+                    ClientCertPattern: {
+                        EnrollmentURI: [
+                            'http://fetch-my-certificate.com'
+                        ],
+                        IssuerCARef: [
+                            '{6ed8dce9-64c8-d568-d225d7e467e37828}'
+                        ]
+                    },
+                    'ClientCertType': 'Pattern',
+                    'Outer': 'EAP-TLS',
+                    'ServerCARef': '{6ed8dce9-64c8-d568-d225d7e467e37828}',
+                    'UseSystemCAs': true
+                },
+                'HiddenSSID': false,
+                'SSID': 'MyTTLSNetwork',
+                'Security': 'WPA-EAP'
+            }
+        }
+}
+
+let serviceId: any = null;
+
+const runApp = () => {
+    var options = {
+        'id': 'Bluetooth Sample App',
+        'bounds': {
+            'width': 1024,
+            'height': 768
+        }
+    };
+
+    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
+        if (request.serviceId) {
+            serviceId = request.serviceId;
+            console.log('Received registered service Id: ' + serviceId);
+        }
+    });
+
+    chrome.app.window.create('test.html', options, (theWindow) => {
+        theWindow.onClosed.addListener(() => {
+            if (serviceId) {
+                console.log('Unregistering service: ' + serviceId);
+                chrome.bluetoothLowEnergy.unregisterService(serviceId, (status) => {
+                    console.log('Unregister service status = ' + status);
+                });
+            }
+        });
+    });
+}
+
+chrome.app.runtime.onLaunched.addListener(runApp);
+chrome.app.runtime.onRestarted.addListener(runApp);
+
+// networking.onc
+
+chrome.networking.onc.getNetworks({ 'networkType': 'All' }, (networkList) => {
+    console.log('Length of Network list: ' + networkList.length);
+    for (let networkObj of networkList) {
+        console.log('GUID: ' + networkObj.GUID);
+        console.log('Connectable: ' + networkObj.Connectable);
+        if (networkObj.WiFi) {
+            // WiFi active :)
+            console.log('Wifi BSID: ' + networkObj.WiFi.BSSID);
+        }
+        chrome.networking.onc.setProperties(networkObj.GUID || '', {
+            WiFi: {
+                Passphrase: 'Can be set :) but not get?'
+            }
+        })
+        // Test that we can't get passphrase
+        chrome.networking.onc.getProperties(networkObj.GUID || '', (props) => {
+            const WiFiResult = props.WiFi;
+        });
+    }
+});
+
+//// AUDIO
+
+chrome.audio.getDevices({}, (audioDeviceInfoList) => {
+    for (let audioObj of audioDeviceInfoList) {
+        console.log('ID: ' + audioObj.id);
+        console.log('Audio Stream Type: ' + audioObj.streamType);
+        console.log('Audio Device Name: ' + audioObj.deviceName);
+    }
+});
+
+
+chrome.desktopCapture.chooseDesktopMedia(["screen", "window", "tab"], () => { });
+chrome.desktopCapture.chooseDesktopMedia([chrome.desktopCapture.DesktopCaptureSourceType.AUDIO], () => { });
+
diff --git a/types/cleave.js/options/index.d.ts b/types/cleave.js/options/index.d.ts
index 60e2e99e40..65d87d79e1 100644
--- a/types/cleave.js/options/index.d.ts
+++ b/types/cleave.js/options/index.d.ts
@@ -19,6 +19,12 @@ export interface CleaveOptions {
     datePattern?: ReadonlyArray;
 }
 
+// Time Options
+export interface CleaveOptions {
+    time?: boolean;
+    timePattern?: ReadonlyArray;
+}
+
 // Numeral Options
 export type NumeralThousandsGroupStyleType = "lakh" | "thousand" | "wan" | "none";
 
diff --git a/types/clipboard/clipboard-tests.ts b/types/clipboard/clipboard-tests.ts
index a2ae8f9354..1a9a170087 100644
--- a/types/clipboard/clipboard-tests.ts
+++ b/types/clipboard/clipboard-tests.ts
@@ -14,6 +14,12 @@ const cb5 = new ClipboardJS(".btn", {
     action: elem => "copy",
     target: elem => null
 });
+const cb6 = new ClipboardJS(".btn", {
+    action: elem => "copy",
+    text: trigger => trigger.getAttribute('aria-label'),
+    target: trigger => trigger.nextElementSibling,
+    container: document.getElementById('modal')
+});
 
 cb1.destroy();
 ClipboardJS.isSupported();
diff --git a/types/clipboard/index.d.ts b/types/clipboard/index.d.ts
index 2405c0c6f0..ceb15b885b 100644
--- a/types/clipboard/index.d.ts
+++ b/types/clipboard/index.d.ts
@@ -49,6 +49,14 @@ declare namespace ClipboardJS {
          * @returns Text to be copied.
          */
         text?(elem: Element): string;
+
+        /**
+         * For use in Bootstrap Modals or with any
+         * other library that changes the focus
+         * you'll want to set the focused element
+         * as the container value.
+         */
+        container?: Element;
     }
 
     interface Event {
diff --git a/types/connect-mongo/index.d.ts b/types/connect-mongo/index.d.ts
index cf3d5ddb3e..ee110ab6b0 100644
--- a/types/connect-mongo/index.d.ts
+++ b/types/connect-mongo/index.d.ts
@@ -104,11 +104,11 @@ declare namespace connectMongo {
     }
 
     export class MongoStore extends session.Store {
-        get: (sid: string, callback: (err: any, session: Express.Session) => void) => void;
+        get: (sid: string, callback: (err: any, session: Express.Session | null) => void) => void;
         set: (sid: string, session: Express.Session, callback?: (err: any) => void) => void;
         destroy: (sid: string, callback?: (err: any) => void) => void;
         length: (callback: (err: any, length: number) => void) => void;
-        clear: (callback?: (err: any) => void) => void;
+        clear: (callback?: (err?: any) => void) => void;
         touch: (sid: string, session: Express.Session, callback?: (err: any) => void) => void;
     }
 }
diff --git a/types/couchbase/couchbase-tests.ts b/types/couchbase/couchbase-tests.ts
index d04b71c907..e6ea7c12d3 100644
--- a/types/couchbase/couchbase-tests.ts
+++ b/types/couchbase/couchbase-tests.ts
@@ -31,6 +31,11 @@ bucket.manager().createPrimaryIndex(function() {
     });
 });
 
+// Ensure bucket.upsert is composable with normal callbacks
+function composable(callback: (err?: Error) => void) {
+    bucket.upsert('key', {value: 1}, callback);
+}
+
 // From https://developer.couchbase.com/documentation/server/current/sdk/nodejs/n1ql-queries-with-sdk.html
 function n1ql_a() {
     const n1qlquery = N1qlQuery.fromString('SELECT name, email FROM users WHERE name=$1');
diff --git a/types/couchbase/index.d.ts b/types/couchbase/index.d.ts
index f55ac6dbe9..813ee8f110 100644
--- a/types/couchbase/index.d.ts
+++ b/types/couchbase/index.d.ts
@@ -2019,10 +2019,10 @@ declare namespace Bucket {
      */
     interface OpCallback {
         /**
-         * @param error The error for the operation. This can either be an Error object or a value which evaluates to false (null, undefined, 0 or false).
+         * @param error The error for the operation. This can either be an Error object or a value which evaluates to false.
          * @param result The result of the operation that was executed. This usually contains at least a cas property, and on some operations will contain a value property as well.
          */
-        (error: CouchbaseError | number, result: any): void;
+        (error: CouchbaseError | null, result: any): void;
     }
 
     /**
diff --git a/types/cqrs-domain/index.d.ts b/types/cqrs-domain/index.d.ts
index f826b45ffd..33db11b857 100644
--- a/types/cqrs-domain/index.d.ts
+++ b/types/cqrs-domain/index.d.ts
@@ -252,7 +252,7 @@ declare namespace Domain {
 
     /**
      * @param data is the command data
-     * @callback callback is optional, if not defined as function argument you can throw errors or return errors here (sync way)
+     * @param callback is optional, if not defined as function argument you can throw errors or return errors here (sync way)
      */
     type preLoadConditionHandler = (data: any, callback?: (err: string | Error) => string | Error) => void | string | Error;
 
@@ -295,7 +295,7 @@ declare namespace Domain {
     /**
      * @param data is the command data
      * @param aggregate is the aggregate object
-     * @callback callback is optional, if not defined as function argument you can throw errors or return errors here (sync way)
+     * @param callback is optional, if not defined as function argument you can throw errors or return errors here (sync way)
      */
     type preConditionHandler = (data: any, aggregate: AggregateModel, callback?: (err: string | Error) => string | Error) => void | string | Error;
 
diff --git a/types/create-react-class/index.d.ts b/types/create-react-class/index.d.ts
index 9a1b0b12b5..9b9d2b2ad5 100644
--- a/types/create-react-class/index.d.ts
+++ b/types/create-react-class/index.d.ts
@@ -2,7 +2,7 @@
 // Project: https://facebook.github.io/react/
 // Definitions by: John Gozde 
 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
-// TypeScript Version: 2.6
+// TypeScript Version: 2.8
 
 import { ComponentSpec, ClassicComponentClass } from "react";
 
diff --git a/types/create-subscription/index.d.ts b/types/create-subscription/index.d.ts
index 79003980ee..8c7d8c1ced 100644
--- a/types/create-subscription/index.d.ts
+++ b/types/create-subscription/index.d.ts
@@ -3,7 +3,7 @@
 // Definitions by: Asana 
 //                 Vincent Siao 
 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
-// TypeScript Version: 2.6
+// TypeScript Version: 2.8
 
 import * as React from "react";
 
diff --git a/types/crypto-random-string/crypto-random-string-tests.ts b/types/crypto-random-string/crypto-random-string-tests.ts
new file mode 100644
index 0000000000..1a66c25981
--- /dev/null
+++ b/types/crypto-random-string/crypto-random-string-tests.ts
@@ -0,0 +1,4 @@
+import generate = require('crypto-random-string');
+
+// $ExpectType string
+generate(10);
diff --git a/types/crypto-random-string/index.d.ts b/types/crypto-random-string/index.d.ts
new file mode 100644
index 0000000000..dc41e18428
--- /dev/null
+++ b/types/crypto-random-string/index.d.ts
@@ -0,0 +1,13 @@
+// Type definitions for crypto-random-string 1.0
+// Project: https://github.com/sindresorhus/crypto-random-string
+// Definitions by: Manuel Warum 
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+/**
+ * Generate a hexadecimal string of the given length.
+ * @param length the length of the random string.
+ * @return a string of the specified length.
+ */
+declare function cryptoRandomString(length: number): string;
+
+export = cryptoRandomString;
diff --git a/types/crypto-random-string/tsconfig.json b/types/crypto-random-string/tsconfig.json
new file mode 100644
index 0000000000..fd68e9d080
--- /dev/null
+++ b/types/crypto-random-string/tsconfig.json
@@ -0,0 +1,23 @@
+{
+    "compilerOptions": {
+        "module": "commonjs",
+        "lib": [
+            "es6"
+        ],
+        "noImplicitAny": true,
+        "noImplicitThis": true,
+        "strictNullChecks": true,
+        "strictFunctionTypes": true,
+        "baseUrl": "../",
+        "typeRoots": [
+            "../"
+        ],
+        "types": [],
+        "noEmit": true,
+        "forceConsistentCasingInFileNames": true
+    },
+    "files": [
+        "index.d.ts",
+        "crypto-random-string-tests.ts"
+    ]
+}
diff --git a/types/crypto-random-string/tslint.json b/types/crypto-random-string/tslint.json
new file mode 100644
index 0000000000..f93cf8562a
--- /dev/null
+++ b/types/crypto-random-string/tslint.json
@@ -0,0 +1,3 @@
+{
+    "extends": "dtslint/dt.json"
+}
diff --git a/types/cssnano/cssnano-tests.ts b/types/cssnano/cssnano-tests.ts
new file mode 100644
index 0000000000..17828e1b02
--- /dev/null
+++ b/types/cssnano/cssnano-tests.ts
@@ -0,0 +1,17 @@
+import cssnano = require('cssnano');
+import { Transformer } from 'postcss';
+
+const nano1: Transformer = cssnano();
+const nano2: Transformer = cssnano({
+    configFile: '/path/to/config',
+});
+const nano3: Transformer = cssnano({
+    preset: 'default',
+});
+const nano4: Transformer = cssnano({
+    preset: ['default', {
+        discardComments: {
+            removeAll: true,
+        },
+    }],
+});
diff --git a/types/cssnano/index.d.ts b/types/cssnano/index.d.ts
new file mode 100644
index 0000000000..bf298f1854
--- /dev/null
+++ b/types/cssnano/index.d.ts
@@ -0,0 +1,19 @@
+// Type definitions for cssnano 4.0
+// Project: https://github.com/cssnano/cssnano
+// Definitions by: Armando Meziat 
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+// TypeScript Version: 2.2
+
+import { Plugin } from 'postcss';
+
+declare namespace cssnano {
+    interface CssNanoOptions {
+        configFile?: string;
+        preset?: [string, object] | string;
+    }
+
+    type CssNano = Plugin;
+}
+
+declare const cssnano: cssnano.CssNano;
+export = cssnano;
diff --git a/types/cssnano/package.json b/types/cssnano/package.json
new file mode 100644
index 0000000000..3c7b1f0f76
--- /dev/null
+++ b/types/cssnano/package.json
@@ -0,0 +1,6 @@
+{
+    "private": true,
+    "dependencies": {
+        "postcss": "5 - 7"
+    }
+}
diff --git a/types/cssnano/tsconfig.json b/types/cssnano/tsconfig.json
new file mode 100644
index 0000000000..5667012b67
--- /dev/null
+++ b/types/cssnano/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",
+        "cssnano-tests.ts"
+    ]
+}
diff --git a/types/cssnano/tslint.json b/types/cssnano/tslint.json
new file mode 100644
index 0000000000..3db14f85ea
--- /dev/null
+++ b/types/cssnano/tslint.json
@@ -0,0 +1 @@
+{ "extends": "dtslint/dt.json" }
diff --git a/types/cytoscape/index.d.ts b/types/cytoscape/index.d.ts
index c38acead19..59482ad507 100644
--- a/types/cytoscape/index.d.ts
+++ b/types/cytoscape/index.d.ts
@@ -2819,13 +2819,13 @@ declare namespace cytoscape {
 
     /**
      * The handler returns true when it finds the desired node, and it returns false to cancel the search.
-     * i - The index indicating this node is the ith visited node.
-     * depth - How many edge hops away this node is from the root nodes.
      * v - The current node.
      * e - The edge connecting the previous node to the current node.
      * u - The previous node.
+     * i - The index indicating this node is the ith visited node.
+     * depth - How many edge hops away this node is from the root nodes.
      */
-    type SearchVisitFunction = (i: number, depth: number, v: NodeCollection, e: EdgeCollection, u: NodeCollection) => boolean;
+    type SearchVisitFunction = (v: NodeCollection,  e: EdgeCollection, u: NodeCollection, i: number, depth: number) => boolean | void;
     interface SearchFirstOptions {
         /**
          * The root nodes (selector or collection) to start the search from.
diff --git a/types/d3-hierarchy/d3-hierarchy-tests.ts b/types/d3-hierarchy/d3-hierarchy-tests.ts
index 65b1f5c392..b75b9fbbd0 100644
--- a/types/d3-hierarchy/d3-hierarchy-tests.ts
+++ b/types/d3-hierarchy/d3-hierarchy-tests.ts
@@ -189,6 +189,10 @@ stratificatorizer = d3Hierarchy.stratify();
 
 // id(...)
 
+stratificatorizer = stratificatorizer.id((d) => {
+    return d.name; // d is of type TabularHierarchyDatum
+});
+
 stratificatorizer = stratificatorizer.id((d, i, data) => {
     console.log('Length of tabular array: ', data.length);
     console.log('Name of first entry in tabular array: ', data[0].name); // data of type Array
@@ -199,6 +203,10 @@ idStringAccessor = stratificatorizer.id();
 
 // parentId(...)
 
+stratificatorizer = stratificatorizer.parentId((d) => {
+    return d.parentId; // d is of type TabularHierarchyDatum
+});
+
 stratificatorizer = stratificatorizer.parentId((d, i, data) => {
     console.log('Length of tabular array: ', data.length);
     console.log('Name of first entry in tabular array: ', data[0].name); // data of type Array
@@ -225,14 +233,12 @@ clusterLayout = d3Hierarchy.cluster();
 
 // size() ----------------------------------------------------------------
 
-clusterLayout = clusterLayout.size(null);
 clusterLayout = clusterLayout.size([200, 200]);
 
 size = clusterLayout.size();
 
 // nodeSize() ------------------------------------------------------------
 
-clusterLayout = clusterLayout.nodeSize(null);
 clusterLayout = clusterLayout.nodeSize([10, 10]);
 size = clusterLayout.nodeSize();
 
@@ -358,14 +364,12 @@ treeLayout = d3Hierarchy.tree();
 
 // size() ----------------------------------------------------------------
 
-treeLayout = treeLayout.size(null);
 treeLayout = treeLayout.size([200, 200]);
 
 size = treeLayout.size();
 
 // nodeSize() ------------------------------------------------------------
 
-treeLayout = treeLayout.nodeSize(null);
 treeLayout = treeLayout.nodeSize([10, 10]);
 size = treeLayout.nodeSize();
 
@@ -416,7 +420,6 @@ tilingFn = treemapLayout.tile();
 
 // size() ----------------------------------------------------------------
 
-treemapLayout = treemapLayout.size(null);
 treemapLayout = treemapLayout.size([400, 200]);
 
 size = treemapLayout.size();
@@ -635,7 +638,6 @@ partitionLayout = d3Hierarchy.partition();
 
 // size() ----------------------------------------------------------------
 
-partitionLayout = partitionLayout.size(null);
 partitionLayout = partitionLayout.size([400, 200]);
 
 size = partitionLayout.size();
@@ -674,7 +676,6 @@ packLayout = d3Hierarchy.pack();
 
 // size() ----------------------------------------------------------------
 
-packLayout = packLayout.size(null);
 packLayout = packLayout.size([400, 400]);
 
 size = packLayout.size();
diff --git a/types/d3-hierarchy/index.d.ts b/types/d3-hierarchy/index.d.ts
index 440a779217..bdb7b652d5 100644
--- a/types/d3-hierarchy/index.d.ts
+++ b/types/d3-hierarchy/index.d.ts
@@ -1,65 +1,208 @@
 // Type definitions for D3JS d3-hierarchy module 1.1
 // Project: https://github.com/d3/d3-hierarchy/
-// Definitions by: Tom Wanzek , Alex Ford , Boris Yankov 
+// Definitions by: Tom Wanzek 
+//                 Alex Ford 
+//                 Boris Yankov 
+//                 denisname 
 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
 
-// Last module patch version validated against: 1.1.1
+// Last module patch version validated against: 1.1.6
 
 // -----------------------------------------------------------------------
 // Hierarchy
 // -----------------------------------------------------------------------
 
 export interface HierarchyLink {
+    /**
+     * The source of the link.
+     */
     source: HierarchyNode;
+
+    /**
+     * The target of the link.
+     */
     target: HierarchyNode;
 }
 
 export interface HierarchyNode {
-    data: Datum;
-    readonly depth: number;
-    readonly height: number;
-    parent: HierarchyNode | null;
-    children?: Array>;
     /**
-     * Aggregated numeric value as calculated by sum(value) or count(),
-     * if previously invoked.
+     * The associated data, as specified to the constructor.
+     */
+    data: Datum;
+
+    /**
+     * Zero for the root node, and increasing by one for each descendant generation.
+     */
+    readonly depth: number;
+
+    /**
+     * Zero for leaf nodes, and the greatest distance from any descendant leaf for internal nodes.
+     */
+    readonly height: number;
+
+    /**
+     * The parent node, or null for the root node.
+     */
+    parent: this | null;
+
+    /**
+     * An array of child nodes, if any; undefined for leaf nodes.
+     */
+    children?: this[];
+
+    /**
+     * Aggregated numeric value as calculated by `sum(value)` or `count()`, if previously invoked.
      */
     readonly value?: number;
+
     /**
-     * Optional Node Id string set by StratifyOperator, if
-     * hierarchical data was created from tabular data using stratify()
+     * Optional node id string set by `StratifyOperator`, if hierarchical data was created from tabular data using stratify().
      */
     readonly id?: string;
-    ancestors(): Array>;
-    descendants(): Array>;
-    leaves(): Array>;
-    path(target: HierarchyNode): Array>;
+
+    /**
+     * Returns the array of ancestors nodes, starting with this node, then followed by each parent up to the root.
+     */
+    ancestors(): this[];
+
+    /**
+     * Returns the array of descendant nodes, starting with this node, then followed by each child in topological order.
+     */
+    descendants(): this[];
+
+    /**
+     * Returns the array of leaf nodes in traversal order; leaves are nodes with no children.
+     */
+    leaves(): this[];
+
+    /**
+     * Returns the shortest path through the hierarchy from this node to the specified target node.
+     * The path starts at this node, ascends to the least common ancestor of this node and the target node, and then descends to the target node.
+     *
+     * @param target The target node.
+     */
+    path(target: this): this[];
+
+    /**
+     * Returns an array of links for this node, where each link is an object that defines source and target properties.
+     * The source of each link is the parent node, and the target is a child node.
+     */
     links(): Array>;
+
+    /**
+     * Evaluates the specified value function for this node and each descendant in post-order traversal, and returns this node.
+     * The `node.value` property of each node is set to the numeric value returned by the specified function plus the combined value of all descendants.
+     *
+     * @param value The value function is passed the node’s data, and must return a non-negative number.
+     */
     sum(value: (d: Datum) => number): this;
+
+    /**
+     * Computes the number of leaves under this node and assigns it to `node.value`, and similarly for every descendant of node.
+     * If this node is a leaf, its count is one. Returns this node.
+     */
     count(): this;
-    sort(compare: (a: HierarchyNode, b: HierarchyNode) => number): this;
-    each(func: (node: HierarchyNode) => void): this;
-    eachAfter(func: (node: HierarchyNode) => void): this;
-    eachBefore(func: (node: HierarchyNode) => void): this;
-    copy(): HierarchyNode;
+
+    /**
+     * Sorts the children of this node, if any, and each of this node’s descendants’ children,
+     * in pre-order traversal using the specified compare function, and returns this node.
+     *
+     * @param compare The compare function is passed two nodes a and b to compare.
+     * If a should be before b, the function must return a value less than zero;
+     * if b should be before a, the function must return a value greater than zero;
+     * otherwise, the relative order of a and b are not specified. See `array.sort` for more.
+     */
+    sort(compare: (a: this, b: this) => number): this;
+
+    /**
+     * Invokes the specified function for node and each descendant in breadth-first order,
+     * such that a given node is only visited if all nodes of lesser depth have already been visited,
+     * as well as all preceding nodes of the same depth.
+     *
+     * @param func The specified function is passed the current node.
+     */
+    each(func: (node: this) => void): this;
+
+    /**
+     * Invokes the specified function for node and each descendant in post-order traversal,
+     * such that a given node is only visited after all of its descendants have already been visited.
+     *
+     * @param func The specified function is passed the current node.
+     */
+    eachAfter(func: (node: this) => void): this;
+
+    /**
+     * Invokes the specified function for node and each descendant in pre-order traversal,
+     * such that a given node is only visited after all of its ancestors have already been visited.
+     *
+     * @param func The specified function is passed the current node.
+     */
+    eachBefore(func: (node: this) => void): this;
+
+    /**
+     * Return a deep copy of the subtree starting at this node. The returned deep copy shares the same data, however.
+     * The returned node is the root of a new tree; the returned node’s parent is always null and its depth is always zero.
+     */
+    copy(): this;
 }
 
+/**
+ * Constructs a root node from the specified hierarchical data.
+ *
+ * @param data The root specified data.
+ * @param children The specified children accessor function invoked for each datum, starting with the root data.
+ * Must return an array of data representing the children, and return null or undefined if the current datum has no children.
+ * If children is not specified, it defaults to: `(d) => d.children`.
+ */
 export function hierarchy(data: Datum, children?: (d: Datum) => (Datum[] | null)): HierarchyNode;
 
 // -----------------------------------------------------------------------
 // Stratify
 // -----------------------------------------------------------------------
 
-// TODO: Review the comment in the API documentation related to 'reserved properties': id, parentId, children. If this is referring to the element on node, it should be 'parent'?
-
 export interface StratifyOperator {
+    /**
+     * Generates a new hierarchy from the specified tabular data. Each node in the returned object has a shallow copy of the properties
+     * from the corresponding data object, excluding the following reserved properties: id, parentId, children.
+     *
+     * @param data The root specified data.
+     * @throws Error on missing id, ambiguous id, cycle, multiple roots or no root.
+     */
     (data: Datum[]): HierarchyNode;
+
+    /**
+     * Returns the current id accessor, which defaults to: `(d) => d.id`.
+     */
     id(): (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined);
+    /**
+     * Sets the id accessor to the given function.
+     * The id accessor is invoked for each element in the input data passed to the stratify operator.
+     * The returned string is then used to identify the node's relationships in conjunction with the parent id.
+     * For leaf nodes, the id may be undefined, null or the empty string; otherwise, the id must be unique.
+     *
+     * @param id The id accessor.
+     */
     id(id: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this;
+
+    /**
+     * Returns the current parent id accessor, which defaults to: `(d) => d.parentId`.
+     */
     parentId(): (d: Datum, i: number, data: Datum[]) => (string | null | '' | undefined);
+    /**
+     * Sets the parent id accessor to the given function.
+     * The parent id accessor is invoked for each element in the input data passed to the stratify operator.
+     * The returned string is then used to identify the node's relationships in conjunction with the id.
+     * For the root node, the parent id should be undefined, null or the empty string.
+     * There must be exactly one root node in the input data, and no circular relationships.
+     *
+     * @param parentId The parent id accessor.
+     */
     parentId(parentId: (d: Datum, i?: number, data?: Datum[]) => (string | null | '' | undefined)): this;
 }
 
+/**
+ * Constructs a new stratify operator with the default settings.
+ */
 export function stratify(): StratifyOperator;
 
 // -----------------------------------------------------------------------
@@ -67,52 +210,86 @@ export function stratify(): StratifyOperator;
 // -----------------------------------------------------------------------
 
 export interface HierarchyPointLink {
+    /**
+     * The source of the link.
+     */
     source: HierarchyPointNode;
+
+    /**
+     * The target of the link.
+     */
     target: HierarchyPointNode;
 }
 
-export interface HierarchyPointNode {
+export interface HierarchyPointNode extends HierarchyNode {
+    /**
+     * The x-coordinate of the node.
+     */
     x: number;
+
+    /**
+     * The y-coordinate of the node.
+     */
     y: number;
-    data: Datum;
-    readonly depth: number;
-    readonly height: number;
-    parent: HierarchyPointNode | null;
-    children?: Array>;
+
     /**
-     * Aggregated numeric value as calculated by sum(value) or count(),
-     * if previously invoked.
+     * Returns an array of links for this node, where each link is an object that defines source and target properties.
+     * The source of each link is the parent node, and the target is a child node.
      */
-    readonly value?: number;
-    /**
-     * Optional Node Id string set by StratifyOperator, if
-     * hierarchical data was created from tabular data using stratify()
-     */
-    readonly id?: string;
-    ancestors(): Array>;
-    descendants(): Array>;
-    leaves(): Array>;
-    path(target: HierarchyPointNode): Array>;
     links(): Array>;
-    sum(value: (d: Datum) => number): this;
-    count(): this;
-    sort(compare: (a: HierarchyPointNode, b: HierarchyPointNode) => number): this;
-    each(func: (node: HierarchyPointNode) => void): this;
-    eachAfter(func: (node: HierarchyPointNode) => void): this;
-    eachBefore(func: (node: HierarchyPointNode) => void): this;
-    copy(): HierarchyPointNode;
 }
 
 export interface ClusterLayout {
+    /**
+     * Lays out the specified root hierarchy.
+     * You may want to call `root.sort` before passing the hierarchy to the cluster layout.
+     *
+     * @param root The specified root hierarchy.
+     */
     (root: HierarchyNode): HierarchyPointNode;
+
+    /**
+     * Returns the current layout size, which defaults to [1, 1]. A layout size of null indicates that a node size will be used instead.
+     */
     size(): [number, number] | null;
+    /**
+     * Sets this cluster layout’s size to the specified [width, height] array and returns the cluster layout.
+     * The size represent an arbitrary coordinate system; for example, to produce a radial layout,
+     * a size of [360, radius] corresponds to a breadth of 360° and a depth of radius.
+     *
+     * @param size The specified two-element size array.
+     */
     size(size: [number, number]): this;
+
+    /**
+     * Returns the current node size, which defaults to null. A node size of null indicates that a layout size will be used instead.
+     */
     nodeSize(): [number, number] | null;
+    /**
+     * Sets this cluster layout’s node size to the specified [width, height] array and returns this cluster layout.
+     * When a node size is specified, the root node is always positioned at <0, 0>.
+     *
+     * @param size The specified two-element size array.
+     */
     nodeSize(size: [number, number]): this;
+
+    /**
+     * Returns the current separation accessor, which defaults to: `(a, b) => a.parent == b.parent ? 1 : 2`.
+     */
     separation(): (a: HierarchyPointNode, b: HierarchyPointNode) => number;
+    /**
+     * Sets the separation accessor to the specified function and returns this cluster layout.
+     * The separation accessor is used to separate neighboring leaves.
+     *
+     * @param separation The separation function is passed two leaves a and b, and must return the desired separation.
+     * The nodes are typically siblings, though the nodes may be more distantly related if the layout decides to place such nodes adjacent.
+     */
     separation(separation: (a: HierarchyPointNode, b: HierarchyPointNode) => number): this;
 }
 
+/**
+ * Creates a new cluster layout with default settings.
+ */
 export function cluster(): ClusterLayout;
 
 // -----------------------------------------------------------------------
@@ -120,15 +297,56 @@ export function cluster(): ClusterLayout;
 // -----------------------------------------------------------------------
 
 export interface TreeLayout {
+    /**
+     * Lays out the specified root hierarchy.
+     * You may want to call `root.sort` before passing the hierarchy to the tree layout.
+     *
+     * @param root The specified root hierarchy.
+     */
     (root: HierarchyNode): HierarchyPointNode;
+
+    /**
+     * Returns the current layout size, which defaults to [1, 1]. A layout size of null indicates that a node size will be used instead.
+     */
     size(): [number, number] | null;
+    /**
+     * Sets this tree layout’s size to the specified [width, height] array and returns the tree layout.
+     * The size represent an arbitrary coordinate system; for example, to produce a radial layout,
+     * a size of [360, radius] corresponds to a breadth of 360° and a depth of radius.
+     *
+     * @param size The specified two-element size array.
+     */
     size(size: [number, number]): this;
+
+    /**
+     * Returns the current node size, which defaults to null. A node size of null indicates that a layout size will be used instead.
+     */
     nodeSize(): [number, number] | null;
+    /**
+     * Sets this tree layout’s node size to the specified [width, height] array and returns this tree layout.
+     * When a node size is specified, the root node is always positioned at <0, 0>.
+     *
+     * @param size The specified two-element size array.
+     */
     nodeSize(size: [number, number]): this;
+
+    /**
+     * Returns the current separation accessor, which defaults to: `(a, b) => a.parent == b.parent ? 1 : 2`.
+     */
     separation(): (a: HierarchyPointNode, b: HierarchyPointNode) => number;
+    /**
+     * Sets the separation accessor to the specified function and returns this tree layout.
+     * The separation accessor is used to separate neighboring nodes.
+     *
+     * @param separation The separation function is passed two nodes a and b, and must return the desired separation.
+     * The nodes are typically siblings, though the nodes may be more distantly related if the layout decides to place such nodes adjacent.
+     */
     separation(separation: (a: HierarchyPointNode, b: HierarchyPointNode) => number): this;
 }
 
+/**
+ * Creates a new tree layout with default settings.
+ */
 export function tree(): TreeLayout;
 
 // -----------------------------------------------------------------------
@@ -136,91 +354,283 @@ export function tree(): TreeLayout;
 // -----------------------------------------------------------------------
 
 export interface HierarchyRectangularLink {
+    /**
+     * The source of the link.
+     */
     source: HierarchyRectangularNode;
+
+    /**
+     * The target of the link.
+     */
     target: HierarchyRectangularNode;
 }
 
-export interface HierarchyRectangularNode {
+export interface HierarchyRectangularNode extends HierarchyNode {
+    /**
+     * The left edge of the rectangle.
+     */
     x0: number;
+
+    /**
+     * The top edge of the rectangle
+     */
     y0: number;
+
+    /**
+     * The right edge of the rectangle.
+     */
     x1: number;
+
+    /**
+     * The bottom edge of the rectangle.
+     */
     y1: number;
-    data: Datum;
-    readonly depth: number;
-    readonly height: number;
-    parent: HierarchyRectangularNode | null;
-    children?: Array>;
+
     /**
-     * Aggregated numeric value as calculated by sum(value) or count(),
-     * if previously invoked.
+     * Returns an array of links for this node, where each link is an object that defines source and target properties.
+     * The source of each link is the parent node, and the target is a child node.
      */
-    readonly value?: number;
-    /**
-     * Optional Node Id string set by StratifyOperator, if
-     * hierarchical data was created from tabular data using stratify()
-     */
-    readonly id?: string;
-    ancestors(): Array>;
-    descendants(): Array>;
-    leaves(): Array>;
-    path(target: HierarchyRectangularNode): Array>;
     links(): Array>;
-    sum(value: (d: Datum) => number): this;
-    count(): this;
-    sort(compare: (a: HierarchyRectangularNode, b: HierarchyRectangularNode) => number): this;
-    each(func: (node: HierarchyRectangularNode) => void): this;
-    eachAfter(func: (node: HierarchyRectangularNode) => void): this;
-    eachBefore(func: (node: HierarchyRectangularNode) => void): this;
-    copy(): HierarchyRectangularNode;
 }
 
 export interface TreemapLayout {
+    /**
+     * Lays out the specified root hierarchy.
+     * You must call `root.sum` before passing the hierarchy to the treemap layout.
+     * You probably also want to call `root.sort` to order the hierarchy before computing the layout.
+     *
+     * @param root The specified root hierarchy.
+     */
     (root: HierarchyNode): HierarchyRectangularNode;
+
+    /**
+     * Returns the current tiling method, which defaults to `d3.treemapSquarify` with the golden ratio.
+     */
     tile(): (node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number) => void;
+    /**
+     * Sets the tiling method to the specified function and returns this treemap layout.
+     *
+     * @param tile The specified tiling function.
+     */
     tile(tile: (node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number) => void): this;
+
+    /**
+     * Returns the current size, which defaults to [1, 1].
+     */
     size(): [number, number];
+    /**
+     * Sets this treemap layout’s size to the specified [width, height] array and returns this treemap layout.
+     *
+     * @param size The specified two-element size array.
+     */
     size(size: [number, number]): this;
+
+    /**
+     * Returns the current rounding state, which defaults to false.
+     */
     round(): boolean;
+    /**
+     * Enables or disables rounding according to the given boolean and returns this treemap layout.
+     *
+     * @param round The specified boolean flag.
+     */
     round(round: boolean): this;
+
+    /**
+     * Returns the current inner padding function.
+     */
     padding(): (node: HierarchyRectangularNode) => number;
+    /**
+     * Sets the inner and outer padding to the specified number and returns this treemap layout.
+     *
+     * @param padding The specified padding value.
+     */
     padding(padding: number): this;
+    /**
+     * Sets the inner and outer padding to the specified function and returns this treemap layout.
+     *
+     * @param padding The specified padding function.
+     */
     padding(padding: (node: HierarchyRectangularNode) => number): this;
+
+    /**
+     * Returns the current inner padding function, which defaults to the constant zero.
+     */
     paddingInner(): (node: HierarchyRectangularNode) => number;
+    /**
+     * Sets the inner padding to the specified number and returns this treemap layout.
+     * The inner padding is used to separate a node’s adjacent children.
+     *
+     * @param padding The specified inner padding value.
+     */
     paddingInner(padding: number): this;
+    /**
+     * Sets the inner padding to the specified function and returns this treemap layout.
+     * The function is invoked for each node with children, being passed the current node.
+     * The inner padding is used to separate a node’s adjacent children.
+     *
+     * @param padding The specified inner padding function.
+     */
     paddingInner(padding: (node: HierarchyRectangularNode) => number): this;
+
+    /**
+     * Returns the current top padding function.
+     */
     paddingOuter(): (node: HierarchyRectangularNode) => number;
+    /**
+     * Sets the top, right, bottom and left padding to the specified function and returns this treemap layout.
+     *
+     * @param padding The specified padding outer value.
+     */
     paddingOuter(padding: number): this;
+    /**
+     * Sets the top, right, bottom and left padding to the specified function and returns this treemap layout.
+     *
+     * @param padding The specified padding outer function.
+     */
     paddingOuter(padding: (node: HierarchyRectangularNode) => number): this;
+
+    /**
+     * Returns the current top padding function, which defaults to the constant zero.
+     */
     paddingTop(): (node: HierarchyRectangularNode) => number;
+    /**
+     * Sets the top padding to the specified number and returns this treemap layout.
+     * The top padding is used to separate the top edge of a node from its children.
+     *
+     * @param padding The specified top padding value.
+     */
     paddingTop(padding: number): this;
+    /**
+     * Sets the top padding to the specified function and returns this treemap layout.
+     * The function is invoked for each node with children, being passed the current node.
+     * The top padding is used to separate the top edge of a node from its children.
+     *
+     * @param padding The specified top padding function.
+     */
     paddingTop(padding: (node: HierarchyRectangularNode) => number): this;
+
+    /**
+     * Returns the current right padding function, which defaults to the constant zero.
+     */
     paddingRight(): (node: HierarchyRectangularNode) => number;
+    /**
+     * Sets the right padding to the specified number and returns this treemap layout.
+     * The right padding is used to separate the right edge of a node from its children.
+     *
+     * @param padding The specified right padding value.
+     */
     paddingRight(padding: number): this;
+    /**
+     * Sets the right padding to the specified function and returns this treemap layout.
+     * The function is invoked for each node with children, being passed the current node.
+     * The right padding is used to separate the right edge of a node from its children.
+     *
+     * @param padding The specified right padding function.
+     */
     paddingRight(padding: (node: HierarchyRectangularNode) => number): this;
+
+    /**
+     * Returns the current bottom padding function, which defaults to the constant zero.
+     */
     paddingBottom(): (node: HierarchyRectangularNode) => number;
+    /**
+     * Sets the bottom padding to the specified number and returns this treemap layout.
+     * The bottom padding is used to separate the bottom edge of a node from its children.
+     *
+     * @param padding The specified bottom padding value.
+     */
     paddingBottom(padding: number): this;
+    /**
+     * Sets the bottom padding to the specified function and returns this treemap layout.
+     * The function is invoked for each node with children, being passed the current node.
+     * The bottom padding is used to separate the bottom edge of a node from its children.
+     *
+     * @param padding The specified bottom padding function.
+     */
     paddingBottom(padding: (node: HierarchyRectangularNode) => number): this;
+
+    /**
+     * Returns the current left padding function, which defaults to the constant zero.
+     */
     paddingLeft(): (node: HierarchyRectangularNode) => number;
+    /**
+     * Sets the left padding to the specified number and returns this treemap layout.
+     * The left padding is used to separate the left edge of a node from its children.
+     *
+     * @param padding The specified left padding value.
+     */
     paddingLeft(padding: number): this;
+    /**
+     * Sets the left padding to the specified function and returns this treemap layout.
+     * The function is invoked for each node with children, being passed the current node.
+     * The left padding is used to separate the left edge of a node from its children.
+     *
+     * @param padding The specified left padding function.
+     */
     paddingLeft(padding: (node: HierarchyRectangularNode) => number): this;
 }
 
+/**
+ * Creates a new treemap layout with default settings.
+ */
 export function treemap(): TreemapLayout;
 
-// Tiling functions ---------------------------------------------------------------------------------
+// Tiling functions -----------------------------------------------------------------------
 
+/**
+ * Recursively partitions the specified nodes into an approximately-balanced binary tree,
+ * choosing horizontal partitioning for wide rectangles and vertical partitioning for tall rectangles.
+ */
 export function treemapBinary(node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void;
+
+/**
+ * Divides the rectangular area specified by x0, y0, x1, y1 horizontally according the value of each of the specified node’s children.
+ * The children are positioned in order, starting with the left edge (x0) of the given rectangle.
+ * If the sum of the children’s values is less than the specified node’s value (i.e., if the specified node has a non-zero internal value),
+ * the remaining empty space will be positioned on the right edge (x1) of the given rectangle.
+ */
 export function treemapDice(node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void;
+
+/**
+ * Divides the rectangular area specified by x0, y0, x1, y1 vertically according the value of each of the specified node’s children.
+ * The children are positioned in order, starting with the top edge (y0) of the given rectangle.
+ * If the sum of the children’s values is less than the specified node’s value (i.e., if the specified node has a non-zero internal value),
+ * the remaining empty space will be positioned on the bottom edge (y1) of the given rectangle.
+ */
 export function treemapSlice(node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void;
+
+/**
+ * If the specified node has odd depth, delegates to treemapSlice; otherwise delegates to treemapDice.
+ */
 export function treemapSliceDice(node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void;
 
 // TODO: Test Factory code
 export interface RatioSquarifyTilingFactory {
     (node: HierarchyRectangularNode, x0: number, y0: number, x1: number, y1: number): void;
+
+    /**
+     * Specifies the desired aspect ratio of the generated rectangles.
+     * Note that the orientation of the generated rectangles (tall or wide) is not implied by the ratio.
+     * Furthermore, the rectangles ratio are not guaranteed to have the exact specified aspect ratio.
+     * If not specified, the aspect ratio defaults to the golden ratio, φ = (1 + sqrt(5)) / 2, per Kong et al.
+     *
+     * @param ratio The specified ratio value greater than or equal to one.
+     */
     ratio(ratio: number): RatioSquarifyTilingFactory;
 }
 
+/**
+ * Implements the squarified treemap algorithm by Bruls et al., which seeks to produce rectangles of a given aspect ratio.
+ */
 export const treemapSquarify: RatioSquarifyTilingFactory;
+
+/**
+ * Like `d3.treemapSquarify`, except preserves the topology (node adjacencies) of the previous layout computed by `d3.treemapResquarify`,
+ * if there is one and it used the same target aspect ratio. This tiling method is good for animating changes to treemaps because
+ * it only changes node sizes and not their relative positions, thus avoiding distracting shuffling and occlusion.
+ * The downside of a stable update, however, is a suboptimal layout for subsequent updates: only the first layout uses the Bruls et al. squarified algorithm.
+ */
 export const treemapResquarify: RatioSquarifyTilingFactory;
 
 // -----------------------------------------------------------------------
@@ -228,15 +638,53 @@ export const treemapResquarify: RatioSquarifyTilingFactory;
 // -----------------------------------------------------------------------
 
 export interface PartitionLayout {
+    /**
+     * Lays out the specified root hierarchy.
+     * You must call `root.sum` before passing the hierarchy to the partition layout.
+     * You probably also want to call `root.sort` to order the hierarchy before computing the layout.
+     *
+     * @param root The specified root hierarchy.
+     */
     (root: HierarchyNode): HierarchyRectangularNode;
+
+    /**
+     * Returns the current size, which defaults to [1, 1].
+     */
     size(): [number, number];
+    /**
+     * Sets this partition layout’s size to the specified [width, height] array and returns this partition layout.
+     *
+     * @param size The specified two-element size array.
+     */
     size(size: [number, number]): this;
+
+    /**
+     * Returns the current rounding state, which defaults to false.
+     */
     round(): boolean;
+    /**
+     * Enables or disables rounding according to the given boolean and returns this partition layout.
+     *
+     * @param round The specified boolean flag.
+     */
     round(round: boolean): this;
+
+    /**
+     * Returns the current padding, which defaults to zero.
+     */
     padding(): number;
+    /**
+     * Sets the padding to the specified number and returns this partition layout.
+     * The padding is used to separate a node’s adjacent children.
+     *
+     * @param padding The specified padding value.
+     */
     padding(padding: number): this;
 }
 
+/**
+ * Creates a new partition layout with the default settings.
+ */
 export function partition(): PartitionLayout;
 
 // -----------------------------------------------------------------------
@@ -244,54 +692,110 @@ export function partition(): PartitionLayout;
 // -----------------------------------------------------------------------
 
 export interface HierarchyCircularLink {
+    /**
+     * The source of the link.
+     */
     source: HierarchyCircularNode;
+
+    /**
+     * The target of the link.
+     */
     target: HierarchyCircularNode;
 }
 
-export interface HierarchyCircularNode {
+export interface HierarchyCircularNode extends HierarchyNode {
+    /**
+     * The x-coordinate of the circle’s center.
+     */
     x: number;
+
+    /**
+     * The y-coordinate of the circle’s center.
+     */
     y: number;
+
+    /**
+     * The radius of the circle.
+     */
     r: number;
-    data: Datum;
-    readonly depth: number;
-    readonly height: number;
-    parent: HierarchyCircularNode | null;
-    children?: Array>;
+
     /**
-     * Aggregated numeric value as calculated by sum(value) or count(),
-     * if previously invoked.
+     * Returns an array of links for this node, where each link is an object that defines source and target properties.
+     * The source of each link is the parent node, and the target is a child node.
      */
-    readonly value?: number;
-    /**
-     * Optional Node Id string set by StratifyOperator, if
-     * hierarchical data was created from tabular data using stratify()
-     */
-    readonly id?: string;
-    ancestors(): Array>;
-    descendants(): Array>;
-    leaves(): Array>;
-    path(target: HierarchyCircularNode): Array>;
     links(): Array>;
-    sum(value: (d: Datum) => number): this;
-    count(): this;
-    sort(compare: (a: HierarchyCircularNode, b: HierarchyCircularNode) => number): this;
-    each(func: (node: HierarchyCircularNode) => void): this;
-    eachAfter(func: (node: HierarchyCircularNode) => void): this;
-    eachBefore(func: (node: HierarchyCircularNode) => void): this;
-    copy(): HierarchyCircularNode;
 }
 
 export interface PackLayout {
+    /**
+     * Lays out the specified root hierarchy.
+     * You must call `root.sum` before passing the hierarchy to the pack layout.
+     * You probably also want to call `root.sort` to order the hierarchy before computing the layout.
+     *
+     * @param root The specified root hierarchy.
+     */
     (root: HierarchyNode): HierarchyCircularNode;
+
+    /**
+     * Returns the current radius accessor, which defaults to null.
+     */
     radius(): null | ((node: HierarchyCircularNode) => number);
+    /**
+     * Sets the pack layout’s radius accessor to the specified function and returns this pack layout.
+     * If the radius accessor is null, the radius of each leaf circle is derived from the leaf `node.value` (computed by `node.sum`);
+     * the radii are then scaled proportionally to fit the layout size.
+     * If the radius accessor is not null, the radius of each leaf circle is specified exactly by the function.
+     *
+     * @param radius The specified radius accessor.
+     */
     radius(radius: (node: HierarchyCircularNode) => number): this;
+
+    /**
+     * Returns the current size, which defaults to [1, 1].
+     */
     size(): [number, number];
+    /**
+     * Sets this pack layout’s size to the specified [width, height] array and returns this pack layout.
+     *
+     * @param size The specified two-element size array.
+     */
     size(size: [number, number]): this;
+
+    /**
+     * Returns the current padding accessor, which defaults to the constant zero.
+     */
     padding(): (node: HierarchyCircularNode) => number;
+    /**
+     * Sets this pack layout’s padding accessor to the specified number and returns this pack layout.
+     * Returns the current padding accessor, which defaults to the constant zero.
+     *
+     * When siblings are packed, tangent siblings will be separated by approximately the specified padding;
+     * the enclosing parent circle will also be separated from its children by approximately the specified padding.
+     * If an explicit radius is not specified, the padding is approximate because a two-pass algorithm
+     * is needed to fit within the layout size: the circles are first packed without padding;
+     * a scaling factor is computed and applied to the specified padding; and lastly the circles are re-packed with padding.
+     *
+     * @param padding The specified padding value.
+     */
     padding(padding: number): this;
+    /**
+     * Sets this pack layout’s padding accessor to the specified function and returns this pack layout.
+     * Returns the current padding accessor, which defaults to the constant zero.
+     *
+     * When siblings are packed, tangent siblings will be separated by approximately the specified padding;
+     * the enclosing parent circle will also be separated from its children by approximately the specified padding.
+     * If an explicit radius is not specified, the padding is approximate because a two-pass algorithm
+     * is needed to fit within the layout size: the circles are first packed without padding;
+     * a scaling factor is computed and applied to the specified padding; and lastly the circles are re-packed with padding.
+     *
+     * @param padding The specified padding function.
+     */
     padding(padding: (node: HierarchyCircularNode) => number): this;
 }
 
+/**
+ * Creates a new pack layout with the default settings.
+ */
 export function pack(): PackLayout;
 
 // -----------------------------------------------------------------------
@@ -299,8 +803,19 @@ export function pack(): PackLayout;
 // -----------------------------------------------------------------------
 
 export interface PackCircle {
+    /**
+     * The radius of the circle.
+     */
     r: number;
+
+    /**
+     * The x-coordinate of the circle’s center.
+     */
     x?: number;
+
+    /**
+     * The y-coordinate of the circle’s center.
+     */
     y?: number;
 }
 
@@ -309,6 +824,19 @@ export interface PackCircle {
 // For invocation of packEnclose the x and y coordinates are mandatory. It seems easier to just comment
 // on the mandatory nature, then to create separate interfaces and having to deal with recasting.
 
+/**
+ * Packs the specified array of circles, each of which must have a `circle.r` property specifying the circle’s radius.
+ * The circles are positioned according to the front-chain packing algorithm by Wang et al.
+ *
+ * @param circles The specified array of circles to pack.
+ */
 export function packSiblings(circles: Datum[]): Datum[];
 
+/**
+ * Computes the smallest circle that encloses the specified array of circles, each of which must have
+ * a `circle.r` property specifying the circle’s radius, and `circle.x` and `circle.y` properties specifying the circle’s center.
+ * The enclosing circle is computed using the Matoušek-Sharir-Welzl algorithm. (See also Apollonius’ Problem.)
+ *
+ * @param circles The specified array of circles to pack.
+ */
 export function packEnclose(circles: Datum[]): { r: number, x: number, y: number };
diff --git a/types/d3-quadtree/d3-quadtree-tests.ts b/types/d3-quadtree/d3-quadtree-tests.ts
index eda00fe130..8180bc0f44 100644
--- a/types/d3-quadtree/d3-quadtree-tests.ts
+++ b/types/d3-quadtree/d3-quadtree-tests.ts
@@ -13,19 +13,21 @@ import * as d3Quadtree from 'd3-quadtree';
 // ---------------------------------------------------------------------------
 
 // custom type guard
-function isLeaf(a: any): a is d3Quadtree.QuadtreeLeaf {
-    return a.data !== undefined;
+function isLeaf(a: d3Quadtree.QuadtreeInternalNode | d3Quadtree.QuadtreeLeaf): a is d3Quadtree.QuadtreeLeaf {
+    return a.length === undefined;
 }
 
 let num: number;
-let extent: [[number, number], [number, number]];
+let num4: 4;
+let undef: undefined;
+let extent: [[number, number], [number, number]] | undefined;
 
 interface TestDatum {
     x: number;
     y: number;
 }
 
-let testDatum: TestDatum;
+let testDatum: TestDatum | undefined;
 
 let testData: TestDatum[] = [
     { x: 10, y: 20 },
@@ -83,7 +85,6 @@ quadtree = d3Quadtree.quadtree(testData); // explicitly typed to Test
 
 // test without data
 quadtree = d3Quadtree.quadtree();
-// quadtree = d3Quadtree.quadtree(); fails, wrong underlying data type
 
 // Configure Quadtree ========================================================
 
@@ -111,12 +112,14 @@ quadtree = quadtree.cover(50, 90);
 // add(...) ------------------------------------------------------------------
 
 quadtree = quadtree.add({ x: 35, y: 35 });
-// quadtree = quadtree.add({x: 35}); // fails, incompatible data type
+// $ExpectError
+quadtree = quadtree.add({x: 35}); // fails, incompatible data type
 
 // addAll(...) ---------------------------------------------------------------
 
 quadtree = quadtree.addAll(testData);
-// quadtree = quadtree.addAll([{x: 35}, {x: 55, y: 13}]); // fails, incompatible data type
+// $ExpectError
+quadtree = quadtree.addAll([{x: 35}, {x: 55, y: 13}]); // fails, incompatible data type
 
 // remove(...) ---------------------------------------------------------------
 
@@ -191,9 +194,10 @@ quadtree = quadtree.visit((node, x0, y0, x1, y1) => {
     }
 });
 
-// quadtree = quadtree.visit(function (node, x0, y0, x1, y1) {
-//     return 10; // fails wrong return type
-// });
+// $ExpectError
+quadtree = quadtree.visit((node, x0, y0, x1, y1) => {
+    return 10; // fails wrong return type
+});
 
 // visitAfter() ---------------------------------------------------------------
 
@@ -232,3 +236,15 @@ quadNode = internalNode[0];
 quadNode = internalNode[1];
 quadNode = internalNode[2];
 quadNode = internalNode[3];
+
+num = internalNode.length;
+num4 = internalNode.length;
+
+quadtree = quadtree.visit((node, x0, y0, x1, y1) => {
+    if (isLeaf(node)) {
+        undef = node.length;
+    } else {
+        num = node.length;
+        num4 = node.length;
+    }
+});
diff --git a/types/d3-quadtree/index.d.ts b/types/d3-quadtree/index.d.ts
index 8128c9e306..8e66ba411c 100644
--- a/types/d3-quadtree/index.d.ts
+++ b/types/d3-quadtree/index.d.ts
@@ -1,17 +1,34 @@
 // Type definitions for D3JS d3-quadtree module 1.0
 // Project: https://github.com/d3/d3-quadtree/
-// 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
 
-// Last module patch version validated against: 1.0.1
+// Last module patch version validated against: 1.0.3
 
 /**
  * Leaf node of the quadtree.
  */
 export interface QuadtreeLeaf {
+    /**
+     * The data associated with this point, as passed to quadtree.add.
+     */
     data: T;
+
+    /**
+     * The next datum in this leaf, if any.
+     */
     next?: QuadtreeLeaf;
+
+    /**
+     * The length property may be used to distinguish leaf nodes from internal nodes: it is undefined for leaf nodes, and 4 for internal nodes.
+     */
+    length?: undefined;
 }
+
 /**
  * Internal nodes of the quadtree are represented as four-element arrays in left-to-right, top-to-bottom order:
  *
@@ -22,32 +39,170 @@ export interface QuadtreeLeaf {
  *
  * A child quadrant may be undefined if it is empty.
  */
-export interface QuadtreeInternalNode extends Array | QuadtreeLeaf | undefined> { }
+export interface QuadtreeInternalNode extends Array | QuadtreeLeaf | undefined> {
+    /**
+     * The length property may be used to distinguish leaf nodes from internal nodes: it is undefined for leaf nodes, and 4 for internal nodes.
+     */
+    length: 4;
+}
 
 export interface Quadtree {
+    /**
+     * Returns the current x-accessor, which defaults to: `x(d) => d[0]`.
+     */
     x(): (d: T) => number;
+    /**
+     * Sets the current x-coordinate accessor and returns the quadtree.
+     * The x-accessors must be consistent, returning the same value given the same input.
+     *
+     * @param x The x-coordinate accessor.
+     */
     x(x: (d: T) => number): this;
+
+    /**
+     * Returns the current y-accessor, which defaults to: `y(d) => d[1]`.
+     */
     y(): (d: T) => number;
+    /**
+     * Sets the current y-coordinate accessor and returns the quadtree.
+     * The y-accessors must be consistent, returning the same value given the same input.
+     *
+     * @param y The y-coordinate accessor.
+     */
     y(y: (d: T) => number): this;
+
+    /**
+     * Returns the quadtree's current extent `[[x0, y0], [x1, y1]]`,
+     * where `x0` and `y0` are the inclusive lower bounds and `x1` and `y1` are the inclusive upper bounds,
+     * or `undefined` if the quadtree has no extent.
+     */
     extent(): [[number, number], [number, number]] | undefined;
+    /**
+     * Expands the quadtree to cover the specified points `[[x0, y0], [x1, y1]]` and returns the quadtree.
+     * The extent may also be expanded by calling `quadtree.cover` or `quadtree.add`.
+     *
+     * @param extend The specified points to cover.
+     */
     extent(extend: [[number, number], [number, number]]): this;
+
+    /**
+     * Expands the quadtree to cover the specified point ⟨x,y⟩, and returns the quadtree.
+     * * If the quadtree’s extent already covers the specified point, this method does nothing.
+     * * If the quadtree has an extent, the extent is repeatedly doubled to cover the specified point, wrapping the root node as necessary.
+     * * If the quadtree is empty, the extent is initialized to the extent `[[⌊x⌋, ⌊y⌋], [⌈x⌉, ⌈y⌉]]`.
+     * Rounding is necessary such that if the extent is later doubled, the boundaries of existing quadrants do not change due to floating point error.
+     *
+     * @param x The x-coordinate for the specified point to cover.
+     * @param y The y-coordinate for the specified point to cover.
+     */
     cover(x: number, y: number): this;
+
+    /**
+     * Adds the specified datum to the quadtree, deriving its coordinates ⟨x,y⟩ using the current x- and y-accessors, and returns the quadtree.
+     * If the new point is outside the current extent of the quadtree, the quadtree is automatically expanded to cover the new point.
+     *
+     * @param datum The specified datum to add.
+     */
     add(datum: T): this;
+
+    /**
+     * Adds the specified array of data to the quadtree, deriving each element’s coordinates ⟨x,y⟩ using the current x- and y-accessors, and return this quadtree.
+     * This is approximately equivalent to calling quadtree.add repeatedly.
+     * However, this method results in a more compact quadtree because the extent of the data is computed first before adding the data.
+     *
+     * @param data The specified array of data to add.
+     */
     addAll(data: T[]): this;
+
+    /**
+     * Removes the specified datum to the quadtree, deriving its coordinates ⟨x,y⟩ using the current x- and y-accessors, and returns the quadtree.
+     * If the specified datum does not exist in this quadtree, this method does nothing.
+     *
+     * @param datum The specified datum to remove.
+     */
     remove(datum: T): this;
+
+    /**
+     * Removes the specified data to the quadtree, deriving their coordinates ⟨x,y⟩ using the current x- and y-accessors, and returns the quadtree.
+     * If a specified datum does not exist in this quadtree, it is ignored.
+     *
+     * @param data The specified array of data to remove.
+     */
     removeAll(data: T[]): this;
+
+    /**
+     * Returns a copy of the quadtree. All nodes in the returned quadtree are identical copies of the corresponding node in the quadtree;
+     * however, any data in the quadtree is shared by reference and not copied.
+     */
     copy(): Quadtree;
+
+    /**
+     * Returns the root node of the quadtree.
+     */
     root(): QuadtreeInternalNode | QuadtreeLeaf;
+
+    /**
+     * Returns an array of all data in the quadtree.
+     */
     data(): T[];
+
+    /**
+     * Returns the total number of data in the quadtree.
+     */
     size(): number;
+
+    /**
+     * Returns the datum closest to the position ⟨x,y⟩ with the given search radius. If radius is not specified, it defaults to infinity.
+     * If there is no datum within the search area, returns undefined.
+     *
+     * @param x The x-coordinate for the search position.
+     * @param y The y-coordinate for the search position.
+     * @param radius The optional search radius.
+     */
     find(x: number, y: number, radius?: number): T | undefined;
-    // TODO: Review below, when validating to strictNullChecks.
-    // tslint:disable-next-line:void-return
-    visit(callback: (node: QuadtreeInternalNode | QuadtreeLeaf, x0: number, y0: number, x1: number, y1: number) => (void | boolean)): this;
+
+    /**
+     * Visits each node in the quadtree in pre-order traversal, invoking the specified callback with arguments `node`, `x0`, `y0`, `x1`, `y1` for each node,
+     * where `node` is the node being visited, ⟨x0, y0⟩ are the lower bounds of the node, and ⟨x1, y1⟩ are the upper bounds, and returns the quadtree.
+     *
+     * If the callback returns true for a given node, then the children of that node are not visited; otherwise, all child nodes are visited.
+     * This can be used to quickly visit only parts of the tree.
+     * Note, however, that child quadrants are always visited in sibling order: top-left, top-right, bottom-left, bottom-right.
+     * In cases such as search, visiting siblings in a specific order may be faster.
+     *
+     * @param callback The callback invoked for each node.
+     */
+    visit(callback: (node: QuadtreeInternalNode | QuadtreeLeaf, x0: number, y0: number, x1: number, y1: number) => void | boolean): this;
+
+    /**
+     * Visits each node in the quadtree in post-order traversal, invoking the specified callback with arguments `node`, `x0`, `y0`, `x1`, `y1` for each node,
+     * where `node` is the node being visited, ⟨x0, y0⟩ are the lower bounds of the node, and ⟨x1, y1⟩ are the upper bounds, and returns the quadtree.
+     *
+     * @param callback The callback invoked for each node.
+     */
     visitAfter(callback: (node: QuadtreeInternalNode | QuadtreeLeaf, x0: number, y0: number, x1: number, y1: number) => void): this;
 }
 
-export function quadtree(): Quadtree<[number, number]>;
-export function quadtree(data: Array<[number, number]>): Quadtree<[number, number]>;
-export function quadtree(): Quadtree;
-export function quadtree(data: T[], x?: (d: T) => number, y?: (d: T) => number): Quadtree;
+/**
+ * Creates a new, empty quadtree with an empty extent and the default x- and y-accessors.
+ *
+ * The generic refers to the data type. If omitted, the default setting assumes that,
+ * the data used with the quadtree are two-element arrays.
+ * The first element corresponds to the x-dimension, the second to the y-dimension.
+ * When using another type, The x- and y-accessors must be specified.
+ */
+export function quadtree(): Quadtree;
+/**
+ * Creates a new quadtree with the specified array of data.
+ * If `x` and `y` are also specified, sets the x- and y- accessors to the specified functions before adding the specified array of data to the quadtree, otherwise use the default x- and y-accessors.
+ *
+ * The generic refers to the data type. If omitted, the default setting assumes that,
+ * the data used with the quadtree are two-element arrays.
+ * The first element corresponds to the x-dimension, the second to the y-dimension.
+ * When using another type, The x- and y-accessors must be specified.
+ *
+ * @param data The specified array of data to add.
+ * @param x The x-coordinate accessor.
+ * @param y The y-coordinate accessor.
+ */
+export function quadtree(data: T[], x?: (d: T) => number, y?: (d: T) => number): Quadtree;
diff --git a/types/d3-quadtree/tsconfig.json b/types/d3-quadtree/tsconfig.json
index cbbb70a658..0f4239c3a6 100644
--- a/types/d3-quadtree/tsconfig.json
+++ b/types/d3-quadtree/tsconfig.json
@@ -7,7 +7,7 @@
         ],
         "noImplicitAny": true,
         "noImplicitThis": true,
-        "strictNullChecks": false,
+        "strictNullChecks": true,
         "strictFunctionTypes": true,
         "baseUrl": "../",
         "typeRoots": [
diff --git a/types/d3-selection/d3-selection-tests.ts b/types/d3-selection/d3-selection-tests.ts
index 54ddb5ea11..b99c81e39a 100644
--- a/types/d3-selection/d3-selection-tests.ts
+++ b/types/d3-selection/d3-selection-tests.ts
@@ -796,7 +796,7 @@ newDiv2 = body.append(function(d, i, g) {
     const index: number = i;
     const group: HTMLBodyElement[] | d3Selection.ArrayLike = g;
     console.log('Body element foo property: ', d.foo); // data of type BodyDatum
-    return this.ownerDocument.createElement('div'); // this-type HTMLBodyElement
+    return this.ownerDocument!.createElement('div'); // this-type HTMLBodyElement
 });
 
 // newDiv2 = body.append(function(d) {
@@ -828,7 +828,7 @@ const typeValueFunction = function(
   i: number,
   g: HTMLBodyElement[] | d3Selection.ArrayLike
 ) {
-    return this.ownerDocument.createElement('p'); // this-type HTMLParagraphElement
+    return this.ownerDocument!.createElement('p'); // this-type HTMLParagraphElement
 };
 
 const beforeValueFunction = function(
diff --git a/types/d3-selection/index.d.ts b/types/d3-selection/index.d.ts
index d1e127dfdf..d9988636fd 100644
--- a/types/d3-selection/index.d.ts
+++ b/types/d3-selection/index.d.ts
@@ -22,7 +22,7 @@ export type BaseType = Element | EnterElement | Document | Window | null;
  */
 export interface ArrayLike {
     length: number;
-    item(index: number): T;
+    item(index: number): T | null;
     [index: number]: T;
 }
 
diff --git a/types/datatables.net/datatables.net-tests.ts b/types/datatables.net/datatables.net-tests.ts
index d22e878d34..de739a673a 100644
--- a/types/datatables.net/datatables.net-tests.ts
+++ b/types/datatables.net/datatables.net-tests.ts
@@ -1073,3 +1073,92 @@ const util_1: boolean = dt.any();
 const util_2: number = dt.count();
 
 //#endregion "Methods-Util"
+
+//#region "ExtSettings"
+
+const ext_classes_settings: DataTables.ExtClassesSettings = {
+};
+const ext_classes_settings_full: DataTables.ExtClassesSettings = {
+    sFilter: "",
+    sFilterInput: "",
+    sFooterTH: "",
+    sHeaderTH: "",
+    sInfo: "",
+    sJUIFooter: "",
+    sJUIHeader: "",
+    sLength: "",
+    sLengthSelect: "",
+    sNoFooter: "",
+    sPageButton: "",
+    sPageButtonActive: "",
+    sPageButtonDisabled: "",
+    sPaging: "",
+    sProcessing: "",
+    sRowEmpty: "",
+    sScrollBody: "",
+    sScrollFoot: "",
+    sScrollFootInner: "",
+    sScrollHead: "",
+    sScrollHeadInner: "",
+    sScrollWrapper: "",
+    sSortable: "",
+    sSortableAsc: "",
+    sSortableDesc: "",
+    sSortableNone: "",
+    sSortAsc: "",
+    sSortColumn: "",
+    sSortDesc: "",
+    sSortIcon: "",
+    sSortJUI: "",
+    sSortJUIAsc: "",
+    sSortJUIAscAllowed: "",
+    sSortJUIDesc: "",
+    sSortJUIDescAllowed: "",
+    sSortJUIWrapper: "",
+    sStripeEven: "",
+    sStripeOdd: "",
+    sTable: "",
+    sWrapper: ""
+};
+
+const ext_type_settings: DataTables.ExtTypeSettings = {
+    detect: [],
+    search: {},
+    order: {}
+};
+ext_type_settings.detect.push((d: string, s: DataTables.Settings) => {
+    return null;
+});
+ext_type_settings.detect.push((d: string, s: DataTables.Settings) => {
+    return "";
+});
+
+const ext_settings: DataTables.ExtSettings = {
+    aTypes: [],
+    afnFiltering: [],
+    afnSortData: {},
+    aoFeatures: [],
+    builder: "",
+    classes: ext_classes_settings,
+    errMode: "",
+    feature: [],
+    fnVersionCheck: (version: string) => "",
+    iApiIndex: 0,
+    internal: {},
+    legacy: {},
+    oApi: {},
+    oJUIClasses: {},
+    oPagination: {},
+    oSort: {},
+    oStdClasses: ext_classes_settings,
+    ofnSearch: {},
+    order: {},
+    pager: {},
+    renderer: {},
+    sVersion: "",
+    search: [],
+    selector: {},
+    type: ext_type_settings
+};
+
+ //#endregion "ExtSettings"
diff --git a/types/datatables.net/index.d.ts b/types/datatables.net/index.d.ts
index ae7edf755a..ed87028502 100644
--- a/types/datatables.net/index.d.ts
+++ b/types/datatables.net/index.d.ts
@@ -2026,7 +2026,10 @@ declare namespace DataTables {
         sVersion: string;
         search: any[];
         selector: object;
-        type: object;
+        /**
+         * Type based plug-ins.
+         */
+        type: ExtTypeSettings;
     }
 
     interface ExtClassesSettings {
@@ -2208,4 +2211,36 @@ declare namespace DataTables {
         sJUIFooter?: string;
     }
     //#endregion "ext internal"
+
+    interface ExtTypeSettings {
+        /**
+         * Type detection functions for plug-in development.
+         *
+         * @see https://datatables.net/manual/plug-ins/type-detection
+         */
+        detect: FunctionExtTypeSettingsDetect[];
+        /**
+         * Type based ordering functions for plug-in development.
+         *
+         * @see https://datatables.net/manual/plug-ins/sorting
+         * @default {}
+         */
+        order: object;
+        /**
+         * Type based search formatting for plug-in development.
+         *
+         * @default {}
+         * @example
+         *   $.fn.dataTable.ext.type.search['title-numeric'] = function ( d ) {
+         *     return d.replace(/\n/g," ").replace( /<.*?>/g, "" );
+         *   }
+         */
+        search: object;
+    }
+
+    /**
+     * @param data Data from the column cell to be analysed.
+     * @param DataTables settings object.
+     */
+    type FunctionExtTypeSettingsDetect = (data: any, settings: Settings) => (string | null);
 }
diff --git a/types/detect-node/detect-node-tests.ts b/types/detect-node/detect-node-tests.ts
new file mode 100644
index 0000000000..01a81a356b
--- /dev/null
+++ b/types/detect-node/detect-node-tests.ts
@@ -0,0 +1,3 @@
+import isNode = require("detect-node");
+
+isNode;
diff --git a/types/detect-node/index.d.ts b/types/detect-node/index.d.ts
new file mode 100644
index 0000000000..38fd280f1e
--- /dev/null
+++ b/types/detect-node/index.d.ts
@@ -0,0 +1,8 @@
+// Type definitions for detect-node 2.0
+// Project: https://github.com/iliakan/detect-node
+// Definitions by: Leonid Logvinov 
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+// TypeScript Version: 2.4
+
+declare const isNode: boolean;
+export = isNode;
diff --git a/types/detect-node/tsconfig.json b/types/detect-node/tsconfig.json
new file mode 100644
index 0000000000..e853bcf92c
--- /dev/null
+++ b/types/detect-node/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", "detect-node-tests.ts"]
+}
diff --git a/types/detect-node/tslint.json b/types/detect-node/tslint.json
new file mode 100644
index 0000000000..3db14f85ea
--- /dev/null
+++ b/types/detect-node/tslint.json
@@ -0,0 +1 @@
+{ "extends": "dtslint/dt.json" }
diff --git a/types/di/di-tests.ts b/types/di/di-tests.ts
new file mode 100644
index 0000000000..4cfd3de5e7
--- /dev/null
+++ b/types/di/di-tests.ts
@@ -0,0 +1,21 @@
+import * as di from "di";
+
+const emptyInjector = new di.Injector();
+const moduleSpecifications = [{}];
+const fullInjector = new di.Injector(moduleSpecifications);
+const childInjector = new di.Injector(moduleSpecifications, emptyInjector);
+
+const dep: {} = fullInjector.get('foo');
+
+const factory = (context: {}, deps: Array<{}>) => {
+	return {};
+};
+
+const invoked: {} = fullInjector.invoke(factory, {});
+
+const oldTimeyClass = {prototype: {}};
+
+const instance: {} = fullInjector.instantiate(oldTimeyClass);
+
+const anotherChildInjector: di.Injector =
+		fullInjector.createChild(moduleSpecifications);
diff --git a/types/di/index.d.ts b/types/di/index.d.ts
new file mode 100644
index 0000000000..ea1d596017
--- /dev/null
+++ b/types/di/index.d.ts
@@ -0,0 +1,15 @@
+// Type definitions for di 0.0
+// Project: https://github.com/vojtajina/node-di
+// Definitions by: John J Barton 
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+// TypeScript Version: 2.8
+
+/// 
+
+export class Injector {
+    get(dep: string): {};
+    invoke(fn: (context: {}, deps: Array<{}>) => {}, context: {}): {};
+    instantiate({prototype: {}}): {};
+    createChild(modules: Array<{}>): Injector;
+    constructor(modules?: Array<{}>, parent?: Injector);
+}
diff --git a/types/di/tsconfig.json b/types/di/tsconfig.json
new file mode 100644
index 0000000000..c7e591ab5a
--- /dev/null
+++ b/types/di/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",
+        "di-tests.ts"
+    ]
+}
diff --git a/types/di/tslint.json b/types/di/tslint.json
new file mode 100644
index 0000000000..3db14f85ea
--- /dev/null
+++ b/types/di/tslint.json
@@ -0,0 +1 @@
+{ "extends": "dtslint/dt.json" }
diff --git a/types/dnssd/dnssd-tests.ts b/types/dnssd/dnssd-tests.ts
index 14b637d384..0fa7498bb2 100644
--- a/types/dnssd/dnssd-tests.ts
+++ b/types/dnssd/dnssd-tests.ts
@@ -1,6 +1,6 @@
 import * as dnssd from 'dnssd';
 
-const serviceType = new dnssd.ServiceType(dnssd.tcp('_mqtt'), dnssd.udp('_mqtt'));
+const serviceType = dnssd.ServiceType.tcp('_mqtt', '_mqtt._udp');
 
 const advertisement = new dnssd.Advertisement(serviceType, 1883, { name: 'broker' });
 const browser: dnssd.Browser = new dnssd.Browser(serviceType);
diff --git a/types/dnssd/index.d.ts b/types/dnssd/index.d.ts
index 9c66a6d6a4..8ef8aa84fd 100644
--- a/types/dnssd/index.d.ts
+++ b/types/dnssd/index.d.ts
@@ -1,30 +1,40 @@
-// Type definitions for dnssd 0.3
+// Type definitions for dnssd 0.4
 // Project: https://github.com/DeMille/dnssd.js#readme
 // Definitions by: Angel Merino 
+//                 Max Rumpf 
 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+// TypeScript Version: 2.2
 
 /// 
 import { EventEmitter } from 'events';
 
 /** Declaration file generated by dts-gen */
 
-export class Advertisement {
-    constructor(type: any, port: any, ...args: any[]);
+export class Advertisement extends EventEmitter {
+    constructor(type: string | string[] | ServiceType, port: number, ...args: any[]);
 
-    start(): any;
+    start(): Advertisement;
 
-    stop(forceImmediate: any, callback: any): void;
+    stop(forceImmediate?: boolean, callback?: () => any): void;
 
     updateTXT(txtObj: any): void;
 }
 
+export class Options {
+    name?: string;
+    host?: string;
+    txt?: any;
+    subtypes?: string[];
+    interface?: string;
+}
+
 /**
  * A service entry as returned by serviceUp
  */
 export class Service {
     fullname: string;         // 'InstanceName._googlecast._tcp.local.'
     name: string;             // 'InstanceName'
-    type: SType;              // { name: 'googlecast'; protocol: 'tcp' }
+    type: ServiceType;        // { name: 'googlecast'; protocol: 'tcp' }
     domain: string;           // 'local'
     host: string;             // 'Hostname.local.'
     port: number;             // 8009
@@ -33,47 +43,47 @@ export class Service {
     txtRaw: any;
 }
 
-export class SType {
+export class ServiceType {
+    constructor(...args: Array)
+    constructor(args: ServiceType);
+
     name: string;
     protocol: string;
+    subtypes: string[];
+
+    toString(): string;
+
+    static all(): ServiceType;
+
+    static tcp(...args: string[]): ServiceType;
+
+    static udp(...args: string[]): ServiceType;
 }
 
 export class Browser extends EventEmitter {
-    constructor(type: any, ...args: any[]);
+    constructor(type: string | string[] | ServiceType, ...args: any[]);
 
-    list(): any;
+    start(): Browser;
 
-    start(): any;
+    stop(): void;
 
-    stop(): any;
+    list(): any[];
 }
 
-export class ServiceType {
-    constructor(...args: any[]);
+export function resolve(name: string, type: string, args: object): Promise;
 
-    toString(): any;
+export function resolve4(name: string, type: string, args: object): Promise;
 
-    static all(): any;
+export function resolve6(name: string, type: string, args: object): Promise;
 
-    static tcp(...args: any[]): any;
+export function resolveSRV(name: string, args: object): Promise;
 
-    static udp(...args: any[]): any;
-}
+export function resolveTXT(name: string, args: object): Promise;
 
-export const resolveA: any;
+export function resolveService(name: string, args: object): Promise;
 
-export const resolveAAAA: any;
+export function tcp(...args: string[]): ServiceType;
 
-export function all(): any;
+export function udp(...args: string[]): ServiceType;
 
-export function resolve(name: any, type: any, ...args: any[]): any;
-
-export function resolveSRV(name: any, opts: any): any;
-
-export function resolveService(name: any, ...args: any[]): any;
-
-export function resolveTXT(name: any, opts: any): any;
-
-export function tcp(...args: any[]): any;
-
-export function udp(...args: any[]): any;
+export function all(): ServiceType;
diff --git a/types/dom4/index.d.ts b/types/dom4/index.d.ts
index 90c9c29966..47a7080a0c 100644
--- a/types/dom4/index.d.ts
+++ b/types/dom4/index.d.ts
@@ -60,11 +60,11 @@ interface Element extends ParentNode {
     matches(selectors: string): boolean;
 }
 
-interface Elements extends ElementTraversal, ParentNode, Array {
+interface Elements extends ParentNode, Array {
 }
 
-interface Document extends ElementTraversal, ParentNode {
+interface Document extends ParentNode {
 }
 
-interface DocumentFragment extends ElementTraversal, ParentNode {
+interface DocumentFragment extends ParentNode {
 }
diff --git a/types/downloadjs/downloadjs-tests.ts b/types/downloadjs/downloadjs-tests.ts
index 00bb5395ef..da110af46d 100644
--- a/types/downloadjs/downloadjs-tests.ts
+++ b/types/downloadjs/downloadjs-tests.ts
@@ -7,6 +7,6 @@ download(new Blob(['hello world']), 'dlTextBlob.txt', 'text/plain');
 
 download('/robots.txt');
 
-download(document.documentElement.outerHTML, 'dlHTML.html', 'text/html');
+download(document.documentElement!.outerHTML, 'dlHTML.html', 'text/html');
 download(new Blob(['hello world'.bold()]), 'dlHtmlBlob.html', 'text/html');
 download('/diff6.png');
diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts
index 4064c9b8a0..06cb8f55f2 100644
--- a/types/draft-js/index.d.ts
+++ b/types/draft-js/index.d.ts
@@ -9,7 +9,7 @@
 //                 Santiago Vilar 
 //                 Ulf Schwekendiek 
 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
-// TypeScript Version: 2.6
+// TypeScript Version: 2.8
 
 import * as React from 'react';
 import * as Immutable from 'immutable';
diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts
index 3583889a74..93babaa0a7 100755
--- a/types/ember/index.d.ts
+++ b/types/ember/index.d.ts
@@ -328,11 +328,11 @@ declare module 'ember' {
              */
             resolveRegistration(fullName: string): Function;
             /**
-             * Registers a factory that can be used for dependency injection (with
+             * Registers a factory or value that can be used for dependency injection (with
              * `inject`) or for service lookup. Each factory is registered with
              * a full name including two parts: `type:name`.
              */
-            register(fullName: string, factory: Function, options?: { singleton?: boolean, instantiate?: boolean }): any;
+            register(fullName: string, factory: any, options?: { singleton?: boolean, instantiate?: boolean }): any;
             /**
              * Unregister a factory.
              */
@@ -3372,7 +3372,48 @@ declare module 'ember' {
     /**
      * The Router service is the public API that provides component/view layer access to the router.
      */
-    class RouterService extends Ember.Service {
+    export class RouterService extends Ember.Service {
+        //
+        /**
+             Name of the current route.
+            This property represent the logical name of the route,
+            which is comma separated.
+            For the following router:
+            ```app/router.js
+            Router.map(function() {
+            this.route('about');
+            this.route('blog', function () {
+                this.route('post', { path: ':post_id' });
+            });
+            });
+            ```
+            It will return:
+            * `index` when you visit `/`
+            * `about` when you visit `/about`
+            * `blog.index` when you visit `/blog`
+            * `blog.post` when you visit `/blog/some-post-id`
+        */
+        readonly currentRouteName: string;
+        //
+        /**
+             Current URL for the application.
+            This property represent the URL path for this route.
+            For the following router:
+            ```app/router.js
+            Router.map(function() {
+            this.route('about');
+            this.route('blog', function () {
+                this.route('post', { path: ':post_id' });
+            });
+            });
+            ```
+            It will return:
+            * `/` when you visit `/`
+            * `/about` when you visit `/about`
+            * `/blog` when you visit `/blog`
+            * `/blog/some-post-id` when you visit `/blog/some-post-id`
+        */
+        readonly currentURL: string;
         //
         /**
          * Determines whether a route is active.
@@ -3776,6 +3817,11 @@ declare module '@ember/routing/router' {
     export default class EmberRouter extends Ember.Router { }
 }
 
+declare module '@ember/routing/router-service' {
+    import { RouterService } from 'ember';
+    export default class extends RouterService { }
+}
+
 declare module '@ember/runloop' {
     import Ember from 'ember';
     export const begin: typeof Ember.run.begin;
diff --git a/types/ember/test/application-instance.ts b/types/ember/test/application-instance.ts
index 9881e4815a..9ae22e5f26 100644
--- a/types/ember/test/application-instance.ts
+++ b/types/ember/test/application-instance.ts
@@ -1,4 +1,5 @@
 import ApplicationInstance from '@ember/application/instance';
+import hbs from 'htmlbars-inline-precompile';
 
 const appInstance = ApplicationInstance.create();
 appInstance.register('some:injection', class Foo {});
@@ -11,6 +12,8 @@ appInstance.register('some:injection', class Foo {}, {
   instantiate: false,
 });
 
+appInstance.register('templates:foo/bar', hbs`

Hello World

`); + appInstance.register('some:injection', class Foo {}, { singleton: false, instantiate: true, diff --git a/types/ember/test/router.ts b/types/ember/test/router.ts index ff5f4c554f..760e9ed5bc 100755 --- a/types/ember/test/router.ts +++ b/types/ember/test/router.ts @@ -1,4 +1,5 @@ import Ember from 'ember'; +import { assertType } from './lib/assert'; const AppRouter = Ember.Router.extend({ }); @@ -25,6 +26,12 @@ AppRouter.map(function() { const RouterServiceConsumer = Ember.Service.extend({ router: Ember.inject.service('router'), + currentRouteName() { + const x: string = Ember.get(this, 'router').currentRouteName; + }, + currentURL() { + const x: string = Ember.get(this, 'router').currentURL; + }, transitionWithoutModel() { Ember.get(this, 'router') .transitionTo('some-route'); diff --git a/types/emoji-mart/index.d.ts b/types/emoji-mart/index.d.ts index 6a8ed65632..22c17731f3 100644 --- a/types/emoji-mart/index.d.ts +++ b/types/emoji-mart/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/missive/emoji-mart // Definitions by: Diogo Franco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 // These definitions should work with 2.3, but the tests doesn't pass on 2.3. diff --git a/types/enzyme-adapter-react-15.4/index.d.ts b/types/enzyme-adapter-react-15.4/index.d.ts index 570cc22e99..2496fb1719 100644 --- a/types/enzyme-adapter-react-15.4/index.d.ts +++ b/types/enzyme-adapter-react-15.4/index.d.ts @@ -2,7 +2,7 @@ // Project: http://airbnb.io/enzyme/ // Definitions by: Nabeelah Ali // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { EnzymeAdapter } from 'enzyme'; diff --git a/types/enzyme-adapter-react-15/index.d.ts b/types/enzyme-adapter-react-15/index.d.ts index 90149cae55..06659d75b9 100644 --- a/types/enzyme-adapter-react-15/index.d.ts +++ b/types/enzyme-adapter-react-15/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/airbnb/enzyme // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { EnzymeAdapter } from 'enzyme'; diff --git a/types/enzyme-adapter-react-16/index.d.ts b/types/enzyme-adapter-react-16/index.d.ts index 53f97ccce6..3e567d956b 100644 --- a/types/enzyme-adapter-react-16/index.d.ts +++ b/types/enzyme-adapter-react-16/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/airbnb/enzyme // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { EnzymeAdapter } from 'enzyme'; diff --git a/types/enzyme-redux/index.d.ts b/types/enzyme-redux/index.d.ts index ad312d6d1f..e231119b89 100644 --- a/types/enzyme-redux/index.d.ts +++ b/types/enzyme-redux/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/Knegusen/enzyme-redux#readme // Definitions by: Dennis Axelsson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { ReactWrapper, ShallowWrapper } from 'enzyme'; import { ReactElement } from 'react'; diff --git a/types/enzyme-to-json/index.d.ts b/types/enzyme-to-json/index.d.ts index d2ba70fc8f..1a8cafb23a 100644 --- a/types/enzyme-to-json/index.d.ts +++ b/types/enzyme-to-json/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/adriantoine/enzyme-to-json#readme // Definitions by: Joscha Feth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { ReactWrapper, ShallowWrapper } from 'enzyme'; diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 7327f69511..a91f60b3c6 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -9,7 +9,7 @@ // Torgeir Hovden // Martin Hochel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// import { ReactElement, Component, AllHTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes } from "react"; diff --git a/types/error-subclass/error-subclass-tests.ts b/types/error-subclass/error-subclass-tests.ts new file mode 100644 index 0000000000..9944bba159 --- /dev/null +++ b/types/error-subclass/error-subclass-tests.ts @@ -0,0 +1,7 @@ +import ErrorSubclass from 'error-subclass'; + +class ExampleError extends ErrorSubclass { + static displayName = 'ExampleError'; +} + +throw new ExampleError('Something went wrong!'); diff --git a/types/error-subclass/index.d.ts b/types/error-subclass/index.d.ts new file mode 100644 index 0000000000..55add2c057 --- /dev/null +++ b/types/error-subclass/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for error-subclass 2.2 +// Project: https://github.com/spudly/error-subclass#readme +// Definitions by: Fitbit +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default class ErrorSubclass extends Error { + static displayName: string; +} diff --git a/types/error-subclass/tsconfig.json b/types/error-subclass/tsconfig.json new file mode 100644 index 0000000000..1574ebeea2 --- /dev/null +++ b/types/error-subclass/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", + "error-subclass-tests.ts" + ] +} diff --git a/types/error-subclass/tslint.json b/types/error-subclass/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/error-subclass/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/espruino/espruino-tests.ts b/types/espruino/espruino-tests.ts index 32f044796d..c1bafc9048 100644 --- a/types/espruino/espruino-tests.ts +++ b/types/espruino/espruino-tests.ts @@ -10,5 +10,8 @@ wifi.startAP('ssid', { password: 'pass', authMode: 'wpa_wpa2' }, err => { console.log("created"); }); +digitalWrite(D2, false); +digitalWrite(D2, true); + I2C1.setup({ scl: D4, sda: D0 }); Serial2.setup(9600, { rx: D16, tx: D17 }); diff --git a/types/espruino/index.d.ts b/types/espruino/index.d.ts index 61cf72f173..cb6151e85a 100644 --- a/types/espruino/index.d.ts +++ b/types/espruino/index.d.ts @@ -3600,7 +3600,7 @@ declare function digitalPulse(pin: Pin, value: boolean, time: any): void; * @param value * @url http://www.espruino.com/Reference#l__global_digitalWrite */ -declare function digitalWrite(pin: Pin, value: number): void; +declare function digitalWrite(pin: Pin, value: number | boolean): void; /** *

Get the digital value of the given pin.

diff --git a/types/eth-lightwallet/eth-lightwallet-tests.ts b/types/eth-lightwallet/eth-lightwallet-tests.ts new file mode 100644 index 0000000000..4907c73cbf --- /dev/null +++ b/types/eth-lightwallet/eth-lightwallet-tests.ts @@ -0,0 +1,3 @@ +import * as lw from "eth-lightwallet"; + +lw.keystore.createVault({}); diff --git a/types/eth-lightwallet/index.d.ts b/types/eth-lightwallet/index.d.ts new file mode 100644 index 0000000000..f55e71884e --- /dev/null +++ b/types/eth-lightwallet/index.d.ts @@ -0,0 +1,64 @@ +// Type definitions for eth-lightwallet 3.0 +// Project: https://github.com/ConsenSys/eth-lightwallet#readme +// Definitions by: Leonid Logvinov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// + +export interface ECSignatureBuffer { + v: number; + r: Buffer; + s: Buffer; +} +export namespace signing { + function signTx( + keystore: keystore, + pwDerivedKey: Uint8Array, + rawTx: string, + signingAddress: string + ): string; + function signMsg( + keystore: keystore, + pwDerivedKey: Uint8Array, + rawMsg: string, + signingAddress: string + ): ECSignatureBuffer; + function signMsgHash( + keystore: keystore, + pwDerivedKey: Uint8Array, + msgHash: string, + signingAddress: string + ): ECSignatureBuffer; + function concatSig(signature: any): string; +} + +export class keystore { + static createVault( + options: any, + callback?: (error: Error, keystore: keystore) => void + ): keystore; + static generateRandomSeed(): string; + static isSeedValid(seed: string): boolean; + static deserialize(keystore: string): keystore; + serialize(): string; + keyFromPassword( + password: string, + callback?: (error: Error, pwDerivedKey: Uint8Array) => void + ): Uint8Array; + isDerivedKeyCorrect(pwDerivedKey: Uint8Array): boolean; + generateNewAddress( + pwDerivedKey: Uint8Array, + numberOfAddresses: number + ): void; + getSeed(pwDerivedKey: Uint8Array): string; + exportPrivateKey(address: string, pwDerivedKey: Uint8Array): string; + getAddresses(): string[]; +} + +export interface VaultOptions { + password: string; + seedPhrase: string; + salt?: string; + hdPathString: string; +} diff --git a/types/eth-lightwallet/tsconfig.json b/types/eth-lightwallet/tsconfig.json new file mode 100644 index 0000000000..80eab8563a --- /dev/null +++ b/types/eth-lightwallet/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", + "eth-lightwallet-tests.ts" + ] +} diff --git a/types/eth-lightwallet/tslint.json b/types/eth-lightwallet/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/eth-lightwallet/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 2ad6a8d1aa..8ad088763d 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -11,7 +11,7 @@ // Tina Roh // Nathan Phillip Brink // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { EventSubscription } from 'fbemitter'; import { Component, ComponentClass, Ref, ComponentType } from 'react'; diff --git a/types/expo/v23/index.d.ts b/types/expo/v23/index.d.ts index 4c33d8b13f..b5c327f6a1 100644 --- a/types/expo/v23/index.d.ts +++ b/types/expo/v23/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/expo/expo-sdk // Definitions by: Konstantin Kai // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { EventSubscription } from 'fbemitter'; import { Component, Ref } from 'react'; diff --git a/types/expo/v24/index.d.ts b/types/expo/v24/index.d.ts index 803ecccf32..35d1e9be92 100644 --- a/types/expo/v24/index.d.ts +++ b/types/expo/v24/index.d.ts @@ -6,7 +6,7 @@ // Sergio Sánchez // Fernando Helwanger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { EventSubscription } from 'fbemitter'; import { Component, ComponentClass, Ref, ComponentType } from 'react'; diff --git a/types/expo/v25/index.d.ts b/types/expo/v25/index.d.ts index 0a7093e2b7..766c055911 100644 --- a/types/expo/v25/index.d.ts +++ b/types/expo/v25/index.d.ts @@ -7,7 +7,7 @@ // Fernando Helwanger // Umidbek Karimov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { EventSubscription } from 'fbemitter'; import { Component, ComponentClass, Ref, ComponentType } from 'react'; diff --git a/types/expo/v26/index.d.ts b/types/expo/v26/index.d.ts index 9b65002305..9804579e66 100644 --- a/types/expo/v26/index.d.ts +++ b/types/expo/v26/index.d.ts @@ -8,7 +8,7 @@ // Umidbek Karimov // Tina Roh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { EventSubscription } from 'fbemitter'; import { Component, ComponentClass, Ref, ComponentType } from 'react'; diff --git a/types/expo__vector-icons/index.d.ts b/types/expo__vector-icons/index.d.ts index 19aadf2a33..529142c0e9 100644 --- a/types/expo__vector-icons/index.d.ts +++ b/types/expo__vector-icons/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/expo/vector-icons // Definitions by: Hyeonsu Lee // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { TextProps } from 'react-native'; diff --git a/types/extsprintf/extsprintf-tests.ts b/types/extsprintf/extsprintf-tests.ts new file mode 100644 index 0000000000..4b45462487 --- /dev/null +++ b/types/extsprintf/extsprintf-tests.ts @@ -0,0 +1,8 @@ +import { sprintf, fprintf, printf } from "extsprintf"; + +fprintf({write: (s: string) => {}}, ''); +fprintf({write: (s: string) => {}}, '', {}, [], null, 0, ''); +printf(''); +printf('', {}, [], null, 0, ''); +sprintf(''); // $ExpectType string +sprintf('', {}, [], null, 0, ''); // $ExpectType string diff --git a/types/extsprintf/index.d.ts b/types/extsprintf/index.d.ts new file mode 100644 index 0000000000..29d073b4c5 --- /dev/null +++ b/types/extsprintf/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for extsprintf 1.4 +// Project: https://github.com/joyent/node-extsprintf#readme +// Definitions by: Alex Hankins +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface Stream { + write(str: string): void; +} + +export function fprintf(stream: Stream, format: string, ...args: any[]): any; +export function printf(format: string, ...args: any[]): any; +export function sprintf(format: string, ...args: any[]): string; diff --git a/types/extsprintf/tsconfig.json b/types/extsprintf/tsconfig.json new file mode 100644 index 0000000000..bc9783f347 --- /dev/null +++ b/types/extsprintf/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", + "extsprintf-tests.ts" + ] +} diff --git a/types/extsprintf/tslint.json b/types/extsprintf/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/extsprintf/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/figlet/figlet-tests.ts b/types/figlet/figlet-tests.ts new file mode 100644 index 0000000000..676fb9003f --- /dev/null +++ b/types/figlet/figlet-tests.ts @@ -0,0 +1,95 @@ +import figlet = require('figlet'); + +figlet('abc', (err, str) => { + // $ExpectType Error | null + err; + // $ExpectType string | undefined + str; +}); +figlet('My World', '1Row', (err, str) => { + // $ExpectType Error | null + err; + // $ExpectType string | undefined + str; +}); +// $ExpectError +figlet('fweGWEPewfe', 'What is the font? I cannot get it'); +// $ExpectError +figlet('qweoqw'); +// $ExpectError +figlet('qweoqw', '1Row'); +// $ExpectError +figlet('qweoqw', '1Row', undefined as any, undefined as any); + +figlet.text('tokiyo tomare', (err, str) => { + // $ExpectType Error | null + err; + // $ExpectType string | undefined + str; +}); +figlet.text('Hi', 'Flower Power', (err, str) => { + // $ExpectType Error | null + err; + // $ExpectType string | undefined + str; +}); +figlet.text('Annyeong', { + font: 'Fun Face', + horizontalLayout: 'full', + verticalLayout: 'fitted', +}, (err, str) => { + // $ExpectType Error | null + err; + // $ExpectType string | undefined + str; +}); +figlet.text('Oreehe', { + font: 'Fun Face', + // $ExpectError + value: 'abc', +}, undefined as any); +// $ExpectError +figlet.text('It cannot make sense'); + +// $ExpectType string +figlet.textSync('test text'); +// $ExpectType string +figlet.textSync('text desu', 'Fuzzy'); +// $ExpectType string +figlet.textSync('oho', { + font: 'Invita', +}); +// $ExpectError +figlet.textSync(); + +figlet.metadata('JS Block Letters', (err, fontOptions, headerComment) => { + // $ExpectType Error | null + err; + // $ExpectType FontOptions | undefined + fontOptions; + // $ExpectType string | undefined + headerComment; +}); +// $ExpectError +figlet.metadata('This is random font name which cannot make sense', undefined as any); +// $ExpectError +figlet.metadata('Alligator', undefined as any, undefined as any); + +// $ExpectType Defaults +figlet.defaults(); +// $ExpectType Defaults +figlet.defaults({}); +// $ExpectType Defaults +figlet.defaults({ + font: 'Patorjk\'s Cheese' +}); + +figlet.fonts((err, fonts) => { + // $ExpectType Error | null + err; + // $ExpectType Fonts[] | undefined + fonts; +}); + +// $ExpectType Fonts[] +figlet.fontsSync(); diff --git a/types/figlet/index.d.ts b/types/figlet/index.d.ts new file mode 100644 index 0000000000..07bb706066 --- /dev/null +++ b/types/figlet/index.d.ts @@ -0,0 +1,406 @@ +// Type definitions for figlet 1.2 +// Project: https://github.com/patorjk/figlet.js +// Definitions by: Junyoung Clare Jang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.1 + +declare namespace figlet { + type Fonts = + | '1Row' + | '3-D' + | '3D Diagonal' + | '3D-ASCII' + | '3x5' + | '4Max' + | '5 Line Oblique' + | 'AMC 3 Line' + | 'AMC 3 Liv1' + | 'AMC AAA01' + | 'AMC Neko' + | 'AMC Razor' + | 'AMC Razor2' + | 'AMC Slash' + | 'AMC Slider' + | 'AMC Thin' + | 'AMC Tubes' + | 'AMC Untitled' + | 'ANSI Shadow' + | 'ASCII New Roman' + | 'Acrobatic' + | 'Alligator' + | 'Alligator2' + | 'Alpha' + | 'Alphabet' + | 'Arrows' + | 'Avatar' + | 'B1FF' + | 'B1FF' + | 'Banner' + | 'Banner3-D' + | 'Banner3' + | 'Banner4' + | 'Barbwire' + | 'Basic' + | 'Bear' + | 'Bell' + | 'Benjamin' + | 'Big Chief' + | 'Big Money-ne' + | 'Big Money-nw' + | 'Big Money-se' + | 'Big Money-sw' + | 'Big' + | 'Bigfig' + | 'Binary' + | 'Block' + | 'Blocks' + | 'Bloody' + | 'Bolger' + | 'Braced' + | 'Bright' + | 'Broadway KB' + | 'Broadway' + | 'Bubble' + | 'Bulbhead' + | 'Caligraphy' + | 'Caligraphy2' + | 'Calvin S' + | 'Cards' + | 'Catwalk' + | 'Chiseled' + | 'Chunky' + | 'Coinstak' + | 'Cola' + | 'Colossal' + | 'Computer' + | 'Contessa' + | 'Contrast' + | 'Cosmike' + | 'Crawford' + | 'Crawford2' + | 'Crazy' + | 'Cricket' + | 'Cursive' + | 'Cyberlarge' + | 'Cybermedium' + | 'Cybersmall' + | 'Cygnet' + | 'DANC4' + | 'DOS Rebel' + | 'DWhistled' + | 'Dancing Font' + | 'Decimal' + | 'Def Leppard' + | 'Delta Corps Priest 1' + | 'Diamond' + | 'Diet Cola' + | 'Digital' + | 'Doh' + | 'Doom' + | 'Dot Matrix' + | 'Double Shorts' + | 'Double' + | 'Dr Pepper' + | 'Efti Chess' + | 'Efti Font' + | 'Efti Italic' + | 'Efti Piti' + | 'Efti Robot' + | 'Efti Wall' + | 'Efti Water' + | 'Electronic' + | 'Elite' + | 'Epic' + | 'Fender' + | 'Filter' + | 'Fire Font-k' + | 'Fire Font-s' + | 'Flipped' + | 'Flower Power' + | 'Four Tops' + | 'Fraktur' + | 'Fun Face' + | 'Fun Faces' + | 'Fuzzy' + | 'Georgi16' + | 'Georgia11' + | 'Ghost' + | 'Ghoulish' + | 'Glenyn' + | 'Goofy' + | 'Gothic' + | 'Graceful' + | 'Gradient' + | 'Graffiti' + | 'Greek' + | 'Heart Left' + | 'Heart Right' + | 'Henry 3D' + | 'Hex' + | 'Hieroglyphs' + | 'Hollywood' + | 'Horizontal Left' + | 'Horizontal Right' + | 'ICL-1900' + | 'Impossible' + | 'Invita' + | 'Isometric1' + | 'Isometric2' + | 'Isometric3' + | 'Isometric4' + | 'Italic' + | 'Ivrit' + | 'JS Block Letters' + | 'JS Bracket Letters' + | 'JS Capital Curves' + | 'JS Cursive' + | 'JS Stick Letters' + | 'Jacky' + | 'Jazmine' + | 'Jerusalem' + | 'Katakana' + | 'Kban' + | 'Keyboard' + | 'Knob' + | 'Konto Slant' + | 'Konto' + | 'LCD' + | 'Larry 3D 2' + | 'Larry 3D' + | 'Lean' + | 'Letters' + | 'Lil Devil' + | 'Line Blocks' + | 'Linux' + | 'Lockergnome' + | 'Madrid' + | 'Marquee' + | 'Maxfour' + | 'Merlin1' + | 'Merlin2' + | 'Mike' + | 'Mini' + | 'Mirror' + | 'Mnemonic' + | 'Modular' + | 'Morse' + | 'Morse2' + | 'Moscow' + | 'Mshebrew210' + | 'Muzzle' + | 'NScript' + | 'NT Greek' + | 'NV Script' + | 'Nancyj-Fancy' + | 'Nancyj-Improved' + | 'Nancyj-Underlined' + | 'Nancyj' + | 'Nipples' + | 'O8' + | 'OS2' + | 'Octal' + | 'Ogre' + | 'Old Banner' + | 'Patorjk\'s Cheese' + | 'Patorjk-HeX' + | 'Pawp' + | 'Peaks Slant' + | 'Peaks' + | 'Pebbles' + | 'Pepper' + | 'Poison' + | 'Puffy' + | 'Puzzle' + | 'Pyramid' + | 'Rammstein' + | 'Rectangles' + | 'Red Phoenix' + | 'Relief' + | 'Relief2' + | 'Reverse' + | 'Roman' + | 'Rot13' + | 'Rot13' + | 'Rotated' + | 'Rounded' + | 'Rowan Cap' + | 'Rozzo' + | 'Runic' + | 'Runyc' + | 'S Blood' + | 'SL Script' + | 'Santa Clara' + | 'Script' + | 'Serifcap' + | 'Shadow' + | 'Shimrod' + | 'Short' + | 'Slant Relief' + | 'Slant' + | 'Slide' + | 'Small Caps' + | 'Small Isometric1' + | 'Small Keyboard' + | 'Small Poison' + | 'Small Script' + | 'Small Shadow' + | 'Small Slant' + | 'Small Tengwar' + | 'Small' + | 'Soft' + | 'Speed' + | 'Spliff' + | 'Stacey' + | 'Stampate' + | 'Stampatello' + | 'Standard' + | 'Star Strips' + | 'Star Wars' + | 'Stellar' + | 'Stforek' + | 'Stick Letters' + | 'Stop' + | 'Straight' + | 'Stronger Than All' + | 'Sub-Zero' + | 'Swamp Land' + | 'Swan' + | 'Sweet' + | 'THIS' + | 'Tanja' + | 'Tengwar' + | 'Term' + | 'Test1' + | 'The Edge' + | 'Thick' + | 'Thin' + | 'Thorned' + | 'Three Point' + | 'Ticks Slant' + | 'Ticks' + | 'Tiles' + | 'Tinker-Toy' + | 'Tombstone' + | 'Train' + | 'Trek' + | 'Tsalagi' + | 'Tubular' + | 'Twisted' + | 'Two Point' + | 'USA Flag' + | 'Univers' + | 'Varsity' + | 'Wavy' + | 'Weird' + | 'Wet Letter' + | 'Whimsy' + | 'Wow' + ; + + type KerningMethods = + | 'default' + | 'full' + | 'fitted' + | 'controlled smushing' + | 'universal smushing' + ; + type PrintDirection = number; + + interface FittingRules { + vLayout: number; + vRule5: boolean; + vRule4: boolean; + vRule3: boolean; + vRule2: boolean; + vRule1: boolean; + hLayout: number; + hRule6: boolean; + hRule5: boolean; + hRule4: boolean; + hRule3: boolean; + hRule2: boolean; + hRule1: boolean; + } + + interface Options { + font?: Fonts; + horizontalLayout?: KerningMethods; + verticalLayout?: KerningMethods; + printDirection?: PrintDirection; + showHardBlanks?: boolean; + } + interface FontOptions { + hardBlank: string; + height: number; + baseline: number; + maxLength: number; + oldLayout: number; + numCommentLines: number; + printDirection: PrintDirection; + fullLayout: number | null; + codeTagCount: number | null; + fittingRules: FittingRules; + } + interface Defaults { + font: Fonts; + fontPath: string; + } + + function text(txt: string, cb: (error: Error | null, result?: string) => void): void; + function text(txt: string, font: Fonts, cb: (error: Error | null, result?: string) => void): void; + /** + * @desc + * This `unified-signatures` is disabled because `Fonts` type is too long + */ + // tslint:disable-next-line: unified-signatures + function text(txt: string, options: Options | undefined, cb: (error: Error | null, result?: string) => void): void; + + function textSync(txt: string, font?: Fonts): string; + /** + * @desc + * This `unified-signatures` is disabled because `Fonts` type is too long + */ + // tslint:disable-next-line: unified-signatures + function textSync(txt: string, options: Options): string; + + function metadata(font: Fonts, cb: (error: Error | null, fontOptions?: FontOptions, headerComment?: string) => void): void; + + function defaults(opt?: Partial): Defaults; + + function loadFont(font: Fonts, cb: (error: Error | null, fontOptions?: FontOptions) => void): void; + /** + * @todo + * Use 'node' namespace to add following methods only in node environment. + */ + /** + * @warn + * This method works in node environment only. + * In browser environment, this method does not work. + */ + function loadFontSync(font: Fonts): FontOptions; + /** + * @warn + * This method exists in node environment only. + * In browser environment, this method does not exist. + */ + function fonts(cb: (error: Error | null, fontList?: Fonts[]) => void): void; + /** + * @warn + * This method exists in node environment only. + * In browser environment, this method does not exist. + */ + function fontsSync(): Fonts[]; +} + +declare function figlet(txt: string, cb: (error: Error | null, result?: string) => void): void; +declare function figlet(txt: string, font: figlet.Fonts, cb: (error: Error | null, result?: string) => void): void; +/** + * @desc + * This `unified-signatures` is disabled because `Fonts` type is too long + */ +// tslint:disable-next-line: unified-signatures +declare function figlet(txt: string, options: figlet.Options | undefined, cb: (error: Error | null, result?: string) => void): void; + +export as namespace figlet; +export = figlet; diff --git a/types/figlet/tsconfig.json b/types/figlet/tsconfig.json new file mode 100644 index 0000000000..946bec6c7d --- /dev/null +++ b/types/figlet/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", + "figlet-tests.ts" + ] +} diff --git a/types/figlet/tslint.json b/types/figlet/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/figlet/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/find/find-tests.ts b/types/find/find-tests.ts index c6c1cd04f5..3ca401f69a 100644 --- a/types/find/find-tests.ts +++ b/types/find/find-tests.ts @@ -16,9 +16,9 @@ find.file(regexPattern, rootDir, (dirs: string[]): void => { }).error(errorCb); find.fileSync(rootDir); // $ExpectType string[] find.fileSync(stringPattern, rootDir); // $ExpectType string[] find.fileSync(regexPattern, rootDir); // $ExpectType string[] -find.eachFile(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachFile(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachFile(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachfile(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachfile(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachfile(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream find.dir(stringPattern, rootDir, (dirs: string[]): void => { }).error(emptyCb); // $ExpectType void find.dir(stringPattern, rootDir, (dirs: string[]): void => { }).error(errorCb); // $ExpectType void @@ -27,6 +27,6 @@ find.dir(rootDir, (dirs: string[]): void => { }).error(errorCb); // $ExpectType find.dirSync(rootDir); // $ExpectType string[] find.dirSync(stringPattern, rootDir); // $ExpectType string[] find.dirSync(regexPattern, rootDir); // $ExpectType string[] -find.eachDir(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachDir(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream -find.eachDir(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachdir(rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachdir(stringPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream +find.eachdir(regexPattern, rootDir, singleStringCb).end(emptyCb).error(errorCb).end(emptyCb); // $ExpectType FindEachStream diff --git a/types/find/index.d.ts b/types/find/index.d.ts index 61166669db..1ffb2f8aee 100644 --- a/types/find/index.d.ts +++ b/types/find/index.d.ts @@ -45,7 +45,7 @@ export function file(pattern: string | RegExp, root: string, callback: (files: s * @param root The root directory * @param callback A callback that accepts each file separately */ -export function eachFile(root: string, callback: (file: string) => void): FindEachStream; +export function eachfile(root: string, callback: (file: string) => void): FindEachStream; /** * Find all files that match a glob pattern in a given directory asynchronously. @@ -53,7 +53,7 @@ export function eachFile(root: string, callback: (file: string) => void): FindEa * @param root The root directory * @param callback A callback that accepts an array of the found files */ -export function eachFile(pattern: string | RegExp, root: string, callback: (file: string) => void): FindEachStream; +export function eachfile(pattern: string | RegExp, root: string, callback: (file: string) => void): FindEachStream; /** * Find all files in a given directory synchronously. @@ -105,7 +105,7 @@ export function dirSync(pattern: string | RegExp, root: string): string[]; * @param root The root directory * @param callback A callback that accepts each of the found directories separately */ -export function eachDir(root: string, callback: (directory: string) => void): FindEachStream; +export function eachdir(root: string, callback: (directory: string) => void): FindEachStream; /** * Find all directories that match a glob pattern in a given directory asynchronously. @@ -113,4 +113,4 @@ export function eachDir(root: string, callback: (directory: string) => void): Fi * @param root The root directory * @param callback A callback that accepts each of the found directories separately */ -export function eachDir(pattern: string | RegExp, root: string, callback: (directory: string) => void): FindEachStream; +export function eachdir(pattern: string | RegExp, root: string, callback: (directory: string) => void): FindEachStream; diff --git a/types/fixed-data-table-2/index.d.ts b/types/fixed-data-table-2/index.d.ts index 0b844ec194..16b0c0f3c5 100644 --- a/types/fixed-data-table-2/index.d.ts +++ b/types/fixed-data-table-2/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/schrodinger/fixed-data-table-2 // Definitions by: Ilya Petukhov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/fixed-data-table/index.d.ts b/types/fixed-data-table/index.d.ts index c8ee33a2a1..4c0b7f176f 100644 --- a/types/fixed-data-table/index.d.ts +++ b/types/fixed-data-table/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/facebook/fixed-data-table // Definitions by: Petar Paar , Stephen Jelfs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/flux/index.d.ts b/types/flux/index.d.ts index ffc0330228..cafb6a5a0b 100644 --- a/types/flux/index.d.ts +++ b/types/flux/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Steve Baker // Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import Dispatcher = require("./lib/Dispatcher"); diff --git a/types/fluxible-router/index.d.ts b/types/fluxible-router/index.d.ts index 2dea024107..097c2b3c2d 100644 --- a/types/fluxible-router/index.d.ts +++ b/types/fluxible-router/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/yahoo/fluxible#readme // Definitions by: xbim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// import * as React from 'react'; import { FluxibleContext } from 'fluxible'; diff --git a/types/fluxxor/index.d.ts b/types/fluxxor/index.d.ts index 3457dba949..191332fa7a 100644 --- a/types/fluxxor/index.d.ts +++ b/types/fluxxor/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/BinaryMuse/fluxxor // Definitions by: Yuichi Murata // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as EventEmitter3 from 'eventemitter3'; import * as React from "react"; diff --git a/types/fork-ts-checker-webpack-plugin/fork-ts-checker-webpack-plugin-tests.ts b/types/fork-ts-checker-webpack-plugin/fork-ts-checker-webpack-plugin-tests.ts index 78ead793b4..7f28a37597 100644 --- a/types/fork-ts-checker-webpack-plugin/fork-ts-checker-webpack-plugin-tests.ts +++ b/types/fork-ts-checker-webpack-plugin/fork-ts-checker-webpack-plugin-tests.ts @@ -21,4 +21,16 @@ config = { ] }; +config = { + plugins: [ + new ForkTsCheckerWebpackPlugin({ + logger: { + error: message => console.error(message), + warn: message => console.warn(message), + info: message => console.info(message), + } + }) + ] +}; + export default config; diff --git a/types/fork-ts-checker-webpack-plugin/index.d.ts b/types/fork-ts-checker-webpack-plugin/index.d.ts index ace3db5b24..715b1fe41b 100644 --- a/types/fork-ts-checker-webpack-plugin/index.d.ts +++ b/types/fork-ts-checker-webpack-plugin/index.d.ts @@ -73,6 +73,12 @@ declare namespace ForkTsCheckerWebpackPlugin { type Formatter = (message: NormalizedMessage, useColors: boolean) => string; + interface Logger { + error(message?: any): void; + warn(message?: any): void; + info(message?: any): void; + } + interface Options { tsconfig?: string; tslint?: string | true; @@ -81,7 +87,7 @@ declare namespace ForkTsCheckerWebpackPlugin { ignoreDiagnostics?: number[]; ignoreLints?: string[]; colors?: boolean; - logger?: Console; + logger?: Logger; formatter?: 'default' | 'codeframe' | Formatter; formatterOptions?: { highlightCode?: boolean diff --git a/types/fork-ts-checker-webpack-plugin/package.json b/types/fork-ts-checker-webpack-plugin/package.json index bc1b130102..2371372125 100644 --- a/types/fork-ts-checker-webpack-plugin/package.json +++ b/types/fork-ts-checker-webpack-plugin/package.json @@ -1,6 +1,7 @@ { "private": true, "dependencies": { - "tslint": "*" + "tslint": "*", + "typescript": "*" } } diff --git a/types/generic-pool/generic-pool-tests.ts b/types/generic-pool/generic-pool-tests.ts index 6cf0292709..09a1e611ea 100644 --- a/types/generic-pool/generic-pool-tests.ts +++ b/types/generic-pool/generic-pool-tests.ts @@ -41,6 +41,8 @@ const opts = { const pool = genericPool.createPool(factory, opts); +pool.start(); + pool.use((conn: Connection) => 'test') .then((result: string) => { }); diff --git a/types/generic-pool/index.d.ts b/types/generic-pool/index.d.ts index 8cae9ce37c..e50682ab12 100644 --- a/types/generic-pool/index.d.ts +++ b/types/generic-pool/index.d.ts @@ -17,6 +17,7 @@ export class Pool extends EventEmitter { max: number; min: number; + start(): void; acquire(priority?: number): PromiseLike; release(resource: T): void; destroy(resource: T): void; diff --git a/types/gestalt/index.d.ts b/types/gestalt/index.d.ts index d3ceb5672e..162d61dd52 100644 --- a/types/gestalt/index.d.ts +++ b/types/gestalt/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/pinterest/gestalt // Definitions by: Nicolás Serrano Arévalo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/gl-matrix/gl-matrix-tests.ts b/types/gl-matrix/gl-matrix-tests.ts index c929323764..cf9c4ef616 100644 --- a/types/gl-matrix/gl-matrix-tests.ts +++ b/types/gl-matrix/gl-matrix-tests.ts @@ -79,6 +79,7 @@ outVec2 = vec2.transformMat2d(outVec2, vec2A, mat2dA); outVec2 = vec2.transformMat3(outVec2, vec2A, mat3A); outVec2 = vec2.transformMat4(outVec2, vec2A, mat4A); vecArray = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); +outVal = vec2.angle(vec2A, vec2B); outStr = vec2.str(vec2A); outBool = vec2.exactEquals(vec2A, vec2B); outBool = vec2.equals(vec2A, vec2B); diff --git a/types/gl-matrix/index.d.ts b/types/gl-matrix/index.d.ts index cad714796d..2c86b6a057 100644 --- a/types/gl-matrix/index.d.ts +++ b/types/gl-matrix/index.d.ts @@ -431,6 +431,14 @@ declare module 'gl-matrix' { public static forEach(a: Float32Array, stride: number, offset: number, count: number, fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; + /** + * Get the angle between two 2D vectors + * @param a The first operand + * @param b The second operand + * @returns The angle in radians + */ + public static angle(a: vec2 | number[], b: vec2 | number[]): number; + /** * Perform some operation over an array of vec2s. * diff --git a/types/gl-texture2d/index.d.ts b/types/gl-texture2d/index.d.ts index 4d979d99f9..59f92b8555 100644 --- a/types/gl-texture2d/index.d.ts +++ b/types/gl-texture2d/index.d.ts @@ -6,6 +6,8 @@ import ndarray = require("ndarray"); +type GLenum = number; + type InputType = ImageData | HTMLCanvasElement | HTMLImageElement | HTMLVideoElement; interface RawObject { diff --git a/types/google-cloud__datastore/google-cloud__datastore-tests.ts b/types/google-cloud__datastore/google-cloud__datastore-tests.ts index cb723d0d5b..df48a70f59 100644 --- a/types/google-cloud__datastore/google-cloud__datastore-tests.ts +++ b/types/google-cloud__datastore/google-cloud__datastore-tests.ts @@ -72,7 +72,7 @@ const complexQuery = ds.createQuery('special_namespace', kind) .offset(10); // Running queries: -const queryCallback: QueryCallback = (err: Error, entities: TestEntity[]) => entities[0][Datastore.KEY]; +const queryCallback: QueryCallback = (err: Error, entities: TestEntity[]) => entities[0][ds.KEY]; ds.runQuery(query, queryCallback); ds.runQuery(query, options, queryCallback); diff --git a/types/google-cloud__datastore/index.d.ts b/types/google-cloud__datastore/index.d.ts index e0ef60b4bb..c6b7ed3462 100644 --- a/types/google-cloud__datastore/index.d.ts +++ b/types/google-cloud__datastore/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/googleapis/nodejs-datastore // Definitions by: Antoine Beauvais-Lacasse // Futa Ogawa +// Thomas den Hollander // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.7 @@ -35,6 +36,15 @@ declare module '@google-cloud/datastore' { import { DatastoreTransaction } from '@google-cloud/datastore/transaction'; class Datastore extends DatastoreRequest_ { + static readonly KEY: unique symbol; + static readonly MORE_RESULTS_AFTER_CURSOR: MoreResultsAfterCursor; + static readonly MORE_RESULTS_AFTER_LIMIT: MoreResultsAfterLimit; + static readonly NO_MORE_RESULTS: NoMoreResults; + + static readonly Query: typeof DatastoreQuery; + static readonly DatastoreRequest: typeof DatastoreRequest_; + static readonly Transaction: typeof DatastoreTransaction; + constructor(options?: InitOptions); readonly KEY: typeof Datastore.KEY; @@ -80,17 +90,6 @@ declare module '@google-cloud/datastore' { keyFilename?: string; credentials?: object; } - - namespace Datastore { - const KEY: unique symbol; - const MORE_RESULTS_AFTER_CURSOR: MoreResultsAfterCursor; - const MORE_RESULTS_AFTER_LIMIT: MoreResultsAfterLimit; - const NO_MORE_RESULTS: NoMoreResults; - - const Query: typeof DatastoreQuery; - const DatastoreRequest: typeof DatastoreRequest_; - const Transaction: typeof DatastoreTransaction; - } } declare module '@google-cloud/datastore/entity' { diff --git a/types/google-cloud__pubsub/index.d.ts b/types/google-cloud__pubsub/index.d.ts index 130e62a5e4..9375b55860 100644 --- a/types/google-cloud__pubsub/index.d.ts +++ b/types/google-cloud__pubsub/index.d.ts @@ -1,7 +1,8 @@ // Type definitions for @google-cloud/pubsub 0.18 -// Project: https://github.com/GoogleCloudPlatform/google-cloud-node/tree/master/packages/pubsub +// Project: https://github.com/googleapis/nodejs-pubsub // Definitions by: Paul Huynh // LunaPg +// Marco Siviero // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -115,11 +116,15 @@ declare namespace PubSub { interface Publisher { publish(data: Buffer, callback: Publisher.PublishCallback): void; - publish(data: Buffer, attributes: object, callback: Publisher.PublishCallback): void; - publish(data: Buffer, attributes?: object): Promise; + publish(data: Buffer, attributes: Publisher.Attributes, callback: Publisher.PublishCallback): void; + publish(data: Buffer, attributes?: Publisher.Attributes): Promise; } namespace Publisher { type PublishCallback = (error: Error | null, messageId: string) => void; + + interface Attributes { + [key: string]: string | Buffer | ArrayBuffer; + } } interface Snapshot { diff --git a/types/google-map-react/index.d.ts b/types/google-map-react/index.d.ts index ca5348323a..ffd8cb90c2 100644 --- a/types/google-map-react/index.d.ts +++ b/types/google-map-react/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/istarkov/google-map-react // Definitions by: Honza Brecka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/google.picker/index.d.ts b/types/google.picker/index.d.ts index b5fc91404d..9a0c95f920 100644 --- a/types/google.picker/index.d.ts +++ b/types/google.picker/index.d.ts @@ -83,7 +83,7 @@ declare namespace google { */ export interface Picker { isVisible(): boolean; - setCallback():Picker; + setCallback(method:Function):Picker; setRelayUrl(url:string):Picker; setVisible(visible:boolean):Picker; } diff --git a/types/gradient-string/gradient-string-tests.ts b/types/gradient-string/gradient-string-tests.ts new file mode 100644 index 0000000000..7216a0862f --- /dev/null +++ b/types/gradient-string/gradient-string-tests.ts @@ -0,0 +1,42 @@ +import tinycolor = require('tinycolor2'); +import gradient = require('gradient-string'); + +// $ExpectType string +gradient('cyan', 'pink')('Hello world!'); + +// $ExpectType Gradient +gradient('red', 'green', 'blue'); +// $ExpectType Gradient +gradient(['#FF0000', '#00FF00', '#0000FF']); + +// $ExpectType Gradient +gradient([ + tinycolor('#FFBB65'), // tinycolor object + {r: 0, g: 255, b: 0}, // RGB object + {h: 240, s: 1, v: 1, a: 1}, // HSVa object + 'rgb(120, 120, 0)', // RGB CSS string + 'gold' // named color +]); + +// $ExpectType string +gradient.rainbow('I love gradient-strings!'); + +// $ExpectType string +gradient('orange', 'yellow').multiline([ + " __", + "<(o )___", + " ( ._> /", + " `---'", +].join('\n')); + +// $ExpectType string +gradient.atlas.multiline('Multi line\nstring'); +// $ExpectType string +gradient('cyan', 'pink').multiline('Multi line\nstring', {interpolation: 'hsv'}); + +// $ExpectType Gradient +gradient([ + {color: '#d8e0de', pos: 0}, + {color: '#255B53', pos: 0.8}, + {color: '#000000', pos: 1}, +]); diff --git a/types/gradient-string/index.d.ts b/types/gradient-string/index.d.ts new file mode 100644 index 0000000000..0191700b19 --- /dev/null +++ b/types/gradient-string/index.d.ts @@ -0,0 +1,43 @@ +// Type definitions for gradient-string 1.1 +// Project: https://github.com/bokub/gradient-string +// Definitions by: Junyoung Clare Jang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import tinycolor = require('tinycolor2'); + +declare namespace gradient { + interface PositionedColorInput { + color: tinycolor.ColorInput; + pos: number; + } + + interface Gradient { + (message?: string, opt?: Options): string; + multiline(message?: string, opt?: Options): string; + } + + interface Options { + interpolation?: string; + hsvSpin?: string; + } + + const atlas: Gradient; + const cristal: Gradient; + const teen: Gradient; + const mind: Gradient; + const morning: Gradient; + const vice: Gradient; + const passion: Gradient; + const fruit: Gradient; + const instagram: Gradient; + const retro: Gradient; + const summer: Gradient; + const rainbow: Gradient; + const pastel: Gradient; +} + +declare function gradient(colors: tinycolor.ColorInput[] | gradient.PositionedColorInput[]): gradient.Gradient; +declare function gradient(...colors: tinycolor.ColorInput[]): gradient.Gradient; +declare function gradient(...colors: gradient.PositionedColorInput[]): gradient.Gradient; +export = gradient; diff --git a/types/gradient-string/tsconfig.json b/types/gradient-string/tsconfig.json new file mode 100644 index 0000000000..d0e3833686 --- /dev/null +++ b/types/gradient-string/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", + "gradient-string-tests.ts" + ] +} diff --git a/types/gradient-string/tslint.json b/types/gradient-string/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/gradient-string/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/graphql/graphql-tests.ts b/types/graphql/graphql-tests.ts index 7c0210249b..e75fecb329 100644 --- a/types/graphql/graphql-tests.ts +++ b/types/graphql/graphql-tests.ts @@ -1,4 +1,4 @@ -import * as graphql from 'graphql'; +import { assertInputType, isInputType, isOutputType } from 'graphql'; /////////////////////////// // graphql // @@ -50,7 +50,10 @@ function language_visitor_tests() { // graphql/type // /////////////////////////// function type_definition_tests() { - // TODO + isInputType(null); + isOutputType(null); + + assertInputType(null); } function type_directives_tests() { diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index b078acccb1..ced45be4a2 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -36,37 +36,37 @@ export function isType(type: any): type is GraphQLType; export function assertType(type: any): GraphQLType; -export function isScalarType(type: GraphQLType): type is GraphQLScalarType; +export function isScalarType(type: any): type is GraphQLScalarType; -export function assertScalarType(type: GraphQLType): GraphQLScalarType; +export function assertScalarType(type: any): GraphQLScalarType; -export function isObjectType(type: GraphQLType): type is GraphQLObjectType; +export function isObjectType(type: any): type is GraphQLObjectType; -export function assertObjectType(type: GraphQLType): GraphQLObjectType; +export function assertObjectType(type: any): GraphQLObjectType; -export function isInterfaceType(type: GraphQLType): type is GraphQLInterfaceType; +export function isInterfaceType(type: any): type is GraphQLInterfaceType; -export function assertInterfaceType(type: GraphQLType): GraphQLInterfaceType; +export function assertInterfaceType(type: any): GraphQLInterfaceType; -export function isUnionType(type: GraphQLType): type is GraphQLUnionType; +export function isUnionType(type: any): type is GraphQLUnionType; -export function assertUnionType(type: GraphQLType): GraphQLUnionType; +export function assertUnionType(type: any): GraphQLUnionType; -export function isEnumType(type: GraphQLType): type is GraphQLEnumType; +export function isEnumType(type: any): type is GraphQLEnumType; -export function assertEnumType(type: GraphQLType): GraphQLEnumType; +export function assertEnumType(type: any): GraphQLEnumType; -export function isInputObjectType(type: GraphQLType): type is GraphQLInputObjectType; +export function isInputObjectType(type: any): type is GraphQLInputObjectType; -export function assertInputObjectType(type: GraphQLType): GraphQLInputObjectType; +export function assertInputObjectType(type: any): GraphQLInputObjectType; -export function isListType(type: GraphQLType): type is GraphQLList; +export function isListType(type: any): type is GraphQLList; -export function assertListType(type: GraphQLType): GraphQLList; +export function assertListType(type: any): GraphQLList; -export function isNonNullType(type: GraphQLType): type is GraphQLNonNull; +export function isNonNullType(type: any): type is GraphQLNonNull; -export function assertNonNullType(type: GraphQLType): GraphQLNonNull; +export function assertNonNullType(type: any): GraphQLNonNull; /** * These types may be used as input types for arguments and directives. @@ -78,9 +78,9 @@ export type GraphQLInputType = | GraphQLList | GraphQLNonNull>; -export function isInputType(type: GraphQLType): type is GraphQLInputType; +export function isInputType(type: any): type is GraphQLInputType; -export function assertInputType(type: GraphQLType): GraphQLInputType; +export function assertInputType(type: any): GraphQLInputType; /** * These types may be used as output types as the result of fields. @@ -101,36 +101,36 @@ export type GraphQLOutputType = | GraphQLList >; -export function isOutputType(type: GraphQLType): type is GraphQLOutputType; +export function isOutputType(type: any): type is GraphQLOutputType; -export function assertOutputType(type: GraphQLType): GraphQLOutputType; +export function assertOutputType(type: any): GraphQLOutputType; /** * These types may describe types which may be leaf values. */ export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumType; -export function isLeafType(type: GraphQLType): type is GraphQLLeafType; +export function isLeafType(type: any): type is GraphQLLeafType; -export function assertLeafType(type: GraphQLType): GraphQLLeafType; +export function assertLeafType(type: any): GraphQLLeafType; /** * These types may describe the parent context of a selection set. */ export type GraphQLCompositeType = GraphQLObjectType | GraphQLInterfaceType | GraphQLUnionType; -export function isCompositeType(type: GraphQLType): type is GraphQLCompositeType; +export function isCompositeType(type: any): type is GraphQLCompositeType; -export function assertCompositeType(type: GraphQLType): GraphQLCompositeType; +export function assertCompositeType(type: any): GraphQLCompositeType; /** * These types may describe the parent context of a selection set. */ export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionType; -export function isAbstractType(type: GraphQLType): type is GraphQLAbstractType; +export function isAbstractType(type: any): type is GraphQLAbstractType; -export function assertAbstractType(type: GraphQLType): GraphQLAbstractType; +export function assertAbstractType(type: any): GraphQLAbstractType; /** * List Modifier @@ -188,9 +188,9 @@ export class GraphQLNonNull { export type GraphQLWrappingType = GraphQLList | GraphQLNonNull; -export function isWrappingType(type: GraphQLType): type is GraphQLWrappingType; +export function isWrappingType(type: any): type is GraphQLWrappingType; -export function assertWrappingType(type: GraphQLType): GraphQLWrappingType; +export function assertWrappingType(type: any): GraphQLWrappingType; /** * These types can all accept null as a value. @@ -204,9 +204,9 @@ export type GraphQLNullableType = | GraphQLInputObjectType | GraphQLList; -export function isNullableType(type: GraphQLType): type is GraphQLNullableType; +export function isNullableType(type: any): type is GraphQLNullableType; -export function assertNullableType(type: GraphQLType): GraphQLNullableType; +export function assertNullableType(type: any): GraphQLNullableType; export function getNullableType(type: void): undefined; export function getNullableType(type: T): T; @@ -223,9 +223,9 @@ export type GraphQLNamedType = | GraphQLEnumType | GraphQLInputObjectType; -export function isNamedType(type: GraphQLType): type is GraphQLNamedType; +export function isNamedType(type: any): type is GraphQLNamedType; -export function assertNamedType(type: GraphQLType): GraphQLNamedType; +export function assertNamedType(type: any): GraphQLNamedType; export function getNamedType(type: void): undefined; export function getNamedType(type: GraphQLType): GraphQLNamedType; diff --git a/types/grid-styled/index.d.ts b/types/grid-styled/index.d.ts index 81c11df405..2a245f2260 100644 --- a/types/grid-styled/index.d.ts +++ b/types/grid-styled/index.d.ts @@ -4,7 +4,7 @@ // Victor Orlov // Louis Hache // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 export type Omit = Pick; diff --git a/types/gulp-imagemin/gulp-imagemin-tests.ts b/types/gulp-imagemin/gulp-imagemin-tests.ts new file mode 100644 index 0000000000..7fc1d86311 --- /dev/null +++ b/types/gulp-imagemin/gulp-imagemin-tests.ts @@ -0,0 +1,20 @@ +import * as GulpImagemin from 'gulp-imagemin'; + +GulpImagemin(); + +GulpImagemin([ + GulpImagemin.gifsicle({ interlaced: true }), + GulpImagemin.jpegtran({ progressive: true }), + GulpImagemin.optipng({ optimizationLevel: 5 }), + GulpImagemin.svgo({ + plugins: [{ removeViewBox: true }, { cleanupIDs: false }] + }) +]); + +GulpImagemin({ verbose: true }); + +GulpImagemin([ + GulpImagemin.svgo({ + plugins: [{ removeViewBox: true }] + }) +], { verbose: true }); diff --git a/types/gulp-imagemin/index.d.ts b/types/gulp-imagemin/index.d.ts new file mode 100644 index 0000000000..42c1ef8d5c --- /dev/null +++ b/types/gulp-imagemin/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for gulp-imagemin 4.1 +// Project: https://github.com/sindresorhus/gulp-imagemin#readme +// Definitions by: Romain Faust +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Transform } from 'stream'; + +declare function imagemin(pluginsOrOptions?: imagemin.Plugin[] | imagemin.Options): Transform; +declare function imagemin(plugins?: imagemin.Plugin[], options?: imagemin.Options): Transform; + +declare namespace imagemin { + interface Options { + verbose?: boolean; + } + + type Plugin = (input: any) => Promise; + type PluginFactory = (options?: any) => Plugin; + + const gifsicle: PluginFactory; + const jpegtran: PluginFactory; + const optipng: PluginFactory; + const svgo: PluginFactory; +} + +export = imagemin; diff --git a/types/gulp-imagemin/tsconfig.json b/types/gulp-imagemin/tsconfig.json new file mode 100644 index 0000000000..1b35a74382 --- /dev/null +++ b/types/gulp-imagemin/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", + "gulp-imagemin-tests.ts" + ] +} diff --git a/types/gulp-imagemin/tslint.json b/types/gulp-imagemin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gulp-imagemin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gulp-template/gulp-template-tests.ts b/types/gulp-template/gulp-template-tests.ts new file mode 100644 index 0000000000..9e5011074c --- /dev/null +++ b/types/gulp-template/gulp-template-tests.ts @@ -0,0 +1,20 @@ +import gulp = require('gulp'); +import gulpTemplate = require('gulp-template'); + +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate({ a: 'A' }, { sourceURL: 'https://www.example.com' }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate({ b: 'B' }, { escape: /x/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate({ c: 'C' }, { evaluate: /y/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate({ d: 'D' }, { imports: /z/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate({ e: 'E' }, { interpolate: /w/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate({ f: 'F' }, { variable: 'some-var' }))); + +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate({ g: 'G' }, { badOption: 'some-var' }))); // $ExpectError + +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate.precompile({ sourceURL: 'https://www.example.com' }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate.precompile({ escape: /x/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate.precompile({ evaluate: /y/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate.precompile({ imports: /z/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate.precompile({ interpolate: /w/ }))); +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate.precompile({ variable: 'some-var' }))); + +gulp.task('replace', () => gulp.src('files').pipe(gulpTemplate.precompile({ badOption: 'some-var' }))); // $ExpectError diff --git a/types/gulp-template/index.d.ts b/types/gulp-template/index.d.ts new file mode 100644 index 0000000000..a2270eb387 --- /dev/null +++ b/types/gulp-template/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for gulp-template 5.0 +// Project: https://github.com/sindresorhus/gulp-template#readme +// Definitions by: Peter Safranek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +/// + +import * as _ from 'lodash'; +import * as stream from 'stream'; + +declare function gulpTemplate(data: any, options: _.TemplateOptions): stream.Transform; + +declare namespace gulpTemplate { + function precompile(options: _.TemplateOptions): stream.Transform; +} + +export = gulpTemplate; diff --git a/types/gulp-template/tsconfig.json b/types/gulp-template/tsconfig.json new file mode 100644 index 0000000000..0666e34adc --- /dev/null +++ b/types/gulp-template/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", + "gulp-template-tests.ts" + ] +} diff --git a/types/gulp-template/tslint.json b/types/gulp-template/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gulp-template/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/halogen/index.d.ts b/types/halogen/index.d.ts index de09f29f43..ab0d4f31f4 100644 --- a/types/halogen/index.d.ts +++ b/types/halogen/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/yuanyan/halogen // Definitions by: Vincent Rouffiat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as react from "react"; diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 5815f7218b..23aaf3608c 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -451,7 +451,7 @@ export interface Request extends Podium { * 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; + readonly pre: Util.Dictionary; /** * Access: read / write (see limitations below). @@ -463,7 +463,7 @@ export interface Request extends Podium { /** * Same as pre but represented as the response object created by the pre method. */ - readonly preResponses: Util.Dictionary; + 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 diff --git a/types/hedron/index.d.ts b/types/hedron/index.d.ts index 6eb34e3638..1e19aaee7a 100644 --- a/types/hedron/index.d.ts +++ b/types/hedron/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/JSBros/hedron // Definitions by: Dmytro Borysov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 07a06256e5..f24004fadb 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -3130,7 +3130,7 @@ declare namespace Highcharts { * chart's two series to be updated with respective options. * @since 5.0.0 */ - chartOptions?: ChartOptions; + chartOptions?: Options; /** * Under which conditions the rule applies. diff --git a/types/highcharts/test/index.ts b/types/highcharts/test/index.ts index d6eeaf8c52..1d6e921461 100644 --- a/types/highcharts/test/index.ts +++ b/types/highcharts/test/index.ts @@ -2591,8 +2591,10 @@ function test_ResponsiveOptions() { const responsiveOptions: Highcharts.ResponsiveOptions = { rules: [ { - chartOptions: { - description: 'just a test' + chartOptions: { + chart: { + description: 'just a test' + } }, condition: { callback: () => { }, diff --git a/types/history/index.d.ts b/types/history/index.d.ts index eb15aaa0fc..1c7b35b8f2 100644 --- a/types/history/index.d.ts +++ b/types/history/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for history 4.6.2 +// Type definitions for history 4.7.2 // Project: https://github.com/mjackson/history // Definitions by: Sergey Buturlakin , Nathan Brown , Young Rok Kim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export as namespace History; export type Action = 'PUSH' | 'POP' | 'REPLACE'; @@ -23,24 +24,24 @@ export interface History { createHref(location: LocationDescriptorObject): Href; } -export interface Location { +export interface Location { pathname: Pathname; search: Search; - state: LocationState; + state: S; hash: Hash; key?: LocationKey; } -export interface LocationDescriptorObject { +export interface LocationDescriptorObject { pathname?: Pathname; search?: Search; - state?: LocationState; + state?: S; hash?: Hash; key?: LocationKey; } export namespace History { - export type LocationDescriptor = Path | LocationDescriptorObject; + export type LocationDescriptor = Path | LocationDescriptorObject; export type LocationKey = string; export type LocationListener = (location: Location, action: Action) => void; export type LocationState = any; @@ -53,7 +54,7 @@ export namespace History { export type Href = string; } -export type LocationDescriptor = History.LocationDescriptor; +export type LocationDescriptor = History.LocationDescriptor; export type LocationKey = History.LocationKey; export type LocationListener = History.LocationListener; export type LocationState = History.LocationState; diff --git a/types/hoist-non-react-statics/hoist-non-react-statics-tests.tsx b/types/hoist-non-react-statics/hoist-non-react-statics-tests.tsx new file mode 100644 index 0000000000..0e1beed2e9 --- /dev/null +++ b/types/hoist-non-react-statics/hoist-non-react-statics-tests.tsx @@ -0,0 +1,46 @@ +import * as React from 'react'; +import * as PropTypes from 'prop-types'; + +import hoistNonReactStatics = require('hoist-non-react-statics'); + +class A extends React.Component<{ x: number; y?: number | null }> { + static a = 'a'; + + static propTypes = { + x: PropTypes.number.isRequired, + y: PropTypes.number, + }; + + getA() { + return A.a; + } +} + +class B extends React.Component { + static b = 'b'; + + static propTypes = { + n: PropTypes.number.isRequired, + }; + + getB() { + return B.b; + } +} + +const C = hoistNonReactStatics(A, B); + +C.a !== C.b; + +C.propTypes.x; +C.prototype.getA(); + +C.propTypes.n; // $ExpectError +C.prototype.getB(); // $ExpectError + +; + +const D = hoistNonReactStatics(A, B, { a: true, b: true }); + +D.a; +D.b; // $ExpectError diff --git a/types/hoist-non-react-statics/index.d.ts b/types/hoist-non-react-statics/index.d.ts new file mode 100644 index 0000000000..414c4c41f0 --- /dev/null +++ b/types/hoist-non-react-statics/index.d.ts @@ -0,0 +1,50 @@ +// Type definitions for hoist-non-react-statics 3.0 +// Project: https://github.com/mridgway/hoist-non-react-statics#readme +// Definitions by: JounQin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +interface REACT_STATICS { + childContextTypes: true; + contextTypes: true; + defaultProps: true; + displayName: true; + getDefaultProps: true; + getDerivedStateFromProps: true; + mixins: true; + propTypes: true; + type: true; +} + +interface KNOWN_STATICS { + name: true; + length: true; + prototype: true; + caller: true; + callee: true; + arguments: true; + arity: true; +} + +declare function hoistNonReactStatics< + T extends React.ComponentType, + S extends React.ComponentType, + C extends { + [key: string]: true + } = {} +>( + TargetComponent: T, + SourceComponent: S, + customStatic?: C, +): T & + { + [key in Exclude< + keyof S, + // only extends static properties, exclude instance properties and known react statics + keyof REACT_STATICS | keyof KNOWN_STATICS | keyof C + >]: S[key] + }; + +export = hoistNonReactStatics; diff --git a/types/hoist-non-react-statics/tsconfig.json b/types/hoist-non-react-statics/tsconfig.json new file mode 100644 index 0000000000..e0d62444e2 --- /dev/null +++ b/types/hoist-non-react-statics/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" + }, + "files": [ + "index.d.ts", + "hoist-non-react-statics-tests.tsx" + ] +} diff --git a/types/hoist-non-react-statics/tslint.json b/types/hoist-non-react-statics/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hoist-non-react-statics/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts b/types/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts index eadfcea369..174a871b9f 100644 --- a/types/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts +++ b/types/i18next-browser-languagedetector/i18next-browser-languagedetector-tests.ts @@ -19,7 +19,7 @@ const options: LngDetector.DetectorOptions = { cookieDomain: "myDomain", // optional htmlTag with lang attribute, the default is: - htmlTag: document.documentElement + htmlTag: document.documentElement! }; i18next.use(LngDetector).init({ diff --git a/types/iarna__toml/iarna__toml-tests.ts b/types/iarna__toml/iarna__toml-tests.ts new file mode 100644 index 0000000000..65dcddbe3a --- /dev/null +++ b/types/iarna__toml/iarna__toml-tests.ts @@ -0,0 +1,35 @@ +import * as TOML from '@iarna/toml'; +import { Readable } from 'stream'; + +TOML.parse('{}'); // $ExpectType Record +TOML.parse.async('{}'); // $ExpectType Promise> +TOML.parse.async('{}', {}); // $ExpectType Promise> +TOML.parse.async('{}', {blocksize: 1}); // $ExpectType Promise> + +TOML.parse.stream(); // $ExpectType Transform +TOML.parse.stream(new Readable()); // $ExpectType Promise> + +TOML.stringify({}); // $ExpectType string +TOML.stringify(1); // $ExpectError + +TOML.stringify.value({}); // $ExpectType string +TOML.stringify.value(1); // $ExpectType string + +import parse = require('@iarna/toml/parse-string'); +parse('{}'); // $ExpectType Record + +import parseAsync = require('@iarna/toml/parse-async'); +parseAsync('{}'); // $ExpectType Promise> +parseAsync('{}', {}); // $ExpectType Promise> +parseAsync('{}', {blocksize: 1}); // $ExpectType Promise> + +import parseStream = require('@iarna/toml/parse-stream'); +parseStream(); // $ExpectType Transform +parseStream(new Readable()); // $ExpectType Promise> + +import stringify = require('@iarna/toml/stringify'); +stringify({}); // $ExpectType string +stringify(1); // $ExpectError + +stringify.value({}); // $ExpectType string +stringify.value(1); // $ExpectType string diff --git a/types/iarna__toml/index.d.ts b/types/iarna__toml/index.d.ts new file mode 100644 index 0000000000..1d7f8b1239 --- /dev/null +++ b/types/iarna__toml/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for @iarna/toml 2.0 +// Project: https://github.com/iarna/iarna-toml#readme +// Definitions by: Klaus Meinhardt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import parseAsync = require('./parse-async'); +import parseStream = require('./parse-stream'); + +export import stringify = require('./stringify'); + +/** Synchronously parse a TOML string and return an object. */ +export function parse(str: string): Record; +export namespace parse { + export { + parseAsync as async, + parseStream as stream, + }; +} diff --git a/types/iarna__toml/parse-async.d.ts b/types/iarna__toml/parse-async.d.ts new file mode 100644 index 0000000000..40ba9b64ba --- /dev/null +++ b/types/iarna__toml/parse-async.d.ts @@ -0,0 +1,10 @@ +/** Asynchronously parse a TOML string and return a promise of the resulting object. */ +declare function parseAsync(str: string, opts?: parseAsync.Options): Promise>; + +declare namespace parseAsync { + interface Options { + /** The amount text to parser per pass through the event loop. Defaults to 40kb. */ + blocksize?: number; + } +} +export = parseAsync; diff --git a/types/iarna__toml/parse-stream.d.ts b/types/iarna__toml/parse-stream.d.ts new file mode 100644 index 0000000000..f844be1f07 --- /dev/null +++ b/types/iarna__toml/parse-stream.d.ts @@ -0,0 +1,9 @@ +/// + +import { Readable, Transform } from "stream"; + +/** Given a readable stream, parse it as it feeds us data. Return a promise of the resulting object. */ +declare function parseStream(readable: Readable): Promise>; +/** Returns a transform stream in object mode. When it completes, emit the resulting object. Only one object will ever be emitted. */ +declare function parseStream(): Transform; +export = parseStream; diff --git a/types/iarna__toml/parse-string.d.ts b/types/iarna__toml/parse-string.d.ts new file mode 100644 index 0000000000..0ef7630951 --- /dev/null +++ b/types/iarna__toml/parse-string.d.ts @@ -0,0 +1,3 @@ +/** Synchronously parse a TOML string and return an object. */ +declare function parseString(str: string): Record; +export = parseString; diff --git a/types/iarna__toml/stringify.d.ts b/types/iarna__toml/stringify.d.ts new file mode 100644 index 0000000000..6596d587f3 --- /dev/null +++ b/types/iarna__toml/stringify.d.ts @@ -0,0 +1,15 @@ +/** + * Serialize an object as TOML. + * + * If an object `TOML.stringify` is serializing has a toJSON method then it will call it to transform the object before serializing it. + * This matches the behavior of JSON.stringify. + * The one exception to this is that toJSON is not called for Date objects because JSON represents dates as strings and TOML can represent them natively. + */ +declare function stringify(obj: Record): string; + +declare namespace stringify { + /** Serialize a value as TOML would. This is a fragment and not a complete valid TOML document. */ + function value(v: any): string; +} + +export = stringify; diff --git a/types/iarna__toml/tsconfig.json b/types/iarna__toml/tsconfig.json new file mode 100644 index 0000000000..fe5c1cbf66 --- /dev/null +++ b/types/iarna__toml/tsconfig.json @@ -0,0 +1,35 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true, + "paths": { + "@iarna/toml": [ + "iarna__toml" + ], + "@iarna/toml/*": [ + "iarna__toml/*" + ] + } + }, + "files": [ + "index.d.ts", + "parse-async.d.ts", + "parse-stream.d.ts", + "parse-string.d.ts", + "stringify.d.ts", + "iarna__toml-tests.ts" + ] +} diff --git a/types/iarna__toml/tslint.json b/types/iarna__toml/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/iarna__toml/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/interact.js/index.d.ts b/types/interact.js/index.d.ts deleted file mode 100644 index 866ced2216..0000000000 --- a/types/interact.js/index.d.ts +++ /dev/null @@ -1,259 +0,0 @@ -// Type definitions for Interacting for interact.js v1.0.25 -// Project: https://github.com/taye/interact.js -// Definitions by: Douglas Eichelberger , Adi Dahiya , Tom Hasner -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// API documentation: http://interactjs.io/docs - -declare namespace Interact { - interface Interactable { - // returns Element or string - accept(): any; - accept(newValue: Element): Interactable; - accept(newValue: string): Interactable; - actionChecker(): Function; - actionChecker(checker: Function): Interactable; - // returns boolean or {[key: string]: any} - autoScroll(): any; - autoScroll(options: boolean): Interactable; - autoScroll(options: {[key: string]: any}): Interactable; - context(): Node; - defaultActionChecker(event: any): string; - deltaSource(): string; - // returns Interactable if newValue is "page" or "client", otherwise returns string - deltaSource(newValue: String): Interactable; - draggable(): boolean; - draggable(options: boolean): Interactable; - draggable(options: {[key: string]: any}): Interactable; - dropCheck(event: MouseEvent): boolean; - dropCheck(event: TouchEvent): boolean; - dropChecker(): Function; - dropChecker(checker: Function): Interactable; - // returns boolean or {[key: string]: any} - dropzone(): any; - dropzone(options: boolean): Interactable; - dropzone(options: {[key: string]: any}): Interactable; - // return HTMLElement or SVGElement - element(): Element; - fire(iEvent: InteractEvent): Interactable; - // returns boolean or {[key: string]: any} - gesturable(): any; - gesturable(options: boolean): Interactable; - gesturable(options: {[key: string]: any}): Interactable; - getRect(): ClientRect; - // returns Element or string - ignoreFrom(): any; - ignoreFrom(newValue: string): Interactable; - ignoreFrom(newValue: Element): Interactable; - // returns boolean or {[key: string]: any} - inertia(): any; - inertia(options: boolean): Interactable; - inertia(options: {[key: string]: any}): Interactable; - off(eventType: string, listener: Function, useCapture?: boolean): Interactable; - on(eventType: string, listener: Function, useCapture?: boolean): Interactable; - origin(): Point; - origin(newValue: HTMLElement): Interactable; - origin(newValue: SVGElement): Interactable; - origin(newValue: Point): Interactable; - preventDefault(newValue: boolean | string): Interactable; - rectChecker(): Function; - rectChecker(newValue: Function): Interactable; - resizable(): Interactable; - resizable(options: boolean): Interactable; - resizable(options: {[key: string]: any}): Interactable; - restrict(): Restrict; - restrict(newValue: Restrict): Interactable; - set(options: {[key: string]: any}): Interactable; - // returns boolean or {[key: string]: any} - snap(): any; - snap(options: boolean): Interactable; - snap(options: {[key: string]: any}): Interactable; - squareResize(): boolean; - squareResize(newValue: boolean): Interactable; - styleCursor(): boolean; - styleCursor(newValue: boolean): Interactable; - unset(): InteractStatic; - validateSetting(context: string, option: string, value: any): any; - } - - interface Coordinates { - clientX: number; - clientY: number; - pageX: number; - pageY: number; - timeStamp: number; - } - - interface Debug { - target: any; - dragging: any; - resizing: any; - gesturing: any; - prepared: any; - - prevCoords: Coordinates; - downCoords: Coordinates; - - pointerIds: any[]; - pointerMoves: any[]; - addPointer: any; - removePointer: any; - recordPointers: any; - - inertia: InertiaStatus; - - downTime: any; - downEvent: any; - prevEvent: any; - - Interactable: any; - IOptions: any; - interactables: any; - dropzones: any; - pointerIsDown: any; - defaultOptions: any; - defaultActionChecker: any; - - actions: any; - dragMove: any; - resizeMove: any; - gestureMove: any; - pointerUp: any; - pointerDown: any; - pointerMove: any; - pointerHover: any; - - events: any; - globalEvents: any; - delegatedEvents: any; - } - - interface InertiaStatus { - active: boolean; - target: any; - targetElement: any; - - startEvent: any; - pointerUp: any - - xe: number; - ye: number; - duration: number; - - t0: number; - vx0: number; - vys: number; - - lambda_v0: number; - one_ve_v0: number; - i: any; - } - - interface Point { - x: number; - y: number; - } - - // value types are either ClientRect or Element - interface Restrict { - drag?: any; - gesture?: any; - resize?: any; - elementRect?: {[direction: string]: number}; - } - - interface InteractEvent { - altKey: boolean; - axes: string; - button: number - clientX0: number; - clientX: number - clientY0: number; - clientY: number - ctrlKey: boolean - dt: number; - duration: number; - dx: number; - dy: number; - metaKey: boolean; - pageX: number; - pageY: number; - shiftKey: boolean; - speed: number; - t0: number; - target: any; - timeStamp: number; - type: string; - velocityX: number; - velocityY: number; - x0: number; - y0: number; - } - - interface TouchEvent { - pageX: number; - pageY: number; - type: string; - } - - interface InteractStatic { - (element: HTMLElement): Interactable; - (element: SVGElement): Interactable; - (element: string): Interactable; - (element: string, options: {context: Element}): Interactable; - // returns boolean or {[key: string]: any} - autoScroll(): any; - autoScroll(options: boolean): InteractStatic; - autoScroll(options: {[key: string]: any}): InteractStatic; - currentAction(): string - debug(): Debug; - deltaSource(): string; - // "page" and "client" are the valid parameters - deltaSource(newValue: string): InteractStatic; - dynamicDrop(): boolean; - dynamicDrop(newValue: boolean): InteractStatic; - enableDragging(): boolean; - enableDragging(newValue: boolean): InteractStatic; - enableGesturing(): boolean; - enableGesturing(newValue: boolean): InteractStatic; - enableResizing(): boolean; - enableResizing(newValue: boolean): InteractStatic; - // returns boolean or {[key: string]: any} - inertia(): any; - inertia(options: boolean): InteractStatic; - inertia(options: {[key: string]: any}): InteractStatic; - isSet(element: Element): boolean; - margin(): number; - margin(newvalue: number): InteractStatic; - off(type: string, listener: Function, useCapture?: boolean): InteractStatic; - on(type: string, listener: Function, useCapture?: boolean): InteractStatic; - restrict(): Restrict; - restrict(newValue: Restrict): InteractStatic; - simulate(action: string, element: Element, pointerEvent?: any): InteractStatic; - // returns boolean or {[key: string]: any} - snap(): any; - snap(options: boolean): InteractStatic; - snap(options: {[key: string]: any}): InteractStatic; - stop(event: Event): InteractStatic; - styleCursor(): boolean; - styleCursor(newValue: boolean): InteractStatic; - supportsTouch(): boolean - } -} - -declare var interact: Interact.InteractStatic; - -// CommonJS module name until version 1.2.6 is "interact.js" - declare module "interact.js" { - export = interact; - } - -// CommonJS module name from version 1.2.7 onward is "interactjs" -declare module "interactjs" { - export = interact; -} - -// AMD module name is "interact" -declare module "interact" { - export = interact; -} diff --git a/types/interact.js/interact.js-tests.ts b/types/interact.js/interact.js-tests.ts deleted file mode 100644 index f2a735e2da..0000000000 --- a/types/interact.js/interact.js-tests.ts +++ /dev/null @@ -1,110 +0,0 @@ - - -import interact = require("interact.js"); - -var button: HTMLElement = document.createElement("BUTTON"); -var rectangle: ClientRect = { - left: 100, - width: 100, - right: 100, - top: 100, - bottom: 100, - height: 100 -}; -let context = document.createElement("a"); -let interactable = interact(".foo", {context: context}); -interactable = interact(button); - -interactable.draggable(); -interactable.draggable(true); -interactable.draggable({ - onstart: (event: Interact.InteractEvent) => {}, - onmove : (event: Interact.InteractEvent) => {}, - onend : (event: Interact.InteractEvent) => {} -}); -interactable.dropzone(); -interactable.dropzone(true); -interactable.dropChecker(() => {}); -interactable.accept(); -interactable.accept("button"); -interactable.accept(button); -interactable.resizable(); -interactable.resizable(true); -interactable.squareResize(); -interactable.squareResize(true); -interactable.gesturable(); -interactable.gesturable(true); -interactable.gesturable({ - onmove: () => {} -}); -interactable.autoScroll(); -interactable.autoScroll(true); -interactable.snap(); -interactable.snap(true); -interactable.inertia(); -interactable.inertia({ - resistance: 1 -}); -interactable.inertia(true); -interactable.actionChecker(); -interactable.actionChecker((event: MouseEvent, defaultAction: string, interactable2: Interact.Interactable) => defaultAction); -var rect: ClientRect = interactable.getRect(); -interactable.rectChecker(); -interactable.styleCursor(); -interactable.origin(); -interactable.origin({x: 0, y: 0}); -interactable.origin(button); -interactable.deltaSource(); -interactable.deltaSource("client"); -interactable.restrict(); -interactable.restrict({ - "drag": button, - "resize": button, - "gesture": button -}); -interactable.context(); -interactable.ignoreFrom(); -interactable.ignoreFrom("button"); -interactable.ignoreFrom(button); -interactable.validateSetting("restrict", "drag", button); -interactable.element(); -interactable.on("click", () => {}, true); -interactable.off("click", () => {}, true); -interactable.unset(); - -interact.isSet(button); -interact.on("click", () => {}, true); -interact.off("click", () => {}, true); -interact.enableDragging(); -interact.enableDragging(true); -interact.enableResizing(); -interact.enableResizing(true); -interact.enableGesturing(); -interact.enableGesturing(true); -interact.debug(); -interact.margin(); -interact.margin(10); -interact.styleCursor(); -interact.styleCursor(true); -interact.autoScroll(true); -interact.autoScroll(); -interact.snap(); -interact.snap(true); -interact.snap({ - mode: "grid" -}); -interact.inertia(); -interact.inertia(true); -interact.supportsTouch(); -interact.currentAction(); -interact.dynamicDrop(); -interact.dynamicDrop(true); -interact.deltaSource(); -interact.deltaSource("page"); - -interact.restrict({ - "drag": rectangle, - "resize": rectangle, - "gesture": rectangle, - "elementRect": { top: 0, left: 0, bottom: 1, right: 1 } -}); diff --git a/types/ioredis/index.d.ts b/types/ioredis/index.d.ts index 45b334a205..e593f4dcc3 100644 --- a/types/ioredis/index.d.ts +++ b/types/ioredis/index.d.ts @@ -6,6 +6,7 @@ // Ebrahim // Shahar Mor // Whemoon Jang +// Francis Gulotta // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -65,10 +66,23 @@ declare namespace IORedis { get(key: string, callback: (err: Error, res: string) => void): void; get(key: string): Promise; + getBuffer(key: string, callback: (err: Error, res: Buffer) => void): void; getBuffer(key: string): Promise; - set(key: string, value: any, ...args: any[]): any; + set(key: string, value: any, expiryMode?: string | any[], time?: number | string, setMode?: number | string): Promise; + + set(key: string, value: any, callback: (err: Error, res: string) => void): void; + set(key: string, value: any, setMode: string | any[], callback: (err: Error, res: string) => void): void; + set(key: string, value: any, expiryMode: string, time: number | string, callback: (err: Error, res: string) => void): void; + set(key: string, value: any, expiryMode: string, time: number | string, setMode: number | string, callback: (err: Error, res: string) => void): void; + + setBuffer(key: string, value: any, expiryMode?: string | any[], time?: number | string, setMode?: number | string): Promise; + + setBuffer(key: string, value: any, callback: (err: Error, res: Buffer) => void): void; + setBuffer(key: string, value: any, setMode: string, callback: (err: Error, res: Buffer) => void): void; + setBuffer(key: string, value: any, expiryMode: string, time: number, callback: (err: Error, res: Buffer) => void): void; + setBuffer(key: string, value: any, expiryMode: string, time: number | string, setMode: number | string, callback: (err: Error, res: Buffer) => void): void; setnx(key: string, value: any, callback: (err: Error, res: any) => void): void; setnx(key: string, value: any): Promise; @@ -241,12 +255,16 @@ declare namespace IORedis { hset(key: string, field: string, value: any, callback: (err: Error, res: 0 | 1) => void): void; hset(key: string, field: string, value: any): Promise<0 | 1>; + hsetBuffer(key: string, field: string, value: any, callback: (err: Error, res: 0 | 1) => void): void; + hsetBuffer(key: string, field: string, value: any): Promise; hsetnx(key: string, field: string, value: any, callback: (err: Error, res: 0 | 1) => void): void; hsetnx(key: string, field: string, value: any): Promise<0 | 1>; hget(key: string, field: string, callback: (err: Error, res: string) => void): void; hget(key: string, field: string): Promise; + hgetBuffer(key: string, field: string, callback: (err: Error, res: Buffer) => void): void; + hgetBuffer(key: string, field: string): Promise; hmset(key: string, field: string, value: any, ...args: string[]): Promise<0 | 1>; hmset(key: string, data: any, callback: (err: Error, res: 0 | 1) => void): void; @@ -471,7 +489,15 @@ declare namespace IORedis { get(key: string, callback?: (err: Error, res: string) => void): Pipeline; getBuffer(key: string, callback?: (err: Error, res: Buffer) => void): Pipeline; - set(key: string, value: any, ...args: any[]): Pipeline; + set(key: string, value: any, callback?: (err: Error, res: string) => void): Pipeline; + set(key: string, value: any, setMode: string, callback?: (err: Error, res: string) => void): Pipeline; + set(key: string, value: any, expiryMode: string, time: number, callback?: (err: Error, res: string) => void): Pipeline; + set(key: string, value: any, expiryMode: string, time: number, setMode: string, callback?: (err: Error, res: string) => void): Pipeline; + + setBuffer(key: string, value: any, callback?: (err: Error, res: Buffer) => void): Pipeline; + setBuffer(key: string, value: any, setMode: string, callback?: (err: Error, res: Buffer) => void): Pipeline; + setBuffer(key: string, value: any, expiryMode: string, time: number, callback?: (err: Error, res: Buffer) => void): Pipeline; + setBuffer(key: string, value: any, expiryMode: string, time: number, setMode: string, callback?: (err: Error, res: Buffer) => void): Pipeline; setnx(key: string, value: any, callback?: (err: Error, res: any) => void): Pipeline; @@ -602,10 +628,12 @@ declare namespace IORedis { zrevrank(key: string, member: string, callback?: (err: Error, res: number) => void): Pipeline; hset(key: string, field: string, value: any, callback?: (err: Error, res: 0 | 1) => void): Pipeline; + hsetBuffer(key: string, field: string, value: any, callback?: (err: Error, res: Buffer) => void): Pipeline; hsetnx(key: string, field: string, value: any, callback?: (err: Error, res: 0 | 1) => void): Pipeline; hget(key: string, field: string, callback?: (err: Error, res: string) => void): Pipeline; + hgetBuffer(key: string, field: string, callback?: (err: Error, res: Buffer) => void): Pipeline; hmset(key: string, field: string, value: any, ...args: string[]): Pipeline; hmset(key: string, data: any, callback?: (err: Error, res: 0 | 1) => void): Pipeline; diff --git a/types/ioredis/ioredis-tests.ts b/types/ioredis/ioredis-tests.ts index 7dd98879a5..32ae5c24d5 100644 --- a/types/ioredis/ioredis-tests.ts +++ b/types/ioredis/ioredis-tests.ts @@ -16,7 +16,20 @@ redis.sadd('set', 1, 3, 5, 7); redis.sadd('set', [1, 3, 5, 7]); // All arguments are passed directly to the redis server: -redis.set('key', '100', 'EX', 10); +redis.set('key', '100'); +redis.set('key', '100', 'XX'); +redis.set('key', '100', 'PX', 10); +redis.set('key', '100', 'EX', 10, 'NX'); +redis.set('key', '100', 'NX', 'EX', 10); +redis.set('key', '100', ['EX', 10, 'NX']); +redis.setBuffer('key', '100', 'NX', 'EX', 10); + +redis.set('key', '100', (err, data) => {}); +redis.set('key', '100', 'XX', (err, data) => {}); +redis.set('key', '100', 'PX', 10, (err, data) => {}); +redis.set('key', '100', 'EX', 10, 'NX', (err, data) => {}); +redis.set('key', '100', ['EX', 10, 'NX'], (err, data) => {}); +redis.setBuffer('key', '100', 'NX', 'EX', 10, (err, data) => {}); new Redis(); // Connect to 127.0.0.1:6379 new Redis(6380); // 127.0.0.1:6380 @@ -59,6 +72,10 @@ redis.on('messageBuffer', (channel: any, message: any) => { const pipeline = redis.pipeline(); pipeline.set('foo', 'bar'); pipeline.del('cc'); +pipeline.hset('hash', 'foo', 4); +pipeline.hget('hash', 'foo'); +pipeline.hsetBuffer('hash', 'fooBuffer', 4); +pipeline.hgetBuffer('hash', 'fooBuffer'); pipeline.exec((err, results) => { // `err` is always null, and `results` is an array of responses // corresponding to the sequence of queued commands. diff --git a/types/is-callable/index.d.ts b/types/is-callable/index.d.ts new file mode 100644 index 0000000000..7e2c89f845 --- /dev/null +++ b/types/is-callable/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for is-callable 1.1 +// Project: https://github.com/ljharb/is-callable +// Definitions by: Daniel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function isCallable(val: any): val is (...args: any[]) => any; + +export = isCallable; diff --git a/types/is-callable/is-callable-tests.ts b/types/is-callable/is-callable-tests.ts new file mode 100644 index 0000000000..7ae8518ffd --- /dev/null +++ b/types/is-callable/is-callable-tests.ts @@ -0,0 +1,26 @@ +import isCallable = require("is-callable"); + +isCallable(undefined); +isCallable(null); +isCallable(false); +isCallable(true); +isCallable([]); +isCallable({}); +isCallable(/a/g); +isCallable(new RegExp("a", "g")); +isCallable(new Date()); +isCallable(42); +isCallable(NaN); +isCallable(Infinity); +isCallable("foo"); +isCallable(Object("foo")); + +function func1() {} +if (isCallable(func1)) { + func1(); +} + +const func2 = (x: number) => x * x; +if (isCallable(func2)) { + func2(0); +} diff --git a/types/is-callable/tsconfig.json b/types/is-callable/tsconfig.json new file mode 100644 index 0000000000..e1334095d7 --- /dev/null +++ b/types/is-callable/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-callable-tests.ts" + ] +} diff --git a/types/is-callable/tslint.json b/types/is-callable/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-callable/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jasmine-enzyme/index.d.ts b/types/jasmine-enzyme/index.d.ts index fd52c65ed8..bc37eda9bf 100644 --- a/types/jasmine-enzyme/index.d.ts +++ b/types/jasmine-enzyme/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/blainekasten/enzyme-matchers/blob/master/packages/jasmine-enzyme/README.md // Definitions by: Umar Bolatov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// /// diff --git a/types/jest-specific-snapshot/index.d.ts b/types/jest-specific-snapshot/index.d.ts index ef0e7f4225..61a65a416a 100644 --- a/types/jest-specific-snapshot/index.d.ts +++ b/types/jest-specific-snapshot/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/igor-dv/jest-specific-snapshot#readme // Definitions by: Janeene Beeforth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 12aa17b643..2f6b8679f6 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -1122,7 +1122,7 @@ export function ref(key: string, options?: ReferenceOptions): Reference; export function isRef(ref: any): ref is Reference; /** - * Get a sub-schema of an existing schema based on a `path` that can be either a string or an array + * Get a sub-schema of an existing schema based on a `path` that can be either a string or an array * of strings For string values path separator is a dot (`.`) */ export function reach(schema: ObjectSchema, path: string): Schema; @@ -1189,6 +1189,11 @@ export function not(values: any[]): Schema; */ export function required(): Schema; +/** + * Alias of `required`. + */ +export function exist(): Schema; + /** * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. */ diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index def9eaafd4..6eb7950682 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -1110,6 +1110,7 @@ schema = Joi.not(x, x); schema = Joi.not([x, x, x]); schema = Joi.required(); +schema = Joi.exist(); schema = Joi.optional(); schema = Joi.forbidden(); schema = Joi.strip(); diff --git a/types/jquery.fileupload/index.d.ts b/types/jquery.fileupload/index.d.ts index 6ca998d41a..28bbf3c969 100644 --- a/types/jquery.fileupload/index.d.ts +++ b/types/jquery.fileupload/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jQuery File Upload Plugin 5.40.1 +// Type definitions for jQuery File Upload Plugin 9.22.0 // Project: https://github.com/blueimp/jQuery-File-Upload // Definitions by: Rob Alarcon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,7 +6,7 @@ /// -// Interface options for the plugin +// Interface options for the plugin interface JQueryFileInputOptions { /** @@ -106,8 +106,8 @@ interface JQueryFileInputOptions { */ redirectParamName?: string; - // The HTTP request method must be "POST" or "PUT" - type?: string, + // The HTTP request method must be "POST" or "PUT" + type?: string, /** * Set the following option to the location of a postMessage window, @@ -199,7 +199,7 @@ interface JQueryFileInputOptions { * handlers using jQuery's Deferred callbacks: * data.submit().done(func).fail(func).always(func); */ - add?: (e: JQueryEventObject, data: JQueryFileInputOptions) => void; + add?: (e: JQueryEventObject, data: JqueryFileUploadAddObject) => void; // The plugin options are used as settings object for the ajax calls. // The following are jQuery ajax settings required for the file uploads: @@ -209,7 +209,7 @@ interface JQueryFileInputOptions { cache?: boolean; timeout?: number; - + active?: Function; progress?: (e: JQueryEventObject, data: JQueryFileUploadProgressObject) => void; send?: (e: JQueryEventObject, data: JQueryFileUploadProgressObject) => void; @@ -217,13 +217,13 @@ interface JQueryFileInputOptions { // Validation /** - * The maximum allowed file size in bytes. - * Type: integer - * Default: undefined - * Example: 10000000 // 10 MB - * Note: This option has only an effect for browsers supporting the File API. - * @see https://github.com/blueimp/jQuery-File-Upload/wiki/Options#maxfilesize - */ + * The maximum allowed file size in bytes. + * Type: integer + * Default: undefined + * Example: 10000000 // 10 MB + * Note: This option has only an effect for browsers supporting the File API. + * @see https://github.com/blueimp/jQuery-File-Upload/wiki/Options#maxfilesize + */ maxFileSize?: number; // Other callbacks: @@ -243,7 +243,7 @@ interface JQueryFileInputOptions { chunkfail?: (e: JQueryEventObject, data: JQueryFileUploadChunkObject) => void; chunkalways?: (e: JQueryEventObject, data: JQueryFileUploadChunkObject) => void; - // Others + // Others url?: string; files?: any; @@ -263,6 +263,12 @@ interface JQuery { fileupload(action: string, message:string, settings: JQueryFileInputOptions | string): JQueryFileUpload; } +interface JqueryFileUploadEnhancedPromise extends JQueryPromise{ + success: JQueryPromise['done'], + error: JQueryPromise['fail'], + complete: JQueryPromise['always'], +} + interface JQuerySupport { fileInput?: boolean; } @@ -275,6 +281,20 @@ interface JQueryFileUploadChangeObject { originalFiles: File[]; } +interface JqueryFileUploadConvenienceObject { + abort: () => JqueryFileUploadEnhancedPromise; + process: (resolveFunc?: Function, rejectFunc?: Function) => JqueryFileUploadEnhancedPromise; + processing: () => JqueryFileUploadEnhancedPromise; + progress: () => JqueryFileUploadEnhancedPromise; + response: () => JqueryFileUploadEnhancedPromise; + submit(): JqueryFileUploadEnhancedPromise; + state: () => JqueryFileUploadEnhancedPromise; +} + +interface JqueryFileUploadAddObject extends JQueryFileUploadChangeObject, JqueryFileUploadConvenienceObject { + paramName?: string | string[]; +} + interface JQueryFileUploadProgressAllObject { loaded?: number; total?: number; @@ -304,4 +324,4 @@ interface JQueryFileUploadProgressObject extends JQueryFileInputOptions, JQueryF } interface JQueryFileUploadDone extends JQueryFileInputOptions, JQueryFileUploadXhr { -} +} \ No newline at end of file diff --git a/types/jquery.gridster/index.d.ts b/types/jquery.gridster/index.d.ts index c91fd6f9e4..0106b448c6 100644 --- a/types/jquery.gridster/index.d.ts +++ b/types/jquery.gridster/index.d.ts @@ -10,23 +10,23 @@ gridster-0.1.0.d.ts may be freely distributed under the MIT license. Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/gridster.d.ts 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 +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 +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 +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. */ @@ -104,7 +104,7 @@ interface GridsterOptions { * Base widget dimensions in pixels. The first index for the width and the second for the height. * Default = [400, 225] **/ - widget_base_dimensions?: number[]; + widget_base_dimensions?: ('auto'|number)[]; /** * Add more columns in addition to those that have been calculated. @@ -292,7 +292,7 @@ interface Gridster { * @return Returns the instance of the Gridster class. **/ enable(): Gridster; - + /** * Disables dragging. * @return Returns the instance of the Gridster class. diff --git a/types/jquery.gridster/jquery.gridster-tests.ts b/types/jquery.gridster/jquery.gridster-tests.ts index 4dc3e3f27e..6703dea785 100644 --- a/types/jquery.gridster/jquery.gridster-tests.ts +++ b/types/jquery.gridster/jquery.gridster-tests.ts @@ -28,6 +28,9 @@ var position = coords.col + coords.row; options.widget_base_dimensions = [100, 200]; gridster.resize_widget_dimensions(options); +options.widget_base_dimensions = ['auto', 200]; +gridster.resize_widget_dimensions(options); + gridster.set_widget_min_size(0, [1, 2]); function noOptions() { @@ -48,13 +51,13 @@ function widgetSelectorString() { }; var grid: Gridster = $('.gridster ul').gridster(opts).data('gridster') -} +} function withNamespace() { var grid: Gridster = $('.gridster ul').gridster({ namespace: 'custom-gridster' }).data('gridster') -} +} function withStylesheet() { var grid: Gridster = $('.gridster ul').gridster({ diff --git a/types/jquery/test/example-tests.ts b/types/jquery/test/example-tests.ts index f725cb2bcb..60fbd431bb 100644 --- a/types/jquery/test/example-tests.ts +++ b/types/jquery/test/example-tests.ts @@ -1,3 +1,17 @@ +// tslint:disable:no-arg +// tslint:disable:no-var-keyword +// tslint:disable:object-literal-key-quotes +// tslint:disable:object-literal-shorthand +// tslint:disable:one-variable-per-declaration +// tslint:disable:only-arrow-functions +// tslint:disable:prefer-conditional-expression +// tslint:disable:prefer-const +// tslint:disable:prefer-for-of +// tslint:disable:prefer-switch +// tslint:disable:prefer-template +// tslint:disable:space-within-parens +// tslint:disable:triple-equals + function examples() { function add_0() { $('div').css('border', '2px solid red') @@ -816,7 +830,7 @@ function examples() { var len = kids.addClass('hilite').length; $('#results span:first').text(len); - $('#results span:last').text(( event.target).tagName); + $('#results span:last').text(event.target.tagName); event.preventDefault(); }); @@ -1600,7 +1614,7 @@ function examples() { function event_target_0() { $('body').click(function(event) { - $('#log').html('clicked: ' + ( event.target).nodeName); + $('#log').html('clicked: ' + event.target.nodeName); }); } @@ -2320,8 +2334,8 @@ function examples() { } function jQuery_contains_0() { - $.contains(document.documentElement, document.body); // true - $.contains(document.body, document.documentElement); // false + $.contains(document.documentElement!, document.body); // true + $.contains(document.body, document.documentElement!); // false } function jQuery_data_0() { diff --git a/types/jquery/test/learn-tests.ts b/types/jquery/test/learn-tests.ts index 17fc7cd285..ef52084da5 100644 --- a/types/jquery/test/learn-tests.ts +++ b/types/jquery/test/learn-tests.ts @@ -11,7 +11,7 @@ interface GreenifyPlugin { } jQuery.fn.greenify = function() { - this.css( "color", "green" ); + this.css("color", "green"); }; -jQuery( "a" ).greenify(); // Makes all the links green. +jQuery("a").greenify(); // Makes all the links green. diff --git a/types/jquery/test/longdesc-tests.ts b/types/jquery/test/longdesc-tests.ts index 3405bb83b5..5275191b5b 100644 --- a/types/jquery/test/longdesc-tests.ts +++ b/types/jquery/test/longdesc-tests.ts @@ -1,3 +1,14 @@ +// tslint:disable:no-var-keyword +// tslint:disable:object-literal-key-quotes +// tslint:disable:object-literal-shorthand +// tslint:disable:one-variable-per-declaration +// tslint:disable:only-arrow-functions +// tslint:disable:prefer-const +// tslint:disable:prefer-for-of +// tslint:disable:prefer-template +// tslint:disable:space-within-parens +// tslint:disable:triple-equals + function longdesc() { function add_0() { $('p').add('div').addClass('widget'); @@ -2358,9 +2369,9 @@ function longdesc() { } function toggle_3(display: boolean) { - if (display === true) { + if (display) { $('#foo').show(); - } else if (display === false) { + } else { $('#foo').hide(); } } diff --git a/types/jquery/tslint.json b/types/jquery/tslint.json index 1d12f59138..93e1f3e072 100644 --- a/types/jquery/tslint.json +++ b/types/jquery/tslint.json @@ -7,21 +7,6 @@ "no-declare-current-package": false, "ban-types": false, - "no-arg": false, - "no-boolean-literal-compare": false, - "no-object-literal-type-assertion": false, - "no-unnecessary-type-assertion": false, - "no-var-keyword": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-for-of": false, - "prefer-switch": false, - "prefer-template": false, - "space-within-parens": false, - "triple-equals": false + "no-object-literal-type-assertion": false } } diff --git a/types/jqueryui/index.d.ts b/types/jqueryui/index.d.ts index a02e3ceb73..a979c65c7a 100644 --- a/types/jqueryui/index.d.ts +++ b/types/jqueryui/index.d.ts @@ -698,6 +698,17 @@ declare namespace JQueryUI { value?: number; values?: number[]; highlight?: boolean; + classes? : SliderClasses; + } + + interface SliderClasses { + "ui-slider"?: string; + "ui-slider-horizontal"?: string; + "ui-slider-vertical"?: string; + "ui-slider-handle"?: string; + "ui-slider-range"?: string; + "ui-slider-range-min"?: string; + "ui-slider-range-max"?: string; } interface SliderUIParams { diff --git a/types/jqueryui/jqueryui-tests.ts b/types/jqueryui/jqueryui-tests.ts index a9f6f0b5ff..32712b8085 100644 --- a/types/jqueryui/jqueryui-tests.ts +++ b/types/jqueryui/jqueryui-tests.ts @@ -1599,6 +1599,7 @@ function test_slider() { $(".selector").slider({ step: 5 }); $(".selector").slider({ value: 10 }); $(".selector").slider({ values: [10, 25] }); + $(".selector").slider({ classes: { "ui-slider": "custom", "ui-slider-handle": "custom-handle" } } ); } diff --git a/types/jsdom/jsdom-tests.ts b/types/jsdom/jsdom-tests.ts index c672580a63..2dbbdca601 100644 --- a/types/jsdom/jsdom-tests.ts +++ b/types/jsdom/jsdom-tests.ts @@ -74,7 +74,7 @@ function test_serialize() { dom.serialize() === 'hello'; // Contrast with: - dom.window.document.documentElement.outerHTML === 'hello'; + dom.window.document.documentElement!.outerHTML === 'hello'; } function test_nodeLocation() { diff --git a/types/jsnox/index.d.ts b/types/jsnox/index.d.ts index 6b626c29f0..91c4361a94 100644 --- a/types/jsnox/index.d.ts +++ b/types/jsnox/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Steve Baker // Dovydas Navickas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/json2csv/JSON2CSVBase.d.ts b/types/json2csv/JSON2CSVBase.d.ts index c5f328db1f..1faf2a5318 100644 --- a/types/json2csv/JSON2CSVBase.d.ts +++ b/types/json2csv/JSON2CSVBase.d.ts @@ -92,9 +92,10 @@ declare abstract class JSON2CSVBase { * Performs the flattening of a data row recursively * * @param {object} dataRow Original JSON object + * @param {string} separator Separator to be used as the flattened field name * @returns {object} Flattened object */ - protected flatten(dataRow: T): object; + protected flatten(dataRow: T, separator: string): object; /** * Performs the unwind recursively in specified sequence diff --git a/types/json2csv/JSON2CSVTransform.d.ts b/types/json2csv/JSON2CSVTransform.d.ts index 1785e09214..f453ece8b1 100644 --- a/types/json2csv/JSON2CSVTransform.d.ts +++ b/types/json2csv/JSON2CSVTransform.d.ts @@ -80,9 +80,10 @@ declare class JSON2CSVTransform extends Transform { // implements JSON2CSVBas * Performs the flattening of a data row recursively * * @param {object} dataRow Original JSON object + * @param {string} separator Separator to be used as the flattened field name * @returns {object} Flattened object */ - protected flatten(dataRow: T): object; + protected flatten(dataRow: T, separator: string): object; /** * Performs the unwind recursively in specified sequence diff --git a/types/json2csv/index.d.ts b/types/json2csv/index.d.ts index 55a1829625..55aca2687c 100644 --- a/types/json2csv/index.d.ts +++ b/types/json2csv/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for json2csv 4.1 +// Type definitions for json2csv 4.2 // Project: https://github.com/zemirco/json2csv // Definitions by: Juanjo Diaz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/json2csv/json2csv-tests.ts b/types/json2csv/json2csv-tests.ts index 67c46cd1c3..42f8a58b70 100644 --- a/types/json2csv/json2csv-tests.ts +++ b/types/json2csv/json2csv-tests.ts @@ -76,7 +76,7 @@ class ParserExt extends Parser { s = this.processValue(new Date(), true); s = this.processValue({}, true); s = this.processValue([], true); - const flattenedData: object = this.flatten({}); + const flattenedData: object = this.flatten({}, '.'); const unwindedData: object[] = this.unwindData([], []); } } @@ -110,7 +110,7 @@ class TransformExt extends Transform { s = this.processValue(new Date(), true); s = this.processValue({}, true); s = this.processValue([], true); - const flattenedData: object = this.flatten({}); + const flattenedData: object = this.flatten({}, '.'); const unwindedData: object[] = this.unwindData([], []); } } diff --git a/types/jsoneditor-for-react/index.d.ts b/types/jsoneditor-for-react/index.d.ts index 707f03c63e..0dedfc8a64 100644 --- a/types/jsoneditor-for-react/index.d.ts +++ b/types/jsoneditor-for-react/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mixj93/jsoneditor-for-react#readme // Definitions by: JoshGoldberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; import JSONEditor, { JSONEditorOptions } from "jsoneditor"; diff --git a/types/kafka-node/index.d.ts b/types/kafka-node/index.d.ts index 71d1fd6728..2f44a7e767 100644 --- a/types/kafka-node/index.d.ts +++ b/types/kafka-node/index.d.ts @@ -9,6 +9,7 @@ export class Client { constructor(connectionString: string, clientId?: string, options?: ZKOptions, noBatchOptions?: AckBatchOptions, sslOptions?: any); close(cb?: () => void): void; + loadMetadataForTopics(topics: string[], cb: (error: TopicsNotExistError | any, data: any) => any): void; topicExists(topics: string[], cb: (error?: TopicsNotExistError | any) => any): void; refreshMetadata(topics: string[], cb?: (error?: any) => any): void; sendOffsetCommitV2Request(group: string, generationId: number, memberId: string, commits: OffsetCommitRequest[], cb: (error: any, data: any) => any): void; @@ -20,6 +21,8 @@ export class Client { export class KafkaClient extends Client { constructor(options?: KafkaClientOptions); connect(): void; + getListGroups(cb: (error: any, data: any) => any): void; + describeGroups(consumerGroups: any, cb: (error: any, data: any) => any): void; } export class Producer { @@ -93,6 +96,12 @@ export class KeyedMessage { constructor(key: string, value: string | Buffer); } +export class Admin { + constructor(kafkaClient: KafkaClient); + listGroups(cb: (error: any, data: any) => any): void; + describeGroups(consumerGroups: any, cb: (error: any, data: any) => any): void; +} + // # Interfaces export interface Message { diff --git a/types/kafka-node/kafka-node-tests.ts b/types/kafka-node/kafka-node-tests.ts index 0ffe5d86b7..1e433172ae 100644 --- a/types/kafka-node/kafka-node-tests.ts +++ b/types/kafka-node/kafka-node-tests.ts @@ -14,6 +14,8 @@ const optionsClient = new kafka.Client('localhost:2181/', 'sendMessage', { }); optionsClient.topicExists(['topic'], (error: any) => { }); +optionsClient.loadMetadataForTopics(['topic'], (error: any, data: any) => { +}); optionsClient.refreshMetadata(['topic'], (error: any) => { }); optionsClient.close(); @@ -48,6 +50,11 @@ const optionsProducer = new kafka.Producer(basicClient, { partitionerType: 0 }); +optionsKafkaClient.getListGroups((error: any, data: any) => { +}); +optionsKafkaClient.describeGroups([], (error: any, data: any) => { +}); + const producer = new kafka.Producer(basicClient); producer.on('error', (error: Error) => { }); @@ -265,3 +272,9 @@ offset.fetchLatestOffsets(['t'], (err, offsets) => { }); offset.fetchEarliestOffsets(['t'], (err, offsets) => { }); + +const admin = new kafka.Admin(basicKafkaClient); +admin.listGroups((err, data) => { +}); +admin.describeGroups({}, (err, data) => { +}); diff --git a/types/kendo-ui/index.d.ts b/types/kendo-ui/index.d.ts index dc9f7d43f0..d9df1942c3 100644 --- a/types/kendo-ui/index.d.ts +++ b/types/kendo-ui/index.d.ts @@ -1081,6 +1081,7 @@ declare namespace kendo.data { query(options?: any): JQueryPromise; read(data?: any): JQueryPromise; remove(model: kendo.data.ObservableObject): void; + skip(): number; sort(sort: DataSourceSortItem): void; sort(sort: DataSourceSortItem[]): void; sort(): DataSourceSortItem[]; diff --git a/types/klaw/v1/index.d.ts b/types/klaw/v1/index.d.ts index 74939f30c2..f65da7af6f 100644 --- a/types/klaw/v1/index.d.ts +++ b/types/klaw/v1/index.d.ts @@ -5,7 +5,7 @@ /// -import * as fs from "fs"; +import { Stats } from "fs"; import { Readable, ReadableOptions } from 'stream'; declare function K(root: string, options?: K.Options): K.Walker; @@ -13,16 +13,16 @@ declare function K(root: string, options?: K.Options): K.Walker; declare namespace K { interface Item { path: string; - stats: fs.Stats; + stats: Stats; } type QueueMethod = "shift" | "pop"; interface Options extends ReadableOptions { queueMethod?: QueueMethod; - pathSorter?: (pathA: string, pathB: string) => number; + pathSorter?(pathA: string, pathB: string): number; fs?: any; // fs or mock-fs - filter?: (path: string) => boolean; + filter?(path: string): boolean; } type Event = "close" | "data" | "end" | "readable" | "error"; diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index 82dbb5f235..c1fb224fa0 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -21,9 +21,10 @@ type Value = string | number | boolean | Date | Array | Array | type ValueMap = { [key: string]: Value | Knex.QueryBuilder }; type ColumnName = string | Knex.Raw | Knex.QueryBuilder | {[key: string]: string }; type TableName = string | Knex.Raw | Knex.QueryBuilder; +type Identifier = { [alias: string]: string }; interface Knex extends Knex.QueryInterface { - (tableName?: TableName): Knex.QueryBuilder; + (tableName?: TableName | Identifier): Knex.QueryBuilder; VERSION: string; __knex__: string; @@ -179,7 +180,7 @@ declare namespace Knex { } interface Table { - (tableName: TableName): QueryBuilder; + (tableName: TableName | Identifier): QueryBuilder; (callback: Function): QueryBuilder; (raw: Raw): QueryBuilder; } @@ -285,12 +286,6 @@ declare namespace Knex { (columnName: string): QueryBuilder; } - interface WhereIn { - (columnName: string, values: Value[]): QueryBuilder; - (columnName: string, callback: QueryCallback): QueryBuilder; - (columnName: string, query: QueryBuilder): QueryBuilder; - } - interface WhereBetween { (columnName: string, range: [Value, Value]): QueryBuilder; } @@ -305,7 +300,8 @@ declare namespace Knex { } interface WhereIn { - (columnName: string, values: Value[]): QueryBuilder; + (columnName: string, values: Value[] | QueryBuilder | QueryCallback): QueryBuilder; + (columnNames: string[], values: Value[][] | QueryBuilder | QueryCallback): QueryBuilder; } interface GroupBy extends RawQueryBuilder, ColumnNameQueryBuilder { @@ -316,9 +312,9 @@ declare namespace Knex { } interface Union { - (callback: QueryCallback, wrap?: boolean): QueryBuilder; - (callbacks: QueryCallback[], wrap?: boolean): QueryBuilder; - (...callbacks: QueryCallback[]): QueryBuilder; + (callback: QueryCallback | QueryBuilder | Raw, wrap?: boolean): QueryBuilder; + (callbacks: (QueryCallback | QueryBuilder | Raw)[], wrap?: boolean): QueryBuilder; + (...callbacks: (QueryCallback | QueryBuilder | Raw)[]): QueryBuilder; // (...callbacks: QueryCallback[], wrap?: boolean): QueryInterface; } diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts index 89a120fac1..0037948415 100644 --- a/types/knex/knex-tests.ts +++ b/types/knex/knex-tests.ts @@ -1103,3 +1103,61 @@ knex.schema table.decimal('dec', null); }) .dropTable('testTable'); + +// allow specifying an alias for a table name +knex.schema + .dropTableIfExists('foo') + .dropTableIfExists('bar') + .createTable('foo', function (table) { + table.uuid('id').primary(); + }) + .createTable('bar', function (table) { + table.uuid('id').primary(); + }); + +knex({ + table1: 'foo', + table2: 'bar' +}) + .select({ + table1Id: 'table1.id', + table2Id: 'table2.id' + }); + +knex('characters') + .select() + .whereIn(['name', 'class'], [['Bar', 'Fighter'], ['Foo', 'Druid']]); + +knex('characters') + .select() + .whereIn('name', knex('characters').select('name')); +knex('characters') + .select() + .whereIn(['name', 'class'], knex('characters').select('name', 'class')); + +knex('characters') + .select() + .whereIn('name', function() { + this.select('name').from('characters'); + }); +knex('characters') + .select() + .whereIn(['name', 'class'], function() { + this.select('name', 'class').from('characters'); + }); + +knex('characters') + .select() + .where({ name: 'Bar', class: 'Fighter' }) + .union(knex('characters').select().where({ name: 'Foo', class: 'Druid' })); +knex('characters') + .select() + .where({ name: 'Bar', class: 'Fighter' }) + .union([knex('characters').select().where({ name: 'Foo', class: 'Druid' })]); +knex('characters') + .select() + .where({ name: 'Bar', class: 'Fighter' }) + .union( + knex('characters').select().where({ name: 'Foo', class: 'Druid' }), + knex('characters').select().where({ name: 'Baz', class: 'Paladin' }) + ); diff --git a/types/knuddels-userapps-api/index.d.ts b/types/knuddels-userapps-api/index.d.ts index 36c0c139de..baff7689f8 100644 --- a/types/knuddels-userapps-api/index.d.ts +++ b/types/knuddels-userapps-api/index.d.ts @@ -1,2741 +1,2933 @@ -// Type definitions for Knuddels UserApps API 1.0 +// Type definitions for Knuddels UserApps API 1.00108823 // Project: https://developer.knuddels.de // Definitions by: Knuddels GmbH & Co. KG // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // JSON definition -interface Json { +export interface Json { [x: string]: string | number | boolean | Date | Json | JsonArray; } -// tslint:disable-next-line no-empty-interface -interface JsonArray extends Array { } +export interface JsonArray extends Array { } + // serializable objects (for persistence) -type KnuddelsSerializable = string | number | boolean | User | BotUser; -interface KnuddelsJson { +export type KnuddelsSerializable = string | number | boolean | User | BotUser; +export interface KnuddelsJson { [x: string]: string | number | boolean | Date | KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable; } -// tslint:disable-next-line no-empty-interface -interface KnuddelsJsonArray extends Array { } +export interface KnuddelsJsonArray extends Array { } + // "data" that may be send between apps and between server and client -type KnuddelsEvent = string | Json | KnuddelsEventArray; -// tslint:disable-next-line no-empty-interface -interface KnuddelsEventArray extends Array { } +export type KnuddelsEvent = string | Json | KnuddelsEventArray; +export interface KnuddelsEventArray extends Array { } -/** - * App ist die abstrakte Klasse einer konkreten App, die ein Entwickler schreiben kann. - * Im eigenen Javascript-Code muss eine Variable mit dem Namen App vorhanden sein, damit eine App lauffähig ist. - */ -interface App { +declare global { /** - * Dieses Methode wird aufgerufen, sobald ein Nutzer versucht den Channel zu betreten. - * Die App kann nun entscheiden, ob der Nutzer den Channel betreten darf. - * - * Hinweis: Um ein responsives User Interface für den Nutzer, - * der den Channel betreten möchte zu garantieren, muss die App innerhalb von einer Sekunde auf diese Anfrage reagieren, - * damit ihre Antwort in das Ergebnis einfliesst. - * - * Mit bestimmten Smileyfeatures ist es derzeit trotzdem möglich, den Channel zu betreten. - * Diese Nutzer können nicht ausgesperrt werden: - *
    - *
  • Channelbesitzer
  • - *
  • Channelmoderatoren und HZAs
  • - *
  • Admins (sofern notwendig)
  • - *
  • Sysadmins
  • - *
  • User Apps Team (Mitarbeiter von Knuddels)
  • - *
- * - * Ist der Channel mit einem Passwort geschützt und der Nutzer, der versucht den Channel zu betreten kennt das Passwort, - * so kann er nicht aus dem Channel ausgeschlossen werden. + * @see https://developer.knuddels.de/docs/classes/App.html */ - mayJoinChannel?(user: User): ChannelJoinPermission; - /** - * Diese Methode wird jedes Mal aufgerufen, sobald ein Nutzer versucht eine öffentliche Nachricht zu senden. - * Die App kann nun entscheiden, ob die Nachricht veröffentlicht werden darf. - * - * Laufen mehrere Apps im selben Channel, so wird die Nachricht veröffentlicht, sofern alle Apps es erlauben. - * - * Dauert das Fragen aller Apps nach Erlaubnis länger als 10 Sekunden, so wird die Antwort genutzt, die bis dahin - * gegeben wurde. - */ - mayShowPublicMessage?(publicMessage: PublicMessage): boolean; - /** - * Diese Methode wird jedes Mal aufgerufen, sobald ein Nutzer versucht eine öffentliche Handlung auszuführen. - * Die App kann nun entscheiden, ob die Handlung ausgeführt werden darf. - * - * Laufen mehrere Apps im selben Channel, so wird die Handlung ausgeführt, sofern alle Apps es erlauben. - * - * Dauert das Fragen aller Apps nach Erlaubnis länger als 10 Sekunden, so wird die Antwort genutzt, die bis dahin - * gegeben wurde. - */ - mayShowPublicActionMessage?(publicActionMessage: PublicActionMessage): boolean; - /** - * Diese Methode wird aufgerufen, sobald die App startet. - * Dies ist der beste Zeipunkt um Werte zu initialisieren und aus der Persistenz zu lesen. - */ - onAppStart?(): void; - /** - * Diese Methode wird aufgerufen, wenn ein User Knuddel an den BotUser gesendet hat. - * Es ist die Aufgabe der App in dieser Methode zu entscheiden, ob sie die Knuddel annimmt oder ablehnt. - * Wird diese Methode von der App nicht implementiert, so werden Knuddel automatisch akzeptiert. - * Ist diese Methode implementiert und es treten Fehler (Exceptions, Timeout,...) auf oder der Entwickler entscheidet nicht, - * was mit den Knuddel geschehen soll, so werden diese vom App-System automatisch an den Absender zurück geschickt. - *
- * Wichtig: Zum Zeitpunkt des Aufrufs dieser Methode wurden die Knuddel noch nicht an den BotUser übertragen. - */ - onBeforeKnuddelReceived?(knuddelTransfer: KnuddelTransfer): void; - /** - * Diese Methode wird aufgerufen, sobald ein BotUser Knuddel von einem User erhalten hat. - */ - onKnuddelReceived?(sender: User, receiver: BotUser, knuddelAmount: KnuddelAmount, transferReason: string): void; - /** - * Diese Methode wird aufgerufen, wenn die App sich darauf vorbereiten soll heruntergefahren zu werden. - * Als Parameter wird die geschätzte Zeit übergeben, die die App noch hat, bis sie heruntergefahren wird - * und der Aufruf App/onShutdown:event folgt. - * - * App/onPrepareShutdown:event kann dazu benutzt werden das Nutzererlebnis zu verbessern, - * sofern eine App heruntergefahren werden muss (bsp. für Updates). - * Eine Spiele-App könnte z.B. entscheiden, dass sie keine weiteren Spiele eröffnet und den Spielern offener Spiele - * die Information anzeigt, wie lange das Spiel noch läuft, bevor es unentschieden endet. - * - *

Achtung: Die Methode kann im Lebenszyklus einer App mehrfach aufgerufen werden. - */ - onPrepareShutdown?(secondsTillShutdown: number): void; - /** - * Diese Methode wird aufgerufen, wenn ein BotUser privat angeschrieben wird. - */ - onPrivateMessage?(privateMessage: PrivateMessage): void; - /** - * Diese Methode wird aufgerufen, wenn im Channel der App - * eine öffentliche Nachricht geschrieben wird. - * Für Nachrichten von BotUsern wird diese Methode nicht aufgerufen. - */ - onPublicMessage?(publicMessage: PublicMessage): void; - /** - * Diese Methode wird aufgerufen, wenn im Channel der App - * eine Event-Nachricht veröffentlicht wird. - * Für Nachrichten von BotUsern wird diese Methode nicht aufgerufen. - */ - onPublicEventMessage?(publicEventMessage: PublicEventMessage): void; - /** - * Diese Methode wird aufgerufen, wenn im Channel der App - * eine öffentliche Handlung durchgeführt wird. - * Für Handlungen von BotUsern wird diese Methode nicht aufgerufen. - */ - onPublicActionMessage?(publicActionMessage: PublicActionMessage): void; - /** - * Diese Methode wird aufgerufen, wenn eine App beendet wird. - * Sobald diese Methode aufgerufen wird, steht nur noch ein begrenzter Teil der API zur Verfügung. - * Die App sollte den kompletten Zustand in der Persistenz speichern, sodass der Zustand - * beim nächsten App/onAppStart:event wiederhergestellt werden kann. - * - * Während des Shutdowns können asynchrone each-Methoden, wie UserPersistenceNumbers/each:method - * und UserAccess/eachAccessibleUser:method nicht zuverlässig genutzt werden. - */ - onShutdown?(): void; - /** - * Diese Methode wird aufgerufen, wenn ein User im Channel der App - * über die Systemfunktionen (/dice, /diceo) würfelt. - * Die App kann auf das Ergebnis zugreifen und die Daten für die Auswertung und Entscheidungen nutzen. - */ - onUserDiced?(diceEvent: DiceEvent): void; - /** - * Diese Methode wird aufgerufen, wenn ein User den Channel der App betritt. - */ - onUserJoined?(user: User): void; - /** - * Diese Methode wird aufgerufen, wenn ein User den Channel der App verlässt. - */ - onUserLeft?(user: User): void; - /** - * Diese Methode wird aufgerufen, wenn aus einer anderen App ein Event mit sendAppEvent versendet wurde. - */ - onAppEventReceived?(appInstance: AppInstance, type: string, data: KnuddelsEvent): void; - /** - * Diese Methode wird aufgerufen, wenn aus dem HTML User Interface ein Event mit - * sendEvent() gesendet wurde. - */ - onEventReceived?(user: User, type: string, data: KnuddelsEvent, appContentSession: AppContentSession): void; - /** - * Diese Methode wird aufgerufen, wenn ein User Knuddel in seinen KnuddelAccount - * eingezahlt hat. - */ - onAccountReceivedKnuddel?(sender: User, receiver: BotUser, knuddelAmount: KnuddelAmount, transferReason: string, knuddelAccount: KnuddelAccount): void; - /** - * Diese Methode wird aufgerufen, wenn sich die Anzahl der Knuddel auf einem KnuddelAccount eines User - * geändert hat. - */ - onAccountChangedKnuddelAmount?(user: User, knuddelAccount: KnuddelAccount, oldKnuddelAmount: KnuddelAmount, newKnuddelAmount: KnuddelAmount): void; - /** - * Ermöglicht das Registrieren eigener Chatbefehle. - * In einem Channel kann nur eine App laufen, die einen bestimmten Chatbefehl nutzt. - * Versucht eine zweite App einen Chatbefehl zu registrieren, den eine andere - * App bereits nutzt, so wird ein Fehler geloggt und die App startet nicht bzw. fährt herunter. - * - * Die Struktur eines registrierten Chatbefehls ist: - * commandName: function (user, params, command) {} - * - * - *
    - *
  • commandName ist der Name der Funktion, wie sie aufgerufen wird (beispielsweise /commandname)
  • - *
  • user ist der Nutzer, der die Funktion aufgerufen hat
  • - *
  • params sind die Parameter, die der Nutzer hinter dem Befehl eingegeben hat (beispielsweise /commandname params)
  • - *
  • command ist der Name des Befehl selbst (beispielsweise commandName)
  • - *
- */ - chatCommands?: { [commandName: string]: (user: User, params: string, command: string) => void }; -} + interface App { + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_mayJoinChannel + */ + mayJoinChannel?( + user: User + ): ChannelJoinPermission; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_mayShowPublicMessage + */ + mayShowPublicMessage?( + publicMessage: PublicMessage + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_mayShowPublicActionMessage + */ + mayShowPublicActionMessage?( + publicActionMessage: PublicActionMessage + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onAppStart + */ + onAppStart?(): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onBeforeKnuddelReceived + */ + onBeforeKnuddelReceived?( + knuddelTransfer: KnuddelTransfer + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onKnuddelReceived + */ + onKnuddelReceived?( + sender: User, + receiver: BotUser, + knuddelAmount: KnuddelAmount, + transferReason: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onPrepareShutdown + */ + onPrepareShutdown?( + secondsTillShutdown: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onPrivateMessage + */ + onPrivateMessage?( + privateMessage: PrivateMessage + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onPublicMessage + */ + onPublicMessage?( + publicMessage: PublicMessage + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onPublicEventMessage + */ + onPublicEventMessage?( + publicEventMessage: PublicEventMessage + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onPublicActionMessage + */ + onPublicActionMessage?( + publicActionMessage: PublicActionMessage + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onShutdown + */ + onShutdown?(): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onUserDiced + */ + onUserDiced?( + diceEvent: DiceEvent + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onUserJoined + */ + onUserJoined?( + user: User + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onUserLeft + */ + onUserLeft?( + user: User + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onAppEventReceived + */ + onAppEventReceived?( + appInstance: AppInstance, + type: string, + data: KnuddelsEvent + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onEventReceived + */ + onEventReceived?( + user: User, + type: string, + data: KnuddelsEvent, + appContentSession: AppContentSession + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onAccountReceivedKnuddel + */ + onAccountReceivedKnuddel?( + sender: User, + receiver: BotUser, + knuddelAmount: KnuddelAmount, + transferReason: string, + knuddelAccount: KnuddelAccount + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onAccountChangedKnuddelAmount + */ + onAccountChangedKnuddelAmount?( + user: User, + knuddelAccount: KnuddelAccount, + oldKnuddelAmount: KnuddelAmount, + newKnuddelAmount: KnuddelAmount + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onUserDeleted + */ + onUserDeleted?( + userId: number, + userPersistence: UserPersistence + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_onDeveloperCommand + * @since AppServer 108662, ChatServer 108662 + */ + onDeveloperCommand?( + user: User, + params: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#method_mayUserDice + */ + mayUserDice?( + user: User, + diceConfig: DiceConfiguration + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/App.html#property_chatCommands + */ + chatCommands?: { [commandName: string]: (user: User, params: string, command: string) => void }; + } -/** - * Ermöglicht Zugriff auf Informationen zu Apps und Events zwischeneinander. - * - * Die Instanz von AppAccess erhält man über den KnuddelsServer - * mit KnuddelsServer.getAppAccess() - */ -declare class AppAccess { /** - * Liefert die Instanz der eigenen App. + * @see https://developer.knuddels.de/docs/classes/AppAccess.html */ - getOwnInstance(): AppInstance; - /** - * Liefert die Instanzen aller anderen Apps, die gerade in diesem Channel laufen. - * @since AppServer 82904 - */ - getAllRunningAppsInChannel(includeSelf?: boolean): AppInstance[]; - /** - * Liefert die Instanzen aller anderen Apps, die gerade in diesem Channel laufen. - * @since AppServer 82904 - */ - getRunningAppInChannel(appId: string): (AppInstance|null); -} + class AppAccess { + /** + * @see https://developer.knuddels.de/docs/classes/AppAccess.html#method_getOwnInstance + */ + getOwnInstance(): AppInstance; + /** + * @see https://developer.knuddels.de/docs/classes/AppAccess.html#method_getAllRunningAppsInChannel + * @since AppServer 82904 + */ + getAllRunningAppsInChannel( + includeSelf?: boolean + ): AppInstance[]; + /** + * @see https://developer.knuddels.de/docs/classes/AppAccess.html#method_getRunningAppInChannel + * @since AppServer 82904 + */ + getRunningAppInChannel( + appId: string + ): (AppInstance|null); + } -/** - * Repräsentiert den visuellen Inhalt einer Applikation, der Usern angezeigt werden soll. - */ -declare class AppContent { /** - * Liefert den AppViewMode. + * @see https://developer.knuddels.de/docs/classes/AppContent.html */ - getAppViewMode(): AppViewMode; - /** - * Liefert das HTMLFile, das beim Anlegen des AppContents - * genutzt wurde. - */ - getHTMLFile(): HTMLFile; - /** - * Liefert die Breite des AppContent. - */ - getWidth(): number; - /** - * Liefert die Höhe des AppContent. - */ - getHeight(): number; - /** - * Liefert die LoadConfiguration, mit der die Optik beim Laden des HTML User Interface beeinflusst werden kann. - */ - getLoadConfiguration(): LoadConfiguration; - /** - * Liefert einen AppContent, der das HTMLFile als Overlay oben rechts im Channel anzeigt. - */ - static overlayContent(htmlFile: HTMLFile, width: number, height: number): AppContent; - /** - * Liefert einen AppContent, der das HTMLFile als Overlay (200x350) oben rechts im Channel anzeigt. - */ - static overlayContent(htmlFile: HTMLFile): AppContent; - /** - * Liefert einen AppContent, der das HTMLFile im Applet/HTML-Chat - * als Popup (300x400) und auf Android als Fullscreen-View anzeigt. - */ - static popupContent(htmlFile: HTMLFile): AppContent; - /** - * Liefert einen AppContent, der das HTMLFile im Applet/HTML-Chat - * als Popup und auf Android als Fullscreen-View anzeigt. - */ - static popupContent(htmlFile: HTMLFile, width: number, height: number): AppContent; - /** - * Sendet Daten an alle Nutzer, die diesen AppContent geöffnet haben. - */ - sendEvent(type: string, data?: KnuddelsEvent): void; - /** - * Liefert eine Liste aller User, die diesen AppContent - * geöffnet haben. - */ - getUsers(): User[]; - /** - * Liefert eine Liste aller AppContentSessions, die dieses AppContent, - * die User gerade geöffnet haben. - */ - getSessions(): AppContentSession[]; - /** - * Ersetzt den AppContent, bei allen Usern, die diesen AppContent - * geöffnet haben durch den neuen AppContent. - * - *

Hinweis: Es können nur AppContent mit demselben AppViewMode - * zum Ersetzen genutzt werden. - */ - replaceWithAppContent(newAppContent: AppContent): void; - /** - * Entfernt diesen AppContent, bei allen Usern, die diesen AppContent - * geöffnet haben. - */ - remove(): void; - /** - * Fügt einen Listener hinzu, der aufgerufen wird, wenn jemand den AppContent schließt. - */ - addCloseListener(callback: { user: User; appContent: AppContent; }): void; -} + class AppContent { + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getAppViewMode + */ + getAppViewMode(): AppViewMode; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getHTMLFile + */ + getHTMLFile(): HTMLFile; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getWidth + */ + getWidth(): number; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getHeight + */ + getHeight(): number; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getLoadConfiguration + */ + getLoadConfiguration(): LoadConfiguration; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_overlayContent + */ + static overlayContent( + htmlFile: HTMLFile, + width: number, + height: number + ): AppContent; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_overlayContent + */ + static overlayContent( + htmlFile: HTMLFile + ): AppContent; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_popupContent + */ + static popupContent( + htmlFile: HTMLFile + ): AppContent; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_popupContent + */ + static popupContent( + htmlFile: HTMLFile, + width: number, + height: number + ): AppContent; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_sendEvent + */ + sendEvent( + type: string, + data?: KnuddelsEvent + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getUsers + */ + getUsers(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_getSessions + */ + getSessions(): AppContentSession[]; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_replaceWithAppContent + */ + replaceWithAppContent( + newAppContent: AppContent + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_remove + */ + remove(): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_addCloseListener + */ + addCloseListener( + callback: { + user: User; + appContent: AppContent; + } + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_setAllowJFXBrowser + */ + setAllowJFXBrowser( + allowJFXBrowser: boolean + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppContent.html#method_isAllowJFXBrowser + */ + isAllowJFXBrowser(): boolean; + } -/** - * Repräsentiert den visuellen Inhalt einer App, der einem User angezeigt wird. - */ -declare class AppContentSession { /** - * Sendet Daten an den verbundenen Client. + * @see https://developer.knuddels.de/docs/classes/AppContentSession.html */ - sendEvent(type: string, data?: KnuddelsEvent): void; - /** - * Liefert den AppViewMode. - */ - getAppViewMode(): AppViewMode; - /** - * Entfernt die AppContentSession beim verbundenen User. - */ - remove(): void; - /** - * Liefert den User. - */ - getUser(): User; - /** - * Liefert den verbundenen AppContent. - */ - getAppContent(): AppContent; -} + class AppContentSession { + /** + * @see https://developer.knuddels.de/docs/classes/AppContentSession.html#method_sendEvent + */ + sendEvent( + type: string, + data?: KnuddelsEvent + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppContentSession.html#method_getAppViewMode + */ + getAppViewMode(): AppViewMode; + /** + * @see https://developer.knuddels.de/docs/classes/AppContentSession.html#method_remove + */ + remove(): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppContentSession.html#method_getUser + */ + getUser(): User; + /** + * @see https://developer.knuddels.de/docs/classes/AppContentSession.html#method_getAppContent + */ + getAppContent(): AppContent; + } -/** - * Die Instanz von AppInfo zur laufenden App erhält man über die AppInstance - * mit appInstance.getAppInfo() - */ -declare class AppInfo { /** - * Liefert die AppUid. - * Diese ist für jede Sub-Channel Instanz der App unterschiedlich. - * Wenn RootAppUid == AppUid dann ist dies die Root-App-Instanz. + * @see https://developer.knuddels.de/docs/classes/AppInfo.html */ - getAppUid(): number; - /** - * Liefert die RootAppUid. - * Diese ist für jede Sub-Channel Instanz der App gleich. - * Wenn RootAppUid == AppUid dann ist dies die Root-App-Instanz. - * - * Sie wird für den Link für Auszahlungen aus einem Knuddel-Account benötigt: /knuddelaccount payout:<RootAppUid>:<BETRAG> - */ - getRootAppUid(): number; - /** - * Liefert den in der Konfiguration eingestellten Namen der App. - */ - getAppName(): string; - /** - * Liefert die Version der App, die in der Konfiguration eingestellt wurde. - */ - getAppVersion(): string; - /** - * Liefert die eindeutige Id der App. - * Die appId setzt sich zusammen aus - *
    - *
  • id des Entwicklungsservers
  • - *
  • FTP-Nutzername
  • - *
  • Ordnername der App -> appKey
  • - *
- */ - getAppId(): string; - /** - * Liefert den eindeutigen Key der App. - * Der appKey ist der Ordnername, in dem die App liegt. - */ - getAppKey(): string; - /** - * Liefert den Entwickler der App, falls die serverId knuddelsDE oder knuddelsDEV ist, ansonsten null. - */ - getAppDeveloper(): User; - /** - * Liefert die Liste der AppManager für diese App. Die Channelbesitzer zählen automatisch auch als AppManager. - */ - getAppManagers(): User[]; - /** - * Liefert den Steuersatz, der bei Auszahlung bereits genutzer Knuddel von einem - * KnuddelAccount an einen User - * anfällt. Die anfallenden Steuern werden bei Auszahlung vom BotUser - * abgezogen. - */ - getTaxRate(): number; - /** - * Liefert den KnuddelAmount, der an Steuern anfallen würde, - * wenn alle User jetzt all ihre Knuddel aus ihrem - * KnuddelAccount abheben würden. - */ - getTotalTaxKnuddelAmount(): KnuddelAmount; - /** - * Liefert den KnuddelAmount, der jetzt noch vom - * BotUser an KnuddelAccounts - * übertragen werden kann, so dass für alle Knuddel noch die Steuern bezahlt werden können. - */ - getMaxPayoutKnuddelAmount(): KnuddelAmount; -} + class AppInfo { + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppUid + */ + getAppUid(): number; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getRootAppUid + */ + getRootAppUid(): number; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppName + */ + getAppName(): string; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppVersion + */ + getAppVersion(): string; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppId + */ + getAppId(): string; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppKey + */ + getAppKey(): string; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppDeveloper + */ + getAppDeveloper(): User; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getAppManagers + */ + getAppManagers(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getTaxRate + */ + getTaxRate(): number; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getTotalTaxKnuddelAmount + */ + getTotalTaxKnuddelAmount(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/AppInfo.html#method_getMaxPayoutKnuddelAmount + */ + getMaxPayoutKnuddelAmount(): KnuddelAmount; + } -/** - * Repräsentiert die Instanz einer App. - * - * Die eigene Instanz von AppInstance erhält man über das AppAccess-Objekt - * mit appAccess.getOwnInstance() - */ -declare class AppInstance { /** - * Liefert die AppInfo. + * @see https://developer.knuddels.de/docs/classes/AppInstance.html */ - getAppInfo(): AppInfo; - /** - * Sendet ein App-Event an diese App-Instanz. - */ - sendAppEvent(type: string, data: KnuddelsEvent): void; - /** - * Informiert, ob die aktuelle AppInstanz eine Root-Instanz ist. - */ - isRootInstance(): boolean; - /** - * Liefert die Root-Instanz der aktuellen App-Instanz. - */ - getRootInstance(): RootAppInstance; - /** - * Liefert alle App-Instanzen dieser App in diesem Channel und Subchannels. - * Mit includeSelf = false kann man die eigene Instanz ausschließen. - */ - getAllInstances(includeSelf?: boolean): AppInstance[]; - /** - * Liefert den Startzeitpunkt dieser AppInstance. - */ - getStartDate(): Date; - /** - * Liefert die Namen der ChatCommands, die diese AppInstnce derzeit registriert hat. - */ - getRegisteredChatCommandNames(): (string[]|null); - /** - * Liefert den Namen des Channels in dem diese AppInstance läuft. - */ - getChannelName(): string; -} + class AppInstance { + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getAppInfo + */ + getAppInfo(): AppInfo; + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_sendAppEvent + */ + sendAppEvent( + type: string, + data: KnuddelsEvent + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_isRootInstance + */ + isRootInstance(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getRootInstance + */ + getRootInstance(): RootAppInstance; + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getAllInstances + */ + getAllInstances( + includeSelf?: boolean + ): AppInstance[]; + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getStartDate + */ + getStartDate(): Date; + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getRegisteredChatCommandNames + */ + getRegisteredChatCommandNames(): (string[]|null); + /** + * @see https://developer.knuddels.de/docs/classes/AppInstance.html#method_getChannelName + */ + getChannelName(): string; + } -/** - * Jede App besitzt eine AppPersistence in der global für diese App - * Informationen gespeichert werden können. An die Instanz der AppPersistence gelangt man durch den Aufruf - * KnuddelsServer.getPersistence();. - */ -declare class AppPersistence extends Persistence { -} + /** + * @see https://developer.knuddels.de/docs/classes/AppPersistence.html + */ + class AppPersistence extends Persistence { + } -/** - * Eine Instanz eines AppProfileEntry repräsentiert einen von einer App erzeugen Profileintrag in Profilen von Usern. - */ -declare class AppProfileEntry { /** - * Liefert den key für den die Topliste, die den Profileintrag erzeugt angelegt wurde. + * @see https://developer.knuddels.de/docs/classes/AppProfileEntry.html */ - getKey(): string; - /** - * Liefert den getDisplayType - */ - getDisplayType(): ToplistDisplayType; - /** - * Liefert das Toplist-Objekt. - */ - getToplist(): Toplist; -} + class AppProfileEntry { + /** + * @see https://developer.knuddels.de/docs/classes/AppProfileEntry.html#method_getKey + */ + getKey(): string; + /** + * @see https://developer.knuddels.de/docs/classes/AppProfileEntry.html#method_getDisplayType + */ + getDisplayType(): ToplistDisplayType; + /** + * @see https://developer.knuddels.de/docs/classes/AppProfileEntry.html#method_getToplist + */ + getToplist(): Toplist; + } -/** - * Mit einer Instanz von AppProfileEntryAccess kann eine App - * AppProfileEntry-Objekte (Profileinträge) erzeugen und verwalten. - * - * Die Instanz für die AppProfileEntryAccess erhält man über das KnuddelsServer-Objekt - * mit KnuddelsServer.getAppProfileEntryAccess() - * - *

Achtung: Derzeit darf eine App bis zu fünf AppProfileEntries haben. - *

Achtung: Profileinträge werden nur dann angezeigt, wenn der Channel sichtbar ist. - */ -declare class AppProfileEntryAccess { /** - * Liefert die Liste aller AppProfileEntry-Objekte, die diese App erzeugt hat. + * @see https://developer.knuddels.de/docs/classes/AppProfileEntryAccess.html */ - getAllProfileEntries(): AppProfileEntry[]; - /** - * Liefert den AppProfileEntry für den übergebenen userPersistenceNumberKey. - */ - getAppProfileEntry(userPersistenceNumberKey: string): AppProfileEntry; - /** - * Erzeugt oder aktualisiert ein AppProfileEntry anhand der übergebenen Toplist - * und dem ToplistDisplayType und liefert den AppProfileEntry im Anschluss zurück. - * - * Profileinträge, die erzeugt werden, sind nur sichtbar, solange die App läuft und werden im Profil ausgeblendet, sofern die App aus ist. - */ - createOrUpdateEntry(toplist: Toplist, toplistDisplayType: ToplistDisplayType): AppProfileEntry; - /** - * Löscht den übergebenen AppProfileEntry. - */ - removeEntry(appProfileEntry: AppProfileEntry): void; -} + class AppProfileEntryAccess { + /** + * @see https://developer.knuddels.de/docs/classes/AppProfileEntryAccess.html#method_getAllProfileEntries + */ + getAllProfileEntries(): AppProfileEntry[]; + /** + * @see https://developer.knuddels.de/docs/classes/AppProfileEntryAccess.html#method_getAppProfileEntry + */ + getAppProfileEntry( + userPersistenceNumberKey: string + ): AppProfileEntry; + /** + * @see https://developer.knuddels.de/docs/classes/AppProfileEntryAccess.html#method_createOrUpdateEntry + */ + createOrUpdateEntry( + toplist: Toplist, + toplistDisplayType: ToplistDisplayType + ): AppProfileEntry; + /** + * @see https://developer.knuddels.de/docs/classes/AppProfileEntryAccess.html#method_removeEntry + */ + removeEntry( + appProfileEntry: AppProfileEntry + ): void; + } -/** - * Liefert Informationen über einen AppServer. - * - * Die Instanz von AppServerInfo erhält man über den KnuddelsServer - * mit KnuddelsServer.getAppServerInfo() - */ -declare class AppServerInfo extends ServerInfo { -} + /** + * @see https://developer.knuddels.de/docs/classes/AppServerInfo.html + */ + class AppServerInfo extends ServerInfo { + } -/** - * null - */ -declare class AppViewMode { /** - * + * @see https://developer.knuddels.de/docs/classes/AppViewMode.html */ - static readonly Overlay: AppViewMode; - /** - * Zum Öffnen eines Popups durch das HTML User Interface - */ - static readonly Popup: AppViewMode; -} + class AppViewMode { + /** + * @see https://developer.knuddels.de/docs/classes/AppViewMode.html#property_Overlay + */ + static readonly Overlay: AppViewMode; + /** + * @see https://developer.knuddels.de/docs/classes/AppViewMode.html#property_Popup + */ + static readonly Popup: AppViewMode; + } -/** - * Ein BotUser repräsentiert einen Nutzer, der für die App als Nutzer im Channel interagieren kann. - * - * Die Instanz für den Standard-BotUser erhält man über das KnuddelsServer-Objekt - * mit KnuddelsServer.getDefaultBotUser() - */ -declare class BotUser extends User { /** - * Sendet eine öffentliche Nachricht in den Channel. + * @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html */ - sendPublicMessage(message: string): void; - /** - * Sendet eine öffentliche Handlung in den Channel. - * Dies funktioniert so, als ob der BotUser /me TEXT im Chat eingeben würde. - */ - sendPublicActionMessage(actionMessage: string): void; - /** - * Sendet eine private Nachricht an bestimmte Nutzer. - */ - sendPrivateMessage(message: string, users?: User[]): void; - /** - * Sendet eine persistente Nachricht an einen bestimmten Nutzer. - */ - sendPostMessage(topic: string, text: string, receivingUser?: User): void; - /** - * Transferiert eine bestimmte Anzahl Knuddel an einen Zielnutzer oder KnuddelAccount.

- * Wichtiger Hinweis: Sollte die App versuchen mehr Knuddel zu transferieren, - * als sie besitzt, so wird der onError-Callback aufgerufen und die App transferiert so viele Knuddel, wie möglich. - * Zudem werden die Schulden für den Channelbesitzer gemerkt. Sobald sich der Channelbesitzer einloggt, erhält er einen Hinweis über offene Schulden - * und sollte diese direkt begleichen. - * Hat ein Channelbesitzer eine gewisse Menge Schulden angesammelt, so schalten wir alle Apps in diesem Channel ab. - *
Es können nur Knuddel transferiert werden zu Nutzern mit UserType.Human. - */ - transferKnuddel( - receivingUserOrAccount: User | KnuddelAccount, - knuddelAmount: KnuddelAmount, - displayReasonText: string): void; - transferKnuddel( - receivingUserOrAccount: User | KnuddelAccount, - knuddelAmount: KnuddelAmount, - parameters?: { - displayReasonText?: string; - transferDisplayType?: KnuddelTransferDisplayType; - onSuccess?(): void; - onError?(message: string): void; - }): void; -} + class AuthenticityClassification { + /** + * @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html#method_getDisplayText + * @since AppServer 94663, ChatServer 94663 + */ + getDisplayText(): string; + /** + * @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html#property_ServiceNotAvailable + */ + static readonly ServiceNotAvailable: AuthenticityClassification; + /** + * @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html#property_Unknown + */ + static readonly Unknown: AuthenticityClassification; + /** + * @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html#property_Trusted + */ + static readonly Trusted: AuthenticityClassification; + /** + * @see https://developer.knuddels.de/docs/classes/AuthenticityClassification.html#property_VeryTrusted + */ + static readonly VeryTrusted: AuthenticityClassification; + } -/** - * Ein Channel ist ein Raum in dem die App läuft. - * - * Die Instanz für den Channel erhält man über das KnuddelsServer-Objekt - * mit KnuddelsServer.getChannel() - */ -declare class Channel { /** - * Gibt Zugriff auf das ChannelConfiguration-Objekt des Channels. + * @see https://developer.knuddels.de/docs/classes/BotUser.html */ - getChannelConfiguration(): ChannelConfiguration; + class BotUser extends User { + /** + * @see https://developer.knuddels.de/docs/classes/BotUser.html#method_sendPublicMessage + */ + sendPublicMessage( + message: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/BotUser.html#method_sendPublicActionMessage + */ + sendPublicActionMessage( + actionMessage: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/BotUser.html#method_sendPrivateMessage + */ + sendPrivateMessage( + message: string, + users?: User[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/BotUser.html#method_sendPostMessage + */ + sendPostMessage( + topic: string, + text: string, + receivingUser?: User + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/BotUser.html#method_transferKnuddel + */ + transferKnuddel( + receivingUserOrAccount: (User|KnuddelAccount), + knuddelAmount: KnuddelAmount, + parameters?: { + displayReasonText?: string; + transferDisplayType?: KnuddelTransferDisplayType; + onSuccess?: () => void; + onError?: (message: string) => void; + } + ): void; + } + /** - * Gibt Zugriff auf das ChannelRestrictions-Objekt des Channels. + * @see https://developer.knuddels.de/docs/classes/Channel.html */ - getChannelRestrictions(): ChannelRestrictions; + class Channel { + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getChannelConfiguration + */ + getChannelConfiguration(): ChannelConfiguration; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getChannelRestrictions + */ + getChannelRestrictions(): ChannelRestrictions; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getChannelDesign + * @since AppServer 87470, ChatServer 87470 + */ + getChannelDesign(): ChannelDesign; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getOnlineUsers + */ + getOnlineUsers( + ...userType: UserType[] + ): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_isVideoChannel + */ + isVideoChannel(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getVideoChannelData + */ + getVideoChannelData(): VideoChannelData; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getChannelName + */ + getChannelName(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getRootChannelName + */ + getRootChannelName(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getTalkMode + */ + getTalkMode(): ChannelTalkMode; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_getAllUsersWithTalkPermission + */ + getAllUsersWithTalkPermission( + ...channelTalkPermission: ChannelTalkPermission[] + ): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/Channel.html#method_isVisible + * @since AppServer 82202 + */ + isVisible(): boolean; + } + /** - * Gibt Zugriff auf das ChannelDesign-Objekt des Channels. + * @see https://developer.knuddels.de/docs/classes/ChannelConfiguration.html + */ + class ChannelConfiguration { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelConfiguration.html#method_getChannelRights + */ + getChannelRights(): ChannelRights; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelConfiguration.html#method_getChannelInformation + */ + getChannelInformation(): ChannelInformation; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ChannelDesign.html * @since AppServer 87470, ChatServer 87470 */ - getChannelDesign(): ChannelDesign; - /** - * Gibt Zugriff auf Nutzer, die gerade im Channel online sind. - */ - getOnlineUsers(...userType: UserType[]): User[]; - /** - * Liefert die Information, ob in diesem Channel Videos gestreamt werden können. - */ - isVideoChannel(): boolean; - /** - * Liefert die VideoChannelData des Channels. - */ - getVideoChannelData(): VideoChannelData; - /** - * Liefert den Namen des Channels. - */ - getChannelName(): string; - /** - * Liefert den Namen des Root-Channels (nur relevant, falls die App Tochterchannel haben kann). - */ - getRootChannelName(): string; - /** - * Liefert den ChannelTalkMode, in dem sich der Channel gerade befindet. - */ - getTalkMode(): ChannelTalkMode; - /** - * Liefert alle User, die bestimmte ChannelTalkPermissions haben. - */ - getAllUsersWithTalkPermission(...channelTalkPermission: ChannelTalkPermission[]): User[]; - /** - * Liefert die Information, ob der Channel sichtbar (true) oder unsichtbar (false) ist. - * @since AppServer 82202 - */ - isVisible(): boolean; -} + class ChannelDesign { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelDesign.html#method_getDefaultFontSize + * @since AppServer 87470, ChatServer 87470 + */ + getDefaultFontSize(): number; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelDesign.html#method_getDefaultFontColor + * @since AppServer 87470, ChatServer 87470 + */ + getDefaultFontColor(): Color; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelDesign.html#method_getBackgroundColor + * @since AppServer 87470, ChatServer 87470 + */ + getBackgroundColor(): Color; + } -/** - * Eine ChannelConfiguration erlaubt Zugriff auf verschiedene Details - * der Konfiguration des Channels, in dem die App läuft. - * - * Die Instanz für die ChannelConfiguration erhält man über das Channel-Objekt - * mit channel.getChannelConfiguration() - */ -declare class ChannelConfiguration { /** - * Liefert das ChannelRights-Objekt des Channels. + * @see https://developer.knuddels.de/docs/classes/ChannelInformation.html */ - getChannelRights(): ChannelRights; - /** - * Liefert das ChannelInformation-Objekt des Channels. - */ - getChannelInformation(): ChannelInformation; -} + class ChannelInformation { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelInformation.html#method_getTopic + */ + getTopic(): string; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelInformation.html#method_setTopic + */ + setTopic( + topic: string, + showMessage: boolean + ): void; + } -/** - * Ermöglicht Zugriff auf Designeinstellungen des Channels. - * @since AppServer 87470, ChatServer 87470 - */ -declare class ChannelDesign { /** - * Liefert die eingestellte Standard-Schriftgröße des Channels. - * @since AppServer 87470, ChatServer 87470 + * @see https://developer.knuddels.de/docs/classes/ChannelJoinPermission.html */ - getDefaultFontSize(): number; - /** - * Liefert die eingestellte Standard-Schriftfarbe des Channels. - * @since AppServer 87470, ChatServer 87470 - */ - getDefaultFontColor(): Color; - /** - * Liefert die eingestellte Hintergrundfarbe des Channels. - * @since AppServer 87470, ChatServer 87470 - */ - getBackgroundColor(): Color; -} + class ChannelJoinPermission { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelJoinPermission.html#method_accepted + */ + static accepted(): ChannelJoinPermission; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelJoinPermission.html#method_denied + */ + static denied( + denyReason: string + ): ChannelJoinPermission; + } -/** - * Ermöglicht Zugriff auf textuelle Channelinformationen und persistente Änderungen. - */ -declare class ChannelInformation { /** - * Liefert das eingestellte Thema des Channels. + * @see https://developer.knuddels.de/docs/classes/ChannelRestrictions.html */ - getTopic(): string; - /** - * Aktualisiert das Thema das Channels. - */ - setTopic(topic: string, showMessage: boolean): void; -} + class ChannelRestrictions { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelRestrictions.html#method_getMutedUsers + */ + getMutedUsers(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelRestrictions.html#method_getColorMutedUsers + */ + getColorMutedUsers(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelRestrictions.html#method_getLockedUsers + */ + getLockedUsers(): User[]; + } -/** - * Eine Instanz der Klasse ChannelJoinPermission wird als Rückgabewert - * der Methode App.mayJoinChannel(user) benötigt. - * - * Hiermit wird bestimmt, ob der anfragende Nutzer den Channel betreten darf. - * - * Erlauben mit ChannelJoinPermission.accepted() - * Verbieten mit ChannelJoinPermission.denied(denyReason) - */ -declare class ChannelJoinPermission { /** - * Erzeugt ein ChannelJoinPermission-Objekt, das den Zugriff in den Channel erlaubt. + * @see https://developer.knuddels.de/docs/classes/ChannelRights.html */ - static accepted(): ChannelJoinPermission; - /** - * Erzeugt ein ChannelJoinPermission-Objekt, das den Zugriff in den Channel verbietet. - */ - static denied(denyReason: string): ChannelJoinPermission; -} + class ChannelRights { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelRights.html#method_getChannelOwners + */ + getChannelOwners(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelRights.html#method_getChannelModerators + */ + getChannelModerators(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelRights.html#method_getEventModerators + */ + getEventModerators(): User[]; + } -/** - * Eine Instanz von ChannelRestrictions ermöglicht es, aktuelle Informationen über Nutzungsbeschränkungen im Channel zu erhalten. - * - * Die Instanz für die ChannelRestrictions erhält man über das Channel-Objekt - * mit channel.getChannelRestrictions() - */ -declare class ChannelRestrictions { /** - * Liefert alle User die im Channel derzeit für das Schreiben öffentlicher Nachrichten gesperrt sind. + * @see https://developer.knuddels.de/docs/classes/ChannelTalkMode.html */ - getMutedUsers(): User[]; - /** - * Liefert alle User die im Channel derzeit für das Nutzen - * von Farben, Textformatierung und Smileys in öffentlichen Nachrichten gesperrt sind. - */ - getColorMutedUsers(): User[]; - /** - * Liefert alle User die für das Betreten des Channel derzeit gesperrt sind. - */ - getLockedUsers(): User[]; -} + class ChannelTalkMode { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkMode.html#property_Everyone + */ + static readonly Everyone: ChannelTalkMode; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkMode.html#property_OnlyWithTalkPermission + */ + static readonly OnlyWithTalkPermission: ChannelTalkMode; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkMode.html#property_FilteredByModerators + */ + static readonly FilteredByModerators: ChannelTalkMode; + } -/** - * Die Instanz für die ChannelRights erhält man über das ChannelConfiguration-Objekt - * mit channelConfiguration.getChannelRights() - */ -declare class ChannelRights { /** - * Liefert die Liste aller Channelbesitzer. In öffentlichen Channels sind dies alle hauptzuständigen betreuenden Mitglieder. (HZA/HZE) + * @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html */ - getChannelOwners(): User[]; - /** - * Liefert die Liste aller Channel-Moderatoren. - */ - getChannelModerators(): User[]; - /** - * Liefert die Liste aller Event-Moderatoren. - */ - getEventModerators(): User[]; -} + class ChannelTalkPermission { + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_NotInChannel + */ + static readonly NotInChannel: ChannelTalkPermission; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_Default + */ + static readonly Default: ChannelTalkPermission; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_TalkOnce + */ + static readonly TalkOnce: ChannelTalkPermission; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_TalkPermanent + */ + static readonly TalkPermanent: ChannelTalkPermission; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_VIP + */ + static readonly VIP: ChannelTalkPermission; + /** + * @see https://developer.knuddels.de/docs/classes/ChannelTalkPermission.html#property_Moderator + */ + static readonly Moderator: ChannelTalkPermission; + } -/** - * ChannelTalkMode repräsentiert das den Gesprächsmodus im Channel. - * - * Die Instanz für die ChannelTalkMode erhält man über das Channel-Objekt - * mit channel.getTalkMode() - */ -declare class ChannelTalkMode { /** - * Jeder darf gerade im Channel schreiben. + * @see https://developer.knuddels.de/docs/classes/ChatServerInfo.html */ - static readonly Everyone: ChannelTalkMode; - /** - * Nur Personen, die besondere Rederechte haben dürfen gerade im Channel schreiben. - */ - static readonly OnlyWithTalkPermission: ChannelTalkMode; - /** - * Nur Personen, die besondere Rederechte haben dürfen gerade im Channel schreiben. - * Die Nachrichten aller anderen Nutzer werden gefiltert und ggf. von den Moderatoren zugelassen. - */ - static readonly FilteredByModerators: ChannelTalkMode; -} + class ChatServerInfo extends ServerInfo { + /** + * @see https://developer.knuddels.de/docs/classes/ChatServerInfo.html#method_isTestSystem + */ + isTestSystem(): boolean; + } -/** - * ChannelTalkPermission repräsentiert das Rederecht eines User - * im Channel. - */ -declare class ChannelTalkPermission { /** - * Der User ist gerade nicht im Channel, - * daher ist die ChannelTalkPermission nicht bekannnt. + * @see https://developer.knuddels.de/docs/classes/Client.html */ - static readonly NotInChannel: ChannelTalkPermission; - /** - * Der User hat keine speziellen Rederechte. - * Beim ChannelTalkMode Default können diese User - * Nachrichten verfassen: - */ - static readonly Default: ChannelTalkPermission; - /** - * Der User kann eine öffentliche Nachricht verfassen. Danach wechselt die - * ChannelTalkPermission automatisch auf Default. - */ - static readonly TalkOnce: ChannelTalkPermission; - /** - * Der User kann permanent öffentliche Nachrichten verfassen. - */ - static readonly TalkPermanent: ChannelTalkPermission; - /** - * Der User ist VIP und kann öffentliche Nachrichten verfassen, - * die farbig und groß dargestellt werden. - */ - static readonly VIP: ChannelTalkPermission; - /** - * Der User ist VIP und kann öffentliche Nachrichten verfassen, - * die farbig und groß dargestellt werden. Moderatoren haben zudem weitere Möglichkeiten, die in der - * Anleitung zum Moderationssystem - * nachgelesen werden können. - */ - static readonly Moderator: ChannelTalkPermission; -} + class Client { + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_close + */ + static close(): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_sendEvent + */ + static sendEvent( + type: string, + data: KnuddelsEvent + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_executeSlashCommand + */ + static executeSlashCommand( + command: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_includeJS + */ + static includeJS( + ...files: string[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_addEventListener + */ + static addEventListener( + type: string, + callback: (event: {type: string, data: KnuddelsEvent}) => void + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_dispatchEvent + */ + static dispatchEvent( + event: Client.Event + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_removeEventListener + */ + static removeEventListener( + type: string, + callback?: (event: {type: string, data: KnuddelsEvent}) => void + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_includeCSS + */ + static includeCSS( + ...files: string[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_playSound + */ + static playSound( + fileName: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_prefetchSound + */ + static prefetchSound( + fileName: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_freeSound + */ + static freeSound( + fileName: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_getHostFrame + */ + static getHostFrame(): Client.HostFrame; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_getNick + */ + static getNick(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_getClientType + */ + static getClientType(): ClientType; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_getCacheInvalidationId + */ + static getCacheInvalidationId(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_getDirectConnection + */ + static getDirectConnection(): Promise; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_addConnectionTypeChangeListener + */ + static addConnectionTypeChangeListener( + callback: (type: string) => void + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#method_removeConnectionTypeChangeListener + */ + static removeConnectionTypeChangeListener( + callback: (type: string) => void + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.html#property_pageData + */ + static pageData: Json; + } -/** - * Liefert Informationen über einen ChatServer. - * - * Die Instanz von ChatServerInfo erhält man über den KnuddelsServer - * mit KnuddelsServer.getChatServerInfo() - */ -declare class ChatServerInfo extends ServerInfo { /** - * Liefert die Information, ob dieser Chat-Server ein Test-System ist. + * @see https://developer.knuddels.de/docs/classes/Client.Color.html */ - isTestSystem(): boolean; -} + namespace Client { + class Color { + /** + * @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_fromRGB + */ + static fromRGB( + red: number, + green: number, + blue: number + ): Color; + /** + * @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_fromHexString + */ + static fromHexString( + colorString: string + ): Color; + /** + * @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_getRed + */ + getRed(): number; + /** + * @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_getGreen + */ + getGreen(): number; + /** + * @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_getBlue + */ + getBlue(): number; + /** + * @see https://developer.knuddels.de/docs/classes/Client.Color.html#method_asHexString + */ + asHexString(): string; + } + } -/** - * Klasse, die es ermöglicht den Client innerhalb des HTML User Interface zu steuern und Daten an den Server zu senden. - */ -declare class Client { /** - * Schließt das HTML User Interface. + * @see https://developer.knuddels.de/docs/classes/Client.Event.html */ - static close(): void; - /** - * Sendet ein Event zum Server, das mit dem AppHook onEventReceived in der App - * abgefangen werden kann. - */ - static sendEvent(type: string, data: KnuddelsEvent): void; - /** - * Sagt dem Chatserver, dass dieser Befehl für den Nutzer, der das HTML User Interface sieht, ausgeführt werden soll. - * Ist der Befehl auf einer Whitelist vom Server, so wird er sofort ausgeführt. Im anderen Falle sieht der Nutzer einen - * Link zum Bestätigen, mit dem er die Aktion starten kann. - * - * Derzeit sind diese Befehle auf der Whitelist: w, info, wc, top, h, dice, d, diceo, w2, serverpp, knuddelaccount, - * /tf-insert, /tf-inserts, /tf-insertb, /tf-insertsb, /tf-override, /tf-overrides, /tf-overrideb, /tf-overridesb, /autotype - */ - static executeSlashCommand(command: string): void; - /** - * Bindet eine Javascript-Datei ein und sorgt dafür, dass immer die aktuellste Version vom Server geladen wird. - */ - static includeJS(...files: string[]): void; - /** - * Registriert sich für ein bestimmtes Event, das vom Server mittels User/sendEvent:method oder vom Client via Client/dispatchEvent:method verschickt wurde. - */ - static addEventListener(type: string, callback: (event: {type: string, data: KnuddelsEvent}) => void): void; - /** - * Sendet ein bestimmtes Event, so dass alle mit Client/addEventListener:method registrierten Listener aufgerufen werden. - */ - static dispatchEvent(event: Client.Event): void; - /** - * Entfernt alle Event-Listener für einen bestimmten Event-Typ. - */ - static removeEventListener(type: string): void; - /** - * Bindet eine CSS-Datei ein und sorgt dafür, dass immer die aktuellste Version vom Server geladen wird. - */ - static includeCSS(...files: string[]): void; - /** - * Spielt einen Sound ab. Der angegebene Dateiname kann hierbei entweder absolut oder relativ zur angezeigten HTML-Datei sein. - * Bisher können nur Dateien mit Wave-Format zuverlässig abgespielt werden. - */ - static playSound(fileName: string): void; - /** - * Lädt einen Sound herunter, damit die Datei später ohne Wartezeit abgespielt werden kann. - * (Android only) - * Der angegebene Dateiname kann hierbei entweder absolut oder relativ zur angezeigten HTML-Datei sein. - */ - static prefetchSound(fileName: string): void; - /** - * Gibt einen Sound wieder frei, der in nächster Zeit vom Client nicht mehr gebraucht wird. - * (Android only) - * Der angegebene Dateiname kann hierbei entweder absolut oder relativ zur angezeigten HTML-Datei sein. - */ - static freeSound(fileName: string): void; - /** - * Liefert den HostFrame des aktuellen Inhalts. - */ - static getHostFrame(): Client.HostFrame; - /** - * Liefert den Nicknamen des Users, der gerade dieses HTML User Interface angezeigt bekommt. - */ - static getNick(): string; - /** - * Liefert den aktuellen ClientType des Nutzers, der gerade dieses HTML User Interface angezeigt bekommt. - */ - static getClientType(): ClientType; - /** - * Liefert die Id, die beim Laden von Skripten und Stylesheets an die URL angehängt wird, um sicherzustellen, dass eine neue Version - * der Datei vom Server geholt wird, statt die Datei aus dem Cache zu laden. - * - * Diese Id kann beim Einbinden eigener Ressourcen zum selben Zweck genutzt werden. - */ - static getCacheInvalidationId(): string; - /** - * Beinhaltet die JSON-Daten, die beim Erstellen des HTMLFile übergeben wurden. - */ - static pageData: Json; -} + namespace Client { + class Event { + /** + * @see https://developer.knuddels.de/docs/classes/Client.Event.html#method_Event + */ + constructor( + type: string, + data: KnuddelsEvent + ); + } + } -/** - * Klasse, mit der clientseitige Farbobjekte erstellt werden können. - */ -declare namespace Client { + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html + */ + namespace Client { + class HostFrame { + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_setTitle + */ + setTitle( + newTitle: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_setBackgroundColor + */ + setBackgroundColor( + newColor: Color, + durationMillis?: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_setIcons + * @since Applet: 9.0bwj, AppServer: 84904 + */ + setIcons( + ...path: string[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_setResizable + */ + setResizable( + resizable: boolean + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_focus + * @since Applet: 9.0bwj, AppServer: 84904 + */ + focus(): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_setSize + * @since Applet: 9.0bwj, AppServer: 84516 + */ + setSize( + width: number, + height: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_getAppViewMode + * @since Applet: 9.0byl + */ + getAppViewMode(): void; + /** + * @see https://developer.knuddels.de/docs/classes/Client.HostFrame.html#method_getBrowserType + * @since Applet: 9.0bzp + */ + getBrowserType(): void; + } + } + + /** + * @see https://developer.knuddels.de/docs/classes/ClientType.html + */ + class ClientType { + /** + * @see https://developer.knuddels.de/docs/classes/ClientType.html#property_Applet + */ + static readonly Applet: ClientType; + /** + * @see https://developer.knuddels.de/docs/classes/ClientType.html#property_Browser + */ + static readonly Browser: ClientType; + /** + * @see https://developer.knuddels.de/docs/classes/ClientType.html#property_Android + */ + static readonly Android: ClientType; + /** + * @see https://developer.knuddels.de/docs/classes/ClientType.html#property_IOS + */ + static readonly IOS: ClientType; + /** + * @see https://developer.knuddels.de/docs/classes/ClientType.html#property_Offline + */ + static readonly Offline: ClientType; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Color.html + */ class Color { /** - * Erzeugt ein Color-Objekt mit RGB-Werten. + * @see https://developer.knuddels.de/docs/classes/Color.html#method_fromRGB */ - static fromRGB(red: number, green: number, blue: number): Color; + static fromRGB( + red: number, + green: number, + blue: number + ): Color; /** - * Erzeugt ein Color-Objekt aus einem HexString. + * @see https://developer.knuddels.de/docs/classes/Color.html#method_fromRGBA */ - static fromHexString(colorString: string): Color; + static fromRGBA( + red: number, + green: number, + blue: number, + alpha: number + ): Color; /** - * Liefert den Rot-Anteil der Farbe als Zahl zwischen 0 und 255. + * @see https://developer.knuddels.de/docs/classes/Color.html#method_getAlpha */ - getRed(): number; + getAlpha(): number; /** - * Liefert den Grün-Anteil der Farbe als Zahl zwischen 0 und 255. - */ - getGreen(): number; - /** - * Liefert den Blau-Anteil der Farbe als Zahl zwischen 0 und 255. + * @see https://developer.knuddels.de/docs/classes/Color.html#method_getBlue */ getBlue(): number; /** - * Liefert die Farbe als in CSS nutzbaren HexString. + * @see https://developer.knuddels.de/docs/classes/Color.html#method_getGreen */ - asHexString(): string; + getGreen(): number; + /** + * @see https://developer.knuddels.de/docs/classes/Color.html#method_getRed + */ + getRed(): number; + /** + * @see https://developer.knuddels.de/docs/classes/Color.html#method_toKCode + */ + toKCode(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Color.html#method_asNumber + */ + asNumber(): number; + /** + * @see https://developer.knuddels.de/docs/classes/Color.html#method_fromNumber + */ + static fromNumber( + value: number + ): Color; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Dice.html + */ + class Dice { + /** + * @see https://developer.knuddels.de/docs/classes/Dice.html#method_Dice + */ + constructor( + count: number /* optional */, + value: number + ); + /** + * @see https://developer.knuddels.de/docs/classes/Dice.html#method_getAmount + */ + getAmount(): number; + /** + * @see https://developer.knuddels.de/docs/classes/Dice.html#method_getNumberOfSides + */ + getNumberOfSides(): number; + } + + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html + */ + class DiceConfiguration { + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_isUsingOpenThrow + */ + isUsingOpenThrow(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_isUsingPrivateThrow + */ + isUsingPrivateThrow(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_getDices + */ + getDices(): Dice[]; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_equals + */ + equals( + diceConfiguration: DiceConfiguration + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_getChatCommand + * @since AppServer 82248 + */ + getChatCommand(): string; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfiguration.html#method_toString + * @since AppServer 108781 + */ + toString(): string; + } + + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html + */ + class DiceConfigurationFactory { + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_addDice + */ + addDice( + dice: Dice + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_computeCurrentDiceCount + */ + computeCurrentDiceCount(): number; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_setUseOpenThrow + */ + setUseOpenThrow( + shouldUseOpenThrow: boolean + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_setShouldUsePrivateThrow + */ + setShouldUsePrivateThrow( + shouldUsePrivateThrow: boolean + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_getDiceConfiguration + */ + getDiceConfiguration(): DiceConfiguration; + /** + * @see https://developer.knuddels.de/docs/classes/DiceConfigurationFactory.html#method_fromString + */ + static fromString( + diceConfigurationString: string + ): DiceConfiguration; + } + + /** + * @see https://developer.knuddels.de/docs/classes/DiceEvent.html + */ + class DiceEvent { + /** + * @see https://developer.knuddels.de/docs/classes/DiceEvent.html#method_getUser + */ + getUser(): User; + /** + * @see https://developer.knuddels.de/docs/classes/DiceEvent.html#method_getDiceResult + */ + getDiceResult(): DiceResult; + } + + /** + * @see https://developer.knuddels.de/docs/classes/DiceResult.html + */ + class DiceResult { + /** + * @see https://developer.knuddels.de/docs/classes/DiceResult.html#method_getDiceConfiguration + */ + getDiceConfiguration(): DiceConfiguration; + /** + * @see https://developer.knuddels.de/docs/classes/DiceResult.html#method_getSingleDiceResults + */ + getSingleDiceResults(): SingleDiceResult[]; + /** + * @see https://developer.knuddels.de/docs/classes/DiceResult.html#method_totalSum + */ + totalSum(): number; + /** + * @see https://developer.knuddels.de/docs/classes/DiceResult.html#method_toString + * @since AppServer 108781 + */ + toString(): string; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Domain.html + */ + class Domain { + /** + * @see https://developer.knuddels.de/docs/classes/Domain.html#method_getDomainName + */ + getDomainName(): string; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html + */ + class ExternalServerAccess { + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_getAllAccessibleDomains + */ + getAllAccessibleDomains(): Domain[]; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_canAccessURL + */ + canAccessURL( + urlString: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_getURL + */ + getURL( + urlString: string, + parameters?: { + onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + } + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_postURL + */ + postURL( + urlString: string, + parameters?: { + onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + data?: Json; + } + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_touchURL + */ + touchURL( + urlString: string, + parameters?: { + onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + } + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerAccess.html#method_callURL + */ + callURL( + urlString: string, + parameters?: { + onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + method?: ("GET" | "POST"); + data?: Json; + } + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html + */ + class ExternalServerResponse { + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html#method_getURLString + */ + getURLString(): string; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html#method_getResponseCode + */ + getResponseCode(): number; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html#method_getHeaderFieldNames + * @since AppServer 108668 + */ + getHeaderFieldNames(): string[]; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html#method_getHeaderFields + */ + getHeaderFields(): { [key: string]: string[] }; + /** + * @see https://developer.knuddels.de/docs/classes/ExternalServerResponse.html#method_getHeaderFieldValues + * @since AppServer 108668 + */ + getHeaderFieldValues( + headerFieldName: string + ): string[]; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Gender.html + */ + class Gender { + /** + * @see https://developer.knuddels.de/docs/classes/Gender.html#property_Male + */ + static readonly Male: Gender; + /** + * @see https://developer.knuddels.de/docs/classes/Gender.html#property_Female + */ + static readonly Female: Gender; + /** + * @see https://developer.knuddels.de/docs/classes/Gender.html#property_Unknown + */ + static readonly Unknown: Gender; + } + + /** + * @see https://developer.knuddels.de/docs/classes/HTMLFile.html + */ + class HTMLFile { + /** + * @see https://developer.knuddels.de/docs/classes/HTMLFile.html#method_HTMLFile + */ + constructor( + assetPath: string, + pageData?: Json + ); + /** + * @see https://developer.knuddels.de/docs/classes/HTMLFile.html#method_getAssetPath + */ + getAssetPath(): string; + /** + * @see https://developer.knuddels.de/docs/classes/HTMLFile.html#method_getPageData + */ + getPageData(): Json; + } + + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html + */ + class KnuddelAccount { + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getKnuddelAmount + */ + getKnuddelAmount(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getKnuddelAmountUsed + */ + getKnuddelAmountUsed(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getKnuddelAmountUnused + */ + getKnuddelAmountUnused(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getTotalKnuddelAmountAppToUser + */ + getTotalKnuddelAmountAppToUser(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getTotalKnuddelAmountUserToApp + */ + getTotalKnuddelAmountUserToApp(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_hasEnough + */ + hasEnough( + knuddelAmount: KnuddelAmount + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_getUser + */ + getUser(): User; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAccount.html#method_use + */ + use( + knuddelAmount: KnuddelAmount, + displayReasonText: string, + parameters?: { + transferReason?: string; + onError?: (message: string) => void; + onSuccess?: () => void; + } + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html + */ + class KnuddelAmount { + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_KnuddelAmount + */ + constructor( + knuddel: number + ); + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_fromCents + */ + static fromCents( + knuddel: number + ): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_fromKnuddel + */ + static fromKnuddel( + knuddel: number + ): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_getKnuddelCents + */ + getKnuddelCents(): number; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_asNumber + */ + asNumber(): number; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_negate + */ + negate(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelAmount.html#method_isNegative + */ + isNegative(): boolean; + } + + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html + */ + class KnuddelPot { + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getId + */ + getId(): number; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getState + */ + getState(): KnuddelPotState; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getKnuddelAmountPerParticipant + */ + getKnuddelAmountPerParticipant(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getKnuddelAmountTotal + */ + getKnuddelAmountTotal(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getParticipants + */ + getParticipants(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getMaxFeeMultiplier + */ + getMaxFeeMultiplier(): number; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_setFee + */ + setFee( + feeUser: BotUser, + feeMultiplier: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getFeeUser + */ + getFeeUser(): User; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_getFeeMultiplier + */ + getFeeMultiplier(): number; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_seal + */ + seal(): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_refund + */ + refund( + reason?: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_addWinner + */ + addWinner( + user: User, + weight?: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPot.html#method_payout + */ + payout( + text?: string + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPotState.html + */ + class KnuddelPotState { + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPotState.html#property_Open + */ + static readonly Open: KnuddelPotState; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPotState.html#property_Sealed + */ + static readonly Sealed: KnuddelPotState; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelPotState.html#property_Closed + */ + static readonly Closed: KnuddelPotState; + } + + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html + */ + class KnuddelTransfer { + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_getSender + */ + getSender(): User; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_getReceiver + */ + getReceiver(): BotUser; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_getKnuddelAmount + */ + getKnuddelAmount(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_getTransferReason + */ + getTransferReason(): string; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_reject + */ + reject( + reason: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_accept + */ + accept(): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_canAddToPot + */ + canAddToPot( + pot: KnuddelPot + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_addToPot + */ + addToPot( + knuddelPot: KnuddelPot + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransfer.html#method_isProcessed + */ + isProcessed(): boolean; + } + + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransferDisplayType.html + */ + class KnuddelTransferDisplayType { + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransferDisplayType.html#property_Public + */ + static readonly Public: KnuddelTransferDisplayType; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransferDisplayType.html#property_Private + */ + static readonly Private: KnuddelTransferDisplayType; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelTransferDisplayType.html#property_Post + */ + static readonly Post: KnuddelTransferDisplayType; + } + + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html + */ + class KnuddelsServer { + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getDefaultBotUser + */ + static getDefaultBotUser(): BotUser; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getPersistence + */ + static getPersistence(): AppPersistence; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getChannel + */ + static getChannel(): Channel; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getUserAccess + */ + static getUserAccess(): UserAccess; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getPaymentAccess + * @since AppServer 108571, ChatServer 108571 + */ + static getPaymentAccess(): PaymentAccess; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getExternalServerAccess + */ + static getExternalServerAccess(): ExternalServerAccess; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_refreshHooks + */ + static refreshHooks(): void; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getDefaultLogger + */ + static getDefaultLogger(): Logger; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getFullImagePath + */ + static getFullImagePath( + imageName: string + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getFullSystemImagePath + */ + static getFullSystemImagePath( + imageName: string + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getChatServerInfo + */ + static getChatServerInfo(): ChatServerInfo; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getAppServerInfo + */ + static getAppServerInfo(): AppServerInfo; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getAppAccess + */ + static getAppAccess(): AppAccess; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_createKnuddelPot + */ + static createKnuddelPot( + knuddelAmount: KnuddelAmount, + params?: { + payoutTimeoutMinutes?: number; + shouldSealPot?: (pot: KnuddelPot) => boolean; + onPotSealed?: (pot: KnuddelPot) => void; + } + ): KnuddelPot; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getKnuddelPot + */ + static getKnuddelPot( + id: number + ): (KnuddelPot|null); + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getAllKnuddelPots + */ + static getAllKnuddelPots(): KnuddelPot[]; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getToplistAccess + */ + static getToplistAccess(): ToplistAccess; + /** + * @see https://developer.knuddels.de/docs/classes/KnuddelsServer.html#method_getAppProfileEntryAccess + */ + static getAppProfileEntryAccess(): AppProfileEntryAccess; + } + + /** + * @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html + */ + class LoadConfiguration { + /** + * @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setBackgroundColor + */ + setBackgroundColor( + color: Color + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setBackgroundImage + */ + setBackgroundImage( + imageUrl: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setText + */ + setText( + text: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setLoadingIndicatorImage + */ + setLoadingIndicatorImage( + imageUrl: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setForegroundColor + */ + setForegroundColor( + color: Color + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/LoadConfiguration.html#method_setEnabled + */ + setEnabled( + enabled: boolean + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Logger.html + */ + class Logger { + /** + * @see https://developer.knuddels.de/docs/classes/Logger.html#method_debug + */ + debug( + ...msg: any[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Logger.html#method_info + */ + info( + ...msg: any[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Logger.html#method_warn + */ + warn( + ...msg: any[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Logger.html#method_error + */ + error( + ...msg: any[] + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Logger.html#method_fatal + */ + fatal( + ...msg: any[] + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Message.html + */ + class Message { + /** + * @see https://developer.knuddels.de/docs/classes/Message.html#method_getAuthor + */ + getAuthor(): User; + /** + * @see https://developer.knuddels.de/docs/classes/Message.html#method_getText + */ + getText(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Message.html#method_getCreationDate + */ + getCreationDate(): Date; + } + + /** + * @see https://developer.knuddels.de/docs/classes/OwnAppInstance.html + */ + class OwnAppInstance { + /** + * @see https://developer.knuddels.de/docs/classes/OwnAppInstance.html#method_getOnlineUsers + * @since AppServer 82560 + */ + getOnlineUsers( + otherAppInstance: AppInstance, + ...userType: UserType[] + ): User[]; + } + + /** + * @see https://developer.knuddels.de/docs/classes/PaymentAccess.html + * @since AppServer 108571, ChatServer 108571 + */ + class PaymentAccess { + /** + * @see https://developer.knuddels.de/docs/classes/PaymentAccess.html#method_startKnuddelPurchase + * @since AppServer 108571, ChatServer 108571 + */ + startKnuddelPurchase( + user: User, + amount: KnuddelAmount, + parameters?: { + customMessage?: string; + transferReason?: string; + toAccount?: boolean; + } + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html + */ + class Persistence { + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_hasString + */ + hasString( + key: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_setString + */ + setString( + key: string, + value: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_getString + */ + getString( + key: string, + defaultValue?: string + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_deleteString + */ + deleteString( + key: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_hasNumber + */ + hasNumber( + key: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_setNumber + */ + setNumber( + key: string, + value: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_addNumber + */ + addNumber( + key: string, + value: number + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_getNumber + */ + getNumber( + key: string, + defaultValue?: number + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_deleteNumber + */ + deleteNumber( + key: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_hasObject + */ + hasObject( + key: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_setObject + */ + setObject( + key: string, + object: (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable) + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_getObject + */ + getObject( + key: string, + defaultValue?: (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable) + ): (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable); + /** + * @see https://developer.knuddels.de/docs/classes/Persistence.html#method_deleteObject + */ + deleteObject( + key: string + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/PrivateMessage.html + */ + class PrivateMessage extends Message { + /** + * @see https://developer.knuddels.de/docs/classes/PrivateMessage.html#method_getReceivingUsers + */ + getReceivingUsers(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/PrivateMessage.html#method_sendReply + */ + sendReply( + text: string + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/PublicActionMessage.html + */ + class PublicActionMessage extends Message { + } + + /** + * @see https://developer.knuddels.de/docs/classes/PublicEventMessage.html + */ + class PublicEventMessage extends Message { + } + + /** + * @see https://developer.knuddels.de/docs/classes/PublicMessage.html + */ + class PublicMessage extends Message { + } + + /** + * @see https://developer.knuddels.de/docs/classes/Quest.html + */ + class Quest { + /** + * @see https://developer.knuddels.de/docs/classes/Quest.html#method_setSolved + * @since AppServer 82290, ChatServer 82290 + */ + setSolved( + count?: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Quest.html#method_getQuestKey + * @since AppServer 82290, ChatServer 82290 + */ + getQuestKey(): string; + } + + /** + * @see https://developer.knuddels.de/docs/classes/QuestAccess.html + */ + class QuestAccess { + /** + * @see https://developer.knuddels.de/docs/classes/QuestAccess.html#method_getQuests + * @since AppServer 82290, ChatServer 82290 + */ + getQuests(): Quest[]; + /** + * @see https://developer.knuddels.de/docs/classes/QuestAccess.html#method_hasQuest + * @since AppServer 82290, ChatServer 82290 + */ + hasQuest( + questKey: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/QuestAccess.html#method_getQuest + * @since AppServer 82290, ChatServer 82290 + */ + getQuest( + questKey: string + ): (Quest|null); + /** + * @see https://developer.knuddels.de/docs/classes/QuestAccess.html#method_getUser + * @since AppServer 82290, ChatServer 82290 + */ + getUser(): User; + } + + /** + * @see https://developer.knuddels.de/docs/classes/RandomOperations.html + */ + class RandomOperations { + /** + * @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_nextInt + */ + static nextInt( + minValue: number /* optional */, + maxValue: number + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_nextInts + */ + static nextInts( + minValue: number /* optional */, + maxValue: number, + count: number, + onlyDifferentNumbers: boolean + ): number[]; + /** + * @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_flipTrue + */ + static flipTrue( + truePropability: number + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_getRandomObject + */ + static getRandomObject( + objects: T[] + ): T; + /** + * @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_shuffleObjects + */ + static shuffleObjects( + objects: T[] + ): T[]; + /** + * @see https://developer.knuddels.de/docs/classes/RandomOperations.html#method_getRandomString + * @since AppServer 92699 + */ + static getRandomString( + length: number, + allowedCharacters?: string + ): string; + } + + /** + * @see https://developer.knuddels.de/docs/classes/RootAppInstance.html + */ + class RootAppInstance extends AppInstance { + /** + * @see https://developer.knuddels.de/docs/classes/RootAppInstance.html#method_updateApp + */ + updateApp( + message: string /* optional */, + logMessage?: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/RootAppInstance.html#method_cancelUpdateApp + * @since AppServer 98117 + */ + cancelUpdateApp(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/RootAppInstance.html#method_stopApp + */ + stopApp( + message: string /* optional */, + logMessage?: string + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ServerInfo.html + */ + class ServerInfo { + /** + * @see https://developer.knuddels.de/docs/classes/ServerInfo.html#method_getServerId + */ + getServerId(): string; + /** + * @see https://developer.knuddels.de/docs/classes/ServerInfo.html#method_getRevision + */ + getRevision(): number; + } + + /** + * @see https://developer.knuddels.de/docs/classes/SingleDiceResult.html + */ + class SingleDiceResult { + /** + * @see https://developer.knuddels.de/docs/classes/SingleDiceResult.html#method_getDice + */ + getDice(): Dice; + /** + * @see https://developer.knuddels.de/docs/classes/SingleDiceResult.html#method_valuesRolled + */ + valuesRolled(): number[]; + /** + * @see https://developer.knuddels.de/docs/classes/SingleDiceResult.html#method_sum + */ + sum(): number; + } + + /** + * @see https://developer.knuddels.de/docs/classes/String.html + */ + interface String { + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_escapeKCode + */ + escapeKCode(): string; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_stripKCode + */ + stripKCode(): string; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_startsWith + */ + startsWith( + prefix: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_endsWith + */ + endsWith( + suffix: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_getPixelWidth + */ + getPixelWidth( + fontSize: number, + isBold: boolean + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_limitString + */ + limitString( + fontSize: number, + isBold: boolean, + maxPixelWidth: number, + abbreviationMarker?: string + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_contains + */ + contains( + needle: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_minimalConversionCost + * @since AppServer 82271 + */ + minimalConversionCost( + otherString: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_hasOnlyNicknameCharacters + * @since AppServer 82271 + */ + hasOnlyNicknameCharacters(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_hasOnlyDigits + * @since AppServer 82271 + */ + hasOnlyDigits(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_hasOnlyAlphanumericalAndWhitespaceCharacters + * @since AppServer 82271 + */ + hasOnlyAlphanumericalAndWhitespaceCharacters(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_isEmpty + * @since AppServer 92695 + */ + isEmpty(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_toCamelCase + * @since AppServer 92695 + */ + toCamelCase(): string; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_capitalize + * @since AppServer 92695 + */ + capitalize(): string; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_replaceAll + */ + replaceAll( + search: string|RegExp, + replacement: string + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/String.html#method_isOk + * @since ChatServer 82262, AppServer 82262 + */ + isOk(): boolean; + } + + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html + */ + class Toplist { + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_getUserPersistenceNumberKey + */ + getUserPersistenceNumberKey(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_getDisplayName + */ + getDisplayName(): string; + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_getChatCommand + */ + getChatCommand( + user_or_userId?: (User|number) + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_getLabel + */ + getLabel( + user_or_userId: (User|number) + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_addLabelChangeListener + */ + addLabelChangeListener( + listener: (labelChangeEvent: ToplistLabelChangeEvent) => void + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_removeLabelChangeListener + */ + removeLabelChangeListener( + listener: (labelChangeEvent: ToplistLabelChangeEvent) => void + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_addRankChangeListener + */ + addRankChangeListener( + listener: (rankChangeEvent: ToplistRankChangeEvent) => void + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/Toplist.html#method_removeRankChangeListener + */ + removeRankChangeListener( + listener: (rankChangeEvent: ToplistRankChangeEvent) => void + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ToplistAccess.html + */ + class ToplistAccess { + /** + * @see https://developer.knuddels.de/docs/classes/ToplistAccess.html#method_getAllToplists + */ + getAllToplists(): Toplist[]; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistAccess.html#method_getToplist + */ + getToplist( + userPersistenceNumberKey: string + ): Toplist; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistAccess.html#method_removeToplist + */ + removeToplist( + toplist: Toplist + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistAccess.html#method_createOrUpdateToplist + */ + createOrUpdateToplist( + userPersistenceNumberKey: string, + displayName: string, + parameters?: { + labelMapping?: { [minValue: string]: string }; + ascending?: boolean; + } + ): Toplist; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ToplistDisplayType.html + */ + class ToplistDisplayType { + /** + * @see https://developer.knuddels.de/docs/classes/ToplistDisplayType.html#property_Label + */ + static readonly Label: ToplistDisplayType; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistDisplayType.html#property_Value + */ + static readonly Value: ToplistDisplayType; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistDisplayType.html#property_LabelAndRank + */ + static readonly LabelAndRank: ToplistDisplayType; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistDisplayType.html#property_ValueAndRank + */ + static readonly ValueAndRank: ToplistDisplayType; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html + */ + class ToplistLabelChangeEvent { + /** + * @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getToplist + */ + getToplist(): Toplist; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getOldLabel + */ + getOldLabel(): string; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getNewLabel + */ + getNewLabel(): string; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getUser + */ + getUser(): User; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getOldValue + */ + getOldValue(): number; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistLabelChangeEvent.html#method_getNewValue + */ + getNewValue(): number; + } + + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html + */ + class ToplistRankChangeEvent { + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getToplist + */ + getToplist(): Toplist; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getOldRank + */ + getOldRank(): number; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getNewRank + */ + getNewRank(): number; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getUser + */ + getUser(): User; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getUsersOvertook + */ + getUsersOvertook(): User[]; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getOldValue + */ + getOldValue(): number; + /** + * @see https://developer.knuddels.de/docs/classes/ToplistRankChangeEvent.html#method_getNewValue + */ + getNewValue(): number; + } + + /** + * @see https://developer.knuddels.de/docs/classes/User.html + */ + class User { + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getUserId + */ + getUserId(): number; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getNick + */ + getNick(): string; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getAge + */ + getAge(): number; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getGender + */ + getGender(): Gender; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getRegDate + */ + getRegDate(): Date; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getUserStatus + */ + getUserStatus(): UserStatus; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getUserType + */ + getUserType(): UserType; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getClientType + */ + getClientType(): ClientType; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_canShowAppViewMode + */ + canShowAppViewMode( + mode: AppViewMode + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_canSendAppContent + */ + canSendAppContent( + appContent: AppContent + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isInTeam + */ + isInTeam( + teamName: string, + subTeamName?: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getPersistence + */ + getPersistence(): UserPersistence; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_sendPrivateMessage + */ + sendPrivateMessage( + message: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_sendPostMessage + */ + sendPostMessage( + topic: string, + text: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isChannelOwner + */ + isChannelOwner(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isLikingChannel + */ + isLikingChannel(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isChannelCoreUser + * @since AppServer 92701, ChatServer 92701 + */ + isChannelCoreUser(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isAppManager + */ + isAppManager(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isMuted + */ + isMuted(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isColorMuted + */ + isColorMuted(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isLocked + */ + isLocked(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isChannelModerator + */ + isChannelModerator(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isEventModerator + */ + isEventModerator(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isAppDeveloper + */ + isAppDeveloper(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getProfileLink + */ + getProfileLink( + displayText?: string + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isOnlineInChannel + */ + isOnlineInChannel(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getKnuddelAmount + */ + getKnuddelAmount(): KnuddelAmount; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isOnline + */ + isOnline(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getReadme + */ + getReadme(): string; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getOnlineMinutes + */ + getOnlineMinutes(): number; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isAway + */ + isAway(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_hasProfilePhoto + */ + hasProfilePhoto(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_sendAppContent + */ + sendAppContent( + appContent: AppContent + ): AppContentSession; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getAppContentSessions + */ + getAppContentSessions(): AppContentSession[]; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getAppContentSession + */ + getAppContentSession( + appViewMode: AppViewMode + ): AppContentSession; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_equals + */ + equals( + user: User + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getProfilePhoto + */ + getProfilePhoto( + width: number, + height: number + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getQuestAccess + * @since AppServer 82290, ChatServer 82290 + */ + getQuestAccess(): QuestAccess; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isStreamingVideo + */ + isStreamingVideo(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getKnuddelAccount + */ + getKnuddelAccount(): KnuddelAccount; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getChannelTalkPermission + */ + getChannelTalkPermission(): ChannelTalkPermission; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isProfilePhotoVerified + */ + isProfilePhotoVerified(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_isAgeVerified + */ + isAgeVerified(): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_addNicklistIcon + */ + addNicklistIcon( + imagePath: string, + imageWidth: number + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_removeNicklistIcon + */ + removeNicklistIcon( + imagePath: string + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_triggerDice + * @since AppServer 89159, ChatServer 89159 + */ + triggerDice( + diceConfiguration: DiceConfiguration + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/User.html#method_getAuthenticityClassification + * @since AppServer 94663, ChatServer 94663 + */ + getAuthenticityClassification(): AuthenticityClassification; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html + */ + class UserAccess { + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_getUserId + */ + getUserId( + nick: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_exists + */ + exists( + nick: string + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_isUserDeleted + */ + isUserDeleted( + userId: number + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_mayAccess + */ + mayAccess( + userId: number + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_getUserById + */ + getUserById( + userId: number + ): User; + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_getNick + */ + getNick( + userId: number + ): string; + /** + * @see https://developer.knuddels.de/docs/classes/UserAccess.html#method_eachAccessibleUser + */ + eachAccessibleUser( + callback: (user: User, index: number, accessibleUserCount: number, key?: string) => boolean, + parameters?: { + onStart?: (accessibleUserCount: number, key?: string) => void; + onEnd?: (accessibleUserCount: number, key?: string) => void; + } + ): void; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistence.html + */ + class UserPersistence extends Persistence { + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistence.html#method_deleteAllNumbers + * @since AppServer 88569 + */ + deleteAllNumbers(): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistence.html#method_deleteAllObjects + * @since AppServer 88569 + */ + deleteAllObjects(): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistence.html#method_deleteAllStrings + * @since AppServer 88569 + */ + deleteAllStrings(): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistence.html#method_deleteAll + * @since AppServer 88569 + */ + deleteAll(): number; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumberEntry.html + */ + class UserPersistenceNumberEntry { + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumberEntry.html#method_getUser + */ + getUser(): User; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumberEntry.html#method_getValue + */ + getValue(): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumberEntry.html#method_getRank + */ + getRank(): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumberEntry.html#method_getPosition + */ + getPosition(): number; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html + */ + class UserPersistenceNumbers { + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getSum + */ + static getSum( + key: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_deleteAll + */ + static deleteAll( + key: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getCount + */ + static getCount( + key: string, + parameters?: { + minimumValue?: number; + maximumValue?: number; + } + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_updateKey + */ + static updateKey( + oldKeyName: string, + newKeyName: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_updateValue + */ + static updateValue( + key: string, + oldValue: number, + newValue: number + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_addNumber + */ + static addNumber( + key: string, + value: number, + parameters?: { + minimumValue?: number; + maximumValue?: number; + targetUsers?: User[]; + } + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getSortedEntries + */ + static getSortedEntries( + key: string, + parameters?: { + ascending?: boolean; + count?: number; + page?: number; + minimumValue?: number; + maximumValue?: number; + } + ): UserPersistenceNumberEntry[]; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getSortedEntriesAdjacent + */ + static getSortedEntriesAdjacent( + key: string, + user_or_userId: (User|number), + parameters?: { + ascending?: boolean; + count?: number; + } + ): UserPersistenceNumberEntry[]; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getPosition + */ + static getPosition( + key: string, + user_or_userId: (User|number), + parameters?: { + ascending?: boolean; + minimumValue?: number; + } + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getRank + */ + static getRank( + key: string, + user_or_userId: (User|number), + parameters?: { + ascending?: boolean; + minimumValue?: number; + } + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_each + */ + static each( + key: string, + callback: (user: User, value: number, index: number, totalCount: number, key: string) => boolean, + parameters?: { + ascending?: boolean; + minimumValue?: number; + maximumValue?: number; + maximumCount?: number; + onStart?: (totalCount: number, key: string) => void; + onEnd?: (totalCount: number, key: string) => void; + } + ): void; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceNumbers.html#method_getAllKeys + * @since AppServer 82483 + */ + static getAllKeys( + filterKey?: string + ): string[]; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceObjects.html + */ + class UserPersistenceObjects { + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceObjects.html#method_deleteAll + * @since AppServer 82478 + */ + static deleteAll( + key: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceObjects.html#method_getAllKeys + * @since AppServer 82483 + */ + static getAllKeys( + filterKey?: string + ): string[]; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceStrings.html + */ + class UserPersistenceStrings { + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceStrings.html#method_exists + * @since AppServer 88571 + */ + static exists( + key: string, + value: string, + ignoreCase?: boolean + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceStrings.html#method_deleteAll + * @since AppServer 82478 + */ + static deleteAll( + key: string + ): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserPersistenceStrings.html#method_getAllKeys + * @since AppServer 82483 + */ + static getAllKeys( + filterKey?: string + ): string[]; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html + */ + class UserStatus { + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#method_getNumericStatus + */ + getNumericStatus(): number; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#method_isAtLeast + */ + isAtLeast( + otherUserStatus: UserStatus + ): boolean; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_Newbie + */ + static readonly Newbie: UserStatus; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_Family + */ + static readonly Family: UserStatus; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_Stammi + */ + static readonly Stammi: UserStatus; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_HonoryMember + */ + static readonly HonoryMember: UserStatus; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_Admin + */ + static readonly Admin: UserStatus; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_SystemBot + */ + static readonly SystemBot: UserStatus; + /** + * @see https://developer.knuddels.de/docs/classes/UserStatus.html#property_Sysadmin + */ + static readonly Sysadmin: UserStatus; + } + + /** + * @see https://developer.knuddels.de/docs/classes/UserType.html + */ + class UserType { + /** + * @see https://developer.knuddels.de/docs/classes/UserType.html#property_AppBot + */ + static readonly AppBot: UserType; + /** + * @see https://developer.knuddels.de/docs/classes/UserType.html#property_SystemBot + */ + static readonly SystemBot: UserType; + /** + * @see https://developer.knuddels.de/docs/classes/UserType.html#property_Human + */ + static readonly Human: UserType; + } + + /** + * @see https://developer.knuddels.de/docs/classes/VideoChannelData.html + */ + class VideoChannelData { + /** + * @see https://developer.knuddels.de/docs/classes/VideoChannelData.html#method_getStreamingVideoUsers + */ + getStreamingVideoUsers(): User[]; } } - -/** - * Klasse, die es ermöglicht ein Event via Client/dispatchEvent:method zu versenden. - */ -declare namespace Client { - class Event { - /** - * Erzeugt ein Event. - */ - constructor(type: string, data: KnuddelsEvent); - } -} - -/** - * Klasse, die es ermöglicht den Inhalte zu steuern, die im Bereich liegen, der das HTML User Interface hostet. - */ -declare namespace Client { - class HostFrame { - /** - * Setzt den Titel der Seite im gezoomten Modus (nur Android). - */ - setTitle(newTitle: string): void; - /** - * Ändert die sichtbare Hintergrundfarbe des Hostframes animiert. (Android-only) - */ - setBackgroundColor(newColor: Color, durationMillis?: number): void; - /** - * Setzt die Icons, die als Fenster-Icon angezeigt werden sollen. (Applet-only, nur mit AppViewMode.Popup) - * Die Bilder müssen von groß nach klein sortiert sein. Die größeren Bilder werden (je nach System) automatisch dann eingesetzt, - * wenn größere Bilder benötigt werden (z.B. in der Task-Leiste, oder beim Alt+Tab Fenster-Wechsel). - * @since Applet: 9.0bwj, AppServer: 84904 - */ - setIcons(...path: string[]): void; - /** - * Setzt, ob das Fenster resizable ist. (Applet-only, nur mit AppViewMode.Popup) - */ - setResizable(resizable: boolean): void; - /** - * Bringt das Fenster der App (App-Popup bzw. Chat-Fenster) in den Vordergrund. (Applet-only) - * @since Applet: 9.0bwj, AppServer: 84904 - */ - focus(): void; - /** - * Ändert die Größe des App-Fensters (AppViewMode.Popup) bzw. App-Overlays (AppViewMode.Overlay). - * @since Applet: 9.0bwj, AppServer: 84516 - */ - setSize(width: number, height: number): void; - } -} - -/** - * ClientType repräsentiert die Art der Chat-Verbindung des Users. - * - * Eine Instanz von ClientType erhält man über das User-Objekt - * mit user.getClientType() - */ -declare class ClientType { - /** - * Der User ist mit dem Java Applet im Chat. - */ - static readonly Applet: ClientType; - /** - * Der User ist mit dem Browser im Chat (Mini-Chat, HTML-Chat). - */ - static readonly Browser: ClientType; - /** - * Der User ist mit der Android-App im Chat. - */ - static readonly Android: ClientType; - /** - * Der User ist mit der iOS-App im Chat. - */ - static readonly IOS: ClientType; - /** - * Der User ist nicht im Chat. - */ - static readonly Offline: ClientType; -} - -/** - * Klasse, mit der serverseitige Farbobjekte erstellt werden können. - */ -declare class Color { - /** - * Erzeugt ein serverseitiges Color-Objekt mit RGB-Werten. - * Als Alpha-Wert wird automatisch 255 genutzt. - */ - static fromRGB(red: number, green: number, blue: number): Color; - /** - * Erzeugt ein serverseitiges Color-Objekt mit RGBA-Werten. - */ - static fromRGBA(red: number, green: number, blue: number, alpha: number): Color; - /** - * Liefert den Alpha-Wert der Farbe als Zahl zwischen 0 und 255. - */ - getAlpha(): number; - /** - * Liefert den Blau-Anteil der Farbe als Zahl zwischen 0 und 255. - */ - getBlue(): number; - /** - * Liefert den Grün-Anteil der Farbe als Zahl zwischen 0 und 255. - */ - getGreen(): number; - /** - * Liefert den Rot-Anteil der Farbe als Zahl zwischen 0 und 255. - */ - getRed(): number; - /** - * Liefert die Farbe als KCode zurück. - */ - toKCode(): string; - /** - * Liefert die numerische Repräsentation der Farbe zurück. - */ - asNumber(): number; - /** - * Erzeugt ein serverseitiges Color-Objekt aus der numerischen Repräsentation einer Farbe. - */ - static fromNumber(value: number): Color; -} - -/** - * Eine Instanz von Dice repräsentiert die Anzahl an Würfeln von einerm bestimmten Typ. - */ -declare class Dice { - /** - * Erzeugt ein Dice-Objekt mit der übergebenen Anzahl Würfel und Augenzahl. - */ - constructor(count: number /* optional */, value: number); - /** - * Liefert die Anzahl der Würfel. - */ - getAmount(): number; - /** - * Liefert die Anzahl der Seiten der Würfel. - */ - getNumberOfSides(): number; -} - -/** - * Eine Instanz von DiceConfiguration repräsentiert eindeutig eine Konfiguration zum würfeln. - * Wurde gewürfelt, so können die Konfigurationen verglichen werden, um zu prüfen, ob exakt die Würfel - * gewürfelt wurden, die gewürfelt werden sollten. - */ -declare class DiceConfiguration { - /** - * Informiert, ob es sich um einen offenen Würfelwurf handelt. - * Offene Würfelwürfe sind speziell. Falls die Augenzahl des Würfels die Maximalsumme zeigt, - * so wird noch einmal gewürfelt und die neue Zahl dazu addiert, solange bis der Würfel - * nicht mehr die Maximalsumme zeigt. - * - * Beispiel: /diceo 1w4 -> 4 -> 4 -> 3 = 11 - */ - isUsingOpenThrow(): boolean; - /** - * Informiert darüber, ob die Würfel privat geworfen worden sind. - * Würfelwürfe zählen als privat, wenn am Ende des Würfelbefehls ein Ausrufezeichen steht. - * Beispiel: /dice 10w2! - */ - isUsingPrivateThrow(): boolean; - /** - * Liefert ein Array mit Würfeln, mit denen gewürfelt wurde. - */ - getDices(): Dice[]; - /** - * Vergleicht, ob zwei Konfigurationen inhaltlich identisch sind - */ - equals(diceConfiguration: DiceConfiguration): boolean; - /** - * Liefert den Befehl, der im Chat eingegeben werden kann, um einen Wurf auszuführen, - * der zur DiceConfiguration passt. - * @since AppServer 82248 - */ - getChatCommand(): string; -} - -/** - * Eine Instanz einer DiceConfigurationFactory kann zur Unterstützung genutzt werden, um eine - * DiceConfiguration zu erzeugen. - */ -declare class DiceConfigurationFactory { - /** - * Fügt der Konfiguration einen Würfel hinzu. - */ - addDice(dice: Dice): void; - /** - * Liefert die Anzahl der Würfel, die zur Konfiguration gehören. - */ - computeCurrentDiceCount(): number; - /** - * Setzt die Information, ob ein offener Wurf oder ein normaler Wurf stattfinden soll. - * Offene Würfelwürfe sind speziell. Falls die Augenzahl des Würfels die Maximalsumme zeigt, - * so wird noch einmal gewürfelt und die neue Zahl dazu addiert, solange bis der Würfel - * nicht mehr die Maximalsumme zeigt. - * - * Beispiel: /diceo 1w4 -> 4 -> 4 -> 3 = 11 - */ - setUseOpenThrow(shouldUseOpenThrow: boolean): void; - /** - * Setzt die Information, ob der Würfelwurf privat stattfinden soll. - */ - setShouldUsePrivateThrow(shouldUsePrivateThrow: boolean): void; - /** - * Liefert die erzeugte Würfelkonfiguration. - */ - getDiceConfiguration(): DiceConfiguration; - /** - * Erzeugt eine Würfelkonfiguration. - */ - static fromString(diceConfigurationString: string): DiceConfiguration; -} - -/** - * Wird in der App die Methode onUserDiced überschrieben, so erhält diese bei jedem Würfelwurf ein DiceEvent. - * Ein DiceEvent ermöglicht einem detaillierte Informationen rund um diesen Würfelwurf in Erfahrung zu bringen. - */ -declare class DiceEvent { - /** - * Liefert den Nutzer, der gewürfelt hat. - */ - getUser(): User; - /** - * Liefert das DiceResult des Würfelwurfs. - */ - getDiceResult(): DiceResult; -} - -/** - * Ein DiceResult beinhaltet konkrete Informationen über einen Würfelwurf. - */ -declare class DiceResult { - /** - * Liefert die Konfiguration mit der gewürfelt wurde. - */ - getDiceConfiguration(): DiceConfiguration; - /** - * Liefert ein Array mit Details zu den einzelnen Ergebnissen pro Würfeltyp. - */ - getSingleDiceResults(): SingleDiceResult[]; - /** - * Liefert die Summe der Augenzahlen aller Würfel - */ - totalSum(): number; -} - -/** - * Die Instanz einer Domain beinhaltet alle relevanten Informationen zur Domain. - */ -declare class Domain { - /** - * Liefert ein den Domain-Namen der aktuellen Domain. - */ - getDomainName(): string; -} - -/** - * Die Instanz von ExternalServerAccess erhält man über die KnuddelsServer.getExternalServerAccess(). - * Damit der Zugriff auf einen externern Server funktioniert, muss auf dem Server eine Datei knuddelsAccess.txt abgelegt werden, die die FTP-User-ID des Entwicklers enthält. - */ -declare class ExternalServerAccess { - /** - * Liefert eine Liste aller zugreifbaren Domains - */ - getAllAccessibleDomains(): Domain[]; - /** - * Prüft den Zugriff auf eine bestimmte URL. Wird je Kombination von "Protokoll + Host + Port" geprüft.
- * Beispiel: http://www.example.de:8080 - */ - canAccessURL(urlString: string): boolean; - /** - * Macht einen GET-Request auf die übergebene URL und liefert den Inhalt zurück. - * Diese Methode ist eine Convenience-Methode für externalServerAccess.callURL(). - */ - getURL( - urlString: string, - parameters?: { - onSuccess?(responseData: string, externalServerResponse: ExternalServerResponse): void; - onFailure?(responseData: string, externalServerResponse: ExternalServerResponse): void; - }): void; - /** - * Macht einen POST-Request auf die übergebene URL und liefert den Inhalt zurück. - * Diese Methode ist eine Convenience-Methode für externalServerAccess.callURL(). - */ - postURL( - urlString: string, - parameters?: { - onSuccess?(responseData: string, externalServerResponse: ExternalServerResponse): void; - onFailure?(responseData: string, externalServerResponse: ExternalServerResponse): void; - data?: Json; - }): void; - /** - * Macht einen GET-Request auf die übergebene URL. Im Gegensatz zum GET-Request wird der Inhalt der Webseite wird nicht ausgelesen. - * Aus diesem Grund ist diese Methode schneller. - * Diese Methode ist eine Convenience-Methode für externalServerAccess.callURL(). - */ - touchURL( - urlString: string, - parameters?: { - onSuccess?(responseData: string, externalServerResponse: ExternalServerResponse): void; - onFailure?(responseData: string, externalServerResponse: ExternalServerResponse): void; - }): void; - /** - * Macht einen Request auf die übergebene URL. - */ - callURL( - urlString: string, - parameters?: { - onSuccess?(responseData: string, externalServerResponse: ExternalServerResponse): void; - onFailure?(responseData: string, externalServerResponse: ExternalServerResponse): void; - method?: ("GET" | "POST"); - data?: Json; - }): void; -} - -/** - * Die Instanz von ExternalServerResponse erhält in den onSuccess- und onFailure-Callbacks der Methoden von - * ExternalServerAccess. Es enthält alle notwendigen Daten zum Verarbeiten. - */ -declare class ExternalServerResponse { - /** - * Liefert die abgefragte URL. - */ - getURLString(): string; - /** - * Liefert den HTTP-Statuscode der Seite. - */ - getResponseCode(): number; - /** - * Liefert ein Objekt, das die Headerdaten der Antwort enthält. - */ - getHeaderFields(): { [key: string]: string[] }; -} - -/** - * Gender repräsentiert das Geschlecht eines User. - */ -declare class Gender { - /** - * Das Geschlecht ist männlich. - */ - static readonly Male: Gender; - /** - * Das Geschlecht ist weiblich. - */ - static readonly Female: Gender; - /** - * Das Geschlecht ist nicht bekannt. - */ - static readonly Unknown: Gender; -} - -/** - * Repräsentiert eine HTML-Datei, die auf dem Server im Ordner /www liegt. - */ -declare class HTMLFile { - /** - * - */ - constructor(assetPath: string, pageData?: Json); - /** - * Liefert den Pfad, der beim Anlegen der HTMLFile-Instanz genutzt wurde. - */ - getAssetPath(): string; - /** - * Liefert die pageData, die beim Anlegen der HTMLFile-Instanz genutzt wurden. - */ - getPageData(): Json; -} - -/** - * Eine Instanz von KnuddelAccount ermöglicht den Zugriff auf die freigegebenen Knuddel - * eines bestimmten User. Knuddel können abgezogen und addiert werden. - */ -declare class KnuddelAccount { - /** - * Liefert den KnuddelAmount eines Users, - * über den die App gerade frei verfügen kann. - */ - getKnuddelAmount(): KnuddelAmount; - /** - * Liefert den KnuddelAmount aus dem KnuddelAccount, - * der bereits von der App genutzt wurde. - * Beim Auszahlen dieser Knuddel aus dem KnuddelAccount an den - * User fallen Steuern an. - */ - getKnuddelAmountUsed(): KnuddelAmount; - /** - * Liefert den KnuddelAmount aus dem KnuddelAccount, - * der noch nicht von der App genutzt wurde. - * Beim Auszahlen dieser Knuddel aus dem KnuddelAccount an den - * User fallen keine Steuern an. - */ - getKnuddelAmountUnused(): KnuddelAmount; - /** - * Liefert die Summe aller Transfers, die die App an diesen KnuddelAccount bzw. User überwiesen hat. - */ - getTotalKnuddelAmountAppToUser(): KnuddelAmount; - /** - * Liefert die Summe aller Transfers, die die App von diesem KnuddelAccount bzw. User abgebucht/erhalten hat. - */ - getTotalKnuddelAmountUserToApp(): KnuddelAmount; - /** - * Liefert die Information, ob in diesem Moment genug Knuddel verfügbar sind. - */ - hasEnough(knuddelAmount: KnuddelAmount): boolean; - /** - * Liefert den Nutzer, dem der KnuddelAccount gehört. - */ - getUser(): User; - /** - * Versucht eine bestimmte Menge Knuddel zu verwenden. Dies ist nur möglich, wenn der User auf seinem KnuddelAccount - * genug Knuddel besitzt und online im Channel ist. - * Vom KnuddelAccount des Besitzer des Channel können Knuddel auch abgebucht werden, wenn dieser nicht im Channel online ist. - * - * Ist das Event App.onBeforeKnuddelReceived implementiert, so wird diese direkt nach dem use aufgerufen, - * um zu entscheiden, ob die Knuddel angenommen werden sollen. - * - *

Hinweis: Knuddel an einen Nutzer senden kannst du mit der Methode BotUser/transferKnuddel:method. - */ - use(knuddelAmount: KnuddelAmount, displayReasonText: string, parameters?: { transferReason?: string; onError?(message: string): void; onSuccess?(): void; }): void; -} - -/** - * Eine Instanz von KnuddelAmount repräsentiert eine bestimmte Anzahl von Knuddel. - */ -declare class KnuddelAmount { - /** - * Erzeugt eine Instanz von KnuddelAmount mit der Anzahl Knuddel. - */ - constructor(knuddel: number); - /** - * Erzeugt eine Instanz von KnuddelAmount mit einer bestimmten Cent-Anzahl. - */ - static fromCents(knuddel: number): KnuddelAmount; - /** - * Erzeugt eine Instanz von KnuddelAmount mit einer bestimmten Knuddel-Anzahl. - */ - static fromKnuddel(knuddel: number): KnuddelAmount; - /** - * Liefert die Anzahl der Knuddel in KnuddelCent zurück. - */ - getKnuddelCents(): number; - /** - * Gibt den Wert der Knuddel als Zahl zurück. - */ - asNumber(): number; - /** - * Liefert eine negierte Kopie des KnuddelAmount zurück. - */ - negate(): KnuddelAmount; - /** - * Liefert die Information, ob der Knuddelwert unter 0 ist. - */ - isNegative(): boolean; -} - -/** - * Repräsentiert einen KnuddelPot. - * Ein KnuddelPot kann nur durch Factory-Methoden des KnuddelsServer erzeugt werden: - * KnuddelsServer/createKnuddelPot:method. - * - * Wird die App heruntergefahren, so werden alle KnuddelPots, die nicht gesealt sind automatisch refunded. - */ -declare class KnuddelPot { - /** - * Liefert die id des KnuddelPot. - */ - getId(): number; - /** - * Liefert den Status des KnuddelPot. - */ - getState(): KnuddelPotState; - /** - * Liefert den beim Kreieren des KnuddelPots festgelegten KnuddelAmount, den jeder Teilnehmer zahlen muss. - */ - getKnuddelAmountPerParticipant(): KnuddelAmount; - /** - * Liefert den KnuddelAmount, der bisher insgesamt in den KnuddelPot eingezahlt wurde. - */ - getKnuddelAmountTotal(): KnuddelAmount; - /** - * Liefert die Liste der Teilnehmer, die bisher in den KnuddelPot eingezahlt haben. - */ - getParticipants(): User[]; - /** - * Liefert den höchsten Multiplikator, der gültig ist. - */ - getMaxFeeMultiplier(): number; - /** - * Setzt den BotUser, der den Anteil der Einzahlungen nach dem Spiel erhält - * und den Anteil, vom Gesamtpot, den er erhalten soll. - */ - setFee(feeUser: BotUser, feeMultiplier: number): void; - /** - * Liefert den mit KnuddelPot/setFee:method gesetzten BotUser an den die Gebühr ausbezahlt wird. - */ - getFeeUser(): User; - /** - * Liefert den mit KnuddelPot/setFee:method gesetzten Multiplikator der Gebühr. - */ - getFeeMultiplier(): number; - /** - * Versiegelt den KnuddelPot, sodass keine weiteren Einzahlungen vorgenommen - * werden können und Gewinne ausgeschüttet werden können. - */ - seal(): void; - /** - * Bezahlt alle Einsätze an die Teilnehmer zurück und informiert mit dem übergeben Text über den Grund. - */ - refund(reason?: string): void; - /** - * Fügt einen Gewinner in die Liste der Gewinner hinzu. - * Der zweite Parameter ist die Gewichtung mit der ausgezahlt werden soll. - * Wird der Parameter weggelassen, so ist er automatisch 1. - */ - addWinner(user: User, weight?: number): void; - /** - * Zahlt den KnuddelPot an die mit addWinner gesetzten Gewinner aus. - */ - payout(text?: string): void; -} - -/** - * Repräsentiert den Status eines KnuddelPot. - */ -declare class KnuddelPotState { - /** - * Der KnuddelPot ist geöffnet und kann neue Teilnehmer annehmen. - */ - static readonly Open: KnuddelPotState; - /** - * Der KnuddelPot ist versiegelt und kann keine neuen Teilnehmer annehmen. - */ - static readonly Sealed: KnuddelPotState; - /** - * Der KnuddelPot ist beendet und die Knuddel bereits ausgezahlt. - */ - static readonly Closed: KnuddelPotState; -} - -/** - * Ein KnuddelTransfer ist ein Container-Objekt für die Daten, die bei einer Knuddel-Transaktion von einem User - * an eine App anfallen. - * - * Implementiert man den App-Hook onBeforeKnuddelReceived, so kann man dort entscheiden, ob man den KnuddelTransfer - * annimmt oder ablehnt. - */ -declare class KnuddelTransfer { - /** - * Liefert den User, der den KnuddelTransfer ausgelöst hat. - */ - getSender(): User; - /** - * Liefert den BotUser, der die Knuddel des KnuddelTransfer erhält, - * wenn dieser mit accept() angenommen wurde. - */ - getReceiver(): BotUser; - /** - * Liefert die Anzahl der Knuddel, die mit diesem Transfer überwiesen werden. - */ - getKnuddelAmount(): KnuddelAmount; - /** - * Liefert den Grund für den Transfer, der bei der Überweisung angegeben wurde mit - * /appknuddel BOTNICK:KNUDDEL:GRUND. - */ - getTransferReason(): string; - /** - * Lehnt die Knuddel aus dem KnuddelTransfer ab und sendet sie zurück an den Absender. - * Als Grund sieht der Absender den übergebenen reason. - * - * Diese Methode wirft eine Exception, wenn sie auf einen bereits verarbeiteten Transfer aufgerufen wird. - * Sie kann nur erfolgreich aus dem AppHook onBeforeKnuddelReceived aufgerufen werden. - * - * In der Methode onBeforeKnuddelReceived kann genau ein Aufruf einer dieser drei Methoden gemacht werden: - * KnuddelTransfer/accept:method, - * KnuddelTransfer/addToPot:method, - * KnuddelTransfer/reject:method - */ - reject(reason: string): void; - /** - * Nimmt die Knuddel aus dem KnuddelTransfer an und übergibt sie an den BotUser, - * der mit getReceiver() abgefragt werden kann. - * - * Diese Methode wirft eine Exception, wenn sie auf einen bereits verarbeiteten Transfer aufgerufen wird. - * Sie kann nur erfolgreich aus dem AppHook onBeforeKnuddelReceived aufgerufen werden. - * In der Methode onBeforeKnuddelReceived kann genau ein Aufruf einer dieser drei Methoden gemacht werden: - * - * KnuddelTransfer/accept:method, - * KnuddelTransfer/addToPot:method, - * KnuddelTransfer/reject:method - */ - accept(): void; - /** - * Liefert die Information, ob ein bestimmter KnuddelTransfer zu einem KnuddelPot hinzugefügt werden kann. - */ - canAddToPot(pot: KnuddelPot): boolean; - /** - * Nimmt die Knuddel aus dem KnuddelTransfer an und übergibt sie an den übergebenen KnuddelPot. - * - * Diese Methode funktioniert analog zu KnuddelTransfer/accept:method, nur dass die Knuddel im KnuddelPot statt beim BotUser landen. - * - * Diese Methode wirft eine Exception, wenn sie auf einen bereits verarbeiteten Transfer aufgerufen wird. - * Sie kann nur erfolgreich aus dem AppHook onBeforeKnuddelReceived aufgerufen werden. - * - * In der Methode onBeforeKnuddelReceived kann genau ein Aufruf einer dieser drei Methoden gemacht werden: - * KnuddelTransfer/accept:method, - * KnuddelTransfer/addToPot:method, - * KnuddelTransfer/reject:method - */ - addToPot(knuddelPot: KnuddelPot): void; - /** - * Liefert die Information, ob der KnuddelTransfer bereits verarbeitet wurde. - * Falls die Methode false zurückliefert muss noch entschieden werden, ob der - * KnuddelTransfer angenommen oder abgelehnt wird. - */ - isProcessed(): boolean; -} - -/** - * KnuddelTransferDisplayType repräsentiert die Art der Darstellung einer Knuddel-Überweisung. - */ -declare class KnuddelTransferDisplayType { - /** - * Nachricht wird öffentlich angezeigt. - */ - static readonly Public: KnuddelTransferDisplayType; - /** - * Nachricht wird privat angezeigt. - */ - static readonly Private: KnuddelTransferDisplayType; - /** - * Nachricht wird als /m zugestellt. - */ - static readonly Post: KnuddelTransferDisplayType; -} - -/** - * KnuddelsServer ist die 'Einstiegsklasse'. Mit den statischen Methoden des KnuddelsServer erhält man Zugriff auf viele - * Objekte und Klassen, die im Verlauf der App-Entwicklung benötigt werden. - */ -declare class KnuddelsServer { - /** - * Liefert den BotUser, der standardmäßig zur App gehört. - */ - static getDefaultBotUser(): BotUser; - /** - * Liefert die AppPersistence, mit der sich Zahlen, Strings und Javascript-Objekte langfristig und über die Session einer App hinaus gespeichert werden können. - */ - static getPersistence(): AppPersistence; - /** - * Liefert den Channel in dem die App läuft. - */ - static getChannel(): Channel; - /** - * Liefert das UserAccess-Objekt, über das - * User zugreifbar werden. - */ - static getUserAccess(): UserAccess; - /** - * Liefert ein ExternalServerAccess-Objekt, mit dem - * andere Server angesteuert werden können. - */ - static getExternalServerAccess(): ExternalServerAccess; - /** - * Aktualisiert die Liste der genutzten Hooks. Werden zur Laufzeit chatCommands oder App-Hooks (wie mayJoinChannel) dynamisch erzeugt oder gelöscht, so muss danach refreshHooks() - * aufgerufen werden, damit diese Änderung wirksam wird. - */ - static refreshHooks(): void; - /** - * Liefert den Standard-Logger für diese App. Alles, was geloggt wird, wird vom Nutzer "App-Logs" als private Nachricht zugestellt. - */ - static getDefaultLogger(): Logger; - /** - * Liefert den Pfad eines Bildes zur Integration in der eigenen App. - * Alle Bilder, die im Ordner /www in der App abgelegt werden können hier referenziert werden. - */ - static getFullImagePath(imageName: string): string; - /** - * Liefert den Pfad eines Systembildes zur Integration in der eigenen App. - * Alle Bilder, die unter http://apps4.knuddels.biz/kimg/ - * erreichbar sind können hier referenziert werden. - */ - static getFullSystemImagePath(imageName: string): string; - /** - * Liefert die Informationen über den ChatServer auf dem die App läuft. - */ - static getChatServerInfo(): ChatServerInfo; - /** - * Liefert die Informationen über den AppServer auf dem die App läuft. - */ - static getAppServerInfo(): AppServerInfo; - /** - * Liefert das AppAccess-Object. - */ - static getAppAccess(): AppAccess; - /** - * Erzeugt einen KnuddelPot. - * - * Ist ein KnuddelPot 30 Minuten nach dem Erzeugen noch nicht gesealt, - * so wird vom Server automatisch ein KnuddelPot/refund:method ausgelöst. - */ - static createKnuddelPot( - knuddelAmount: KnuddelAmount, - params?: { - payoutTimeoutMinutes?: number; - shouldSealPot?(pot: KnuddelPot): boolean; - onPotSealed?(pot: KnuddelPot): void; - }): KnuddelPot; - /** - * Liefert den KnuddelPot mit der angegeben id. - */ - static getKnuddelPot(id: number): (KnuddelPot|null); - /** - * Liefert alle für die App noch verwaltbaren KnuddelPot-Objekte. - */ - static getAllKnuddelPots(): KnuddelPot[]; - /** - * Liefert das ToplistAccess-Objekt, über das - * Toplisten erzeugt und verwaltet werden können. - */ - static getToplistAccess(): ToplistAccess; - /** - * Liefert das AppProfileEntryAccess-Objekt, über das - * App-Profileinträge erzeugt und verwaltet werden können. - */ - static getAppProfileEntryAccess(): AppProfileEntryAccess; -} - -/** - * Mit einer Instanz einer LoadConfiguration kann gestaltet werden, wie der Inhalt des HTML User Interface aussieht, bevor es fertig geladen ist. - */ -declare class LoadConfiguration { - /** - * Setzt die Farbe des Hintergrundes vom Loading-View, der angezeigt wird, während das HTML User Interface lädt. (standardmäßig weiß) - */ - setBackgroundColor(color: Color): void; - /** - * Setzt das Hintergrundbild vom Loading-View, das angezeigt wird, während das HTML User Interface lädt. (standardmäßig nicht gesetzt) - */ - setBackgroundImage(imageUrl: string): void; - /** - * Setzt den Text des Ladehinweiseses im Loading-View, der angezeigt wird, während das HTML User Interface lädt. (standardmäßig "Lädt...") - * Hinweis: Wird mit setLoadingIndicatorImage ein Loaading-Indicator-Bild gesetzt, so wird der mit setText gesetzte Texte ignoriert. - */ - setText(text: string): void; - /** - * Setzt ein Loading-Indicator-Bild im Loading-View, das angezeigt wird, während das HTML User Interface lädt. (standardmäßig nicht gesetzt) - * Hinweis: Wird mit setLoadingIndicatorImage ein Loaading-Indicator-Bild gesetzt, so wird der mit setText gesetzte Texte ignoriert. - */ - setLoadingIndicatorImage(imageUrl: string): void; - /** - * Setzt die Farbe des Textes im Loading-View, der angezeigt wird, während das HTML User Interface lädt. (standardmäßig schwarz) - */ - setForegroundColor(color: Color): void; - /** - * Aktiviert/Deaktiviert die Nutzung vom Loading-View. (standardmäßig aktiviert) - * Es kann sinnvoll sein, den Loading-View zu deaktivieren, wenn man selbst einen komplett eigenen Loading-View in seine App einbauen möchte. - */ - setEnabled(enabled: boolean): void; -} - -/** - * Eine Instanz eines Logger ermöglicht das Loggen von Inhalten. - * - * Diese erhält man über das KnuddelsServer-Objekt - * mit KnuddelsServer.getDefaultLogger() - * - * Die Log-Einträge werden je nach Einstellungen im /apps-Fenster an den Besitzer des Channels, - * die App-Manager und den App-Entwickler zugestellt. - */ -declare class Logger { - /** - * Logge einen Text mit Level DEBUG. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt. Siehe: /apps, Tab: Logs. - * - * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. - */ - debug(...msg: any[]): void; - /** - * Logge einen Text mit Level INFO. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt. Siehe: /apps, Tab: Logs. - * - * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. - */ - info(...msg: any[]): void; - /** - * Logge einen Text mit Level WARN. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt, sowie im /apps Fenster im Log angezeigt. Siehe: /apps, Tab: Logs. - * - * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. - */ - warn(...msg: any[]): void; - /** - * Logge einen Text mit Level ERROR. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt, sowie im /apps Fenster im Log angezeigt. Siehe: /apps, Tab: Logs. - * - * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. - */ - error(...msg: any[]): void; - /** - * Logge einen Text mit Level FATAL. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt, sowie im /apps Fenster im Log angezeigt. Siehe: /apps, Tab: Logs. - * - * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. - */ - fatal(...msg: any[]): void; -} - -/** - * Message ist eine abstrakte Klasse und repräsentiert eine Nachricht im Chat. - */ -declare class Message { - /** - * Liefert den User, der die Nachricht verfasst hat. - */ - getAuthor(): User; - /** - * Liefert den Inhalt der Nachricht. - */ - getText(): string; - /** - * Liefert den genauen Zeitpunkt, zu dem die Nachricht erstellt wurde. - */ - getCreationDate(): Date; -} - -/** - * Repräsentiert die Instanz der konkreten App, auf die dieser Code Zugriff hat. - * - * Die Instanz von OwnAppInstance erhält man über das AppAccess-Objekt - * mit appAccess.getOwnInstance() - */ -declare class OwnAppInstance { - /** - * Gibt Zugriff auf Nutzer, die gerade im Channel dieser AppInstance online sind. - * @since AppServer 82560 - */ - getOnlineUsers(otherAppInstance: AppInstance, ...userType: UserType[]): User[]; -} - -/** - * Eine Instanz von Persistence ermöglicht die persistente Speicherung von Zahlen, Zeichenketten und JSON-Objekten. - * Es gibt die zwei Arten AppPersistence und UserPersistence - * - * Jeder eigene Datentyp hat seinen eigenen Namensraum. - * So kann derselbe key für eine Zahl, Zeichenkette und auch JSON-Objekt genutzt werden. - * - *

Hinweis: Mit der Persistence gespeicherte Informationen überleben - * sogar die Deinstallation und Neuinstallation der App. - */ -declare class Persistence { - /** - * Informiert darüber, ob unter dem key ein String abgespeichert ist. - */ - hasString(key: string): boolean; - /** - * Setzt die Zeichenkette value für den key. - * Falls bereits eine Zeichenkette für den key existiert, so wird diese überschrieben. - */ - setString(key: string, value: string): void; - /** - * Liefert die Zeichenkette, die für den key gespeichert ist. - * Falls für key keine Zeichenkette gespeichert ist, so gibt die Methode - * den defaultValue zurück. - */ - getString(key: string, defaultValue?: string): string; - /** - * Löscht die Zeichenkette, die unter key gespeichert ist. - */ - deleteString(key: string): void; - /** - * Informiert darüber, ob unter dem key eine Zahl abgespeichert ist. - */ - hasNumber(key: string): boolean; - /** - * Setzt die Zahl value für den key. - * Falls bereits eine Zahl für den key existiert, so wird diese überschrieben. - */ - setNumber(key: string, value: number): void; - /** - * Addiert den übergebenen value auf die unter dem Key key vorhandenen Wert drauf. - * Value kann auch negativ sein um eine Subtraktion durchzuführen. - * Falls keine Zahl für den key existiert, so wird der value für key gespeichert. - */ - addNumber(key: string, value: number): number; - /** - * Liefert die Zahl, die für den key gespeichert ist. - * Falls für key keine Zahl gespeichert ist, so gibt die Methode - * den defaultValue zurück. - */ - getNumber(key: string, defaultValue?: number): number; - /** - * Löscht die Zahl, die unter key gespeichert ist. - */ - deleteNumber(key: string): void; - /** - * Informiert darüber, ob unter dem key ein Objekt abgespeichert ist. - */ - hasObject(key: string): boolean; - /** - * Setzt das Objekt value für den key. - * Falls bereits ein Objekt für den key existiert, so wird dieses überschrieben. - * Das als JSON serialisierte Objekt darf maximal 100kb groß sein. - */ - setObject(key: string, object: (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable)): void; - /** - * Liefert das Objekt, das für den key gespeichert ist. - * Falls für key kein Objekt gespeichert ist, so gibt die Methode - * den defaultValue zurück. - */ - getObject(key: string, defaultValue?: (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable)): (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable); - /** - * Löscht das Objekt, das unter key gespeichert ist. - */ - deleteObject(key: string): void; -} - -/** - * Eine Instanz von PrivateMessage repräsentiert eine private Nachricht im Chat. - * Die App erhält sämtliche private Nachrichten, die an einen ihrer BotUser - * geschickt werden. - * - *

Hinweis: Eine App hat keinen Zugriff auf private Nachrichten, - * die Nutzer untereinander schreiben, ohne dass ein BotUser als Empfänger involviert ist. - */ -declare class PrivateMessage extends Message { - /** - * Liefert die Liste der Empfänger der Nachricht. - */ - getReceivingUsers(): User[]; - /** - * Sendet eine private Nachricht an alle Beteiligten des Gespräches. - */ - sendReply(text: string): void; -} - -/** - * Eine Instanz von PublicActionMessage repräsentiert eine öffentliche Handlung im Chat. - * Die App erhält die öffentlichen Handlungen. - */ -declare class PublicActionMessage extends Message { -} - -/** - * Eine Instanz von PublicEventMessage repräsentiert ein öffentliches Event im Chat. - * Die App erhält die öffentlichen Events. - */ -declare class PublicEventMessage extends Message { -} - -/** - * Eine Instanz von PublicMessage repräsentiert eine öffentliche Nachricht im Chat. - * Die App erhält die öffentlichen Nachrichten, die geschrieben werden. - */ -declare class PublicMessage extends Message { -} - -/** - * Eine Quest ist eine konkrete Aufgabe, die ein User in der App zu erledigen hat. - * - * Im Blog findest du Informationen darüber, wie man eine Quest für seine App erhält: - * https://blog.developer.knuddels.de/2015/10/29/how-to-get-a-quest/ - */ -declare class Quest { - /** - * Löst ein Quest-Event aus. - * @since AppServer 82290, ChatServer 82290 - */ - setSolved(count?: number): void; - /** - * Liefert den Key der Quest. - * @since AppServer 82290, ChatServer 82290 - */ - getQuestKey(): string; -} - -/** - * Ein QuestAccess-Objekt ermöglicht den Zugriff auf die Quests, die ein Nutzer des Chats, für die laufende App hat. - * - * Im Blog findest du Informationen darüber, wie man eine Quest für seine App erhält: - * https://blog.knuddels.de/2015/10/29/how-to-get-a-quest/ - */ -declare class QuestAccess { - /** - * Liefert die Quests - * für diesen Nutzer in dieser App. - * @since AppServer 82290, ChatServer 82290 - */ - getQuests(): Quest[]; - /** - * Liefert die Information, ob eine bestimmte Quest offen ist. - * @since AppServer 82290, ChatServer 82290 - */ - hasQuest(questKey: string): boolean; - /** - * Liefert eine bestimmte Quest, falls vorhanden. - * @since AppServer 82290, ChatServer 82290 - */ - getQuest(questKey: string): (Quest|null); - /** - * Liefert den User, der zu diesem QuestAccess-Objekt gehört. - * @since AppServer 82290, ChatServer 82290 - */ - getUser(): User; -} - -/** - * RandomOperations bietet eine Sammlung verschiedener Zufallsoperationen, die man für Glücksspiele und Ähnliches nutzen kann. - */ -declare class RandomOperations { - /** - * Liefert eine Zufallszahl zwischen minValue (inklusiv) und maxValue (exklusiv). - */ - static nextInt(minValue: number /* optional */, maxValue: number): number; - /** - * Liefert ein Array mit Zufallszahlen zwischen minValue (inklusiv) und n (exklusiv). - */ - static nextInts(minValue: number /* optional */, maxValue: number, count: number, onlyDifferentNumbers: boolean): number[]; - /** - * Liefert true in truePropability/1 Fällen - */ - static flipTrue(truePropability: number): boolean; - /** - * Liefert ein zufälliges Objekt aus einem Array. - * Falls das Array leer ist, wird null zurückgeliefert. - */ - static getRandomObject(objects: T[]): T; - /** - * Mischt das Array der übergebenen Objekte und liefert es zurück. - */ - static shuffleObjects(objects: T[]): T[]; - /** - * Liefert einen zufälligen String zurück. - * @since AppServer 92699 - */ - static getRandomString(length: number, allowedCharacters?: string): string; -} - -/** - * Repräsentiert die Root-Instanz einer App, die im Hauptchannel läuft. - * - * Die Instanz für die RootAppInstance erhält man über das AppInstance-Objekt - * mit appInstance.getRootInstance() - */ -declare class RootAppInstance extends AppInstance { - /** - * Aktualisiert diese App im Channel (und ggf. vorhandenen Tochterchanneln) auf die neueste Version. - */ - updateApp(message: string /* optional */, logMessage?: string): void; - /** - * Stoppt diese App. - */ - stopApp(message: string /* optional */, logMessage?: string): void; -} - -/** - * Liefert Informationen über einen Server. - */ -declare class ServerInfo { - /** - * Liefert die interne ServerId des Servers. - */ - getServerId(): string; - /** - * Liefert die Code-Revision des Servers. - */ - getRevision(): number; -} - -/** - * Ein SingleDiceResult enthält das Ergebnis aller Würfel desselben Typs. - * Würfelt man beispielsweise mit der Konfiguration "1w2 + 10w5" so gibt es im DiceResult - * zwei SingleDiceResult-Objekte. Eines für "1w2" und eines für "10w5". - */ -declare class SingleDiceResult { - /** - * Liefert den Würfel zurück, durch den dieses SingleDiceResult erzeugt wurde. - */ - getDice(): Dice; - /** - * Liefert die Ziffern, die gewürfelt wurden. - */ - valuesRolled(): number[]; - /** - * Liefert die Summe der Augenzahlen des SingleDiceResult. - */ - sum(): number; -} - -/** - * Diese Dokumentation beschreibt, welche Erweiterungen am serverseitigen String-Objekt vorgenommen wurden. - */ -interface String { - /** - * Die Methode liefert den String zurück, auf dem sie aufgerufen wurde mit KCode escaped. - */ - escapeKCode(): string; - /** - * Entfernt jeglichen KCode aus dem String und gibt ihn zurück. - */ - stripKCode(): string; - /** - * Diese Methode liefert die Information, ob der String auf dem die Methode aufgerufen wurde - * mit einem bestimmten Prefix beginnt. - */ - startsWith(prefix: string): boolean; - /** - * Diese Methode liefert die Information, ob der String auf dem die Methode aufgerufen wurde - * mit einem bestimmten Suffix endet. - */ - endsWith(suffix: string): boolean; - /** - * Liefert die Breite des Strings in der Schriftart Arial mit der gegeben Schriftgröße und Information, ob Text fett dargestellt werden soll. - */ - getPixelWidth(fontSize: number, isBold: boolean): number; - /** - * Liefert einen String, der in der Schriftart Arial mit der gegeben Schriftgröße und Information, ob Text fett dargestellt werden soll - * maximal maxPixelWidth breit ist. Wird der Text dafür gekürzt, so wird an das Ende abbreviationMarker angehangen. - * Falls abbreviationMarker nicht übergeben wurde, so ist es automatisch '...'. - */ - limitString(fontSize: number, isBold: boolean, maxPixelWidth: number, abbreviationMarker?: string): string; - /** - * Liefert die Information, ob ein bestimmter String in diesem String vorhanden ist. - */ - contains(needle: string): boolean; - /** - * Liefert die Levenshtein-Distanz zum übergebenen String. - * Levenshtein-Distanz: Minimale Anzahl von Einfüge-, Lösch- und Ersetz-Operationen, um die erste Zeichenkette in die zweite umzuwandeln. - * @since AppServer 82271 - */ - minimalConversionCost(otherString: string): number; - /** - * Liefert die Information, ob der String nur aus Zeichen besteht, die in einem Nicknamen - * vorkommen dürfen. - * @since AppServer 82271 - */ - hasOnlyNicknameCharacters(): boolean; - /** - * Liefert die Information, ob der String nur aus Zeichen besteht, die Nummern sind. - * @since AppServer 82271 - */ - hasOnlyDigits(): boolean; - /** - * Liefert die Information, ob der String nur aus Zeichen besteht, die alphanumerisch + Whitespaces sind. - * @since AppServer 82271 - */ - hasOnlyAlphanumericalAndWhitespaceCharacters(): boolean; - /** - * Liefert die Information, ob der String leer oder null ist. - * @since AppServer 92695 - */ - isEmpty(): boolean; - /** - * Liefert den String in CamelCase. - * @since AppServer 92695 - */ - toCamelCase(): string; - /** - * Liefert den String mit dem ersten Buchstaben als Großbuchstaben. - * @since AppServer 92695 - */ - capitalize(): string; - /** - * Erstellt eine Kopie des String, in dem alle Vorkommnisse des String search in replacement - * ersetzt werden und liefert diesen zurück. - */ - replaceAll(search: string | RegExp, replacement: string): string; - /** - * Prüft primitiv, ob der String laut Knuddels-Filterregeln ok ist. - * @since ChatServer 82262, AppServer 82262 - */ - isOk(): boolean; -} - -/** - * Eine Instanz einer Toplist repräsentiert eine eigene Topliste für einen bestimmten userPersistenceNumberKey. - */ -declare class Toplist { - /** - * Liefert den userPersistenceNumberKey mit dem die Topliste erzeugt wurde. - */ - getUserPersistenceNumberKey(): string; - /** - * Liefert den Anzeigenamen der Topliste. - */ - getDisplayName(): string; - /** - * Liefert den Befehl, der im Chat eingegeben werden kann, um diese Topliste zu öffnen. - * Wird ein User oder eine userId übergeben, so öffnet sich die Topliste mit diesem Nutzer im Fokus. - */ - getChatCommand(user_or_userId?: (User|number)): string; - /** - * Liefert den Anzeigenamen für den übergebenen User oder eine userId. - */ - getLabel(user_or_userId: (User|number)): string; - /** - * Legt einen Change-Listener an, der jedes mal aufgerufen wird, wenn ein User - * einen neuen Anzeigenamen erhält. - */ - addLabelChangeListener(listener: (labelChangeEvent: ToplistLabelChangeEvent) => void): void; - /** - * Löscht einen LabelChangeListener, der mit Toplist/addLabelChangeListener:method erzeugt wurde. - */ - removeLabelChangeListener(listener: (labelChangeEvent: ToplistLabelChangeEvent) => void): void; - /** - * Legt einen Change-Listener an, der jedes mal aufgerufen wird, wenn ein sich der Rang User eines Nutzers ändert. - */ - addRankChangeListener(listener: (rankChangeEvent: ToplistRankChangeEvent) => void): void; - /** - * Löscht einen RankChangeListener, der mit Toplist/addRankChangeListener:method erzeugt wurde. - */ - removeRankChangeListener(listener: (rankChangeEvent: ToplistRankChangeEvent) => void): void; -} - -/** - * Mit einer Instanz von ToplistAccess kann eine App - * Toplist erzeugen und verwalten. - * - * Die Instanz für die ToplistAccess erhält man über das KnuddelsServer-Objekt - * mit KnuddelsServer.getToplistAccess() - */ -declare class ToplistAccess { - /** - * Liefert die Liste aller Toplisten, die diese App erzeugt hat. - */ - getAllToplists(): Toplist[]; - /** - * Liefert die Toplist mit dem Persistenz-Key zurück. - */ - getToplist(userPersistenceNumberKey: string): Toplist; - /** - * Löscht die übergebene Toplist oder die Toplist mit dem Persistenz-Key. - */ - removeToplist(toplist: Toplist): void; - /** - * Erzeugt oder aktualisiert die Toplist für den übergebenen userPersistenceNumberKey. - */ - createOrUpdateToplist(userPersistenceNumberKey: string, displayName: string, parameters?: { labelMapping?: { [minValue: string]: string }; ascending?: boolean; }): Toplist; -} - -/** - * ToplistDisplayType repräsentiert den Anzeigetyp eines Toplisteneintrags im Profil vonUsern. - */ -declare class ToplistDisplayType { - /** - * Nur Anzeigename anzeigen. - */ - static readonly Label: ToplistDisplayType; - /** - * Gespeicherten Wert anzeigen. - */ - static readonly Value: ToplistDisplayType; - /** - * Anzeigename und Rang anzeigen. - */ - static readonly LabelAndRank: ToplistDisplayType; - /** - * Wert und Rang anzeigen. - */ - static readonly ValueAndRank: ToplistDisplayType; -} - -/** - * ToplistLabelChangeEvents erhalten EventListener die bei einer - * Toplist mit der Methode Toplist/addLabelChangeListener:method - * erzeugt wurden, nachdem sich der Anzeigename für einen User geändert hat. - * - * Das ToplistLabelChangeEvent enthält alle wichtigen Daten, um auf die Änderung zu reagieren - * und dem User beispielsweise für den Aufstieg zu gratulieren. - */ -declare class ToplistLabelChangeEvent { - /** - * Liefert die zugehörige Toplist. - */ - getToplist(): Toplist; - /** - * Liefert den vorherigen Anzeigenamen. Hatte der User vorher keinen - * Anzeigenamen, so ist dieser Wert null. - */ - getOldLabel(): string; - /** - * Liefert den neuen Anzeigenamen. Hatte der User nun keinen - * Anzeigenamen mehr, so ist dieser Wert null. - */ - getNewLabel(): string; - /** - * Liefert den User für den das Event ausgelöst wurde. - */ - getUser(): User; - /** - * Liefert den Wert, der vor der Änderung gespeichert war. - */ - getOldValue(): number; - /** - * Liefert den neuen Wert. - */ - getNewValue(): number; -} - -/** - * ToplistRankChangeEvents erhalten EventListener die bei einer - * Toplist mit der Methode Toplist/addRankChangeListener:method - * erzeugt wurden, nachdem sich der Rang für einen User geändert hat. - * - * Das ToplistRankChangeEvent enthält alle wichtigen Daten, um auf die Änderung zu reagieren - * und den überholten Usern eine Nachricht zu senden. - */ -declare class ToplistRankChangeEvent { - /** - * Liefert die zugehörige Toplist. - */ - getToplist(): Toplist; - /** - * Liefert den Toplisten-Rang, den der User vor der Änderung hatte. - */ - getOldRank(): number; - /** - * Liefert den neuen Toplisten-Rang, des Users. - */ - getNewRank(): number; - /** - * Liefert den User für den das Event ausgelöst wurde. - */ - getUser(): User; - /** - * Liefert die User, die bei dieser Änderung überholt worden sind. - *

Achtung: Wenn mehr als 10 User - * überholt wurden, so liefert die Methode die besten 10 überholten User. - */ - getUsersOvertook(): User[]; - /** - * Liefert den Wert, der vor der Änderung gespeichert war. - */ - getOldValue(): number; - /** - * Liefert den neuen Wert. - */ - getNewValue(): number; -} - -/** - * Ein User ist ein Nutzer des Chats, in dem die App läuft. - */ -declare class User { - /** - * Liefert die eindeutige Nutzerkennung des Nutzers. - */ - getUserId(): number; - /** - * Liefert den Nicknamen des Nutzers. - */ - getNick(): string; - /** - * Liefert das Alter des Nutzers. Bei Nutzern, die bereits sehr lange in der Plattform sind kann es vorkommen, dass kein Alter angegeben wurde. In diesem Fall ist das Alter 0. - */ - getAge(): number; - /** - * Liefert das Geschlecht des Nutzers. - */ - getGender(): Gender; - /** - * Liefert den Zeitpunkt der Registrierung des Nutzers. - */ - getRegDate(): Date; - /** - * Liefert den UserStatus des Nutzers. - */ - getUserStatus(): UserStatus; - /** - * Liefert den UserType des Nutzers. - */ - getUserType(): UserType; - /** - * Liefert den aktuellen ClientType des Nutzers oder Offline wenn er nicht im Chat online ist. - */ - getClientType(): ClientType; - /** - * Prüft ob der Client des Users den übergebenen AppViewMode (für User/sendAppContent:method) anzeigen kann. - */ - canShowAppViewMode(mode: AppViewMode): boolean; - /** - * Prüft ob der Client des User's den übergebenen AppContent anzeigen kann. - */ - canSendAppContent(appContent: AppContent): boolean; - /** - * Prüft, ob der User in dem angegebenen Team ist. - * Dies funktioniert derzeit nur für Teams, die eine eigene /fa haben. - * - * Achtung: Bei Nutzern, die neu in ein Team kommen, funktioniert die Abfrage erst dann korrekt, - * wenn er sich neu in den Channel eingeloggt hat. - */ - isInTeam(teamName: string, subTeamName?: string): boolean; - /** - * Liefert ein UserPersistence-Objekt für diesen Nutzer. Mit diesem Objekt kann eine App sich Dinge über diesen speziellen Nutzer merken. - */ - getPersistence(): UserPersistence; - /** - * Shortcut-Funktion um mit dem DefaultBotUser eine private Nachricht zu versenden. - */ - sendPrivateMessage(message: string): void; - /** - * Shortcut-Funktion um mit dem DefaultBotUser eine /m zu versenden. - */ - sendPostMessage(topic: string, text: string): void; - /** - * Liefert die Information, ob dieser Nutzer Channelbesitzer im Channel der App ist. - */ - isChannelOwner(): boolean; - /** - * Liefert die Information, ob der Channel der App - * ein Lieblingschannel des Nutzers ist. - */ - isLikingChannel(): boolean; - /** - * Liefert die Information, ob der Nutzer im harten Kern des Channels der App ist. - * @since AppServer 92701, ChatServer 92701 - */ - isChannelCoreUser(): boolean; - /** - * Liefert die Information, ob dieser Nutzer ein AppManager für diese App ist. Die Channelbesitzer zählen automatisch auch als AppManager. - */ - isAppManager(): boolean; - /** - * Liefert Information, ob dieser Nutzer derzeit für das Schreiben öffentlicher Nachrichten im Channel gesperrt ist. - */ - isMuted(): boolean; - /** - * Liefert Information, ob dieser Nutzer beim Schreiben öffentlicher Nachrichten im Channel - * derzeit für die Verwendung von Textformatierungen, Farben und Smileys gesperrt ist. - */ - isColorMuted(): boolean; - /** - * Liefert Information, ob dieser Nutzer derzeit für das Betreten des Channel gesperrt ist. - */ - isLocked(): boolean; - /** - * Liefert Information, ob dieser Nutzer Channelmoderator im Channel der App ist. - */ - isChannelModerator(): boolean; - /** - * Liefert Information, ob dieser Nutzer Eventmoderator im Channel der App ist. - */ - isEventModerator(): boolean; - /** - * Liefert Information, ob dieser Nutzers der Entwickler der App ist. - */ - isAppDeveloper(): boolean; - /** - * Liefert einen Link zum Profil des Nutzers, den man im Chat anzeigen kann. - */ - getProfileLink(displayText?: string): string; - /** - * Liefert die Information, ob der Nutzer online im Channel der App ist. - */ - isOnlineInChannel(): boolean; - /** - * Liefert die Anzahl der Knuddel, die der Nutzer besitzt. - */ - getKnuddelAmount(): KnuddelAmount; - /** - * Liefert die Information, ob der Nutzer irgendwo im Chat online ist. - */ - isOnline(): boolean; - /** - * Liefert die Readme des Nutzers, die er mit /readme TEXT in sein Profil gesetzt hat. - */ - getReadme(): string; - /** - * Liefert die vom Nutzer verbrachte Zeit im gesamten Chatsystem In Minuten. - * Hinweis: Die Minutenzahl wird derzeit immer nur zu dem Zeitpunkt aktualisiert, - * wenn der Nutzer offline geht. - */ - getOnlineMinutes(): number; - /** - * Liefert die Information, ob der Nutzer sich mittels /away-Funktion kurz abgemeldet hat. - */ - isAway(): boolean; - /** - * Liefert die Information, ob der Nutzer ein Profilfoto hat. - */ - hasProfilePhoto(): boolean; - /** - * (Er)setzt den übergebenen AppContent beim Nutzer. - */ - sendAppContent(appContent: AppContent): AppContentSession; - /** - * Liefert alle AppContentSession, die der User - * aktuell geöffnet hat. - */ - getAppContentSessions(): AppContentSession[]; - /** - * Liefert die AppContentSession, die der User - * mit einem bestimmten AppViewMode aktuell geöffnet hat. - */ - getAppContentSession(appViewMode: AppViewMode): AppContentSession; - /** - * Vergleicht den übergebenen Nutzer und liefert true, falls der übergebene Nutzer - * identisch ist mit dem aktuellen Nutzer. - */ - equals(user: User): boolean; - /** - * Liefert die URL zum Profilfoto des Nutzers. Die übergebene Breite und Höhe - * liefern dem Server einen Anhaltswert, um das bestmögliche Foto zu finden, - * sind aber keine Garantie, dass das Foto diese Ausmaße haben wird. - */ - getProfilePhoto(width: number, height: number): string; - /** - * Liefert das QuestAccess-Objekt - * für diesen Nutzer in dieser App. - * @since AppServer 82290, ChatServer 82290 - */ - getQuestAccess(): QuestAccess; - /** - * Liefert die Information, ob der Nutzer gerade sein Video streamt. - */ - isStreamingVideo(): boolean; - /** - * Liefert den KnuddelAccount des Nutzers. - */ - getKnuddelAccount(): KnuddelAccount; - /** - * Liefert die ChannelTalkPermission für diesen Nutzer in diesem - * Channel. - */ - getChannelTalkPermission(): ChannelTalkPermission; - /** - * Liefert die Information, ob der User ein verifiziertes Profilbild hat. - */ - isProfilePhotoVerified(): boolean; - /** - * Liefert die Information, ob das Alter des Users verifiziert ist. - */ - isAgeVerified(): boolean; - /** - * Setzt dem Nutzer ein Icon in die Nickliste, das auf der rechten Seite seines Nicks angezeigt wird. - * Der Eintrag wird automatisch entfernt, sobald der Nutzer den Channel verlässt, - * kann aber auch mit User/removeNicklistIcon:method - * entfernt werden. - */ - addNicklistIcon(imagePath: string, imageWidth: number): void; - /** - * Entfernt dem Nutzer ein über die API gesetztes Icon in die Nickliste. - */ - removeNicklistIcon(imagePath: string): void; - /** - * Startet einen Würfelwurf für den Nutzer, falls er online im Channel ist und er nicht gemuted ist. - * @since AppServer 89159, ChatServer 89159 - */ - triggerDice(diceConfiguration: DiceConfiguration): void; -} - -/** - * Mit einer Instanz von UserAccess kann eine App - * auf User zugreifen, die bereits einmal im Channel waren, - * als die App lief. Für alle nicht zugreifbaren User kann man via UserAccess den korrekt geschriebenen Nicknamen erhalten. - * - * Die Instanz für die UserAccess erhält man über das KnuddelsServer-Objekt - * mit KnuddelsServer.getUserAccess() - */ -declare class UserAccess { - /** - * Liefert die userId des Nutzers mit dem übergebenen Nicknamen. - */ - getUserId(nick: string): number; - /** - * Informiert darüber, ob ein Nutzer mit dem übergebenen Nicknamen existiert. - */ - exists(nick: string): boolean; - /** - * Informiert darüber, ob der Nutzer mit der übergebenen userId geladen werden darf. Neben dem AppDeveloper können nur Nutzer geladen werden, die sich einmal im Channel befanden, als die App - * lief. - */ - mayAccess(userId: number): boolean; - /** - * Liefert den Nutzer mit der übergebenen userId. Neben dem AppDeveloper können nur Nutzer geladen werden, die sich einmal im Channel befanden, als die App lief. Es wird empfohlen vor der - * Abfrage von getUserById(userId) mit UserAccess/mayAccess:method abzufragen, ob dies funktionieren wird. - */ - getUserById(userId: number): User; - /** - * Liefert den Nicknamen des Nutzers mit der übergebenen userId in der korrekten Schreibweise. - */ - getNick(userId: number): string; - /** - * Loopt über alle zugreifbaren User sortiert nach Registrierzeitpunkt und - * führt für jeden User das übergebene Callback aus. - */ - eachAccessibleUser( - callback: (user: User, index: number, accessibleUserCount: number, key?: string) => boolean, - parameters?: { - onStart?(accessibleUserCount: number, key?: string): void; - onEnd?(accessibleUserCount: number, key?: string): void; - }): void; -} - -/** - * Für jeden User kann eine UserPersistence angefordert werden, um sich - * für einen bestimmten Nutzer Dinge persistent zu merken. - */ -declare class UserPersistence extends Persistence { - /** - * Löscht alle Zahlenwerte, die in dieser UserPersistence gespeichert sind. - * @since AppServer 88569 - */ - deleteAllNumbers(): number; - /** - * Löscht alle Objekte, die in dieser UserPersistence gespeichert sind. - * @since AppServer 88569 - */ - deleteAllObjects(): number; - /** - * Löscht alle Zeichenketten, die in dieser UserPersistence gespeichert sind. - * @since AppServer 88569 - */ - deleteAllStrings(): number; - /** - * Löscht alle Daten, die in dieser UserPersistence gespeichert sind. - * @since AppServer 88569 - */ - deleteAll(): number; -} - -/** - * Diese Klasse repräsentiert einen Eintrag der Persistenz. - */ -declare class UserPersistenceNumberEntry { - /** - * Liefert den Nutzer. - */ - getUser(): User; - /** - * Liefert den Wert. - */ - getValue(): number; - /** - * Liefert den Rang des Elements in der Persistenz. - */ - getRank(): number; - /** - * Liefert die Position des Elements in der Persistenz. - */ - getPosition(): number; -} - -/** - * Mit dieser Klasse ist es möglich nicht User-spezifische Abfragen auf die UserPersistence auszuführen. - */ -declare class UserPersistenceNumbers { - /** - * Liefert die Summe aller via UserPersistence gespeicherten Zahlen für den übergebenen key. - */ - static getSum(key: string): number; - /** - * Löscht alle gespeicherten Zahlen-Werte für den übergebenen key. - */ - static deleteAll(key: string): number; - /** - * Liefert die Anzahl aller unterschiedlichen Nutzer, die Werte für einen bestimmten key gespeichert haben. - * Hierbei kann optional der Wertebereich über die parameters eingegrenzt werden. - */ - static getCount(key: string, parameters?: { minimumValue?: number; maximumValue?: number; }): number; - /** - * Ändert einen bestimmten key bei allen UserPersistence. - */ - static updateKey(oldKeyName: string, newKeyName: string): number; - /** - * Ändert alle Werte für einen bestimmten key, die vorher einen bestimmten anderen Wert hatten in der UserPersistence. - *
Hinweis: Da diese Methode ein Batch-Update ist werden keine Change-Listener (ToplistRankChangeEvent, ToplistLabelChangeEvent) ausgelöst. - */ - static updateValue(key: string, oldValue: number, newValue: number): number; - /** - * Addiert einen Wert für Einträge mit einem bestimmten key in der UserPersistence. - *
Hinweis: Da diese Methode ein Batch-Update ist werden keine Change-Listener (ToplistRankChangeEvent, ToplistLabelChangeEvent) ausgelöst. - */ - static addNumber(key: string, value: number, parameters?: { minimumValue?: number; maximumValue?: number; targetUsers?: User[]; }): number; - /** - * Liefert ein Array mit UserPersistenceNumberEntry-Objekten für einen bestimmten key. - * Hierdurch kann beispielsweise eine blätterbare Topliste abgebildet werden. - */ - static getSortedEntries(key: string, parameters?: { ascending?: boolean; count?: number; page?: number; minimumValue?: number; maximumValue?: number; }): UserPersistenceNumberEntry[]; - /** - * Liefert ein Array mit UserPersistenceNumberEntry-Objekten für einen bestimmten key. Hierbei werden die nähesten Elemente gewählt, - * die am übergebenen User/UserId liegen. - * - * Beispiel: Der Nutzer ist in der Liste auf Position 20, dann werden die Resultate von 14-24 bei einem Count von 10 ausgegeben. - * Beispiel: Der Nutzer ist in der Liste auf Position 3, dann werden die Resultate von 1-10 bei einem Count von 10 ausgegeben. - */ - static getSortedEntriesAdjacent(key: string, user_or_userId: (User|number), parameters?: { ascending?: boolean; count?: number; }): UserPersistenceNumberEntry[]; - /** - * Liefert die absolute Position des Nutzers in der Liste. Die Position ist im Gegensatz zum Rang immer eindeutig. - * - * Bei gleichem Wert hat der Nutzer die höhere Position, der zuerst einen Eintrag in der Persistenz hatte. - * - * Mit der Methode UserPersistenceNumbers/getRank:method kann man den Rang des Nutzers herausfinden. Dieser ist identisch, wenn - * unterschiedliche Nutzer denselben Wert haben. - */ - static getPosition(key: string, user_or_userId: (User|number), parameters?: { ascending?: boolean; minimumValue?: number; }): number; - /** - * Liefert den Rang des Nutzers. Der Rang ist nicht eindeutig. Bei gleicher Punktzahl haben Nutzer denselben Rang. - * Mit der Methode UserPersistenceNumbers/getPosition:method kann man die Position eindeutige Position, statt des Ranges herausfinden. - */ - static getRank(key: string, user_or_userId: (User|number), parameters?: { ascending?: boolean; minimumValue?: number; }): number; - /** - * Ruft eine Funktion für alle Nutzer auf, die einen bestimmten key in der UserPersistence gesetzt haben. - * Hierbei greifen die übergebenen Filter. - */ - static each( - key: string, - callback: { user: User; value: number; index: number; totalCount: number; key: string; }, - parameters?: { - ascending?: boolean; - minimumValue?: number; - maximumValue?: number; - maximumCount?: number; - onStart?(totalCount: number, key: string): void; - onEnd?(totalCount: number, key: string): void; - }): void; - /** - * Liefert alle keys, die für User in der Persistence - * gespeichert wurden. - * @since AppServer 82483 - */ - static getAllKeys(filterKey?: string): string[]; -} - -/** - * Mit dieser Klasse ist es möglich nicht User-spezifische Abfragen auf die UserPersistence auszuführen. - */ -declare class UserPersistenceObjects { - /** - * Löscht alle gespeicherten Objekte für den übergebenen key. - * @since AppServer 82478 - */ - static deleteAll(key: string): number; - /** - * Liefert alle keys, die für User in der Persistence - * gespeichert wurden. - * @since AppServer 82483 - */ - static getAllKeys(filterKey?: string): string[]; -} - -/** - * Mit dieser Klasse ist es möglich nicht User-spezifische Abfragen auf die UserPersistence auszuführen. - */ -declare class UserPersistenceStrings { - /** - * Liefert die Information, ob für einen bestimmten key und value bei einem beliebigen Nutzer eine Paarung existiert. - * @since AppServer 88571 - */ - static exists(key: string, value: string, ignoreCase?: boolean): boolean; - /** - * Löscht alle gespeicherten Strings für den übergebenen key. - * @since AppServer 82478 - */ - static deleteAll(key: string): number; - /** - * Liefert alle keys, die für User in der Persistence - * gespeichert wurden. - * @since AppServer 82483 - */ - static getAllKeys(filterKey?: string): string[]; -} - -/** - * Repräsentiert den Status eines User. - */ -declare class UserStatus { - /** - * Liefert den numerischen Wert das UserStatus. - */ - getNumericStatus(): number; - /** - * Liefert die Information ob der aktuelle UserStatus mindestens so hoch ist, wie der übergebene UserStatus. - */ - isAtLeast(otherUserStatus: UserStatus): boolean; - /** - * - */ - static readonly Newbie: UserStatus; - /** - * - */ - static readonly Family: UserStatus; - /** - * - */ - static readonly Stammi: UserStatus; - /** - * - */ - static readonly HonoryMember: UserStatus; - /** - * - */ - static readonly Admin: UserStatus; - /** - * - */ - static readonly SystemBot: UserStatus; - /** - * - */ - static readonly Sysadmin: UserStatus; -} - -/** - * Repräsentiert den Typ eines User. - */ -declare class UserType { - /** - * Bot der App. - */ - static readonly AppBot: UserType; - /** - * Bot des Knuddels-Chatsystems. - */ - static readonly SystemBot: UserType; - /** - * Menschlicher User. - */ - static readonly Human: UserType; -} - -/** - * VideoChannelData hält Informationen zu laufenden Video-Streams im Channel bereit. - */ -declare class VideoChannelData { - /** - * Liefert alle User die im Channel derzeit ihr Video streamen. - */ - getStreamingVideoUsers(): User[]; -} diff --git a/types/knuddels-userapps-api/knuddels-userapps-api-tests.ts b/types/knuddels-userapps-api/knuddels-userapps-api-tests.ts index 4ee25c84ec..25319722c0 100644 --- a/types/knuddels-userapps-api/knuddels-userapps-api-tests.ts +++ b/types/knuddels-userapps-api/knuddels-userapps-api-tests.ts @@ -8,7 +8,7 @@ class Server implements App { onAppStart() { KnuddelsServer.getChannel() .getOnlineUsers(UserType.Human) - .forEach((user) => { + .forEach((user: User) => { this.onUserJoined(user); }); } @@ -23,7 +23,9 @@ class Server implements App { onUserLeft(user: User) { if (this.usersPlaying.get(user.getNick()) === 1) { KnuddelsServer.getDefaultBotUser() - .transferKnuddel(user, new KnuddelAmount(1), 'Du hast den Channel verlassen.'); + .transferKnuddel(user, new KnuddelAmount(1), { + displayReasonText: 'Du hast den Channel verlassen.' + }); this.usersPlaying.delete(user.getNick()); } @@ -39,8 +41,10 @@ class Server implements App { const user = KnuddelsServer.getUserAccess() .getUserById(userId); - KnuddelsServer.getDefaultBotUser() - .transferKnuddel(user, new KnuddelAmount(1), 'Die App fährt gleich herunter.'); + KnuddelsServer.getDefaultBotUser() + .transferKnuddel(user, new KnuddelAmount(1), { + displayReasonText: 'Die App fährt gleich herunter.' + }); user.getAppContentSessions() .forEach((session: AppContentSession) => { session.remove(); @@ -104,7 +108,9 @@ class Server implements App { if (hasWon) { KnuddelsServer.getDefaultBotUser() - .transferKnuddel(user, new KnuddelAmount(2), 'Richtig getippt...'); + .transferKnuddel(user, new KnuddelAmount(2), { + displayReasonText: 'Richtig getippt...' + }); } setTimeout(() => { diff --git a/types/koa-html-minifier/index.d.ts b/types/koa-html-minifier/index.d.ts new file mode 100644 index 0000000000..5343257116 --- /dev/null +++ b/types/koa-html-minifier/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for koa-html-minifier 1.0 +// Project: https://github.com/koajs/html-minifier +// Definitions by: Romain Faust +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Middleware } from 'koa'; +import { Options } from 'html-minifier'; + +declare function minifier(options?: Options): Middleware; + +declare namespace minifier {} + +export = minifier; diff --git a/types/koa-html-minifier/koa-html-minifier-tests.ts b/types/koa-html-minifier/koa-html-minifier-tests.ts new file mode 100644 index 0000000000..c068d303af --- /dev/null +++ b/types/koa-html-minifier/koa-html-minifier-tests.ts @@ -0,0 +1,8 @@ +import * as Koa from 'koa'; +import * as KoaHtmlMinifier from 'koa-html-minifier'; + +const app = new Koa() + .use(KoaHtmlMinifier()) + .use(KoaHtmlMinifier({ + collapseWhitespace: true + })); diff --git a/types/koa-html-minifier/tsconfig.json b/types/koa-html-minifier/tsconfig.json new file mode 100644 index 0000000000..9a46770f6f --- /dev/null +++ b/types/koa-html-minifier/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-html-minifier-tests.ts" + ] +} diff --git a/types/koa-html-minifier/tslint.json b/types/koa-html-minifier/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-html-minifier/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-joi-router/index.d.ts b/types/koa-joi-router/index.d.ts index bf3f387d31..e9e8670726 100644 --- a/types/koa-joi-router/index.d.ts +++ b/types/koa-joi-router/index.d.ts @@ -1,30 +1,36 @@ // Type definitions for koa-joi-router 5.0 // Project: https://github.com/koajs/joi-router // Definitions by: Matthew Bull +// Dave Welsh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 import * as Koa from 'koa'; import * as Joi from 'joi'; -interface Spec { - method: string; - path: string|RegExp; - handler: (ctx: createRouter.Context) => void; - validate?: { - type: string; - body?: Joi.AnySchema; - params?: Joi.AnySchema; - output?: {[status: number]: Joi.AnySchema}; - }; -} - interface createRouter { (): createRouter.Router; Joi: typeof Joi; } declare namespace createRouter { + interface Spec { + method: string; + path: string|RegExp; + handler: (ctx: Context) => void; + validate?: { + header?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; + query?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; + params?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; + body?: Joi.AnySchema|{[key: string]: Joi.AnySchema}; + maxBody?: number; + failure?: number; + type?: 'form'|'json'|'multipart'; + output?: {[status: number]: Joi.AnySchema}; + continueOnError?: boolean; + }; + } + interface Request extends Koa.Request { body: any; params: {[key: string]: string}; diff --git a/types/koa-joi-router/koa-joi-router-tests.ts b/types/koa-joi-router/koa-joi-router-tests.ts index 76a392bdec..90dac8d752 100644 --- a/types/koa-joi-router/koa-joi-router-tests.ts +++ b/types/koa-joi-router/koa-joi-router-tests.ts @@ -2,7 +2,7 @@ import router = require('koa-joi-router'); const { Joi } = router; -const spec1 = { +const spec1: router.Spec = { path: '/user', method: 'POST', handler: (ctx: router.Context) => ctx.body = '', @@ -10,7 +10,7 @@ const spec1 = { router().route(spec1); -const spec2 = { +const spec2: router.Spec = { method: 'PATCH', path: '/user', validate: { @@ -21,7 +21,7 @@ const spec2 = { router().route(spec2); -const spec3 = { +const spec3: router.Spec = { method: 'PATCH', path: '/user', validate: { @@ -33,7 +33,7 @@ const spec3 = { router().route(spec3); -const spec4 = { +const spec4: router.Spec = { method: 'PATCH', path: '/user', validate: { @@ -50,7 +50,7 @@ const spec4 = { router().route(spec4); -const spec5 = { +const spec5: router.Spec = { method: 'PUT', path: '/user', handler: (ctx: router.Context) => { @@ -61,7 +61,7 @@ const spec5 = { router().route(spec5); -const spec6 = { +const spec6: router.Spec = { method: 'GET', path: '/user', handler: (ctx: router.Context) => { @@ -72,6 +72,39 @@ const spec6 = { router().route(spec6); +const spec7: router.Spec = { + method: 'GET', + path: '/user', + validate: { + query: { + id: Joi.number(), + name: Joi.string(), + } + }, + handler: (ctx: router.Context) => { + ctx.status = 201; + ctx.body = ctx.request.params; + }, +}; + +router().route(spec7); + +const spec8: router.Spec = { + method: 'POST', + path: '/user', + validate: { + header: { + authentication: Joi.string(), + } + }, + handler: (ctx: router.Context) => { + ctx.status = 201; + ctx.body = ctx.request.params; + }, +}; + +router().route(spec8); + router().route([spec1, spec2, spec3]); router().routes.map(({ path }) => path); diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index 7382dd91e6..f8a31e71cb 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Jerry Chin // Pavel Ivanov // JounQin +// Romain Faust // Definitions: https://github.com/hellopao/DefinitelyTyped // TypeScript Version: 2.3 @@ -51,6 +52,10 @@ declare namespace Router { * url params */ params: any; + /** + * the router instance + */ + router: Router; } export interface IMiddleware { diff --git a/types/koa-router/koa-router-tests.ts b/types/koa-router/koa-router-tests.ts index 1325da0de0..b2bec9ad0c 100644 --- a/types/koa-router/koa-router-tests.ts +++ b/types/koa-router/koa-router-tests.ts @@ -8,21 +8,27 @@ const router = new Router({ }); router - .param('id', function(id, ctx, next) { - next(); - }) - .get('/', function (ctx, next) { - ctx.body = 'Hello World!'; - }) - .post('/users', function (ctx, next) { - // ... - }) - .put('/users/:id', function (ctx, next) { - ctx.body = ctx.params.id; - }) - .del('/users/:id', function () { - // ... - }); + .param('id', function (id, ctx, next) { + next(); + }) + .get('/', function (ctx, next) { + ctx.body = 'Hello World!'; + }) + .get('/users/:id', function (ctx, next) { + ctx.body = ctx.router.url('user-accounts', { id: ctx.params.id }) + }) + .get('user-accounts', '/users/:id/accounts', function (ctx, next) { + // ... + }) + .post('/users', function (ctx, next) { + // ... + }) + .put('/users/:id', function (ctx, next) { + ctx.body = ctx.params.id; + }) + .del('/users/:id', function () { + // ... + }); router.get('user', '/users/:id', function (ctx) { ctx.body = "sdsd"; diff --git a/types/koa__cors/index.d.ts b/types/koa__cors/index.d.ts index 25d337716e..da58136652 100644 --- a/types/koa__cors/index.d.ts +++ b/types/koa__cors/index.d.ts @@ -1,10 +1,13 @@ // Type definitions for @koa/cors 2.2 // Project: https://github.com/koajs/cors -// Definitions by: Xavier Stouder , Izayoi Ko , Steve Hipwell +// Definitions by: Xavier Stouder +// Izayoi Ko +// Steve Hipwell +// Steven McDowall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as Koa from "koa"; +import * as Koa from 'koa'; export = cors; @@ -12,7 +15,7 @@ declare function cors(options?: cors.Options): Koa.Middleware; declare namespace cors { interface Options { - origin?: ((req: Koa.Request) => string) | string; + origin?: ((ctx: Koa.Context) => string) | string; allowMethods?: string[] | string; exposeHeaders?: string[] | string; allowHeaders?: string[] | string; diff --git a/types/koa__cors/koa__cors-tests.ts b/types/koa__cors/koa__cors-tests.ts index 135845f205..25f068eb13 100644 --- a/types/koa__cors/koa__cors-tests.ts +++ b/types/koa__cors/koa__cors-tests.ts @@ -3,3 +3,11 @@ import cors = require('@koa/cors'); const app = new Koa(); app.use(cors()); + +// Trying using cors() passing in a function .. +function testCorsFunction(ctx: Koa.Context) { + const requestOrigin = ctx.request.origin; + return requestOrigin; +} + +app.use(cors({ origin: testCorsFunction })); diff --git a/types/lazy.js/index.d.ts b/types/lazy.js/index.d.ts index 3a44d2ce40..cea9ef0dea 100644 --- a/types/lazy.js/index.d.ts +++ b/types/lazy.js/index.d.ts @@ -4,259 +4,283 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace LazyJS { - interface LazyStatic { - - (value: string): StringLikeSequence; - (value: T[]): ArrayLikeSequence; - (value: any[]): ArrayLikeSequence; - (value: Object): ObjectLikeSequence; - (value: Object): ObjectLikeSequence; - - strict(): LazyStatic; - - generate(generatorFn: GeneratorCallback, length?: number): GeneratedSequence; - - range(to: number): GeneratedSequence; - range(from: number, to: number, step?: number): GeneratedSequence; - - repeat(value: T, count?: number): GeneratedSequence; - - on(eventType: string): Sequence; - - readFile(path: string): StringLikeSequence; - makeHttpRequest(path: string): StringLikeSequence; + (value: string): StringLikeSequence; + (value: T[]): ArrayLikeSequence; + (value: any[]): ArrayLikeSequence; + (value: Object): ObjectLikeSequence; + (value: Object): ObjectLikeSequence; + + strict(): LazyStatic; + + generate( + generatorFn: GeneratorCallback, + length?: number + ): GeneratedSequence; + + range(to: number): GeneratedSequence; + range(from: number, to: number, step?: number): GeneratedSequence; + + repeat(value: T, count?: number): GeneratedSequence; + + on(eventType: string): Sequence; + + readFile(path: string): StringLikeSequence; + makeHttpRequest(path: string): StringLikeSequence; } - + interface ArrayLike { - length: number; - [index: number]: T; + length: number; + [index: number]: T; } - + interface Callback { - (): void; + (): void; } - + interface ErrorCallback { - (error: any): void; + (error: any): void; } - + interface ValueCallback { - (value: T): void; + (value: T): void; } - + interface GetKeyCallback { - (value: T): string; + (value: T): string; } - - interface TestCallback { - (value: T): boolean; + + interface TestCallback { + (value: T, index: U): boolean; } - + interface MapCallback { - (value: T): U; + (value: T): U; } - + interface MapStringCallback { - (value: string): string; + (value: string): string; } - + interface NumberCallback { - (value: T): number; + (value: T): number; } - + interface MemoCallback { - (memo: U, value: T): U; + (memo: U, value: T): U; } - + interface GeneratorCallback { - (index: number): T; + (index: number): T; } - + interface CompareCallback { - (x: any, y: any): number; + (x: any, y: any): number; } - + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + interface Iterator { - new (sequence: Sequence): Iterator; - current(): T; - moveNext(): boolean; + new (sequence: Sequence): Iterator; + current(): T; + moveNext(): boolean; } - + interface GeneratedSequence extends Sequence { - new(generatorFn: GeneratorCallback, length: number): GeneratedSequence; - length(): number; + new (generatorFn: GeneratorCallback, length: number): GeneratedSequence< + T + >; + length(): number; } - + interface AsyncSequence extends SequenceBase { - each(callback: ValueCallback): AsyncHandle; + each(callback: ValueCallback): AsyncHandle; } - + interface AsyncHandle { - cancel(): void; - onComplete(callback: Callback): void; - onError(callback: ErrorCallback): void; + cancel(): void; + onComplete(callback: Callback): void; + onError(callback: ErrorCallback): void; } - + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + namespace Sequence { - function define(methodName: string[], overrides: Object): Function; + function define(methodName: string[], overrides: Object): Function; } - + interface Sequence extends SequenceBase { - each(eachFn: ValueCallback): Sequence; + each(eachFn: ValueCallback): Sequence; } - + interface SequenceBase extends SequenceBaser { - first(): any; - first(count: number): Sequence; - indexOf(value: any, startIndex?: number): Sequence; - - last(): any; - last(count: number): Sequence; - lastIndexOf(value: any): Sequence; - - reverse(): Sequence; + first(): any; + first(count: number): Sequence; + indexOf(value: any, startIndex?: number): Sequence; + + last(): any; + last(count: number): Sequence; + lastIndexOf(value: any): Sequence; + + reverse(): Sequence; } - + interface SequenceBaser { - // TODO improve define() (needs ugly overload) - async(interval: number): AsyncSequence; - chunk(size: number): Sequence; - compact(): Sequence; - concat(var_args: T[]): Sequence; - consecutive(length: number): Sequence; - contains(value: T): boolean; - countBy(keyFn: GetKeyCallback): ObjectLikeSequence; - countBy(propertyName: string): ObjectLikeSequence; - dropWhile(predicateFn: TestCallback): Sequence; - every(predicateFn: TestCallback): boolean; - filter(predicateFn: TestCallback): Sequence; - find(predicateFn: TestCallback): T; - findWhere(properties: Object): T; - - flatten(): Sequence; - groupBy(keyFn: GetKeyCallback): ObjectLikeSequence; - initial(count?: number): Sequence; - intersection(var_args: T[]): Sequence; - invoke(methodName: string): Sequence; - isEmpty(): boolean; - join(delimiter?: string): string; - map(mapFn: MapCallback): Sequence; - - max(valueFn?: NumberCallback): T; - min(valueFn?: NumberCallback): T; - none(valueFn?: TestCallback): boolean; - pluck(propertyName: string): Sequence; - reduce(aggregatorFn: MemoCallback, memo?: U): U; - reduceRight(aggregatorFn: MemoCallback, memo: U): U; - reject(predicateFn: TestCallback): Sequence; - rest(count?: number): Sequence; - shuffle(): Sequence; - some(predicateFn?: TestCallback): boolean; - sort(sortFn?: CompareCallback, descending?: boolean): Sequence; - sortBy(sortFn: string, descending?: boolean): Sequence; - sortBy(sortFn: NumberCallback, descending?: boolean): Sequence; - sortedIndex(value: T): Sequence; - size(): number; - sum(valueFn?: NumberCallback): T; - takeWhile(predicateFn: TestCallback): Sequence; - union(var_args: T[]): Sequence; - uniq(): Sequence; - where(properties: Object): Sequence; - without(...var_args: T[]): Sequence; - without(var_args: T[]): Sequence; - zip(var_args: T[]): Sequence; - - toArray(): T[]; - toObject(): Object; + // TODO improve define() (needs ugly overload) + async(interval: number): AsyncSequence; + chunk(size: number): Sequence; + compact(): Sequence; + concat(var_args: T[]): Sequence; + consecutive(length: number): Sequence; + contains(value: T): boolean; + countBy(keyFn: GetKeyCallback): ObjectLikeSequence; + countBy(propertyName: string): ObjectLikeSequence; + dropWhile(predicateFn: TestCallback): Sequence; + every(predicateFn: TestCallback): boolean; + filter(predicateFn: TestCallback): Sequence; + find(predicateFn: TestCallback): T; + findWhere(properties: Object): T; + flatten(): Sequence; + groupBy(keyFn: GetKeyCallback): ObjectLikeSequence; + initial(count?: number): Sequence; + intersection(var_args: T[]): Sequence; + invoke(methodName: string): Sequence; + isEmpty(): boolean; + join(delimiter?: string): string; + map(mapFn: MapCallback): Sequence; + max(valueFn?: NumberCallback): T; + min(valueFn?: NumberCallback): T; + none(valueFn?: TestCallback): boolean; + pluck(propertyName: string): Sequence; + reduce(aggregatorFn: MemoCallback, memo?: U): U; + reduceRight(aggregatorFn: MemoCallback, memo: U): U; + reject(predicateFn: TestCallback): Sequence; + rest(count?: number): Sequence; + shuffle(): Sequence; + size(): number; + some(predicateFn?: TestCallback): boolean; + sort(sortFn?: CompareCallback, descending?: boolean): Sequence; + sortBy(sortFn: NumberCallback, descending?: boolean): Sequence; + sortBy(sortFn: string, descending?: boolean): Sequence; + sortedIndex(value: T): Sequence; + sum(valueFn?: NumberCallback): T; + takeWhile(predicateFn: TestCallback): Sequence; + toArray(): T[]; + toObject(): Object; + union(var_args: T[]): Sequence; + uniq(): Sequence; + where(properties: Object): Sequence; + without(...var_args: T[]): Sequence; + without(var_args: T[]): Sequence; + zip(var_args: T[]): Sequence; } - + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + namespace ArrayLikeSequence { - function define(methodName: string[], overrides: Object): Function; + function define(methodName: string[], overrides: Object): Function; } - + interface ArrayLikeSequence extends Sequence { - // define()X; - concat(var_args: T[]): ArrayLikeSequence; - first(count?: number): ArrayLikeSequence; - get(index: number): T; - length(): number; - map(mapFn: MapCallback): ArrayLikeSequence; - pop(): ArrayLikeSequence; - rest(count?: number): ArrayLikeSequence; - reverse(): ArrayLikeSequence; - shift(): ArrayLikeSequence; - slice(begin: number, end?: number): ArrayLikeSequence; + // define()X; + concat(var_args: T[]): ArrayLikeSequence; + first(count?: number): ArrayLikeSequence; + get(index: number): T; + length(): number; + map(mapFn: MapCallback): ArrayLikeSequence; + pop(): ArrayLikeSequence; + push(value: T): ArrayLikeSequence; + rest(count?: number): ArrayLikeSequence; + reverse(): ArrayLikeSequence; + shift(): ArrayLikeSequence; + slice(begin: number, end?: number): ArrayLikeSequence; + unshift(value: T): ArrayLikeSequence; + + dropWhile(predicateFn: TestCallback): Sequence; + every(predicateFn: TestCallback): boolean; + filter(predicateFn: TestCallback): Sequence; + find(predicateFn: TestCallback): T; + none(valueFn?: TestCallback): boolean; + reject(predicateFn: TestCallback): Sequence; + some(predicateFn?: TestCallback): boolean; + takeWhile(predicateFn: TestCallback): Sequence; } - + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + namespace ObjectLikeSequence { - function define(methodName: string[], overrides: Object): Function; + function define(methodName: string[], overrides: Object): Function; } - + interface ObjectLikeSequence extends Sequence { - assign(other: Object): ObjectLikeSequence; - // throws error - //async(): X; - defaults(defaults: Object): ObjectLikeSequence; - functions(): Sequence; - get(property: string): ObjectLikeSequence; - invert(): ObjectLikeSequence; - keys(): Sequence; - merge(others: Object | ObjectLikeSequence, mergeFn?: Function): ObjectLikeSequence; - omit(properties: string[]): ObjectLikeSequence; - pairs(): Sequence; - pick(properties: string[]): ObjectLikeSequence; - toArray(): T[]; - toObject(): Object; - values(): Sequence; + assign(other: Object): ObjectLikeSequence; + // throws error + //async(): X; + defaults(defaults: Object): ObjectLikeSequence; + functions(): Sequence; + get(property: string): ObjectLikeSequence; + invert(): ObjectLikeSequence; + keys(): Sequence; + merge(others: Object | ObjectLikeSequence, mergeFn?: Function): ObjectLikeSequence; + omit(properties: string[]): ObjectLikeSequence; + pairs(): Sequence; + pick(properties: string[]): ObjectLikeSequence; + toArray(): T[]; + toObject(): Object; + values(): Sequence; + watch(propertyNames: string | string[]): Sequence<{property: string; value: any;}>; + + dropWhile(predicateFn: TestCallback): Sequence; + every(predicateFn: TestCallback): boolean; + filter(predicateFn: TestCallback): Sequence; + find(predicateFn: TestCallback): T; + none(valueFn?: TestCallback): boolean; + reject(predicateFn: TestCallback): Sequence; + some(predicateFn?: TestCallback): boolean; + takeWhile(predicateFn: TestCallback): Sequence; } - + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + namespace StringLikeSequence { - function define(methodName: string[], overrides: Object): Function; + function define(methodName: string[], overrides: Object): Function; } - + interface StringLikeSequence extends SequenceBaser { - charAt(index: number): string; - charCodeAt(index: number): number; - contains(value: string): boolean; - endsWith(suffix: string): boolean; + charAt(index: number): string; + charCodeAt(index: number): number; + contains(value: string): boolean; + endsWith(suffix: string): boolean; + first(): string; + indexOf(substring: string, startIndex?: number): number; + last(): string; + last(count: number): StringLikeSequence; + lastIndexOf(substring: string, startIndex?: number): number; + mapString(mapFn: MapStringCallback): StringLikeSequence; + match(pattern: RegExp): StringLikeSequence; + reverse(): StringLikeSequence; + split(delimiter: RegExp): StringLikeSequence; + split(delimiter: string): StringLikeSequence; + startsWith(prefix: string): boolean; + substring(start: number, stop?: number): StringLikeSequence; + toLowerCase(): StringLikeSequence; + toUpperCase(): StringLikeSequence; - first(): string; - first(count: number): StringLikeSequence; - - indexOf(substring: string, startIndex?: number): number; - - last(): string; - last(count: number): StringLikeSequence; - - lastIndexOf(substring: string, startIndex?: number): number; - mapString(mapFn: MapStringCallback): StringLikeSequence; - match(pattern: RegExp): StringLikeSequence; - reverse(): StringLikeSequence; - - split(delimiter: string): StringLikeSequence; - split(delimiter: RegExp): StringLikeSequence; - - startsWith(prefix: string): boolean; - substring(start: number, stop?: number): StringLikeSequence; - toLowerCase(): StringLikeSequence; - toUpperCase(): StringLikeSequence; + dropWhile(predicateFn: TestCallback): Sequence; + every(predicateFn: TestCallback): boolean; + filter(predicateFn: TestCallback): Sequence; + find(predicateFn: TestCallback): string; + first(count: number): StringLikeSequence; + none(valueFn?: TestCallback): boolean; + reject(predicateFn: TestCallback): Sequence; + some(predicateFn?: TestCallback): boolean; + takeWhile(predicateFn: TestCallback): Sequence; } -} - -declare var Lazy: LazyJS.LazyStatic; - -declare module 'lazy.js' { -export = Lazy; -} - + } + + declare var Lazy: LazyJS.LazyStatic; + + declare module 'lazy.js' { + export = Lazy; + } + \ No newline at end of file diff --git a/types/leaflet-routing-machine/index.d.ts b/types/leaflet-routing-machine/index.d.ts index 16da37f7c5..2ec6d9ef27 100644 --- a/types/leaflet-routing-machine/index.d.ts +++ b/types/leaflet-routing-machine/index.d.ts @@ -111,6 +111,7 @@ declare module 'leaflet' { profile?: string; polylinePrecision?: number; useHints?: boolean; + routingOptions?: any; } class Formatter { @@ -190,6 +191,7 @@ declare module 'leaflet' { allowUTurns: boolean; geometryOnly: boolean; fileFormat: string; + simplifyGeometry: boolean; } // tslint:disable-next-line interface-name diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index 47b2ebc515..89c9cbd9b9 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -1406,6 +1406,7 @@ export class Map extends Evented { scrollWheelZoom: Handler; tap?: Handler; touchZoom: Handler; + zoomControl: Control.Zoom; options: MapOptions; } diff --git a/types/less/index.d.ts b/types/less/index.d.ts index bca5c21c33..7d69273a52 100644 --- a/types/less/index.d.ts +++ b/types/less/index.d.ts @@ -52,6 +52,11 @@ declare namespace Less { interface StaticOptions { async: boolean; fileAsync: boolean; + modifyVars: { [variable: string]: string }; + } + + interface ImportManager { + contents: { [fileName: string]: string }; } interface Options { @@ -76,21 +81,33 @@ declare namespace Less { map: string; imports: string[]; } + + interface RefreshOutput { + endTime: Date; + startTime: Date; + sheets: number; + totalMilliseconds: number; + } } interface LessStatic { options: Less.StaticOptions; - - modifyVars(vars: { [name: string]: string }): void; - + + importManager?: Less.ImportManager; + sheets: HTMLLinkElement[]; + + modifyVars(vars: { [name: string]: string }): Promise; + refreshStyles(): void; - + render(input: string, callback: (error: Less.RenderError, output: Less.RenderOutput) => void): void; render(input: string, options: Less.Options, callback: (error: Less.RenderError, output: Less.RenderOutput) => void): void; render(input: string): Promise; render(input: string, options: Less.Options): Promise; + refresh(reload?: boolean, modifyVars?: { [variable: string]: string }, clearFileCache?: boolean): Promise; + version: number[]; watch(): void; diff --git a/types/less/less-tests.ts b/types/less/less-tests.ts index 5d0029475a..20a1f587a9 100644 --- a/types/less/less-tests.ts +++ b/types/less/less-tests.ts @@ -39,8 +39,22 @@ less.render("h1 { background: red; }", options); less.modifyVars({ '@buttonFace': '#5B83AD', '@buttonText': '#D9EEF2' +}).then((output) => { + console.log('Successfully modified vars.'); }); less.refreshStyles(); less.watch(); + +less.refresh(true, { + '@buttonFace': '#5B83AD' +}, true).then((output) => { + console.log('successfully refreshed less files'); +}); + +if (less.importManager) { + for (let fileName in less.importManager.contents) { + let fileContents = less.importManager.contents[fileName]; + } +} \ No newline at end of file diff --git a/types/lodash/common/common.d.ts b/types/lodash/common/common.d.ts index dcbe28cb3a..864450b1bd 100644 --- a/types/lodash/common/common.d.ts +++ b/types/lodash/common/common.d.ts @@ -179,16 +179,17 @@ declare module "../index" { } type NotVoid = {} | null | undefined; + type IterateeShorthand = PropertyName | [PropertyName, any] | PartialDeep; type ArrayIterator = (value: T, index: number, collection: T[]) => TResult; type ListIterator = (value: T, index: number, collection: List) => TResult; - type ListIteratee = ListIterator | string | [string, any] | PartialDeep; - type ListIterateeCustom = ListIterator | string | [string, any] | PartialDeep; + type ListIteratee = ListIterator | IterateeShorthand; + type ListIterateeCustom = ListIterator | IterateeShorthand; type ListIteratorTypeGuard = (value: T, index: number, collection: List) => value is S; // Note: key should be string, not keyof T, because the actual object may contain extra properties that were not specified in the type. type ObjectIterator = (value: TObject[keyof TObject], key: string, collection: TObject) => TResult; - type ObjectIteratee = ObjectIterator | string | [string, any] | PartialDeep; - type ObjectIterateeCustom = ObjectIterator | string | [string, any] | PartialDeep; + type ObjectIteratee = ObjectIterator | IterateeShorthand; + type ObjectIterateeCustom = ObjectIterator | IterateeShorthand; type ObjectIteratorTypeGuard = (value: TObject[keyof TObject], key: string, collection: TObject) => value is S; type StringIterator = (char: string, index: number, string: string) => TResult; @@ -207,10 +208,11 @@ declare module "../index" { type MemoVoidDictionaryIterator = (acc: TResult, curr: T, key: string, dict: Dictionary) => void; type MemoVoidIteratorCapped = (acc: TResult, curr: T) => void; - type ValueIteratee = ((value: T) => NotVoid) | string | [string, any] | PartialDeep; - type ValueIterateeCustom = ((value: T) => TResult) | string | [string, any] | PartialDeep; + type ValueIteratee = ((value: T) => NotVoid) | IterateeShorthand; + type ValueIterateeCustom = ((value: T) => TResult) | IterateeShorthand; type ValueIteratorTypeGuard = (value: T) => value is S; - type ValueKeyIteratee = ((value: T, key: string) => NotVoid) | string | [string, any] | PartialDeep; + type ValueKeyIteratee = ((value: T, key: string) => NotVoid) | IterateeShorthand; + type ValueKeyIterateeTypeGuard = (value: T, key: string) => value is S; type Comparator = (a: T, b: T) => boolean; type Comparator2 = (a: T1, b: T2) => boolean; @@ -263,6 +265,6 @@ declare module "../index" { type DictionaryIteratorTypeGuard = ObjectIteratorTypeGuard, S>; // NOTE: keys of objects at run time are always strings, even when a NumericDictionary is being iterated. type NumericDictionaryIterator = (value: T, key: string, collection: NumericDictionary) => TResult; - type NumericDictionaryIteratee = NumericDictionaryIterator | string | [string, any] | PartialDeep; - type NumericDictionaryIterateeCustom = NumericDictionaryIterator | string | [string, any] | PartialDeep; + type NumericDictionaryIteratee = NumericDictionaryIterator | IterateeShorthand; + type NumericDictionaryIterateeCustom = NumericDictionaryIterator | IterateeShorthand; } diff --git a/types/lodash/common/object.d.ts b/types/lodash/common/object.d.ts index edb9e1736c..b136e9469b 100644 --- a/types/lodash/common/object.d.ts +++ b/types/lodash/common/object.d.ts @@ -3111,11 +3111,19 @@ declare module "../index" { * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ - pickBy( - object: T | null | undefined, - predicate: ObjectIteratorTypeGuard + pickBy( + object: Dictionary | null | undefined, + predicate: ValueKeyIterateeTypeGuard ): Dictionary; + /** + * @see _.pickBy + */ + pickBy( + object: NumericDictionary | null | undefined, + predicate: ValueKeyIterateeTypeGuard + ): NumericDictionary; + /** * @see _.pickBy */ @@ -3145,11 +3153,19 @@ declare module "../index" { /** * @see _.pickBy */ - pickBy( - this: LoDashImplicitWrapper, - predicate: ObjectIteratorTypeGuard + pickBy( + this: LoDashImplicitWrapper | null | undefined>, + predicate: ValueKeyIterateeTypeGuard ): LoDashImplicitWrapper>; + /** + * @see _.pickBy + */ + pickBy( + this: LoDashImplicitWrapper | null | undefined>, + predicate: ValueKeyIterateeTypeGuard + ): LoDashImplicitWrapper>; + /** * @see _.pickBy */ @@ -3179,11 +3195,19 @@ declare module "../index" { /** * @see _.pickBy */ - pickBy( - this: LoDashExplicitWrapper, - predicate: ObjectIteratorTypeGuard + pickBy( + this: LoDashExplicitWrapper | null | undefined>, + predicate: ValueKeyIterateeTypeGuard ): LoDashExplicitWrapper>; + /** + * @see _.pickBy + */ + pickBy( + this: LoDashExplicitWrapper | null | undefined>, + predicate: ValueKeyIterateeTypeGuard + ): LoDashExplicitWrapper>; + /** * @see _.pickBy */ diff --git a/types/lodash/fp.d.ts b/types/lodash/fp.d.ts index f373d81a27..cdc850d444 100644 --- a/types/lodash/fp.d.ts +++ b/types/lodash/fp.d.ts @@ -2887,28 +2887,35 @@ declare namespace _ { type LodashPick2x1 = (object: T | null | undefined) => lodash.PartialDeep; type LodashPick2x2 = (props: lodash.PropertyPath) => lodash.PartialDeep; interface LodashPickBy { - (predicate: lodash.ValueIteratorTypeGuard): LodashPickBy1x1; - (predicate: lodash.__, object: T | null | undefined): LodashPickBy1x2; - (predicate: lodash.ValueIteratorTypeGuard, object: T | null | undefined): lodash.Dictionary; - (predicate: lodash.ValueKeyIteratee): LodashPickBy2x1; - (predicate: lodash.__, object: lodash.Dictionary | null | undefined): LodashPickBy2x2; + (predicate: lodash.ValueKeyIterateeTypeGuard): LodashPickBy1x1; + (predicate: lodash.__, object: lodash.Dictionary | null | undefined): LodashPickBy1x2; + (predicate: lodash.ValueKeyIterateeTypeGuard, object: lodash.Dictionary | null | undefined): lodash.Dictionary; + (predicate: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashPickBy2x2; + (predicate: lodash.ValueKeyIterateeTypeGuard, object: lodash.NumericDictionary | null | undefined): lodash.NumericDictionary; + (predicate: lodash.ValueKeyIteratee): LodashPickBy3x1; (predicate: lodash.ValueKeyIteratee, object: lodash.Dictionary | null | undefined): lodash.Dictionary; - (predicate: lodash.__, object: lodash.NumericDictionary | null | undefined): LodashPickBy3x2; (predicate: lodash.ValueKeyIteratee, object: lodash.NumericDictionary | null | undefined): lodash.NumericDictionary; + (predicate: lodash.__, object: T | null | undefined): LodashPickBy5x2; (predicate: lodash.ValueKeyIteratee, object: T | null | undefined): lodash.PartialObject; } - type LodashPickBy1x1 = (object: T | null | undefined) => lodash.Dictionary; - interface LodashPickBy1x2 { - (predicate: lodash.ValueIteratorTypeGuard): lodash.Dictionary; - (predicate: lodash.ValueKeyIteratee): lodash.PartialObject; + interface LodashPickBy1x1 { + (object: lodash.Dictionary | null | undefined): lodash.Dictionary; + (object: lodash.NumericDictionary | null | undefined): lodash.NumericDictionary; } - interface LodashPickBy2x1 { + interface LodashPickBy1x2 { + (predicate: lodash.ValueKeyIterateeTypeGuard): lodash.Dictionary; + (predicate: lodash.ValueKeyIteratee): lodash.Dictionary; + } + interface LodashPickBy2x2 { + (predicate: lodash.ValueKeyIterateeTypeGuard): lodash.NumericDictionary; + (predicate: lodash.ValueKeyIteratee): lodash.NumericDictionary; + } + interface LodashPickBy3x1 { (object: lodash.Dictionary | null | undefined): lodash.Dictionary; (object: lodash.NumericDictionary | null | undefined): lodash.NumericDictionary; (object: T1 | null | undefined): lodash.PartialObject; } - type LodashPickBy2x2 = (predicate: lodash.ValueKeyIteratee) => lodash.Dictionary; - type LodashPickBy3x2 = (predicate: lodash.ValueKeyIteratee) => lodash.NumericDictionary; + type LodashPickBy5x2 = (predicate: lodash.ValueKeyIteratee) => lodash.PartialObject; interface LodashProp { (path: TKey | [TKey]): LodashProp1x1; (path: lodash.__, object: TObject): LodashProp1x2; diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index 2201a9a5cd..0515136714 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -2539,65 +2539,67 @@ _.chain([1, 2, 3, 4]).unshift(5, 6); // $ExpectType LoDashExplicitWrapper ""; + const subKey: string | number | symbol = anything; _.keyBy("abcd"); // $ExpectType Dictionary _.keyBy("abcd", stringIterator); // $ExpectType Dictionary _.keyBy(list); // $ExpectType Dictionary _.keyBy(list, valueIterator); // $ExpectType Dictionary - _.keyBy(list, "a"); // $ExpectType Dictionary + _.keyBy(list, subKey); // $ExpectType Dictionary _.keyBy(list, { a: 42 }); // $ExpectType Dictionary _.keyBy(dictionary); // $ExpectType Dictionary _.keyBy(dictionary, valueIterator); // $ExpectType Dictionary - _.keyBy(dictionary, "a"); // $ExpectType Dictionary + _.keyBy(dictionary, subKey); // $ExpectType Dictionary _.keyBy(dictionary, { a: 42 }); // $ExpectType Dictionary _.keyBy(numericDictionary); // $ExpectType Dictionary _.keyBy(numericDictionary, valueIterator); // $ExpectType Dictionary _.keyBy(numericDictionary, "a"); // $ExpectType Dictionary + _.keyBy(numericDictionary, subKey); // $ExpectType Dictionary _.keyBy(numericDictionary, { a: 42 }); // $ExpectType Dictionary _("abcd").keyBy(); // $ExpectType LoDashImplicitWrapper> _("abcd").keyBy(stringIterator); // $ExpectType LoDashImplicitWrapper> _(list).keyBy(); // $ExpectType LoDashImplicitWrapper> _(list).keyBy(valueIterator); // $ExpectType LoDashImplicitWrapper> - _(list).keyBy("a"); // $ExpectType LoDashImplicitWrapper> + _(list).keyBy(subKey); // $ExpectType LoDashImplicitWrapper> _(list).keyBy({ a: 42 }); // $ExpectType LoDashImplicitWrapper> _(dictionary).keyBy(); // $ExpectType LoDashImplicitWrapper> _(dictionary).keyBy(valueIterator); // $ExpectType LoDashImplicitWrapper> - _(dictionary).keyBy("a"); // $ExpectType LoDashImplicitWrapper> + _(dictionary).keyBy(subKey); // $ExpectType LoDashImplicitWrapper> _(dictionary).keyBy({ a: 42 }); // $ExpectType LoDashImplicitWrapper> _(numericDictionary).keyBy(); // $ExpectType LoDashImplicitWrapper> _(numericDictionary).keyBy(valueIterator); // $ExpectType LoDashImplicitWrapper> - _(numericDictionary).keyBy("a"); // $ExpectType LoDashImplicitWrapper> + _(numericDictionary).keyBy(subKey); // $ExpectType LoDashImplicitWrapper> _(numericDictionary).keyBy({ a: 42 }); // $ExpectType LoDashImplicitWrapper> _.chain("abcd").keyBy(); // $ExpectType LoDashExplicitWrapper> _.chain("abcd").keyBy(stringIterator); // $ExpectType LoDashExplicitWrapper> _.chain(list).keyBy(); // $ExpectType LoDashExplicitWrapper> _.chain(list).keyBy(valueIterator); // $ExpectType LoDashExplicitWrapper> - _.chain(list).keyBy("a"); // $ExpectType LoDashExplicitWrapper> + _.chain(list).keyBy(subKey); // $ExpectType LoDashExplicitWrapper> _.chain(list).keyBy({ a: 42 }); // $ExpectType LoDashExplicitWrapper> _.chain(dictionary).keyBy(); // $ExpectType LoDashExplicitWrapper> _.chain(dictionary).keyBy(valueIterator); // $ExpectType LoDashExplicitWrapper> - _.chain(dictionary).keyBy("a"); // $ExpectType LoDashExplicitWrapper> + _.chain(dictionary).keyBy(subKey); // $ExpectType LoDashExplicitWrapper> _.chain(dictionary).keyBy({ a: 42 }); // $ExpectType LoDashExplicitWrapper> _.chain(numericDictionary).keyBy(); // $ExpectType LoDashExplicitWrapper> _.chain(numericDictionary).keyBy(valueIterator); // $ExpectType LoDashExplicitWrapper> - _.chain(numericDictionary).keyBy("a"); // $ExpectType LoDashExplicitWrapper> + _.chain(numericDictionary).keyBy(subKey); // $ExpectType LoDashExplicitWrapper> _.chain(numericDictionary).keyBy({ a: 42 }); // $ExpectType LoDashExplicitWrapper> fp.keyBy(valueIterator, list); // $ExpectType Dictionary fp.keyBy(valueIterator)(list); // $ExpectType Dictionary - fp.keyBy("a", list); // $ExpectType Dictionary + fp.keyBy(subKey, list); // $ExpectType Dictionary fp.keyBy({ a: 42 }, list); // $ExpectType Dictionary - fp.keyBy(["a", 42], list); // $ExpectType Dictionary + fp.keyBy([subKey, 42], list); // $ExpectType Dictionary fp.keyBy(valueIterator, dictionary); // $ExpectType Dictionary - fp.keyBy("a", dictionary); // $ExpectType Dictionary + fp.keyBy(subKey, dictionary); // $ExpectType Dictionary fp.keyBy({ a: 42 }, dictionary); // $ExpectType Dictionary - fp.keyBy(["a", 42], dictionary); // $ExpectType Dictionary + fp.keyBy([subKey, 42], dictionary); // $ExpectType Dictionary fp.keyBy(valueIterator, numericDictionary); // $ExpectType Dictionary - fp.keyBy("a", numericDictionary); // $ExpectType Dictionary + fp.keyBy(subKey, numericDictionary); // $ExpectType Dictionary fp.keyBy({ a: 42 }, numericDictionary); // $ExpectType Dictionary - fp.keyBy(["a", 42], numericDictionary); // $ExpectType Dictionary + fp.keyBy([subKey, 42], numericDictionary); // $ExpectType Dictionary } // _.invoke @@ -3026,74 +3028,76 @@ _.chain([1, 2, 3, 4]).unshift(5, 6); // $ExpectType LoDashExplicitWrapper _.chain(list).some(listIterator); // $ExpectType LoDashExplicitWrapper - _.chain(list).some("a"); // $ExpectType LoDashExplicitWrapper - _.chain(list).some(["a", 42]); // $ExpectType LoDashExplicitWrapper + _.chain(list).some(subKey); // $ExpectType LoDashExplicitWrapper + _.chain(list).some([subKey, 42]); // $ExpectType LoDashExplicitWrapper _.chain(list).some({ a: 42 }); // $ExpectType LoDashExplicitWrapper _.chain(dictionary).some(); // $ExpectType LoDashExplicitWrapper _.chain(dictionary).some(dictionaryIterator); // $ExpectType LoDashExplicitWrapper - _.chain(dictionary).some("a"); // $ExpectType LoDashExplicitWrapper - _.chain(dictionary).some(["a", 42]); // $ExpectType LoDashExplicitWrapper + _.chain(dictionary).some(subKey); // $ExpectType LoDashExplicitWrapper + _.chain(dictionary).some([subKey, 42]); // $ExpectType LoDashExplicitWrapper _.chain(dictionary).some({ a: 42 }); // $ExpectType LoDashExplicitWrapper _.chain(numericDictionary).some(); // $ExpectType LoDashExplicitWrapper _.chain(numericDictionary).some(numericDictionaryIterator); // $ExpectType LoDashExplicitWrapper - _.chain(numericDictionary).some("a"); // $ExpectType LoDashExplicitWrapper - _.chain(numericDictionary).some(["a", 42]); // $ExpectType LoDashExplicitWrapper + _.chain(numericDictionary).some(subKey); // $ExpectType LoDashExplicitWrapper + _.chain(numericDictionary).some([subKey, 42]); // $ExpectType LoDashExplicitWrapper _.chain(numericDictionary).some({ a: 42 }); // $ExpectType LoDashExplicitWrapper fp.some(valueIterator, list); // $ExpectType boolean - fp.some("a")(list); // $ExpectType boolean + fp.some(subKey)(list); // $ExpectType boolean fp.some({ a: 42 }, list); // $ExpectType boolean - fp.some(["a", 42], list); // $ExpectType boolean + fp.some([subKey, 42], list); // $ExpectType boolean fp.some(valueIterator, dictionary); // $ExpectType boolean - fp.some("a")(dictionary); // $ExpectType boolean + fp.some(subKey)(dictionary); // $ExpectType boolean fp.some({ a: 42 })(dictionary); // $ExpectType boolean - fp.some(["a", 42])(dictionary); // $ExpectType boolean + fp.some([subKey, 42])(dictionary); // $ExpectType boolean fp.some(valueIterator, numericDictionary); // $ExpectType boolean - fp.some("a")(numericDictionary); // $ExpectType boolean + fp.some(subKey)(numericDictionary); // $ExpectType boolean fp.some({ a: 42 })(numericDictionary); // $ExpectType boolean - fp.some(["a", 42])(numericDictionary); // $ExpectType boolean + fp.some([subKey, 42])(numericDictionary); // $ExpectType boolean } // _.sortBy @@ -5627,9 +5631,19 @@ fp.now(); // $ExpectType number const mixedDictionary: _.Dictionary | null | undefined = anything; - _.pickBy(mixedDictionary, (item: string | number): item is number => typeof item === "number"); // $ExpectType Dictionary - _(mixedDictionary).pickBy((item: string | number): item is number => typeof item === "number"); // $ExpectType LoDashImplicitWrapper> - _.chain(mixedDictionary).pickBy((item: string | number): item is number => typeof item === "number"); // $ExpectType LoDashExplicitWrapper> + const userDefinedTypeGuard = (item: string | number): item is number => typeof item === "number"; + + _.pickBy(mixedDictionary, userDefinedTypeGuard); // $ExpectType Dictionary + _(mixedDictionary).pickBy(userDefinedTypeGuard); // $ExpectType LoDashImplicitWrapper> + _.chain(mixedDictionary).pickBy(userDefinedTypeGuard); // $ExpectType LoDashExplicitWrapper> + fp.pickBy(userDefinedTypeGuard)(mixedDictionary); // $ExpectType Dictionary + + const mixedNumericDictionary: _.NumericDictionary | null | undefined = anything; + + _.pickBy(mixedNumericDictionary, userDefinedTypeGuard); // $ExpectType NumericDictionary + _(mixedNumericDictionary).pickBy(userDefinedTypeGuard); // $ExpectType LoDashImplicitWrapper> + _.chain(mixedNumericDictionary).pickBy(userDefinedTypeGuard); // $ExpectType LoDashExplicitWrapper> + fp.pickBy(userDefinedTypeGuard)(mixedNumericDictionary); // $ExpectType NumericDictionary } // _.result diff --git a/types/lowdb/_lodash.d.ts b/types/lowdb/_lodash.d.ts index dc34d17db0..ca8aace259 100644 --- a/types/lowdb/_lodash.d.ts +++ b/types/lowdb/_lodash.d.ts @@ -1297,10 +1297,14 @@ declare module "./index" { this: LoDashExplicitSyncWrapper, ...props: _.PropertyPath[] ): LoDashExplicitSyncWrapper<_.PartialObject>; - pickBy( - this: LoDashExplicitSyncWrapper, - predicate: _.ObjectIteratorTypeGuard + pickBy( + this: LoDashExplicitSyncWrapper<_.Dictionary | null | undefined>, + predicate: _.ValueKeyIterateeTypeGuard ): LoDashExplicitSyncWrapper<_.Dictionary>; + pickBy( + this: LoDashExplicitSyncWrapper<_.NumericDictionary | null | undefined>, + predicate: _.ValueKeyIterateeTypeGuard + ): LoDashExplicitSyncWrapper<_.NumericDictionary>; pickBy( this: LoDashExplicitSyncWrapper<_.Dictionary | null | undefined>, predicate?: _.ValueKeyIteratee @@ -2889,10 +2893,14 @@ declare module "./index" { this: LoDashExplicitAsyncWrapper, ...props: _.PropertyPath[] ): LoDashExplicitAsyncWrapper<_.PartialObject>; - pickBy( - this: LoDashExplicitAsyncWrapper, - predicate: _.ObjectIteratorTypeGuard + pickBy( + this: LoDashExplicitAsyncWrapper<_.Dictionary | null | undefined>, + predicate: _.ValueKeyIterateeTypeGuard ): LoDashExplicitAsyncWrapper<_.Dictionary>; + pickBy( + this: LoDashExplicitAsyncWrapper<_.NumericDictionary | null | undefined>, + predicate: _.ValueKeyIterateeTypeGuard + ): LoDashExplicitAsyncWrapper<_.NumericDictionary>; pickBy( this: LoDashExplicitAsyncWrapper<_.Dictionary | null | undefined>, predicate?: _.ValueKeyIteratee diff --git a/types/lunr/index.d.ts b/types/lunr/index.d.ts index e16851b52b..da87ae95d8 100644 --- a/types/lunr/index.d.ts +++ b/types/lunr/index.d.ts @@ -238,7 +238,6 @@ declare namespace lunr { * A query builder callback provides a query object to be used to express * the query to perform on the index. * - * @callback lunr.Index~queryBuilder * @param query - The query object to build up. */ type QueryBuilder = (this: Query, query: Query) => void; @@ -658,7 +657,6 @@ declare namespace lunr { * A token update function is used when updating or optionally * when cloning a token. * - * @callback lunr.Token~updateFunction * @param str - The string representation of the token. * @param metadata - All metadata associated with this token. */ diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index 17706a9002..e96e389894 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -319,8 +319,8 @@ declare module 'luxon' { } type IntervalObject = { - start: DateTime; - end: DateTime; + start?: DateTime; + end?: DateTime; }; class Interval { @@ -338,8 +338,8 @@ declare module 'luxon' { ): Interval; static fromISO(string: string, options?: DateTimeOptions): Interval; static invalid(reason?: string): Interval; - static merge(intervals: Interval[]): [Interval]; - static xor(intervals: Interval[]): [Interval]; + static merge(intervals: Interval[]): Interval[]; + static xor(intervals: Interval[]): Interval[]; end: DateTime; invalidReason: string; isValid: boolean; diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index de0aca9bfd..017f07b0c6 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -78,6 +78,7 @@ const i = Interval.fromDateTimes(now, later); i.length(); i.length('years'); i.contains(DateTime.local(2019)); +i.set({end: DateTime.local(2020)}); i.toISO(); i.toString(); diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 5f64b7470b..d85af4fd5a 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.45.0 +// Type definitions for Mapbox GL JS v0.47.0 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer , Patrick Reames // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -26,17 +26,15 @@ declare namespace mapboxgl { export class Map extends Evented { constructor(options?: MapboxOptions); - addControl(control: Control, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; + addControl(control: Control | IControl, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; - addControl(control: IControl, position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'): this; + removeControl(control: Control | IControl): this; - removeControl(control: Control): this; + resize(eventData?: EventData): this; - removeControl(control: IControl): this; + getBounds(): LngLatBounds; - resize(): this; - - getBounds(): mapboxgl.LngLatBounds; + getMaxBounds(): LngLatBounds; setMaxBounds(lnglatbounds?: LngLatBoundsLike): this; @@ -48,6 +46,10 @@ declare namespace mapboxgl { getMaxZoom(): number; + getRenderWorldCopies(): boolean; + + setRenderWorldCopies(renderWorldCopies?: boolean): this; + project(lnglat: LngLatLike): mapboxgl.Point; unproject(point: PointLike): mapboxgl.LngLat; @@ -62,13 +64,13 @@ declare namespace mapboxgl { querySourceFeatures(sourceID: string, parameters?: { sourceLayer?: string, filter?: any[] }): GeoJSON.Feature[]; - setStyle(style: mapboxgl.Style | string): this; + setStyle(style: mapboxgl.Style | string, options?: { diff?: boolean, localIdeographFontFamily?: string }): this; getStyle(): mapboxgl.Style; isStyleLoaded(): boolean; - addSource(id: string, source: VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; + addSource(id: string, source: VectorSource | RasterSource | RasterDemSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; isSourceLoaded(id: string): boolean; @@ -76,9 +78,9 @@ declare namespace mapboxgl { removeSource(id: string): this; - getSource(id: string): VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource; + getSource(id: string): VectorSource | RasterSource | RasterDemSource | GeoJSONSource | ImageSource | VideoSource; - addImage(name: string, image: HTMLImageElement | ArrayBufferView, options?: { width?: number, height?: number, pixelRatio?: number }): this; + addImage(name: string, image: HTMLImageElement | ArrayBufferView | { width: number, height: number, data: Uint8Array | Uint8ClampedArray } | ImageData, options?: { pixelRatio?: number, sdf?: any }): this; hasImage(name: string): boolean; @@ -86,6 +88,8 @@ declare namespace mapboxgl { loadImage(url: string, callback: Function): this; + listImages(): string[]; + addLayer(layer: mapboxgl.Layer, before?: string): this; moveLayer(id: string, beforeId?: string): this; @@ -96,7 +100,7 @@ declare namespace mapboxgl { setFilter(layer: string, filter?: any[]): this; - setLayerZoomRange(layerId: string, minzoom?: number, maxzoom?: number): this; + setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this; getFilter(layer: string): any[]; @@ -108,10 +112,14 @@ declare namespace mapboxgl { getLayoutProperty(layer: string, name: string, klass?: string): any; - setLight(options: mapboxgl.Light, lightOptions: any): this; + setLight(options: mapboxgl.Light, lightOptions?: any): this; getLight(): mapboxgl.Light; + setFeatureState(feature: {source?: string, sourceLayer?: string, id?: string}, state: any): void; + + getFeatureState(feature: {source?: string, sourceLayer?: string, id?: string}): any; + getContainer(): HTMLElement; getCanvasContainer(): HTMLElement; @@ -134,7 +142,7 @@ declare namespace mapboxgl { setCenter(center: LngLatLike, eventData?: mapboxgl.EventData): this; - panBy(offset: number[], options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + panBy(offset: PointLike, options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; panTo(lnglat: LngLatLike, options?: mapboxgl.AnimationOptions, eventdata?: mapboxgl.EventData): this; @@ -162,6 +170,8 @@ declare namespace mapboxgl { setPitch(pitch: number, eventData?: EventData): this; + cameraForBounds(bounds: LngLatBoundsLike, options?: {padding?: number | PaddingOptions, offset?: PointLike, maxZoom?: number}): CameraOptions; + fitBounds(bounds: LngLatBoundsLike, options?: mapboxgl.FitBoundsOptions, eventData?: mapboxgl.EventData): this; jumpTo(options: mapboxgl.CameraOptions, eventData?: mapboxgl.EventData): this; @@ -204,6 +214,12 @@ declare namespace mapboxgl { /** initial map center */ center?: LngLatLike; + clickTolerance?: number; + + collectResourceTiming?: boolean; + + crossSourceCollisions?: boolean; + /** ID of the container element */ container?: string | Element; @@ -219,6 +235,8 @@ declare namespace mapboxgl { /** If true, the map will track and update the page URL according to map position */ hash?: boolean; + fadeDuration?: number; + /** If true, map creation will fail if the implementation determines that the performance of the created WebGL context would be dramatically lower than expected. */ failIfMajorPerformanceCaveat?: boolean; @@ -228,6 +246,8 @@ declare namespace mapboxgl { /** If true, enable keyboard shortcuts (see KeyboardHandler). */ keyboard?: boolean; + localIdeographFontFamily?: string; + logoPosition?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; /** If set, the map is constrained to the given bounds. */ @@ -244,6 +264,8 @@ declare namespace mapboxgl { pitch?: number; + pitchWithRotate?: boolean; + refreshExpiredTiles?: boolean; renderWorldCopies?: boolean; @@ -257,6 +279,8 @@ declare namespace mapboxgl { /** If true, the map will automatically resize when the browser window resizes */ trackResize?: boolean; + transformRequest?: Function; + /** If true, enable the "pinch to rotate and zoom" interaction (see TouchZoomRotateHandler). */ touchZoomRotate?: boolean; @@ -500,7 +524,7 @@ declare namespace mapboxgl { } export interface Source { - type: 'vector' | 'raster' | 'geojson' | 'image' | 'video' | 'canvas'; + type: 'vector' | 'raster' | 'raster-dem' | 'geojson' | 'image' | 'video' | 'canvas'; } export type GeoJSONGeometry = GeoJSON.Point | GeoJSON.LineString | GeoJSON.MultiPoint | GeoJSON.Polygon | GeoJSON.MultiLineString | GeoJSON.MultiPolygon | GeoJSON.GeometryCollection; @@ -519,6 +543,12 @@ declare namespace mapboxgl { constructor(options?: mapboxgl.GeoJSONSourceOptions); setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; + + getClusterExpansionZoom(clusterId: number, callback: (error: any, zoom: number) => void): this; + + getClusterChildren(clusterId: number, callback: (error: any, features: GeoJSON.Feature[]) => void): this; + + getClusterLeaves(cluserId: number, limit: number, offset: number, callback: (error: any, features: GeoJSON.Feature[]) => void): this; } export interface GeoJSONSourceOptions { @@ -526,6 +556,8 @@ declare namespace mapboxgl { maxzoom?: number; + attribution?: string; + buffer?: number; tolerance?: number; @@ -591,6 +623,10 @@ declare namespace mapboxgl { canvas: string | HTMLCanvasElement; + play(): void; + + pause(): void; + getCanvas(): HTMLCanvasElement; setCoordinates(coordinates: number[][]): this; @@ -608,17 +644,35 @@ declare namespace mapboxgl { type: 'vector'; url?: string; tiles?: string[]; + bounds?: number[]; + scheme?: 'xyz' | 'tms'; minzoom?: number; maxzoom?: number; + attribution?: string; } interface RasterSource extends Source { type: 'raster'; url?: string; tiles?: string[]; + bounds?: number[]; minzoom?: number; maxzoom?: number; tileSize?: number; + scheme?: 'xyz' | 'tms'; + attribution?: string; + } + + interface RasterDemSource extends Source { + type: 'raster-dem'; + url?: string; + tiles?: string[]; + bounds?: number[]; + minzoom?: number; + maxzoom?: number; + tileSize?: number; + attribution?: string; + encoding?: 'terrarium' | 'mapbox'; } /** @@ -752,7 +806,7 @@ declare namespace mapboxgl { /** * Marker */ - export class Marker { + export class Marker extends Evented { constructor(options?: mapboxgl.MarkerOptions); constructor(element?: HTMLElement, options?: mapboxgl.MarkerOptions); @@ -765,15 +819,21 @@ declare namespace mapboxgl { setLngLat(lngLat: LngLatLike): this; + getElement(): HTMLElement; + setPopup(popup?: Popup): this; getPopup(): Popup; + togglePopup(): this; + getOffset(): PointLike; setOffset(offset: PointLike): this; - togglePopup(): this; + setDraggable(shouldBeDraggable: boolean): this; + + isDraggable(): boolean; } export interface MarkerOptions { @@ -784,6 +844,8 @@ declare namespace mapboxgl { anchor?: Anchor; color?: string + + draggable?: boolean; } /** @@ -831,6 +893,7 @@ declare namespace mapboxgl { export class MapTouchEvent { type: string; + target: Map; map: Map; originalEvent: TouchEvent; point: mapboxgl.Point; @@ -967,7 +1030,7 @@ declare namespace mapboxgl { metadata?: any; ref?: string; - source?: string | VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw; + source?: string | VectorSource | RasterSource | RasterDemSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw; 'source-layer'?: string; @@ -1008,14 +1071,14 @@ declare namespace mapboxgl { } export interface FillPaint { - 'fill-antialias'?: boolean; + 'fill-antialias'?: boolean | Expression; 'fill-opacity'?: number | StyleFunction | Expression; 'fill-opacity-transition'?: Transition; 'fill-color'?: string | StyleFunction | Expression; 'fill-color-transition'?: Transition; 'fill-outline-color'?: string | StyleFunction | Expression; 'fill-outline-color-transition'?: Transition; - 'fill-translate'?: number[] | Expression; + 'fill-translate'?: number[]; 'fill-translate-transition'?: Transition; 'fill-translate-anchor'?: 'map' | 'viewport'; 'fill-pattern'?: string; @@ -1046,7 +1109,7 @@ declare namespace mapboxgl { visibility?: 'visible' | 'none'; 'line-cap'?: 'butt' | 'round' | 'square'; - 'line-join'?: 'bevel' | 'round' | 'miter'; + 'line-join'?: 'bevel' | 'round' | 'miter' | Expression; 'line-miter-limit'?: number | Expression; 'line-round-limit'?: number | Expression; } @@ -1077,7 +1140,7 @@ declare namespace mapboxgl { export interface SymbolLayout { visibility?: 'visible' | 'none'; - 'symbol-placement'?: 'point' | 'line'; + 'symbol-placement'?: 'point' | 'line' | 'line-center'; 'symbol-spacing'?: number | Expression; 'symbol-avoid-edges'?: boolean; 'icon-allow-overlap'?: boolean | StyleFunction; @@ -1092,7 +1155,7 @@ declare namespace mapboxgl { 'icon-padding'?: number | Expression; 'icon-keep-upright'?: boolean; 'icon-offset'?: number[] | StyleFunction | Expression; - 'icon-anchor'?: Anchor; + 'icon-anchor'?: Anchor | StyleFunction | Expression; 'icon-pitch-alignment'?: 'map' | 'viewport' | 'auto'; 'text-pitch-alignment'?: 'map' | 'viewport' | 'auto'; 'text-rotation-alignment'?: 'map' | 'viewport' | 'auto'; @@ -1103,7 +1166,7 @@ declare namespace mapboxgl { 'text-line-height'?: number | Expression; 'text-letter-spacing'?: number | Expression; 'text-justify'?: 'left' | 'center' | 'right'; - 'text-anchor'?: Anchor; + 'text-anchor'?: Anchor | StyleFunction | Expression; 'text-max-angle'?: number | Expression; 'text-rotate'?: number | StyleFunction | Expression; 'text-padding'?: number | Expression; @@ -1162,6 +1225,7 @@ declare namespace mapboxgl { 'raster-contrast'?: number | Expression; 'raster-contrast-transition'?: Transition; 'raster-fade-duration'?: number | Expression; + 'raster-resample'?: 'linear' | 'nearest'; } export interface CircleLayout { diff --git a/types/mapbox__geo-viewport/index.d.ts b/types/mapbox__geo-viewport/index.d.ts index 9193e891ec..6cfa8638f8 100644 --- a/types/mapbox__geo-viewport/index.d.ts +++ b/types/mapbox__geo-viewport/index.d.ts @@ -12,4 +12,4 @@ export type BoundingBox = [number, number, number, number]; export function viewport(bounds: BoundingBox, dimensions: [number, number], minzoom?: number, maxzoom?: number, tileSize?: number): GeoViewport; -export function bounds(viewport: { lon: number; lat: number }, zoom: number, dimensions: [number, number], tileSize?: number): BoundingBox; +export function bounds(viewport: { lon: number; lat: number } | [number, number], zoom: number, dimensions: [number, number], tileSize?: number): BoundingBox; diff --git a/types/mapbox__geo-viewport/mapbox__geo-viewport-tests.ts b/types/mapbox__geo-viewport/mapbox__geo-viewport-tests.ts index c5349ac782..7a8ac93fea 100644 --- a/types/mapbox__geo-viewport/mapbox__geo-viewport-tests.ts +++ b/types/mapbox__geo-viewport/mapbox__geo-viewport-tests.ts @@ -11,3 +11,5 @@ const boundingBox = bounds({ lon: 100, lat: 200, }, 14, [640, 480]); + +const boundingBox2 = bounds([100, 200], 14, [640, 480]); diff --git a/types/markdown-it/index.d.ts b/types/markdown-it/index.d.ts index 5f5129e8b0..24513c3e56 100644 --- a/types/markdown-it/index.d.ts +++ b/types/markdown-it/index.d.ts @@ -97,7 +97,7 @@ declare module MarkdownIt { type TokenRender = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => void; interface Rule { - (state: any): void; + (state: any, silent?: boolean): void; } interface Ruler { diff --git a/types/markdown-pdf/index.d.ts b/types/markdown-pdf/index.d.ts new file mode 100644 index 0000000000..1df6a9f314 --- /dev/null +++ b/types/markdown-pdf/index.d.ts @@ -0,0 +1,92 @@ +// Type definitions for MarkdownPDF (markdown-pdf) 9.0 +// Project: https://github.com/alanshaw/markdown-pdf +// Definitions by: Ange PICARD +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = MarkdownPDF; + +declare function MarkdownPDF(options?: MarkdownPDF.Options): MarkdownPDF.OptionsBuilder; + +declare namespace MarkdownPDF { + /** Configuration options */ + interface Options { + /** Current working directory. */ + cwd?: string; + /** Path to the phantomjs library. */ + phantomPath?: string; + /** Path to custom CSS file, relative to current directory. */ + cssPath?: string; + /** Path to custorm highlight CSS file (for code highlighting with highlight.js), relative to the current directory. */ + highlightCssPath?: string; + /** Path to CommonJS module which sets the page header and footer (see runnings.js). */ + runningsPath?: string; + /** Delay (in ms) before the PDF is rendered. */ + renderDelay?: number; + /** If renderDelay option isn't set, this is the timeout (in ms) before the page is rendered in case the page.onLoadFinished event doesn't fire. */ + loadTimeout?: number; + /** Supported dimension units are: 'mm', 'cm', 'in', 'px' */ + paperBorder?: string; + paperFormat?: PaperFormat; + paperOrientation?: PaperOrientation; + /** A function that returns a through2 stream that transforms the markdown before it is converted to HTML. */ + preProcessMd?: () => any; + /** A function that returns a through2 stream that transforms the HTML before it is converted to PDF. */ + preProcessHtml?: () => any; + /** A config object that is passed to remarkable, the underlying markdown parser */ + remarkable?: any; // FIXME: remarkable config types + } + type PaperFormat = "A3" | "A4" | "A5" | "Legal" | "Letter" | "Tabloid"; + type PaperOrientation = "portait" | "landscape"; + + interface OptionsBuilder { + /** Create a readable stream and pipe it to markdown pdf. */ + from: FromOptionsBuilder & FromFunction; + /** Concatenates stream and pipe them to markdown pdf. */ + concat: ConcatOptionsBuilder; + } + + type FromFunction = + /** Create a readable stream from path and pipe to markdown-pdf. path can be a single path or array of paths. */ + (path: string | string[]) => ToOptionsBuilder; + interface FromOptionsBuilder { + /** Create a readable stream from string and pipe to markdown-pdf. string can be a single string or array of strings. */ + string(markdown: string | string[]): ToOptionsBuilder; + /** Create a readable stream from path and pipe to markdown-pdf. path can be a single path or array of paths. */ + path(path: string | string[], opts: any): ToOptionsBuilder; + } + + interface ConcatOptionsBuilder { + from: ConcatFromOptionsBuilder; + } + interface ConcatFromOptionsBuilder { + /** Create and concatenate readable streams from strings and pipe to markdown-pdf. */ + strings(markdownTexts: string[], opts: any): ToOptionsBuilder; + /** Create and concatenate readable streams from paths and pipe to markdown-pdf. */ + paths(paths: string[], opts: any): ToOptionsBuilder; + } + + interface ToOptionsBuilder { + to: ToBuilder & ToFunction; + } + + interface ToBuilder { + /** + * Create a writeable stream to path and pipe output from markdown-pdf to it. + * path can be a single path, or array of output paths if you specified an array of inputs. + * The callback function cb will be invoked when data has finished being written. + */ + path(path: string, callback?: () => void): void; + /** Create a concat-stream and pipe output from markdown-pdf to it. The callback function cb will be invoked when the buffer has been created. */ + buffer(opts: any, callback?: () => void): void; + /** Create a concat-stream and pipe output from markdown-pdf to it. The callback function cb will be invoked when the string has been created. */ + string(opts: any, callback?: () => void): void; + } + + type ToFunction = + /** + * Create a writeable stream to path and pipe output from markdown-pdf to it. + * path can be a single path, or array of output paths if you specified an array of inputs. + * The callback function cb will be invoked when data has finished being written. + */ + (path: string, callback?: () => void) => void; +} diff --git a/types/markdown-pdf/markdown-pdf-tests.ts b/types/markdown-pdf/markdown-pdf-tests.ts new file mode 100644 index 0000000000..429028bf8b --- /dev/null +++ b/types/markdown-pdf/markdown-pdf-tests.ts @@ -0,0 +1,11 @@ +import mdPdf = require('markdown-pdf'); + +mdPdf().from('path').to('path', () => { }); // $ExpectType void +mdPdf().from.string('markdown').to('path', () => { }); // $ExpectType void +mdPdf({ paperOrientation: 'landscape', paperFormat: 'A3' }).from('lol').to('lol', () => { }); // $ExpectType void +mdPdf().concat.from.paths(['lol', 'lol'], {}).to('path', () => { }); // $ExpectType void +mdPdf().concat.from.strings(['lol', 'lol'], {}).to('path', () => { }); // $ExpectType void +mdPdf().from('path').to.path('path', () => { }); // $ExpectType void +mdPdf().from('path').to('path'); // $ExpectType void + +mdPdf({ paperFormat: 'wrongFormat' }); // $ExpectError diff --git a/types/markdown-pdf/tsconfig.json b/types/markdown-pdf/tsconfig.json new file mode 100644 index 0000000000..8ce150383b --- /dev/null +++ b/types/markdown-pdf/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", + "markdown-pdf-tests.ts" + ] +} diff --git a/types/markdown-pdf/tslint.json b/types/markdown-pdf/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/markdown-pdf/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/material-ui-datatables/index.d.ts b/types/material-ui-datatables/index.d.ts index e456f84e7d..ece700fe23 100644 --- a/types/material-ui-datatables/index.d.ts +++ b/types/material-ui-datatables/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/hyojin/material-ui-datatables#readme // Definitions by: Ravi L. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/material__menu/constants.d.ts b/types/material__menu/constants.d.ts index 8bec0c2e0c..8c76365ef8 100644 --- a/types/material__menu/constants.d.ts +++ b/types/material__menu/constants.d.ts @@ -66,12 +66,12 @@ export interface CornerBit extends MDCNumbers { * Likewise END maps to RIGHT or LEFT depending on the directionality. */ export interface Corner extends MDCNumbers { - TOP_LEFT: 0; - TOP_RIGHT: CornerBit["RIGHT"]; - BOTTOM_LEFT: CornerBit["BOTTOM"]; - BOTTOM_RIGHT: CornerBit["BOTTOM"] | CornerBit["RIGHT"]; - TOP_START: CornerBit["FLIP_RTL"]; - TOP_END: CornerBit["FLIP_RTL"] | CornerBit["RIGHT"]; - BOTTOM_START: CornerBit["BOTTOM"] | CornerBit["FLIP_RTL"]; - BOTTOM_END: CornerBit["BOTTOM"] | CornerBit["RIGHT"] | CornerBit["FLIP_RTL"]; + TOP_LEFT: 0; + TOP_RIGHT: 4; + BOTTOM_LEFT: 1; + BOTTOM_RIGHT: 5; + TOP_START: 8; + TOP_END: 12; + BOTTOM_START: 9; + BOTTOM_END: 13; } diff --git a/types/memjs/index.d.ts b/types/memjs/index.d.ts new file mode 100644 index 0000000000..8ab8290ae3 --- /dev/null +++ b/types/memjs/index.d.ts @@ -0,0 +1,410 @@ +// Type definitions for memjs 1.2 +// Project: http://github.com/memcachier/memjs +// Definitions by: Zongmin Lei +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +export interface ClientOptions { + /** + * `failoverTime` - how much to wait until retring a failed server. Default + * is 60 seconds. + */ + failoverTime?: number; + /** + * `retries` - the number of times to retry an operation in lieu of failures + * (default 2) + */ + retries?: number; + /** + * `retry_delay` - default is 0.2 + */ + retry_delay?: number; + /** + * `expires` - the default expiration in seconds to use (default 0 - never + * expire). If `expires` is greater than 30 days (60 x 60 x 24 x 30), it is + * treated as a UNIX time (number of seconds since January 1, 1970). + */ + expires?: number; + /** + * `logger` - a logger object that responds to `log(string)` method calls. + */ + logger?: { + log(...args: any[]): void; + }; +} +export class Client { + /** + * Creates a new client given an optional config string and optional hash of + * options. The config string should be of the form: + * + * "[user:pass@]server1[:11211],[user:pass@]server2[:11211],..." + * + * If the argument is not given, fallback on the `MEMCACHIER_SERVERS` environment + * variable, `MEMCACHE_SERVERS` environment variable or `"localhost:11211"`. + * + * The options hash may contain the options: + * + * * `retries` - the number of times to retry an operation in lieu of failures + * (default 2) + * * `expires` - the default expiration in seconds to use (default 0 - never + * expire). If `expires` is greater than 30 days (60 x 60 x 24 x 30), it is + * treated as a UNIX time (number of seconds since January 1, 1970). + * * `logger` - a logger object that responds to `log(string)` method calls. + * * `failover` - whether to failover to next server. Defaults to false. + * * `failoverTime` - how much to wait until retring a failed server. Default + * is 60 seconds. + * + * ~~~~ + * log(msg1[, msg2[, msg3[...]]]) + * ~~~~ + * + * Defaults to `console`. + * + * Or options for the servers including: + * * `username` and `password` for fallback SASL authentication credentials. + * * `timeout` in seconds to determine failure for operations. Default is 0.5 + * seconds. + * * 'conntimeout' in seconds to connection failure. Default is twice the value + * of `timeout`. + * * `keepAlive` whether to enable keep-alive functionality. Defaults to false. + * * `keepAliveDelay` in seconds to the initial delay before the first keepalive + * probe is sent on an idle socket. Defaults is 30 seconds. + */ + static create(serversStr?: string, options?: ClientOptions): Client; + + servers: string[]; + + /** + * Client initializer takes a list of Servers and an options dictionary. See Client.create for details. + * @param servers + * @param options + */ + constructor(servers: string, options?: ClientOptions); + + /** + * Chooses the server to talk to by hashing the given key. + * @param key + */ + server(key: string): string; + + /** + * GET + * + * Retrieves the value at the given key in memcache. + * + * The callback signature is: + * + * callback(err, value, flags) + * + * _value_ and _flags_ are both `Buffer`s. If the key is not found, the + * callback is invoked with null for both arguments and no error + * @param key + * @param callback + */ + get( + key: string, + callback: (err?: Error | null, value?: Buffer, flags?: Buffer) => void + ): void; + + /** + * SET + * + * Sets the given _key_ and _value_ in memcache. + * + * The options dictionary takes: + * * _expires_: overrides the default expiration (see `Client.create`) for this + * particular key-value pair. + * + * The callback signature is: + * + * callback(err, success) + * @param key + * @param value + * @param options + * @param callback + */ + set( + key: string, + value: string | Buffer, + options: { expires?: number }, + callback: (err?: Error | null, success?: boolean) => void + ): void; + + /** + * ADD + * + * Adds the given _key_ and _value_ to memcache. The operation only succeeds + * if the key is not already set. + * + * The options dictionary takes: + * * _expires_: overrides the default expiration (see `Client.create`) for this + * particular key-value pair. + * + * The callback signature is: + * + * callback(err, success) + * @param key + * @param value + * @param options + * @param callback + */ + add( + key: string, + value: string | Buffer, + options: { expires?: number }, + callback: (err?: Error | null, success?: boolean) => void + ): void; + + /** + * REPLACE + * + * Replaces the given _key_ and _value_ to memcache. The operation only succeeds + * if the key is already present. + * + * The options dictionary takes: + * * _expires_: overrides the default expiration (see `Client.create`) for this + * particular key-value pair. + * + * The callback signature is: + * + * callback(err, success) + * @param key + * @param value + * @param options + * @param callback + */ + replace( + key: string, + value: string | Buffer, + options: { expires?: number }, + callback: (err?: Error | null, success?: boolean) => void + ): void; + + /** + * DELETE + * + * Deletes the given _key_ from memcache. The operation only succeeds + * if the key is already present. + * + * The callback signature is: + * + * callback(err, success) + * @param key + * @param callback + */ + delete( + key: string, + callback: (err?: Error | null, success?: boolean) => void + ): void; + + /** + * INCREMENT + * + * Increments the given _key_ in memcache. + * + * The options dictionary takes: + * * _initial_: the value for the key if not already present, defaults to 0. + * * _expires_: overrides the default expiration (see `Client.create`) for this + * particular key-value pair. + * + * The callback signature is: + * + * callback(err, success, value) + * @param key + * @param amount + * @param options + * @param callback + */ + increment( + key: string, + amount: number, + options: { initial?: number; expires?: number }, + callback: ( + err?: Error | null, + success?: boolean, + value?: number + ) => void + ): void; + + /** + * DECREMENT + * + * Decrements the given _key_ in memcache. + * + * The options dictionary takes: + * * _initial_: the value for the key if not already present, defaults to 0. + * * _expires_: overrides the default expiration (see `Client.create`) for this + * particular key-value pair. + * + * The callback signature is: + * + * callback(err, success, value) + * @param key + * @param amount + * @param options + * @param callback + */ + decrement( + key: string, + amount: number, + options: { initial?: number; expires?: number }, + callback: ( + err?: Error | null, + success?: boolean, + value?: number + ) => void + ): void; + + /** + * APPEND + * + * Append the given _value_ to the value associated with the given _key_ in + * memcache. The operation only succeeds if the key is already present. The + * callback signature is: + * + * callback(err, success) + * @param key + * @param value + * @param callback + */ + append( + key: string, + value: string | Buffer, + callback: (err?: Error | null, success?: boolean) => void + ): void; + + /** + * PREPEND + * + * Prepend the given _value_ to the value associated with the given _key_ in + * memcache. The operation only succeeds if the key is already present. The + * callback signature is: + * + * callback(err, success) + * @param key + * @param value + * @param callback + */ + prepend( + key: string, + value: string | Buffer, + callback: (err?: Error | null, success?: boolean) => void + ): void; + + /** + * TOUCH + * + * Touch sets an expiration value, given by _expires_, on the given _key_ in + * memcache. The operation only succeeds if the key is already present. The + * callback signature is: + * + * callback(err, success) + * @param key + * @param expires + * @param callback + */ + touch( + key: string, + expires: number, + callback: (err?: Error | null, success?: boolean) => void + ): void; + + /** + * FLUSH + * + * Flushes the cache on each connected server. The callback signature is: + * + * callback(lastErr, results) + * + * where _lastErr_ is the last error encountered (or null, in the common case + * of no errors). _results_ is a dictionary mapping `"hostname:port"` to either + * `true` (if the operation was successful), or an error. + * @param callback + */ + flush( + callback: ( + err?: Error | null, + results?: Record + ) => void + ): void; + + /** + * STATS_WITH_KEY + * + * Sends a memcache stats command with a key to each connected server. The + * callback is invoked **ONCE PER SERVER** and has the signature: + * + * callback(err, server, stats) + * + * _server_ is the `"hostname:port"` of the server, and _stats_ is a dictionary + * mapping the stat name to the value of the statistic as a string. + * @param key + * @param callback + */ + statsWithKey( + key: string, + callback: ( + err?: Error | null, + server?: string, + stats?: Record + ) => void + ): void; + + /** + * RESET_STATS + * + * Reset the statistics each server is keeping back to zero. This doesn't clear + * stats such as item count, but temporary stats such as total number of + * connections over time. + * + * The callback is invoked **ONCE PER SERVER** and has the signature: + * + * callback(err, server) + * + * _server_ is the `"hostname:port"` of the server. + * @param callback + */ + resetStats(callback: (err?: Error | null, server?: string) => void): void; + + /** + * QUIT + * + * Closes the connection to each server, notifying them of this intention. Note + * that quit can race against already outstanding requests when those requests + * fail and are retried, leading to the quit command winning and closing the + * connection before the retries complete. + */ + quit(): void; + + /** + * CLOSE + * + * Closes (abruptly) connections to all the servers. + */ + close(): void; + + /** + * Perform a generic single response operation (get, set etc) on a server + * serv: the server to perform the operation on + * request: a buffer containing the request + * seq: the sequence number of the operation. It is used to pin the callbacks + * to a specific operation and should never change during a `perform`. + * callback: a callback invoked when a response is received or the request + * fails + * retries: number of times to retry request on failure + * @param key + * @param request + * @param seq + * @param callback + * @param retries + */ + perform( + key: string, + request: Buffer, + seq: number, + callback: () => void, + retries: number + ): void; +} diff --git a/types/memjs/memjs-tests.ts b/types/memjs/memjs-tests.ts new file mode 100644 index 0000000000..2e3c34a3b5 --- /dev/null +++ b/types/memjs/memjs-tests.ts @@ -0,0 +1,10 @@ +import * as memjs from "memjs"; + +const client = memjs.Client.create(); + +client.set("hello", "world", { expires: 600 }, (err, val) => { + console.log(err, val); +}); +client.get("hello", (err, val) => { + console.log(err, val); +}); diff --git a/types/memjs/tsconfig.json b/types/memjs/tsconfig.json new file mode 100644 index 0000000000..8df1e4876a --- /dev/null +++ b/types/memjs/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", + "memjs-tests.ts" + ] +} diff --git a/types/memjs/tslint.json b/types/memjs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/memjs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/meteor-univserse-i18n/index.d.ts b/types/meteor-universe-i18n/index.d.ts similarity index 100% rename from types/meteor-univserse-i18n/index.d.ts rename to types/meteor-universe-i18n/index.d.ts diff --git a/types/meteor-univserse-i18n/meteor-univserse-i18n-tests.ts b/types/meteor-universe-i18n/meteor-universe-i18n-tests.ts similarity index 100% rename from types/meteor-univserse-i18n/meteor-univserse-i18n-tests.ts rename to types/meteor-universe-i18n/meteor-universe-i18n-tests.ts diff --git a/types/meteor-universe-i18n/tsconfig.json b/types/meteor-universe-i18n/tsconfig.json new file mode 100644 index 0000000000..3b4c98a86d --- /dev/null +++ b/types/meteor-universe-i18n/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", + "meteor-universe-i18n-tests.ts" + ] +} diff --git a/types/meteor-universe-i18n/tslint.json b/types/meteor-universe-i18n/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/meteor-universe-i18n/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mocha/mocha-tests.ts b/types/mocha/mocha-tests.ts index e175c1cc53..b21abb9ffd 100644 --- a/types/mocha/mocha-tests.ts +++ b/types/mocha/mocha-tests.ts @@ -748,16 +748,14 @@ function test_reporter_string(localMocha: LocalMocha) { // $ExpectType BrowserMocha mocha.reporter('html'); - // $ExpectType Mocha - localMocha.reporter('html'); + const m: Mocha = localMocha.reporter('html'); } function test_reporter_function(localMocha: LocalMocha) { // $ExpectType BrowserMocha mocha.reporter(class extends LocalMocha.reporters.Base { }); - // $ExpectType Mocha - localMocha.reporter(class extends LocalMocha.reporters.Base { }); + const m: Mocha = localMocha.reporter(class extends LocalMocha.reporters.Base { }); } function test_browser_mocha_setup_slow_option() { @@ -836,63 +834,51 @@ function test_browser_mocha_setup_all_options() { } function test_constructor_slow_option() { - // $ExpectType Mocha - new LocalMocha({ slow: 25 }); + const m: Mocha = new LocalMocha({ slow: 25 }); } function test_constructor_timeout_option() { - // $ExpectType Mocha - new LocalMocha({ timeout: 25 }); + const m: Mocha = new LocalMocha({ timeout: 25 }); } function test_constructor_globals_option() { - // $ExpectType Mocha - new LocalMocha({ globals: ['mocha'] }); + const m: Mocha = new LocalMocha({ globals: ['mocha'] }); } function test_constructor_ui_option() { - // $ExpectType Mocha - new LocalMocha({ ui: 'bdd' }); + const m: Mocha = new LocalMocha({ ui: 'bdd' }); } function test_constructor_reporter_string_option() { - // $ExpectType Mocha - new LocalMocha({ reporter: 'html' }); + const m: Mocha = new LocalMocha({ reporter: 'html' }); } function test_constructor_reporter_function_option() { - // $ExpectType Mocha - new LocalMocha({ reporter: class extends LocalMocha.reporters.Base { } }); + const m: Mocha = new LocalMocha({ reporter: class extends LocalMocha.reporters.Base { } }); } function test_constructor_bail_option() { - // $ExpectType Mocha - new LocalMocha({ bail: false }); + const m: Mocha = new LocalMocha({ bail: false }); } function test_constructor_ignore_leaks_option() { - // $ExpectType Mocha - new LocalMocha({ ignoreLeaks: false }); + const m: Mocha = new LocalMocha({ ignoreLeaks: false }); } function test_constructor_grep_string_option() { - // $ExpectType Mocha - new LocalMocha({ grep: "describe" }); + const m: Mocha = new LocalMocha({ grep: "describe" }); } function test_constructor_grep_regex_option() { - // $ExpectType Mocha - new LocalMocha({ grep: new RegExp('describe') }); + const m: Mocha = new LocalMocha({ grep: new RegExp('describe') }); } function test_constructor_grep_regex_literal_option() { - // $ExpectType Mocha - new LocalMocha({ grep: /(expect|should)/i }); + const m: Mocha = new LocalMocha({ grep: /(expect|should)/i }); } function test_constructor_all_options() { - // $ExpectType Mocha - new LocalMocha({ + const m: Mocha = new LocalMocha({ slow: 25, timeout: 25, ui: 'bdd', @@ -1154,8 +1140,7 @@ function test_suite_events(suite: LocalMocha.Suite) { context; // $ExpectType string file; - // $ExpectType Mocha - mocha; + const m: Mocha = mocha; }); // $ExpectType Suite @@ -1164,8 +1149,7 @@ function test_suite_events(suite: LocalMocha.Suite) { module; // $ExpectType string file; - // $ExpectType Mocha - mocha; + const m: Mocha = mocha; }); // $ExpectType Suite @@ -1174,8 +1158,7 @@ function test_suite_events(suite: LocalMocha.Suite) { context; // $ExpectType string file; - // $ExpectType Mocha - mocha; + const m: Mocha = mocha; }); } diff --git a/types/moment-timezone/index.d.ts b/types/moment-timezone/index.d.ts index fac79f728f..395ab77c82 100644 --- a/types/moment-timezone/index.d.ts +++ b/types/moment-timezone/index.d.ts @@ -53,7 +53,7 @@ declare module "moment" { names(): string[]; guess(ignoreCache?: boolean): string; - setDefault(timezone: string): void; + setDefault(timezone: string): MomentTimezone; } interface Moment { diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 8ce8f52fa4..cba04cb046 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -13,6 +13,7 @@ // Bastien Arata // Wan Bachtiar // Geraldine Lemeur +// Jimmy Shimizu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -201,8 +202,10 @@ export interface SocketOptions { autoReconnect?: boolean; // TCP Socket NoDelay option. default:true noDelay?: boolean; - // TCP KeepAlive on the socket with a X ms delay before start. default:0 - keepAlive?: number; + // TCP KeepAlive enabled on the socket. default:true + keepAlive?: boolean; + // TCP KeepAlive initial delay before sending first keep-alive packet when idle. default:300000 + keepAliveInitialDelay?: number; // TCP Connection timeout setting. default 0 connectTimeoutMS?: number; // TCP Socket timeout setting. default 0 diff --git a/types/mongodb/v2/index.d.ts b/types/mongodb/v2/index.d.ts index 4c26149d81..bc23cdf893 100644 --- a/types/mongodb/v2/index.d.ts +++ b/types/mongodb/v2/index.d.ts @@ -2,7 +2,6 @@ // Project: https://github.com/mongodb/node-mongodb-native/tree/2.2 // Definitions by: Federico Caselli // Alan Marcell -// Gady Piazza // Jason Dreyzehner // Gaurav Lahoti // Mariano Cortesi @@ -22,7 +21,7 @@ export function connect(uri: string, options?: MongoClientOptions): Promise; export function connect(uri: string, callback: MongoCallback): void; export function connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; -export { Binary, Double, Long, Decimal128, MaxKey, MinKey, ObjectID, ObjectId, Timestamp, DBRef } from 'bson'; +export { Binary, DBRef, Decimal128, Double, Int32, Long, MaxKey, MinKey, ObjectID, ObjectId, Timestamp } from 'bson'; // Class documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html export class MongoClient { @@ -158,8 +157,10 @@ export interface SocketOptions { autoReconnect?: boolean; // TCP Socket NoDelay option. default:true noDelay?: boolean; - // TCP KeepAlive on the socket with a X ms delay before start. default:0 - keepAlive?: number; + // TCP KeepAlive enabled on the socket. default:true + keepAlive?: boolean; + // TCP KeepAlive initial delay before sending first keep-alive packet when idle. default:300000 + keepAliveInitialDelay?: number; // TCP Connection timeout setting. default 0 connectTimeoutMS?: number; // TCP Socket timeout setting. default 0 diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 6933a916f2..fbdad58c4b 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -151,7 +151,7 @@ declare module "mongoose" { * @param fn plugin callback * @param opts optional options */ - export function plugin(fn: Function, opts?: any): typeof mongoose; + export function plugin(fn: Function, opts?: T): typeof mongoose; /** Sets mongoose options */ export function set(key: string, value: any): void; @@ -655,7 +655,7 @@ declare module "mongoose" { * Registers a plugin for this schema. * @param plugin callback */ - plugin(plugin: (schema: Schema, options?: any) => void, opts?: any): this; + plugin(plugin: (schema: Schema, options?: T) => void, opts?: T): this; /** * Defines a post hook for the document @@ -2983,6 +2983,8 @@ declare module "mongoose" { rawResult?: boolean; /** overwrites the schema's strict mode option for this update */ strict?: boolean; + /** The context option lets you set the value of this in update validators to the underlying query. */ + context?: string; } interface ModelFindOneAndUpdateOptions extends ModelFindByIdAndUpdateOptions { diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index c9d9c9266a..cadc7d9a83 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -592,6 +592,30 @@ export default function(schema: mongoose.Schema) { }); } +// plugins +interface PluginOption { + modelName: string; + timestamp: string; +} + +function logger(modelName: string, timestamp: string) { + // call special logger with options +} + +function AwesomeLoggerPlugin(schema: mongoose.Schema, options?: PluginOption) { + if (options) { + schema.pre('save', function (next: Function) { + logger(options.modelName, options.timestamp) + }) + } +} + +new mongoose.Schema({}) + .plugin(AwesomeLoggerPlugin, {modelName: 'Executive', timestamp: 'yyyy/MM/dd'}) + +mongoose.plugin(AwesomeLoggerPlugin, {modelName: 'Executive', timestamp: 'yyyy/MM/dd'}) + + /* * section document.js * http://mongoosejs.com/docs/api.html#document-js diff --git a/types/mongoose/v3/index.d.ts b/types/mongoose/v3/index.d.ts index 805f3f1de2..b38a20179c 100644 --- a/types/mongoose/v3/index.d.ts +++ b/types/mongoose/v3/index.d.ts @@ -14,7 +14,7 @@ declare module "mongoose" { function model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; function modelNames(): string[]; - function plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; + function plugin(plugin: (schema: Schema, options?: T) => void, options?: T): Mongoose; function get(key: string): any; function set(key: string, value: any): void; @@ -33,7 +33,7 @@ declare module "mongoose" { get(key: string): any; model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; modelNames(): string[]; - plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; + plugin(plugin: (schema: Schema, options?: T) => void, options?: T): Mongoose; set(key: string, value: any): void; mongo: any; @@ -273,7 +273,7 @@ declare module "mongoose" { path(path: string): any; path(path: string, constructor: any): Schema; pathType(path: string): string; - plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Schema; + plugin(plugin: (schema: Schema, options?: T) => void, options?: T): Schema; pre(method: string, fn: HookSyncCallback, errorCb?: HookErrorCallback): Schema; pre(method: string, isAsync: boolean, fn: HookAsyncCallback, errorCb?: HookErrorCallback): Schema; diff --git a/types/mongoose/v3/mongoose-tests.ts b/types/mongoose/v3/mongoose-tests.ts index ee56b9cc1b..4659348fd7 100644 --- a/types/mongoose/v3/mongoose-tests.ts +++ b/types/mongoose/v3/mongoose-tests.ts @@ -387,4 +387,27 @@ var eq = id.equals(id2); var kitty1 = new Kitty({}); var kitty2 = new Kitty({}); -var kittyEq = kitty1._id.equals(kitty2._id); \ No newline at end of file +var kittyEq = kitty1._id.equals(kitty2._id); + +// plugins +interface PluginOption { + modelName: string; + timestamp: string; +} + +function logger(modelName: string, timestamp: string) { + // call special logger with options +} + +function AwesomeLoggerPlugin(schema: mongoose.Schema, options?: PluginOption) { + if (options) { + schema.pre('save', function (next: Function) { + logger(options.modelName, options.timestamp) + }) + } +} + +new mongoose.Schema({}) + .plugin(AwesomeLoggerPlugin, {modelName: 'Executive', timestamp: 'yyyy/MM/dd'}) + +mongoose.plugin(AwesomeLoggerPlugin, {modelName: 'Executive', timestamp: 'yyyy/MM/dd'}) diff --git a/types/mongoose/v4/index.d.ts b/types/mongoose/v4/index.d.ts index a09aefa8e2..6dfd75308a 100644 --- a/types/mongoose/v4/index.d.ts +++ b/types/mongoose/v4/index.d.ts @@ -173,7 +173,7 @@ declare module "mongoose" { * @param fn plugin callback * @param opts optional options */ - export function plugin(fn: Function, opts?: any): typeof mongoose; + export function plugin(fn: Function, opts?: T): typeof mongoose; /** Sets mongoose options */ export function set(key: string, value: any): void; @@ -678,7 +678,7 @@ declare module "mongoose" { * Registers a plugin for this schema. * @param plugin callback */ - plugin(plugin: (schema: Schema, options?: any) => void, opts?: any): this; + plugin(plugin: (schema: Schema, options?: T) => void, opts?: T): this; /** * Defines a post hook for the document diff --git a/types/mongoose/v4/mongoose-tests.ts b/types/mongoose/v4/mongoose-tests.ts index 82f92ec9ad..ddf96848b9 100644 --- a/types/mongoose/v4/mongoose-tests.ts +++ b/types/mongoose/v4/mongoose-tests.ts @@ -426,6 +426,29 @@ new mongoose.Schema({ } }); +// plugins +interface PluginOption { + modelName: string; + timestamp: string; +} + +function logger(modelName: string, timestamp: string) { + // call special logger with options +} + +function AwesomeLoggerPlugin(schema: mongoose.Schema, options?: PluginOption) { + if (options) { + schema.pre('save', function (next: Function) { + logger(options.modelName, options.timestamp) + }) + } +} + +new mongoose.Schema({}) + .plugin(AwesomeLoggerPlugin, {modelName: 'Executive', timestamp: 'yyyy/MM/dd'}) + +mongoose.plugin(AwesomeLoggerPlugin, {modelName: 'Executive', timestamp: 'yyyy/MM/dd'}) + export default function(schema: mongoose.Schema) { schema.pre('init', function(this: mongoose.Document, next: (err?: Error) => void, data: any): void { data.name = 'Hello world'; diff --git a/types/moonjs/index.d.ts b/types/moonjs/index.d.ts index 13dcbbe04e..c003f7ad58 100644 --- a/types/moonjs/index.d.ts +++ b/types/moonjs/index.d.ts @@ -22,11 +22,11 @@ declare namespace Moon { } interface MoonConstructor { - new (options?: ConstructorOptions): Instance>; + new (options?: ConstructorOptions): Instance>; } interface MoonStatic extends MoonConstructor { - component(name: string, options: ComponentOptions): MoonConstructor; + component(name: string, options: ComponentOptions): MoonConstructor; config: MoonConfig; use(plugin: object): void; compile(template: string): void; diff --git a/types/moonjs/moonjs-tests.ts b/types/moonjs/moonjs-tests.ts index aa6527ea82..34d1d8d359 100644 --- a/types/moonjs/moonjs-tests.ts +++ b/types/moonjs/moonjs-tests.ts @@ -17,6 +17,7 @@ const count = app.get("count"); count; // $ExpectType number app.get("increment")(); // $ExpectType void app.callMethod("increment"); // $ExpectType any +app.get("blahblahblah"); // $ExpectError app.destroy(); diff --git a/types/mssql/index.d.ts b/types/mssql/index.d.ts index 109a515515..db1256e2a3 100644 --- a/types/mssql/index.d.ts +++ b/types/mssql/index.d.ts @@ -201,6 +201,7 @@ export declare class ConnectionPool extends events.EventEmitter { public close(): Promise; public close(callback: (err: any) => void): void; public request(): Request; + public transaction(): Transaction; } export declare class ConnectionError implements Error { @@ -297,6 +298,7 @@ export declare class Transaction extends events.EventEmitter { public commit(callback: (err?: any) => void): void; public rollback(): Promise; public rollback(callback: (err?: any) => void): void; + public request(): Request; } export declare class TransactionError implements Error { diff --git a/types/muicss/index.d.ts b/types/muicss/index.d.ts index f195ae5d23..813abbfdcc 100644 --- a/types/muicss/index.d.ts +++ b/types/muicss/index.d.ts @@ -2,6 +2,6 @@ // Project: https://www.muicss.com/ // Definitions by: Samuel Neff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 // all definitions in react.d.ts and subdirs diff --git a/types/nanographql/index.d.ts b/types/nanographql/index.d.ts index 36bec2367a..aca13fdaa5 100644 --- a/types/nanographql/index.d.ts +++ b/types/nanographql/index.d.ts @@ -6,4 +6,4 @@ export = nanographql; -declare function nanographql(query: TemplateStringsArray): (variables?: object) => string; +declare function nanographql(query: TemplateStringsArray | string): (variables?: object) => string; diff --git a/types/nanographql/nanographql-tests.ts b/types/nanographql/nanographql-tests.ts index ecff5ce5e9..22ff648033 100644 --- a/types/nanographql/nanographql-tests.ts +++ b/types/nanographql/nanographql-tests.ts @@ -1,10 +1,24 @@ import gql = require('nanographql'); -const queryFactory = gql` + +// TemplateStringArray query test +const templateStringQueryFactory = gql` query($name: String!) { movie (name: $name) { releaseDate } } `; -const query = queryFactory({ name: 'Back to the Future' }); -JSON.parse(query); +const templatedQuery = templateStringQueryFactory({ name: 'Back to the Future' }); +JSON.parse(templatedQuery); + +// string query test +const stringField = 'movie'; +const strinQueryFactory = gql(` + query($name: String!) { + ${stringField} (name: $name) { + releaseDate + } + } +`); +const stringQuery = strinQueryFactory({ name: 'Back to the Future' }); +JSON.parse(stringQuery); diff --git a/types/navigation-react/index.d.ts b/types/navigation-react/index.d.ts index 3d98c0d5a5..330f0e9a52 100644 --- a/types/navigation-react/index.d.ts +++ b/types/navigation-react/index.d.ts @@ -2,7 +2,7 @@ // Project: http://grahammendick.github.io/navigation/ // Definitions by: Graham Mendick // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { StateNavigator } from 'navigation'; import { Component, HTMLProps } from 'react'; diff --git a/types/next/index.d.ts b/types/next/index.d.ts index 1beaffdfac..2d87121d61 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -7,7 +7,7 @@ // Scott Jones // Joao Vieira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/next/router.d.ts b/types/next/router.d.ts index 74aafd4a33..fe3563d473 100644 --- a/types/next/router.d.ts +++ b/types/next/router.d.ts @@ -62,7 +62,16 @@ export interface RouterProps { options?: EventChangeOptions, ): Promise; - // events + // events (deprecated soonish) + onAppUpdated?(nextRoute: string): void; + onBeforeHistoryChange?(as: string): void; + onHashChangeStart?(url: string): void; + onHashChangeComplete?(url: string): void; + onRouteChangeComplete?(url: string): void; + onRouteChangeError?(error: RouteChangeError, url: string): void; + onRouteChangeStart?(url: string): void; + + // events API (6.1.1+) readonly events: { on: (eventName: EventName, handler: EventHandler | ErrorEventHandler) => void; off: (eventName: EventName, handler: (url: string) => any) => void; diff --git a/types/node-zopfli-es/index.d.ts b/types/node-zopfli-es/index.d.ts new file mode 100644 index 0000000000..e015655d8b --- /dev/null +++ b/types/node-zopfli-es/index.d.ts @@ -0,0 +1,69 @@ +// Type definitions for node-zopfli-es 0.0 +// Project: https://github.com/jaeh/node-zopfli-es +// Definitions by: Alorel +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Transform } from 'stream'; + +declare class Zopfli extends Transform { + constructor(format?: Zopfli.Format, options?: Zopfli.Options); + + static createGzip(options?: Zopfli.Options): Zopfli; + static createDeflate(options?: Zopfli.Options): Zopfli; + static createZlib(options?: Zopfli.Options): Zopfli; + + static gzipSync(options?: Zopfli.Options): Buffer; + static deflateSync(options?: Zopfli.Options): Buffer; + static zlibSync(options?: Zopfli.Options): Buffer; + + static deflate(input: Buffer, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static deflate(input: Buffer, cb: (err: Error, out: Buffer) => void): void; + static deflate(input: Buffer, options?: Zopfli.Options): Promise; + + static gzip(input: Buffer, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static gzip(input: Buffer, cb: (err: Error, out: Buffer) => void): void; + static gzip(input: Buffer, options?: Zopfli.Options): Promise; + + static zlib(input: Buffer, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static zlib(input: Buffer, cb: (err: Error, out: Buffer) => void): void; + static zlib(input: Buffer, options?: Zopfli.Options): Promise; + + static compress(input: Buffer, format: Zopfli.Format, options: Zopfli.Options, cb: (err: Error, out: Buffer) => void): void; + static compress(input: Buffer, format: Zopfli.Format, cb: (err: Error, out: Buffer) => void): void; + static compress(input: Buffer, format: Zopfli.Format, options?: Zopfli.Options): Promise; +} + +declare namespace Zopfli { + type Format = 'deflate' | 'gzip' | 'zlib'; + + interface Options { + verbose?: boolean; + verbose_more?: boolean; + /** + * Maximum amount of times to rerun forward and backward pass to optimize LZ77 compression cost. + * Good values: 10, 15 for small files, 5 for files over several MB in size or it will be too slow. + */ + numiterations?: number; + /** + * If true, splits the data in multiple deflate blocks with optimal choice for the block boundaries. + * Block splitting gives better compression. + */ + blocksplitting?: boolean; + /** + * If true, chooses the optimal block split points only after doing the iterative LZ77 compression. + * If false, chooses the block split points first, then does iterative LZ77 on each individual block. + * Depending on the file, either first or last gives the best compression. + */ + blocksplittinglast?: boolean; + /** + * Maximum amount of blocks to split into (0 for unlimited, + * but this can give extreme results that hurt compression on some files). + */ + blocksplittingmax?: number; + } +} + +export = Zopfli; diff --git a/types/node-zopfli-es/node-zopfli-es-tests.ts b/types/node-zopfli-es/node-zopfli-es-tests.ts new file mode 100644 index 0000000000..3f3294cf3f --- /dev/null +++ b/types/node-zopfli-es/node-zopfli-es-tests.ts @@ -0,0 +1,51 @@ +import * as Zopfli from 'node-zopfli-es'; +import * as fs from 'fs'; + +const opts: Zopfli.Options = { + verbose: true, + numiterations: 1 +}; +let input: Buffer = Buffer.from('foo'); +const read = fs.createReadStream('foo'); +const write = fs.createWriteStream('foo'); + +function cb(e: Error, b: Buffer): void {} +function then(b: Buffer): void {} + +Zopfli.zlib(input, cb); +Zopfli.zlib(input, opts, cb); +Zopfli.zlib(input, opts).then(then); +Zopfli.zlib(input).then(then); + +Zopfli.gzip(input, cb); +Zopfli.gzip(input, opts, cb); +Zopfli.gzip(input, opts).then(then); +Zopfli.gzip(input).then(then); + +Zopfli.deflate(input, cb); +Zopfli.deflate(input, opts, cb); +Zopfli.deflate(input, opts).then(then); +Zopfli.deflate(input).then(then); + +Zopfli.compress(input, 'zlib', cb); +Zopfli.compress(input, 'zlib', opts, cb); +Zopfli.compress(input, 'zlib', opts).then(then); +Zopfli.compress(input, 'zlib').then(then); + +input = Zopfli.gzipSync(); +input = Zopfli.gzipSync(opts); + +input = Zopfli.deflateSync(); +input = Zopfli.deflateSync(opts); + +input = Zopfli.zlibSync(); +input = Zopfli.zlibSync(opts); + +read.pipe(Zopfli.createGzip()).pipe(write); +read.pipe(Zopfli.createGzip(opts)).pipe(write); + +read.pipe(Zopfli.createDeflate()).pipe(write); +read.pipe(Zopfli.createDeflate(opts)).pipe(write); + +read.pipe(Zopfli.createZlib()).pipe(write); +read.pipe(Zopfli.createZlib(opts)).pipe(write); diff --git a/types/node-zopfli-es/tsconfig.json b/types/node-zopfli-es/tsconfig.json new file mode 100644 index 0000000000..bbd6de30e8 --- /dev/null +++ b/types/node-zopfli-es/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", + "node-zopfli-es-tests.ts" + ] +} diff --git a/types/node-zopfli-es/tslint.json b/types/node-zopfli-es/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/node-zopfli-es/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 46810993df..ed04749756 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -26,6 +26,7 @@ // Lishude // Andrew Makarov // Zane Hannan AU +// Eugene Y. Q. Shen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** inspector module types */ @@ -694,7 +695,7 @@ declare namespace NodeJS { columns?: number; rows?: number; _write(chunk: any, encoding: string, callback: Function): void; - _destroy(err: Error, callback: Function): void; + _destroy(err: Error | null, callback: Function): void; _final(callback: Function): void; setDefaultEncoding(encoding: string): this; cork(): void; @@ -707,7 +708,7 @@ declare namespace NodeJS { isRaw?: boolean; setRawMode?(mode: boolean): void; _read(size: number): void; - _destroy(err: Error, callback: Function): void; + _destroy(err: Error | null, callback: Function): void; push(chunk: any, encoding?: string): boolean; destroy(error?: Error): void; } @@ -1151,7 +1152,6 @@ declare module "http" { constructor(); setTimeout(msecs: number, callback?: () => void): this; - destroy(error: Error): void; setHeader(name: string, value: number | string | string[]): void; getHeader(name: string): number | string | string[] | undefined; getHeaders(): OutgoingHttpHeaders; @@ -2225,24 +2225,31 @@ declare module "child_process" { encoding: string | null; // specify `null`. } + export interface ExecException extends Error { + cmd?: string; + killed?: boolean; + code?: number; + signal?: string; + } + // no `options` definitely means stdout/stderr are `string`. - export function exec(command: string, callback?: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. - export function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: Error | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; // `options` with well known `encoding` means stdout/stderr are definitely `string`. - export function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. - export function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + export function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; // `options` without an `encoding` means stdout/stderr are definitely `string`. - export function exec(command: string, options: ExecOptions, callback?: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; // fallback if nothing else matches. Worst case is always `string | Buffer`. - export function exec(command: string, options: ({ encoding?: string | null } & ExecOptions) | undefined | null, callback?: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + export function exec(command: string, options: ({ encoding?: string | null } & ExecOptions) | undefined | null, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. export namespace exec { @@ -2503,7 +2510,7 @@ declare module "url" { append(name: string, value: string): void; delete(name: string): void; entries(): IterableIterator<[string, string]>; - forEach(callback: (value: string, name: string) => void): void; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; @@ -2770,7 +2777,6 @@ declare module "net" { bufferSize: number; setEncoding(encoding?: string): this; - destroy(err?: any): void; pause(): this; resume(): this; setTimeout(timeout: number, callback?: Function): this; @@ -3136,7 +3142,6 @@ declare module "fs" { export class ReadStream extends stream.Readable { close(): void; - destroy(): void; bytesRead: number; path: string | Buffer; @@ -5858,8 +5863,8 @@ declare module "crypto" { export interface Signer extends NodeJS.WritableStream { update(data: string | Buffer | NodeJS.TypedArray | DataView): Signer; update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Signer; - sign(private_key: string | { key: string; passphrase: string }): Buffer; - sign(private_key: string | { key: string; passphrase: string }, output_format: HexBase64Latin1Encoding): string; + sign(private_key: string | { key: string; passphrase: string, padding?: number, saltLength?: number }): Buffer; + sign(private_key: string | { key: string; passphrase: string, padding?: number, saltLength?: number }, output_format: HexBase64Latin1Encoding): string; } export function createVerify(algorith: string, options?: stream.WritableOptions): Verify; export interface Verify extends NodeJS.WritableStream { @@ -5971,8 +5976,8 @@ declare module "stream" { highWaterMark?: number; encoding?: string; objectMode?: boolean; - read?: (this: Readable, size?: number) => any; - destroy?: (error?: Error) => any; + read?(this: Readable, size: number): void; + destroy?(this: Readable, error: Error | null, callback: (error: Error | null) => void): void; } export class Readable extends Stream implements NodeJS.ReadableStream { @@ -5990,7 +5995,7 @@ declare module "stream" { unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): this; push(chunk: any, encoding?: string): boolean; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; destroy(error?: Error): void; /** @@ -6002,66 +6007,66 @@ declare module "stream" { * 4. readable * 5. error */ - addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; addListener(event: "end", listener: () => void): this; addListener(event: "readable", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; emit(event: "close"): boolean; - emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "data", chunk: any): boolean; emit(event: "end"): boolean; emit(event: "readable"): boolean; emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; - on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "data", listener: (chunk: any) => void): this; on(event: "end", listener: () => void): this; on(event: "readable", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "data", listener: (chunk: any) => void): this; once(event: "end", listener: () => void): this; once(event: "readable", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; prependListener(event: "end", listener: () => void): this; prependListener(event: "readable", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; prependOnceListener(event: "end", listener: () => void): this; prependOnceListener(event: "readable", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: string, listener: (...args: any[]) => void): this; removeListener(event: "close", listener: () => void): this; - removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; removeListener(event: "end", listener: () => void): this; removeListener(event: "readable", listener: () => void): this; removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - [Symbol.asyncIterator](): AsyncIterableIterator; + [Symbol.asyncIterator](): AsyncIterableIterator; } export interface WritableOptions { highWaterMark?: number; decodeStrings?: boolean; objectMode?: boolean; - write?: (chunk: any, encoding: string, callback: Function) => any; - writev?: (chunks: Array<{ chunk: any, encoding: string }>, callback: Function) => any; - destroy?: (error?: Error) => any; - final?: (callback: (error?: Error) => void) => void; + write?(this: Writable, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Writable, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + destroy?(this: Writable, error: Error | null, callback: (error: Error | null) => void): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; } export class Writable extends Stream implements NodeJS.WritableStream { @@ -6069,16 +6074,16 @@ declare module "stream" { readonly writableHighWaterMark: number; readonly writableLength: number; constructor(opts?: WritableOptions); - _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; - _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; - _destroy(err: Error, callback: Function): void; - _final(callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; + _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; setDefaultEncoding(encoding: string): this; - end(cb?: Function): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: string, cb?: () => void): void; cork(): void; uncork(): void; destroy(error?: Error): void; @@ -6093,67 +6098,72 @@ declare module "stream" { * 5. pipe * 6. unpipe */ - addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: () => void): this; addListener(event: "drain", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "finish", listener: () => void): this; addListener(event: "pipe", listener: (src: Readable) => void): this; addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: string | symbol, ...args: any[]): boolean; emit(event: "close"): boolean; - emit(event: "drain", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; emit(event: "error", err: Error): boolean; emit(event: "finish"): boolean; emit(event: "pipe", src: Readable): boolean; emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; - on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; on(event: "drain", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "finish", listener: () => void): this; on(event: "pipe", listener: (src: Readable) => void): this; on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; once(event: "drain", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; once(event: "finish", listener: () => void): this; once(event: "pipe", listener: (src: Readable) => void): this; once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "drain", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "finish", listener: () => void): this; prependListener(event: "pipe", listener: (src: Readable) => void): this; prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "drain", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: "finish", listener: () => void): this; prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: string, listener: (...args: any[]) => void): this; removeListener(event: "close", listener: () => void): this; removeListener(event: "drain", listener: () => void): this; removeListener(event: "error", listener: (err: Error) => void): this; removeListener(event: "finish", listener: () => void): this; removeListener(event: "pipe", listener: (src: Readable) => void): this; removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; } export interface DuplexOptions extends ReadableOptions, WritableOptions { allowHalfOpen?: boolean; readableObjectMode?: boolean; writableObjectMode?: boolean; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Duplex, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; } // Note: Duplex extends both Readable and Writable. @@ -6162,31 +6172,36 @@ declare module "stream" { readonly writableHighWaterMark: number; readonly writableLength: number; constructor(opts?: DuplexOptions); - _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; - _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; - _destroy(err: Error, callback: Function): void; - _final(callback: Function): void; - write(chunk: any, cb?: Function): boolean; - write(chunk: any, encoding?: string, cb?: Function): boolean; + _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; setDefaultEncoding(encoding: string): this; - end(cb?: Function): void; - end(chunk: any, cb?: Function): void; - end(chunk: any, encoding?: string, cb?: Function): void; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: string, cb?: () => void): void; cork(): void; uncork(): void; } - type TransformCallback = (err?: Error, data?: any) => void; + type TransformCallback = (error?: Error, data?: any) => void; export interface TransformOptions extends DuplexOptions { - transform?: (chunk: any, encoding: string, callback: TransformCallback) => any; - flush?: (callback: TransformCallback) => any; + read?(this: Transform, size: number): void; + write?(this: Transform, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Transform, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: string, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; } export class Transform extends Duplex { constructor(opts?: TransformOptions); _transform(chunk: any, encoding: string, callback: TransformCallback): void; - destroy(error?: Error): void; + _flush(callback: TransformCallback): void; } export class PassThrough extends Transform { } @@ -6367,7 +6382,7 @@ declare module "util" { } declare module "assert" { - function internal(value: any, message?: string): void; + function internal(value: any, message?: string | Error): void; namespace internal { export class AssertionError implements Error { name: string; @@ -6376,46 +6391,42 @@ declare module "assert" { expected: any; operator: string; generatedMessage: boolean; + code: 'ERR_ASSERTION'; constructor(options?: { message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function + operator?: string; stackStartFn?: Function }); } - export function fail(message: string): never; - /** @deprecated since v10.0.0 */ - export function fail(actual: any, expected: any, message?: string, operator?: string): never; - export function ok(value: any, message?: string): void; - /** @deprecated use strictEqual() */ - export function equal(actual: any, expected: any, message?: string): void; - /** @deprecated use notStrictEqual() */ - export function notEqual(actual: any, expected: any, message?: string): void; - /** @deprecated use deepStrictEqual() */ - export function deepEqual(actual: any, expected: any, message?: string): void; - /** @deprecated use notDeepStrictEqual() */ - export function notDeepEqual(acutal: any, expected: any, message?: string): void; - export function strictEqual(actual: any, expected: any, message?: string): void; - export function notStrictEqual(actual: any, expected: any, message?: string): void; - export function deepStrictEqual(actual: any, expected: any, message?: string): void; - export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; + export function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + export function fail(actual: any, expected: any, message?: string | Error, operator?: string, stackStartFn?: Function): never; + export function ok(value: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use strictEqual() instead. */ + export function equal(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notStrictEqual() instead. */ + export function notEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use deepStrictEqual() instead. */ + export function deepEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */ + export function notDeepEqual(actual: any, expected: any, message?: string | Error): void; + export function strictEqual(actual: any, expected: any, message?: string | Error): void; + export function notStrictEqual(actual: any, expected: any, message?: string | Error): void; + export function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; + export function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; - export function throws(block: Function, message?: string): void; - export function throws(block: Function, error: Function, message?: string): void; - export function throws(block: Function, error: RegExp, message?: string): void; - export function throws(block: Function, error: (err: any) => boolean, message?: string): void; - - export function doesNotThrow(block: Function, message?: string): void; - export function doesNotThrow(block: Function, error: Function, message?: string): void; - export function doesNotThrow(block: Function, error: RegExp, message?: string): void; - export function doesNotThrow(block: Function, error: (err: any) => boolean, message?: string): void; + export function throws(block: Function, message?: string | Error): void; + export function throws(block: Function, error: RegExp | Function | Object | Error, message?: string | Error): void; + export function doesNotThrow(block: Function, message?: string | Error): void; + export function doesNotThrow(block: Function, error: RegExp | Function, message?: string | Error): void; export function ifError(value: any): void; - export function rejects(block: Function | Promise, message?: string): Promise; - export function rejects(block: Function | Promise, error: Function | RegExp | Object | Error, message?: string): Promise; - export function doesNotReject(block: Function | Promise, message?: string): Promise; - export function doesNotReject(block: Function | Promise, error: Function | RegExp | Object | Error, message?: string): Promise; + export function rejects(block: Function | Promise, message?: string | Error): Promise; + export function rejects(block: Function | Promise, error: RegExp | Function | Object | Error, message?: string | Error): Promise; + export function doesNotReject(block: Function | Promise, message?: string | Error): Promise; + export function doesNotReject(block: Function | Promise, error: RegExp | Function, message?: string | Error): Promise; export var strict: typeof internal; } @@ -7181,6 +7192,7 @@ declare module "http2" { readonly alpnProtocol?: string; close(callback?: () => void): void; readonly closed: boolean; + readonly connecting: boolean; destroy(error?: Error, code?: number): void; readonly destroyed: boolean; readonly encrypted?: boolean; @@ -7188,6 +7200,8 @@ declare module "http2" { readonly localSettings: Settings; readonly originSet?: string[]; readonly pendingSettingsAck: boolean; + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping(payload: Buffer | DataView | NodeJS.TypedArray , callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; ref(): void; readonly remoteSettings: Settings; rstStream(stream: Http2Stream, code?: number): void; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 86907ebb39..9c38a5672e 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -690,9 +690,10 @@ namespace url_tests { const searchParams = new url.URLSearchParams('abc=123'); assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string): void => { + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { assert.equal(name, 'abc'); assert.equal(value, '123'); + assert.equal(me, searchParams); }); assert.equal(searchParams.get('abc'), '123'); @@ -952,74 +953,149 @@ const unzipped: Buffer = zlib.unzipSync(compressMe); function simplified_stream_ctor_test() { new stream.Readable({ read(size) { - size.toFixed(); + // $ExpectType Readable + this; + // $ExpectType number + size; }, - destroy(error) { - error.stack; + destroy(error, cb) { + // $ExpectType Error + error; + // $ExpectType (error: Error) => void + cb; } }); new stream.Writable({ write(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb(); + // $ExpectType Writable + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType (error?: Error) => void + cb; }, writev(chunks, cb) { - chunks[0].chunk.slice(0); - chunks[0].encoding.charAt(0); - cb(); + // $ExpectType Writable + this; + // $ExpectType { chunk: any; encoding: string; }[] + chunks; + // $ExpectType (error?: Error) => void + cb; }, - destroy(error) { - error.stack; + destroy(error, cb) { + // $ExpectType Writable + this; + // $ExpectType Error + error; + // $ExpectType (error: Error) => void + cb; }, final(cb) { - cb(null); + // $ExpectType Writable + this; + // $ExpectType (error?: Error) => void + cb; } }); new stream.Duplex({ read(size) { - size.toFixed(); + // $ExpectType Duplex + this; + // $ExpectType number + size; }, write(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb(); + // $ExpectType Duplex + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType (error?: Error) => void + cb; }, writev(chunks, cb) { - chunks[0].chunk.slice(0); - chunks[0].encoding.charAt(0); - cb(); + // $ExpectType Duplex + this; + // $ExpectType { chunk: any; encoding: string; }[] + chunks; + // $ExpectType (error?: Error) => void + cb; + }, + destroy(error, cb) { + // $ExpectType Duplex + this; + // $ExpectType Error + error; + // $ExpectType (error: Error) => void + cb; + }, + final(cb) { + // $ExpectType Duplex + this; + // $ExpectType (error?: Error) => void + cb; }, readableObjectMode: true, writableObjectMode: true }); new stream.Transform({ - transform(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb(); - }, - flush(cb) { - cb(); - }, read(size) { - size.toFixed(); + // $ExpectType Transform + this; + // $ExpectType number + size; }, write(chunk, enc, cb) { - chunk.slice(1); - enc.charAt(0); - cb(); + // $ExpectType Transform + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType (error?: Error) => void + cb; }, writev(chunks, cb) { - chunks[0].chunk.slice(0); - chunks[0].encoding.charAt(0); - cb(); + // $ExpectType Transform + this; + // $ExpectType { chunk: any; encoding: string; }[] + chunks; + // $ExpectType (error?: Error) => void + cb; }, - destroy(error) { - error.stack; + destroy(error, cb) { + // $ExpectType Transform + this; + // $ExpectType Error + error; + // $ExpectType (error: Error) => void + cb; + }, + final(cb) { + // $ExpectType Transform + this; + // $ExpectType (error?: Error) => void + cb; + }, + transform(chunk, enc, cb) { + // $ExpectType Transform + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType TransformCallback + cb; + }, + flush(cb) { + // $ExpectType TransformCallback + cb; }, allowHalfOpen: true, readableObjectMode: true, @@ -3623,6 +3699,7 @@ namespace http2_tests { let pendingSettingsAck: boolean = http2Session.pendingSettingsAck; let settings: http2.Settings = http2Session.localSettings; let closed: boolean = http2Session.closed; + let connecting: boolean = http2Session.connecting; settings = http2Session.remoteSettings; http2Session.ref(); @@ -3669,6 +3746,10 @@ namespace http2_tests { }); http2Session.settings(settings); + + http2Session.ping((err: Error | null, duration: number, payload: Buffer) => {}); + http2Session.ping(Buffer.from(''), (err: Error | null, duration: number, payload: Buffer) => {}); + http2Session.ping(new DataView(new Int8Array(1).buffer), (err: Error | null, duration: number, payload: Buffer) => {}); } // Http2Stream diff --git a/types/node/v0/index.d.ts b/types/node/v0/index.d.ts index dce2a1a54d..3bc1b3ed5d 100644 --- a/types/node/v0/index.d.ts +++ b/types/node/v0/index.d.ts @@ -573,42 +573,42 @@ declare module "http" { */ export interface ClientResponse extends IncomingMessage { } - export interface AgentOptions { - /** - * Keep sockets around in a pool to be used by other requests in the future. Default = false - */ - keepAlive?: boolean; - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - */ - keepAliveMsecs?: number; - /** - * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity - */ - maxSockets?: number; - /** - * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. - */ - maxFreeSockets?: number; - } + export interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + } export class Agent { - maxFreeSockets: number; - maxSockets: number; - sockets: any; - requests: any; + maxFreeSockets: number; + maxSockets: number; + sockets: any; + requests: any; - constructor(opts?: AgentOptions); + constructor(opts?: AgentOptions); - /** - * Destroy any sockets that are currently in use by the agent. - * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, - * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, - * sockets may hang open for quite a long time before the server terminates them. - */ - destroy(): void; - } + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } export var METHODS: string[]; @@ -1858,7 +1858,7 @@ declare module "util" { } declare module "assert" { - function internal (value: any, message?: string): void; + function internal(value: any, message?: string): void; namespace internal { export class AssertionError implements Error { name: string; @@ -1868,8 +1868,10 @@ declare module "assert" { operator: string; generatedMessage: boolean; - constructor(options?: {message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function}); + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFn?: Function + }); } export function fail(actual?: any, expected?: any, message?: string, operator?: string): never; @@ -1877,22 +1879,14 @@ declare module "assert" { export function equal(actual: any, expected: any, message?: string): void; export function notEqual(actual: any, expected: any, message?: string): void; export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function notDeepEqual(actual: any, expected: any, message?: string): void; export function strictEqual(actual: any, expected: any, message?: string): void; export function notStrictEqual(actual: any, expected: any, message?: string): void; - export var throws: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; - export var doesNotThrow: { - (block: Function, message?: string): void; - (block: Function, error: Function, message?: string): void; - (block: Function, error: RegExp, message?: string): void; - (block: Function, error: (err: any) => boolean, message?: string): void; - }; + export function throws(block: Function, message?: string): void; + export function throws(block: Function, error: RegExp | Function, message?: string): void; + export function doesNotThrow(block: Function, message?: string): void; + export function doesNotThrow(block: Function, error: RegExp | Function, message?: string): void; export function ifError(value: any): void; } diff --git a/types/node/v0/node-tests.ts b/types/node/v0/node-tests.ts index d8e0a40699..37ef4f9e81 100644 --- a/types/node/v0/node-tests.ts +++ b/types/node/v0/node-tests.ts @@ -179,37 +179,37 @@ function stream_readable_pipe_test() { var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); function crypto_cipher_decipher_string_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:string = "This is the clear text."; - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherText:string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); + var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + var clearText:string = "This is the clear text."; + var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + var cipherText:string = cipher.update(clearText, "utf8", "hex"); + cipherText += cipher.final("hex"); - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var clearText2:string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); + var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + var clearText2:string = decipher.update(cipherText, "hex", "utf8"); + clearText2 += decipher.final("utf8"); - assert.equal(clearText2, clearText); + assert.equal(clearText2, clearText); } function crypto_cipher_decipher_buffer_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherBuffers:Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); + var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); + var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + var cipherBuffers:Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); - var cipherText:Buffer = Buffer.concat(cipherBuffers); + var cipherText:Buffer = Buffer.concat(cipherBuffers); - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var decipherBuffers:Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); + var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + var decipherBuffers:Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); - var clearText2:Buffer = Buffer.concat(decipherBuffers); + var clearText2:Buffer = Buffer.concat(decipherBuffers); - assert.deepEqual(clearText2, clearText); + assert.deepEqual(clearText2, clearText); } //////////////////////////////////////////////////// @@ -242,14 +242,14 @@ namespace http_tests { var codeMessage = http.STATUS_CODES['400']; var codeMessage = http.STATUS_CODES[400]; - var agent: http.Agent = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256 - }); + var agent: http.Agent = new http.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256 + }); - var agent: http.Agent = http.globalAgent; + var agent: http.Agent = http.globalAgent; http.request('http://www.example.com/xyz'); } diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index bdce459efe..a53098f615 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -2440,7 +2440,7 @@ declare module "util" { } declare module "assert" { - function internal (value: any, message?: string): void; + function internal(value: any, message?: string): void; namespace internal { export class AssertionError implements Error { name: string; @@ -2450,8 +2450,10 @@ declare module "assert" { operator: string; generatedMessage: boolean; - constructor(options?: {message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function}); + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFn?: Function + }); } export function fail(actual: any, expected: any, message?: string, operator?: string): never; @@ -2459,21 +2461,16 @@ declare module "assert" { export function equal(actual: any, expected: any, message?: string): void; export function notEqual(actual: any, expected: any, message?: string): void; export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function notDeepEqual(actual: any, expected: any, message?: string): void; export function strictEqual(actual: any, expected: any, message?: string): void; export function notStrictEqual(actual: any, expected: any, message?: string): void; export function deepStrictEqual(actual: any, expected: any, message?: string): void; export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; export function throws(block: Function, message?: string): void; - export function throws(block: Function, error: Function, message?: string): void; - export function throws(block: Function, error: RegExp, message?: string): void; - export function throws(block: Function, error: (err: any) => boolean, message?: string): void; - + export function throws(block: Function, error: RegExp | Function, message?: string): void; export function doesNotThrow(block: Function, message?: string): void; - export function doesNotThrow(block: Function, error: Function, message?: string): void; - export function doesNotThrow(block: Function, error: RegExp, message?: string): void; - export function doesNotThrow(block: Function, error: (err: any) => boolean, message?: string): void; + export function doesNotThrow(block: Function, error: RegExp | Function, message?: string): void; export function ifError(value: any): void; } diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 9cceb11e71..44083060ee 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -2002,7 +2002,7 @@ declare module "url" { append(name: string, value: string): void; delete(name: string): void; entries(): Iterator; - forEach(callback: (value: string, name: string) => void): void; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; @@ -3944,30 +3944,26 @@ declare module "assert" { constructor(options?: { message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function + operator?: string; stackStartFn?: Function }); } - export function fail(actual: any, expected: any, message?: string, operator?: string): never; + export function fail(message?: string): never; + export function fail(actual: any, expected: any, message?: string, operator?: string, stackStartFn?: Function): never; export function ok(value: any, message?: string): void; export function equal(actual: any, expected: any, message?: string): void; export function notEqual(actual: any, expected: any, message?: string): void; export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function notDeepEqual(actual: any, expected: any, message?: string): void; export function strictEqual(actual: any, expected: any, message?: string): void; export function notStrictEqual(actual: any, expected: any, message?: string): void; export function deepStrictEqual(actual: any, expected: any, message?: string): void; export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; export function throws(block: Function, message?: string): void; - export function throws(block: Function, error: Function, message?: string): void; - export function throws(block: Function, error: RegExp, message?: string): void; - export function throws(block: Function, error: (err: any) => boolean, message?: string): void; - + export function throws(block: Function, error: RegExp | Function, message?: string): void; export function doesNotThrow(block: Function, message?: string): void; - export function doesNotThrow(block: Function, error: Function, message?: string): void; - export function doesNotThrow(block: Function, error: RegExp, message?: string): void; - export function doesNotThrow(block: Function, error: (err: any) => boolean, message?: string): void; + export function doesNotThrow(block: Function, error: RegExp | Function, message?: string): void; export function ifError(value: any): void; } diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index 6ab45137c4..5ca32d660c 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -538,9 +538,10 @@ namespace url_tests { const searchParams = new url.URLSearchParams('abc=123'); assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string): void => { + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { assert.equal(name, 'abc'); assert.equal(value, '123'); + assert.equal(me, searchParams); }); assert.equal(searchParams.get('abc'), '123'); @@ -785,13 +786,13 @@ namespace crypto_tests { let clearText: string = "This is the clear text."; let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); let cipherText: string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); + cipherText += cipher.final("hex"); let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); let clearText2: string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); + clearText2 += decipher.final("utf8"); - assert.equal(clearText2, clearText); + assert.equal(clearText2, clearText); } { @@ -800,19 +801,19 @@ namespace crypto_tests { let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); let cipherBuffers: Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); let cipherText: Buffer = Buffer.concat(cipherBuffers); let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); let decipherBuffers: Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); let clearText2: Buffer = Buffer.concat(decipherBuffers); - assert.deepEqual(clearText2, clearText); + assert.deepEqual(clearText2, clearText); } { @@ -838,8 +839,8 @@ namespace tls_tests { var blah = ctx.context; var connOpts: tls.ConnectionOptions = { - host: "127.0.0.1", - port: 55 + host: "127.0.0.1", + port: 55 }; var tlsSocket = tls.connect(connOpts); } @@ -1042,14 +1043,14 @@ namespace http_tests { } { - var agent: http.Agent = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256 - }); + var agent: http.Agent = new http.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256 + }); - var agent: http.Agent = http.globalAgent; + var agent: http.Agent = http.globalAgent; http.request({ agent: false }); http.request({ agent: agent }); diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index b93c70017b..da7c47d68e 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -2045,7 +2045,7 @@ declare module "url" { append(name: string, value: string): void; delete(name: string): void; entries(): Iterator; - forEach(callback: (value: string, name: string) => void): void; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; @@ -3988,30 +3988,26 @@ declare module "assert" { constructor(options?: { message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function + operator?: string; stackStartFn?: Function }); } - export function fail(actual: any, expected: any, message?: string, operator?: string): never; + export function fail(message?: string): never; + export function fail(actual: any, expected: any, message?: string, operator?: string, stackStartFn?: Function): never; export function ok(value: any, message?: string): void; export function equal(actual: any, expected: any, message?: string): void; export function notEqual(actual: any, expected: any, message?: string): void; export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function notDeepEqual(actual: any, expected: any, message?: string): void; export function strictEqual(actual: any, expected: any, message?: string): void; export function notStrictEqual(actual: any, expected: any, message?: string): void; export function deepStrictEqual(actual: any, expected: any, message?: string): void; export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; export function throws(block: Function, message?: string): void; - export function throws(block: Function, error: Function, message?: string): void; - export function throws(block: Function, error: RegExp, message?: string): void; - export function throws(block: Function, error: (err: any) => boolean, message?: string): void; - + export function throws(block: Function, error: RegExp | Function, message?: string): void; export function doesNotThrow(block: Function, message?: string): void; - export function doesNotThrow(block: Function, error: Function, message?: string): void; - export function doesNotThrow(block: Function, error: RegExp, message?: string): void; - export function doesNotThrow(block: Function, error: (err: any) => boolean, message?: string): void; + export function doesNotThrow(block: Function, error: RegExp | Function, message?: string): void; export function ifError(value: any): void; } diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index a74a438665..764dc6e8d0 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -520,9 +520,10 @@ namespace url_tests { const searchParams = new url.URLSearchParams('abc=123'); assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string): void => { + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { assert.equal(name, 'abc'); assert.equal(value, '123'); + assert.equal(me, searchParams); }); assert.equal(searchParams.get('abc'), '123'); @@ -1024,14 +1025,14 @@ namespace http_tests { } { - var agent: http.Agent = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256 - }); + var agent: http.Agent = new http.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256 + }); - var agent: http.Agent = http.globalAgent; + var agent: http.Agent = http.globalAgent; http.request({ agent: false }); http.request({ agent: agent }); @@ -1055,7 +1056,7 @@ namespace http_tests { request.abort(); } - // http request options + // http request options { const requestOpts: http.RequestOptions = { timeout: 30000 diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index da0db26be4..06283dd1dd 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -532,7 +532,7 @@ declare namespace NodeJS { columns?: number; rows?: number; _write(chunk: any, encoding: string, callback: Function): void; - _destroy(err: Error, callback: Function): void; + _destroy(err: Error | undefined, callback: Function): void; _final(callback: Function): void; setDefaultEncoding(encoding: string): this; cork(): void; @@ -544,7 +544,7 @@ declare namespace NodeJS { isRaw?: boolean; setRawMode?(mode: boolean): void; _read(size: number): void; - _destroy(err: Error, callback: Function): void; + _destroy(err: Error | undefined, callback: Function): void; push(chunk: any, encoding?: string): boolean; destroy(error?: Error): void; } @@ -2378,7 +2378,7 @@ declare module "url" { append(name: string, value: string): void; delete(name: string): void; entries(): IterableIterator<[string, string]>; - forEach(callback: (value: string, name: string) => void): void; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; @@ -5299,7 +5299,7 @@ declare module "stream" { encoding?: string; objectMode?: boolean; read?: (this: Readable, size?: number) => any; - destroy?: (error?: Error) => any; + destroy?: (error: Error | null, callback: (error?: Error) => void) => void; } export class Readable extends Stream implements NodeJS.ReadableStream { @@ -5316,7 +5316,7 @@ declare module "stream" { unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): this; push(chunk: any, encoding?: string): boolean; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error?: Error) => void): void; destroy(error?: Error): void; /** @@ -5384,7 +5384,7 @@ declare module "stream" { objectMode?: boolean; write?: (chunk: any, encoding: string, callback: Function) => any; writev?: (chunks: Array<{ chunk: any, encoding: string }>, callback: Function) => any; - destroy?: (error?: Error) => any; + destroy?: (error: Error | null, callback: (error?: Error) => void) => void; final?: (callback: (error?: Error) => void) => void; } @@ -5394,7 +5394,7 @@ declare module "stream" { constructor(opts?: WritableOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error?: Error) => void): void; _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; write(chunk: any, encoding?: string, cb?: Function): boolean; @@ -5486,7 +5486,7 @@ declare module "stream" { constructor(opts?: DuplexOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error?: Error) => void): void; _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; write(chunk: any, encoding?: string, cb?: Function): boolean; @@ -5634,34 +5634,30 @@ declare module "assert" { expected: any; operator: string; generatedMessage: boolean; + code: 'ERR_ASSERTION'; constructor(options?: { message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function + operator?: string; stackStartFn?: Function }); } - export function fail(message: string): never; - export function fail(actual: any, expected: any, message?: string, operator?: string): never; + export function fail(message?: string): never; + export function fail(actual: any, expected: any, message?: string, operator?: string, stackStartFn?: Function): never; export function ok(value: any, message?: string): void; export function equal(actual: any, expected: any, message?: string): void; export function notEqual(actual: any, expected: any, message?: string): void; export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function notDeepEqual(actual: any, expected: any, message?: string): void; export function strictEqual(actual: any, expected: any, message?: string): void; export function notStrictEqual(actual: any, expected: any, message?: string): void; export function deepStrictEqual(actual: any, expected: any, message?: string): void; export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; export function throws(block: Function, message?: string): void; - export function throws(block: Function, error: Function, message?: string): void; - export function throws(block: Function, error: RegExp, message?: string): void; - export function throws(block: Function, error: (err: any) => boolean, message?: string): void; - + export function throws(block: Function, error: RegExp | Function, message?: string): void; export function doesNotThrow(block: Function, message?: string): void; - export function doesNotThrow(block: Function, error: Function, message?: string): void; - export function doesNotThrow(block: Function, error: RegExp, message?: string): void; - export function doesNotThrow(block: Function, error: (err: any) => boolean, message?: string): void; + export function doesNotThrow(block: Function, error: RegExp | Function, message?: string): void; export function ifError(value: any): void; } diff --git a/types/node/v8/node-tests.ts b/types/node/v8/node-tests.ts index dee74cc036..9cec14a88e 100644 --- a/types/node/v8/node-tests.ts +++ b/types/node/v8/node-tests.ts @@ -654,9 +654,10 @@ namespace url_tests { const searchParams = new url.URLSearchParams('abc=123'); assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string): void => { + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { assert.equal(name, 'abc'); assert.equal(value, '123'); + assert.equal(me, searchParams); }); assert.equal(searchParams.get('abc'), '123'); @@ -913,8 +914,9 @@ function simplified_stream_ctor_test() { read(size) { size.toFixed(); }, - destroy(error) { + destroy(error, cb) { error.stack; + cb(error); } }); @@ -929,8 +931,9 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, - destroy(error) { + destroy(error, cb) { error.stack; + cb(error); }, final(cb) { cb(null); @@ -951,6 +954,10 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, + destroy(error, cb) { + error.stack; + cb(error); + }, readableObjectMode: true, writableObjectMode: true }); @@ -977,8 +984,9 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, - destroy(error) { + destroy(error, cb) { error.stack; + cb(error); }, allowHalfOpen: true, readableObjectMode: true, diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 86866daa77..aed5a0f9a0 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -25,6 +25,7 @@ // Alexander T. // Lishude // Andrew Makarov +// Eugene Y. Q. Shen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** inspector module types */ @@ -674,7 +675,7 @@ declare namespace NodeJS { columns?: number; rows?: number; _write(chunk: any, encoding: string, callback: Function): void; - _destroy(err: Error, callback: Function): void; + _destroy(err: Error | undefined, callback: Function): void; _final(callback: Function): void; setDefaultEncoding(encoding: string): this; cork(): void; @@ -687,7 +688,7 @@ declare namespace NodeJS { isRaw?: boolean; setRawMode?(mode: boolean): void; _read(size: number): void; - _destroy(err: Error, callback: Function): void; + _destroy(err: Error | undefined, callback: Function): void; push(chunk: any, encoding?: string): boolean; destroy(error?: Error): void; } @@ -2459,7 +2460,7 @@ declare module "url" { append(name: string, value: string): void; delete(name: string): void; entries(): IterableIterator<[string, string]>; - forEach(callback: (value: string, name: string) => void): void; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; get(name: string): string | null; getAll(name: string): string[]; has(name: string): boolean; @@ -5376,7 +5377,7 @@ declare module "stream" { encoding?: string; objectMode?: boolean; read?: (this: Readable, size?: number) => any; - destroy?: (error?: Error) => any; + destroy?: (error: Error | null, callback: (error?: Error) => void) => void; } export class Readable extends Stream implements NodeJS.ReadableStream { @@ -5394,7 +5395,7 @@ declare module "stream" { unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): this; push(chunk: any, encoding?: string): boolean; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error?: Error) => void): void; destroy(error?: Error): void; /** @@ -5462,7 +5463,7 @@ declare module "stream" { objectMode?: boolean; write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; writev?: (chunks: Array<{ chunk: string | Buffer, encoding: string }>, callback: Function) => any; - destroy?: (error?: Error) => any; + destroy?: (error: Error | null, callback: (error?: Error) => void) => void; final?: (callback: (error?: Error) => void) => void; } @@ -5473,7 +5474,7 @@ declare module "stream" { constructor(opts?: WritableOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error?: Error) => void): void; _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; write(chunk: any, encoding?: string, cb?: Function): boolean; @@ -5566,7 +5567,7 @@ declare module "stream" { constructor(opts?: DuplexOptions); _write(chunk: any, encoding: string, callback: (err?: Error) => void): void; _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (err?: Error) => void): void; - _destroy(err: Error, callback: Function): void; + _destroy(error: Error | null, callback: (error?: Error) => void): void; _final(callback: Function): void; write(chunk: any, cb?: Function): boolean; write(chunk: any, encoding?: string, cb?: Function): boolean; @@ -5708,7 +5709,7 @@ declare module "util" { } declare module "assert" { - function internal(value: any, message?: string): void; + function internal(value: any, message?: string | Error): void; namespace internal { export class AssertionError implements Error { name: string; @@ -5717,34 +5718,30 @@ declare module "assert" { expected: any; operator: string; generatedMessage: boolean; + code: 'ERR_ASSERTION'; constructor(options?: { message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function + operator?: string; stackStartFn?: Function }); } - export function fail(message: string): never; - export function fail(actual: any, expected: any, message?: string, operator?: string): never; - export function ok(value: any, message?: string): void; - export function equal(actual: any, expected: any, message?: string): void; - export function notEqual(actual: any, expected: any, message?: string): void; - export function deepEqual(actual: any, expected: any, message?: string): void; - export function notDeepEqual(acutal: any, expected: any, message?: string): void; - export function strictEqual(actual: any, expected: any, message?: string): void; - export function notStrictEqual(actual: any, expected: any, message?: string): void; - export function deepStrictEqual(actual: any, expected: any, message?: string): void; - export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; + export function fail(message?: string | Error): never; + export function fail(actual: any, expected: any, message?: string | Error, operator?: string, stackStartFn?: Function): never; + export function ok(value: any, message?: string | Error): void; + export function equal(actual: any, expected: any, message?: string | Error): void; + export function notEqual(actual: any, expected: any, message?: string | Error): void; + export function deepEqual(actual: any, expected: any, message?: string | Error): void; + export function notDeepEqual(actual: any, expected: any, message?: string | Error): void; + export function strictEqual(actual: any, expected: any, message?: string | Error): void; + export function notStrictEqual(actual: any, expected: any, message?: string | Error): void; + export function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; + export function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; - export function throws(block: Function, message?: string): void; - export function throws(block: Function, error: Function, message?: string): void; - export function throws(block: Function, error: RegExp, message?: string): void; - export function throws(block: Function, error: (err: any) => boolean, message?: string): void; - - export function doesNotThrow(block: Function, message?: string): void; - export function doesNotThrow(block: Function, error: Function, message?: string): void; - export function doesNotThrow(block: Function, error: RegExp, message?: string): void; - export function doesNotThrow(block: Function, error: (err: any) => boolean, message?: string): void; + export function throws(block: Function, message?: string | Error): void; + export function throws(block: Function, error: RegExp | Function, message?: string | Error): void; + export function doesNotThrow(block: Function, message?: string | Error): void; + export function doesNotThrow(block: Function, error: RegExp | Function, message?: string | Error): void; export function ifError(value: any): void; } diff --git a/types/node/v9/node-tests.ts b/types/node/v9/node-tests.ts index 72ce012a3c..3d7861f532 100644 --- a/types/node/v9/node-tests.ts +++ b/types/node/v9/node-tests.ts @@ -680,9 +680,10 @@ namespace url_tests { const searchParams = new url.URLSearchParams('abc=123'); assert.equal(searchParams.toString(), 'abc=123'); - searchParams.forEach((value: string, name: string): void => { + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { assert.equal(name, 'abc'); assert.equal(value, '123'); + assert.equal(me, searchParams); }); assert.equal(searchParams.get('abc'), '123'); @@ -942,8 +943,9 @@ function simplified_stream_ctor_test() { read(size) { size.toFixed(); }, - destroy(error) { + destroy(error, cb) { error.stack; + cb(error); } }); @@ -958,8 +960,9 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, - destroy(error) { + destroy(error, cb) { error.stack; + cb(error); }, final(cb) { cb(null); @@ -980,6 +983,10 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, + destroy(error, cb) { + error.stack; + cb(error); + }, readableObjectMode: true, writableObjectMode: true }); @@ -1006,8 +1013,9 @@ function simplified_stream_ctor_test() { chunks[0].encoding.charAt(0); cb(); }, - destroy(error) { + destroy(error, cb) { error.stack; + cb(error); }, allowHalfOpen: true, readableObjectMode: true, diff --git a/types/ns-api/index.d.ts b/types/ns-api/index.d.ts index 267bb319c5..598c7dd493 100644 --- a/types/ns-api/index.d.ts +++ b/types/ns-api/index.d.ts @@ -10,47 +10,27 @@ interface nsApi { /** * Vertrektijden - departure times * - * @callback callback * @param station - Station ID - * @param callback - `function (err, data) {}` */ vertrektijden(station: string, callback: (err: string, data: {}) => void): void; /** * Reisadvies - travel advise - * - * @callback callback - * @param params - Parameters - * @param callback - `function (err, data) {}` */ reisadvies(params: {}, callback: (err: string, data: {}) => void): void; - /** - * Prijzen - tariffs - * - * @callback callback - * @param params - Parameters - * @param callback - `function (err, data) {}` - */ + /** Prijzen - tariffs */ prijzen(params: {}, callback: (err: any, data: {}) => void): void; /** * List available stations * - * @callback callback * @param [treeKey] - Group by this key - * @param callback - `function (err, data) {}` */ stations(treeKey: string, callback: (err: string, data: {}) => void): void; stations(callback: (err: string, data: {}) => void): void; - /** - * List disruptions - * - * @callback callback - * @param params - Parameters - * @param callback - `function (err, data) {}` - */ + /** List disruptions */ storingen(params: {}, callback: (err: string, data: {}) => void): void; } diff --git a/types/nuka-carousel/index.d.ts b/types/nuka-carousel/index.d.ts index 9766b64481..dcecb92a99 100644 --- a/types/nuka-carousel/index.d.ts +++ b/types/nuka-carousel/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/FormidableLabs/nuka-carousel // Definitions by: Roman Charugin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 6f88772854..36af5da50a 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -25,7 +25,9 @@ declare namespace Office { startCustomFunctions(): Promise; } - /** A Promise object. Promises can be chained via ".then", and errors can be caught via ".catch". When a browser-provided native Promise implementation is available, Office.Promise will switch to use the native Promise instead. */ + /** A Promise object. Promises can be chained via ".then", and errors can be caught via ".catch". + * When a browser-provided native Promise implementation is available, Office.Promise will switch to use the native Promise instead. + */ var Promise: IPromiseConstructor; // Note: this is a copy of the PromiseConstructor object from @@ -237,6 +239,25 @@ declare namespace Office { /** * Gets the Context object that represents the runtime environment of the add-in and provides access to the top-level objects of the API. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ var context: Context; /** @@ -251,7 +272,23 @@ declare namespace Office { * *Note*: The reason parameter of the initialize event listener function only returns an `InitializationReason` enumeration value for task pane and content add-ins. It does not return a value for Outlook add-ins. * * @remarks - *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
* * @param reason Indicates how the app was initialized. */ @@ -267,7 +304,23 @@ declare namespace Office { * Toggles on and off the `Office` alias for the full `Microsoft.Office.WebExtension` namespace. * * @remarks - *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
* * @param useShortNamespace True to use the shortcut alias; otherwise false to disable it. The default is true. */ @@ -277,9 +330,25 @@ declare namespace Office { * Specifies the result of an asynchronous call. * * @remarks - *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
* - * Returned by the status property of the AsyncResult object. + * Returned by the `status` property of the {@link Office.AsyncResult | AsyncResult} object. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y
*/ enum AsyncResultStatus { /** @@ -295,7 +364,20 @@ declare namespace Office { * Specifies whether the add-in was just inserted or was already contained in the document. * * @remarks - *
HostsExcel, Project, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
*/ enum InitializationReason { /** @@ -311,7 +393,24 @@ declare namespace Office { * Specifies the host Office application in which the add-in is running. * * @remarks - *
HostsExcel, Word, PowerPoint, Outlook, OneNote, Project, Access
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
OneNote Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ enum HostType { /** @@ -347,7 +446,24 @@ declare namespace Office { * Specifies the OS or other platform on which the Office host application is running. * * @remarks - *
HostsExcel, Word, PowerPoint, Outlook, OneNote, Project, Access
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
OneNote Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ enum PlatformType { /** @@ -386,35 +502,99 @@ declare namespace Office { */ interface AsyncResult { /** - * Gets the user-defined item passed to the optional `asyncContext` parameter of the invoked method in the same state as it was passed in. This the user-defined item (which can be of any JavaScript type: String, Number, Boolean, Object, Array, Null, or Undefined) passed to the optional `asyncContext` parameter of the invoked method. Returns Undefined, if you didn't pass anything to the asyncContext parameter. + * Gets the user-defined item passed to the optional `asyncContext` parameter of the invoked method in the same state as it was passed in. This returns the user-defined item (which can be of any JavaScript type: String, Number, Boolean, Object, Array, Null, or Undefined) passed to the optional `asyncContext` parameter of the invoked method. Returns Undefined, if you didn't pass anything to the asyncContext parameter. * * @remarks - *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project
Word Y Y Y
*/ asyncContext: any; /** - * Gets the {@link Office.AsyncResultStatus} of the asynchronous operation. - * - * @remarks - *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
- */ - status: AsyncResultStatus; - /** * Gets an {@link Office.Error} object that provides a description of the error, if any error occurred. * * @remarks - *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ error: Office.Error; /** + * Gets the {@link Office.AsyncResultStatus} of the asynchronous operation. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
+ */ + status: AsyncResultStatus; + /** * Gets the payload or content of this asynchronous operation, if any. * * @remarks - *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
- * - * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the `getSelectedDataAsync` and `setSelectedDataAsync` methods of the Document object. + * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the `getSelectedDataAsync` and `setSelectedDataAsync` methods of the {@link Office.Document | Document} object. * - * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. For a complete listing of the "Async" methods, see the Remarks section of the AsyncResult object topic. + * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. + * To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ value: any; } @@ -433,11 +613,46 @@ declare namespace Office { * True, if the current platform allows the add-in to display a UI for selling or upgrading; otherwise returns False. * * @remarks - * The iOS App Store doesn't support apps with add-ins that provide links to additional payment systems. However, Office Add-ins running on the Windows desktop or for Office Online in the browser, do allow such links. If you want the UI of your add-in to provide a link to an external payment system on platforms other than iOS, you can use the commerceAllowed property to control when that link is displayed. + * The iOS App Store doesn't support apps with add-ins that provide links to additional payment systems. However, Office Add-ins running on the Windows desktop or for Office Online in the browser do allow such links. If you want the UI of your add-in to provide a link to an external payment system on platforms other than iOS, you can use the commerceAllowed property to control when that link is displayed. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + *
Office for iPad
Excel Y
Word Y
*/ commerceAllowed: boolean; /** * Gets the locale (language) specified by the user for editing the document or item. + * + * @remarks + * The `contentLanguage` value reflects the **Editing Language** setting specified with **File > Options > Language** in the Office host application. + * + * In content add-ins for Access web apps, the `contentLanguage` property gets the add-in culture (e.g., "en-GB"). + * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ contentLanguage: string; /** @@ -446,14 +661,57 @@ declare namespace Office { diagnostics: ContextInformation; /** * Gets the locale (language) specified by the user for the UI of the Office host application. + * * @remarks + * + * The returned value is a string in the RFC 1766 Language tag format, such as en-US. + * + * The `displayLanguage` value reflects the current **Display Language** setting specified with **File > Options > Language** in the Office host application. + * + * In content add-ins for Access web apps, the `displayLanguage property` gets the add-in language (e.g., "en-US"). + * * When using in Outlook, the applicable modes are Compose or read. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y
*/ displayLanguage: string; /** * Gets an object that represents the document the content or task pane add-in is interacting with. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ - document: Document; + document: Office.Document; /** * Contains the Office application host in which the add-in is running. */ @@ -480,7 +738,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read */ - mailbox: Mailbox; + mailbox: Office.Mailbox; /** * Provides access to the properties for Office theme colors. */ @@ -505,12 +763,26 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read */ - roamingSettings: RoamingSettings; + roamingSettings: Office.RoamingSettings; /** - * Specifies whether the platform and device allows touch interaction. + * Specifies whether the platform and device allows touch interaction. True if the add-in is running on a touch device, such as an iPad; false otherwise. * * @remarks * Use the touchEnabled property to determine when your add-in is running on a touch device and if necessary, adjust the kind of controls, and size and spacing of elements in your add-in's UI to accommodate touch interactions. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for iPad
Excel Y
PowerPoint Y
Word Y
*/ touchEnabled: boolean; /** @@ -522,9 +794,24 @@ declare namespace Office { * Provides specific information about an error that occurred during an asynchronous data operation. * * @remarks - *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
- * * The Error object is accessed from the AsyncResult object that is returned in the function passed as the callback argument of an asynchronous data operation, such as the setSelectedDataAsync method of the Document object. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this interface is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this interface. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ interface Error { /** @@ -544,13 +831,9 @@ declare namespace Office { /** * The event object is passed as a parameter to add-in functions invoked by UI-less command buttons. The object allows the add-in to identify which button was clicked and to signal the host that it has completed its processing. * - * [Api set: Mailbox 1.3] - * * @remarks * - * - * - * + *
HostsExcel, Outlook, PowerPoint, Word
Add-in typeContent, task pane, Outlook
* * * @@ -559,10 +842,21 @@ declare namespace Office { interface Event { /** - * Information about the control that triggered calling this function + * Information about the control that triggered calling this function. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this property. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + *
Add-in typeContent, task pane, Outlook
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}Restricted
+ * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Outlook Y (Mailbox 1.3)
*/ source:Source; - /** * Indicates that the add-in has completed processing that was triggered by an add-in command button or event handler. * @@ -578,6 +872,21 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Outlook Y (Mailbox 1.3)
PowerPoint Y Y Y
Word Y Y Y
+ * * @param options Optional. An object literal that contains one or more of the following properties. * allowEvent: A boolean value. When the completed method is used to signal completion of an event handler, this value indicates of the handled event should continue execution or be canceled. For example, an add-in that handles the ItemSend event can set allowEvent = false to cancel sending of the message. */ @@ -758,7 +1067,8 @@ declare namespace Office { * @remarks * * - *
HostsExcel, OneNote, Outlook, PowerPoint, Word
Requirement setsIdentityAPI
+ * Requirement sets{@link https://docs.microsoft.com/office/dev/add-ins/develop/specify-office-hosts-and-api-requirements +| IdentityAPI} * * This API requires a single sign-on configuration that bridges the add-in to an Azure application. Office users sign-in with Organizational Accounts and Microsoft Accounts. Microsoft Azure returns tokens intended for both user account types to access resources in the Microsoft Graph. * @@ -1101,7 +1411,21 @@ declare namespace Office { * Using Office theme colors lets you coordinate the color scheme of your add-in with the current Office theme selected by the user with File > Office Account > Office Theme UI, which is applied across all Office host applications. Using Office theme colors is appropriate for mail and task pane add-ins. * * @remarks - *
HostsExcel, Outlook, Powerpoint, Project, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that these properties are supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop
Excel Y
Outlook Y
PowerPoint Y
Word Y
*/ interface OfficeTheme { /** @@ -1149,13 +1473,40 @@ declare namespace Office { * Returns a promise of an object described in the expression. Callback is invoked only if method fails. * @param expression The object to be retrieved. Example "bindings#BindingName", retrieves a binding promise for a binding named 'BindingName' * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y
*/ function select(expression: string, callback?: (result: AsyncResult) => void): Binding; // Enumerations /** * Specifies the state of the active view of the document, for example, whether the user can edit the document. * @remarks - *
HostsPowerPoint
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
PowerPoint Y Y Y
*/ enum ActiveView { /** @@ -1170,7 +1521,20 @@ declare namespace Office { /** * Specifies the type of the binding object that should be returned. * @remarks - *
HostsAccess, Excel, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
*/ enum BindingType { /** @@ -1182,7 +1546,7 @@ declare namespace Office { */ Matrix, /** - * Tabular data with a header row. Data is returned as a TableData object. + * Tabular data with a header row. Data is returned as a {@link Office.TableData | TableData} object. */ Table } @@ -1190,49 +1554,65 @@ declare namespace Office { * Specifies how to coerce data returned or set by the invoked method. * * @remarks - *
HostsAccess, Excel, Outlook, PowerPoint, Project, Word
+ * PowerPoint supports only `Office.CoercionType.Text`, `Office.CoercionType.Image`, and `Office.CoercionType.SlideRange`. * - * PowerPoint supports only `Office.CoercionType.Text`, `Office.CoercionType.Image`, and `Office.CoercionType.SlideRange`. Project supports only `Office.CoercionType.Text`. + * Project supports only `Office.CoercionType.Text`. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
Access Y
Excel Y Y Y
Outlook Y Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
*/ enum CoercionType { /** - * Return or set data as text (string).Data is returned or set as a one-dimensional run of characters. + * Return or set data as text (string). Data is returned or set as a one-dimensional run of characters. */ Text, /** * Return or set data as tabular data with no headers. Data is returned or set as an array of arrays containing one-dimensional runs of characters. For example, three rows of string values in two columns would be: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. - * @remarks - * Only applies to data in Excel and Word. + * + * Note: Only applies to data in Excel and Word. */ Matrix, /** * Return or set data as tabular data with optional headers. Data is returned or set as an array of arrays with optional headers. - * @remarks - * Only applies to data in Access, Excel and Word. + * + * Note: Only applies to data in Access, Excel, and Word. */ Table, /** * Return or set data as HTML. - * @remarks - * Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). + * + * Note: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). */ Html, /** * Return or set data as Office Open XML. - * @remarks - * Only applies to data in Word. + * + * Note: Only applies to data in Word. */ Ooxml, /** - * Return a JSON object that contains an array of the ids, titles, and indexes of the selected slides.For example, `{"slides":[{"id":257,"title":"Slide 2","index":2},{"id":256,"title":"Slide 1","index":1}]}` for a selection of two slides. - * @remarks - * Only applies to data in PowerPoint when calling the Document.getSelectedData method to get the current slide or selected range of slides. + * Return a JSON object that contains an array of the ids, titles, and indexes of the selected slides. For example, `{"slides":[{"id":257,"title":"Slide 2","index":2},{"id":256,"title":"Slide 1","index":1}]}` for a selection of two slides. + * + * Note: Only applies to data in PowerPoint when calling the {@link Office.Document | Document}.getSelectedData method to get the current slide or selected range of slides. */ SlideRange, /** * Data is returned or set as an image stream. - * @remarks - * Only applies to data in Excel, Word and PowerPoint. + * Note: Only applies to data in Excel, Word and PowerPoint. */ Image } @@ -1240,9 +1620,23 @@ declare namespace Office { * Specifies whether the document in the associated application is read-only or read-write. * * @remarks - *
HostsExcel, PowerPoint, Project, Word
+ * + * Returned by the mode property of the {@link Office.Document | Document} object. * - * Returned by the mode property of the Document object. + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y
*/ enum DocumentMode { /** @@ -1258,9 +1652,19 @@ declare namespace Office { * Specifies the type of the XML node. * * @remarks - * + *
HostsWord
Requirement SetsCustomXmlParts
* - * Requirement SetsCustomXmlParts + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y Y
*/ enum CustomXMLNodeType { /** @@ -1294,29 +1698,88 @@ declare namespace Office { } /** * Specifies the kind of event that was raised. Returned by the `type` property of an *EventArgs object. - * - * @remarks - * - *
HostsAccess, Excel, PowerPoint, Project, Word
Hosts (BindingDataChanged and BindingSelectionChanged)Access, Excel, Word
- * * * Add-ins for Project support the `Office.EventType.ResourceSelectionChanged`, `Office.EventType.TaskSelectionChanged`, and `Office.EventType.ViewSelectionChanged` event types. + * + * BindingDataChanged and BindingSelectionChanged hosts
Access, Excel, Word
+ * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Outlook Y Y Y
PowerPoint Y Y
Project Y
Word Y Y
*/ enum EventType { /** * A Document.ActiveViewChanged event was raised. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
PowerPoint Y Y Y
*/ ActiveViewChanged, /** * Occurs when data within the binding is changed. * To add an event handler for the BindingDataChanged event of a binding, use the addHandlerAsync method of the Binding object. * The event handler receives an argument of type {@link Office.BindingDataChangedEventArgs}. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
*/ BindingDataChanged, /** * Occurs when the selection is changed within the binding. * To add an event handler for the BindingSelectionChanged event of a binding, use the addHandlerAsync method of the Binding object. * The event handler receives an argument of type {@link Office.BindingSelectionChangedEventArgs}. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
*/ BindingSelectionChanged, /** @@ -1329,26 +1792,45 @@ declare namespace Office { DialogEventReceived, /** * Triggers when a document level selection happens + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y
Word Y Y
*/ DocumentSelectionChanged, /** - * A Document.SelectionChanged event was raised. + * Triggers when the selected Outlook item was changed. + * + * [Api set: Mailbox 1.1] */ ItemChanged, /** - * Triggers when a customXmlPart node was deleted + * Triggers when a customXmlPart node was deleted. */ NodeDeleted, /** - * Triggers when a customXmlPart node was inserted + * Triggers when a customXmlPart node was inserted. */ NodeInserted, /** - * Triggers when a customXmlPart node was replaced + * Triggers when a customXmlPart node was replaced. */ NodeReplaced, /** - * The recurrence pattern of the selected series has changed. + * Triggers when the recurrence pattern of the selected series was changed in Outlook. + * + * [Api set: Mailbox Preview] + * + * @beta */ RecurrencePatternChanged, /** @@ -1357,6 +1839,21 @@ declare namespace Office { ResourceSelectionChanged, /** * A Settings.settingsChanged event was raised. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
*/ SettingsChanged, /** @@ -1372,7 +1869,21 @@ declare namespace Office { * Specifies the format in which to return the document. * * @remarks - *
HostsPowerPoint, Word
+ * FileType.Text is only supported in Word, FileType.Pdf is only supported in Word for Windows, Word for Mac, Word Online, and PowerPoint. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
*/ enum FileType { /** @@ -1380,7 +1891,7 @@ declare namespace Office { */ Text, /** - * Returns the entire document (.pptx, .docx, or .xslx) in Office Open XML (OOXML) format as a byte array. + * Returns the entire document (.pptx, .docx, or .xlsx) in Office Open XML (OOXML) format as a byte array. */ Compressed, /** @@ -1392,7 +1903,20 @@ declare namespace Office { * Specifies whether filtering from the host application is applied when the data is retrieved. * * @remarks - *
HostsExcel, Project, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
*/ enum FilterType { /** @@ -1408,32 +1932,101 @@ declare namespace Office { * Specifies the type of place or object to navigate to. * * @remarks - *
HostsExcel, PowerPoint, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y
*/ enum GoToType { /** * Goes to a binding object using the specified binding id. + * + * Supported hosts: Excel, Word */ Binding, /** * Goes to a named item using that item's name. * In Excel, you can use any structured reference for a named range or table: "Worksheet2!Table1" + * + * Supported hosts: Excel */ NamedItem, /** * Goes to a slide using the specified id. + * + * Supported hosts: PowerPoint */ Slide, /** - * Goes to the specified index by slide number or Office.Index + * Goes to the specified index by slide number or {@link Office.Index}. + * + * Supported hosts: PowerPoint */ Index } /** - * Specifies whether to select (highlight) the location to navigate to (when using the Document.goToByIdAsync method). + * Specifies the relative PowerPoint slide. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
PowerPoint Y Y Y
+ */ + enum Index { + /** + * Represents the first PowerPoint slide + */ + First, + /** + * Represents the last PowerPoint slide + */ + Last, + /** + * Represents the next PowerPoint slide + */ + Next, + /** + * Represents the previous PowerPoint slide + */ + Previous + } + /** + * Specifies whether to select (highlight) the location to navigate to (when using the {@link Office.Document | Document}.goToByIdAsync method). * * @remarks - *
HostsExcel, PowerPoint, Word
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y
Word Y Y
*/ enum SelectionMode { Default, @@ -1442,7 +2035,7 @@ declare namespace Office { */ Selected, /** - * The cursor is moved the beginning of the location. + * The cursor is moved to the beginning of the location. */ None } @@ -1450,10 +2043,22 @@ declare namespace Office { * Specifies whether values, such as numbers and dates, returned by the invoked method are returned with their formatting applied. * * @remarks - *
HostsExcel, Project, Word
- * * For example, if the valueFormat parameter is specified as "formatted", a number formatted as currency, or a date formatted as mm/dd/yy in the host application will have its formatting preserved. * If the valueFormat parameter is specified as "unformatted", a date will be returned in its underlying sequential serial number form. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Project Y
Word Y Y
*/ enum ValueFormat { /** @@ -1470,38 +2075,41 @@ declare namespace Office { * Represents a binding to a section of the document. * * @remarks - * - * - *
HostsAccess, Excel, Word
Requirement SetsMatrixBinding, TableBinding, TextBinding
+ *
Requirement SetsMatrixBinding, TableBinding, TextBinding
* * The Binding object exposes the functionality possessed by all bindings regardless of type. * - * The Binding object is never called directly. It is the abstract parent class of the objects that represent each type of binding: MatrixBinding, TableBinding, or TextBinding. All three of these objects inherit the getDataAsync and setDataAsync methods from the Binding object that enable to you interact with the data in the binding. They also inherit the id and type properties for querying those property values. Additionally, the MatrixBinding and TableBinding objects expose additional methods for matrix- and table-specific features, such as counting the number of rows and columns. + * The Binding object is never called directly. It is the abstract parent class of the objects that represent each type of binding: {@link Office.MatrixBinding}, {@link Office.TableBinding}, or {@link Office.TextBinding}. All three of these objects inherit the getDataAsync and setDataAsync methods from the Binding object that enable to you interact with the data in the binding. They also inherit the id and type properties for querying those property values. Additionally, the MatrixBinding and TableBinding objects expose additional methods for matrix- and table-specific features, such as counting the number of rows and columns. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this interface is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this interface. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
*/ interface Binding { /** * Get the Document object associated with the binding. - * - * @remarks - *
HostsAccess, Excel, Word
*/ - document: Document; + document: Office.Document; /** - * A string that uniquely identifies this binding among the bindings in the same Document object. - * - * @remarks - *
HostsAccess, Excel, Word
+ * A string that uniquely identifies this binding among the bindings in the same {@link Office.Document} object. */ id: string; /** * Gets the type of the binding. - * - * @remarks - *
HostsAccess, Excel, Word
*/ - type: BindingType; + type: Office.BindingType; /** * Adds an event handler to the object for the specified {@link Office.EventType}. Supported EventTypes are `Office.EventType.BindingDataChanged` and `Office.EventType.BindingSelectionChanged`. * @@ -1511,30 +2119,26 @@ declare namespace Office { * @param eventType The event type. For bindings, it can be `Office.EventType.BindingDataChanged` or `Office.EventType.BindingSelectionChanged`. * @param handler The event handler function to add, whose only parameter is of type {@link Office.BindingDataChangedEventArgs} or {@link Office.BindingSelectionChangedEventArgs}. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. - * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ - addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: Office.AsyncResult) => void): void; /** * Returns the data contained within the binding. * * @remarks - * - * - *
HostsAccess, Excel, Word
Requirement SetsMatrixBindings, TableBindings, TextBindings
+ *
Requirement SetsMatrixBindings, TableBindings, TextBindings
* * When called from a MatrixBinding or TableBinding, the getDataAsync method will return a subset of the bound values if the optional startRow, startColumn, rowCount, and columnCount parameters are specified (and they specify a contiguous and valid range). * * @param options Provides options for how to get the data in a binding. - * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. */ getDataAsync(options?: GetBindingDataOptions, callback?: (result: AsyncResult) => void): void; /** * Removes the specified handler from the binding for the specified event type. * * @remarks - * - * - *
HostsAccess, Excel, Word
Requirement SetsBindingEvents
+ *
Requirement SetsBindingEvents
* * @param eventType The event type. For bindings, it can be `Office.EventType.BindingDataChanged` or `Office.EventType.BindingSelectionChanged`. * @param options Provides options to determine which event handler or handlers are removed. @@ -1545,10 +2149,8 @@ declare namespace Office { * Writes data to the bound section of the document represented by the specified binding object. * * @remarks - * - * * - *
HostsAccess, Excel, Word
Requirement SetsMatrixBindings, TableBindings, TextBindings
+ *
Requirement SetsMatrixBindings, TableBindings, TextBindings
* * The value passed for data contains the data to be written in the binding. The kind of value passed determines what will be written as described in the following table. * @@ -1740,25 +2342,33 @@ declare namespace Office { /** * Represents the bindings the add-in has within the document. - * - * @remarks - *
HostsAccess, Excel, Word
*/ interface Bindings { /** - * Gets an {@link Office.Document} object that represents the document associated with this set of bindings. - * - * @remarks - *
HostsAccess, Excel, Word
- */ + * Gets an {@link Office.Document} object that represents the document associated with this set of bindings. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this property. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
+ */ document: Document; /** * Creates a binding against a named object in the document. * * @remarks - * - * - *
HostsAccess, Excel, Word
Requirement SetsMatrixBindings, TableBindings, TextBindings
+ *
Requirement SetsMatrixBindings, TableBindings, TextBindings
* * For Excel, the itemName parameter can refer to a named range or a table. * @@ -1772,6 +2382,19 @@ declare namespace Office { * * Note: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one these content controls with this method (by specifying its name as the itemName parameter), the operation will fail. * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
* @param itemName Name of the bindable object in the document. For Example 'MyExpenses' table in Excel." * @param bindingType The {@link Office.BindingType} for the data. The method returns null if the selected object cannot be coerced into the specified type. * @param options Provides options for configuring the binding that is created. @@ -1782,11 +2405,22 @@ declare namespace Office { * Create a binding by prompting the user to make a selection on the document. * * @remarks - * - * - *
HostsAccess, Excel
Requirement SetsNot in a set
+ *
Requirement SetsNot in a set
* * Adds a binding object of the specified type to the Bindings collection, which will be identified with the supplied id. The method fails if the specified selection cannot be bound. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
* * @param bindingType Specifies the type of the binding object to create. Required. Returns null if the selected object cannot be coerced into the specified type. * @param options Provides options for configuring the prompt and identifying the binding that is created. @@ -1797,13 +2431,26 @@ declare namespace Office { * Create a binding based on the user's current selection. * * @remarks - * - * - *
HostsAccess, Excel, Word
Requirement SetsMatrixBindings, TableBindings, TextBindings
+ *
Requirement SetsMatrixBindings, TableBindings, TextBindings
* * Adds the specified type of binding object to the Bindings collection, which will be identified with the supplied id. * - * Note In Excel, if you call the addFromSelectionAsync method passing in the Binding.id of an existing binding, the Binding.type of that binding is used, and its type cannot be changed by specifying a different value for the bindingType parameter.If you need to use an existing id and change the bindingType, call the Bindings.releaseByIdAsync method first to release the binding, and then call the addFromSelectionAsync method to reestablish the binding with a new type. + * Note In Excel, if you call the addFromSelectionAsync method passing in the Binding.id of an existing binding, the Binding.type of that binding is used, and its type cannot be changed by specifying a different value for the bindingType parameter. + * If you need to use an existing id and change the bindingType, call the Bindings.releaseByIdAsync method first to release the binding, and then call the addFromSelectionAsync method to reestablish the binding with a new type. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
* * @param bindingType Specifies the type of the binding object to create. Required. Returns null if the selected object cannot be coerced into the specified type. * @param options Provides options for configuring the prompt and identifying the binding that is created. @@ -1814,9 +2461,21 @@ declare namespace Office { * Gets all bindings that were previously created. * * @remarks - * - * - *
HostsAccess, Excel, Word
Requirement SetsMatrixBindings, TableBindings, TextBindings
+ *
Requirement SetsMatrixBindings, TableBindings, TextBindings
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
* * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. @@ -1826,11 +2485,23 @@ declare namespace Office { * Retrieves a binding based on its Name * * @remarks - * - * - *
HostsAccess, Excel, Word
Requirement SetsCustomXmlParts, MatrixBindings, TableBindings, TextBindings
+ *
Requirement SetsCustomXmlParts, MatrixBindings, TableBindings, TextBindings
* * Fails if the specified id does not exist. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
* * @param id Specifies the unique name of the binding object. Required. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -1841,11 +2512,23 @@ declare namespace Office { * Removes the binding from the document * * @remarks - * - * - *
HostsAccess, Excel, Word
Requirement SetsMatrixBindings, TableBindings, TextBindings
+ *
Requirement SetsMatrixBindings, TableBindings, TextBindings
* * Fails if the specified id does not exist. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
* * @param id Specifies the unique name to be used to identify the binding object. Required. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -1857,45 +2540,47 @@ declare namespace Office { * Represents an XML node in a tree in a document. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
+ *
Requirement SetsCustomXmlParts
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this interface is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this interface. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y Y
*/ interface CustomXmlNode { /** * Gets the base name of the node without the namespace prefix, if one exists. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
+ *
Requirement SetsCustomXmlParts
*/ baseName: string; /** * Retrieves the string GUID of the CustomXMLPart. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
+ *
Requirement SetsCustomXmlParts
*/ namespaceUri: string; /** * Gets the type of the CustomXMLNode. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
+ *
Requirement SetsCustomXmlParts
*/ nodeType: string; /** * Gets the nodes associated with the XPath expression. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
+ *
Requirement SetsCustomXmlParts
* * @param xPath The XPath expression that specifies the nodes to get. Required. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -1906,9 +2591,7 @@ declare namespace Office { * Gets the node value. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
+ *
Requirement SetsCustomXmlParts
* * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. @@ -1918,9 +2601,7 @@ declare namespace Office { * Gets the text of an XML node in a custom XML part. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
+ *
Requirement SetsCustomXmlParts
* * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. @@ -1930,9 +2611,7 @@ declare namespace Office { * Gets the node's XML. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
+ *
Requirement SetsCustomXmlParts
* * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. @@ -1942,9 +2621,7 @@ declare namespace Office { * Sets the node value. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
+ *
Requirement SetsCustomXmlParts
* * @param value The value to be set on the node * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -1968,9 +2645,7 @@ declare namespace Office { * Sets the node XML. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
+ *
Requirement SetsCustomXmlParts
* * @param xml The XML to be set on the node * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -1982,36 +2657,31 @@ declare namespace Office { * Represents a single CustomXMLPart in an {@link Office.CustomXmlParts} collection. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
+ *
Requirement SetsCustomXmlParts
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this interface is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this interface. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y Y
*/ interface CustomXmlPart { /** * True, if the custom XML part is built in; otherwise false. - * - * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
*/ builtIn: boolean; /** * Gets the GUID of the CustomXMLPart. - * - * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
*/ id: string; /** * Gets the set of namespace prefix mappings ({@link Office.CustomXmlPrefixMappings}) used against the current CustomXMLPart. - * - * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
*/ namespaceManager: CustomXmlPrefixMappings; @@ -2019,7 +2689,6 @@ declare namespace Office { * Adds an event handler to the object using the specified event type. * * @remarks - *
HostsWord
* * You can add multiple event handlers for the specified eventType as long as the name of each event handler function is unique. * @@ -2033,9 +2702,6 @@ declare namespace Office { * Deletes the Custom XML Part. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
* * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. @@ -2045,9 +2711,6 @@ declare namespace Office { * Asynchronously gets any CustomXmlNodes in this custom XML part which match the specified XPath. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
* * @param xPath An XPath expression that specifies the nodes you want returned. Required. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -2058,9 +2721,6 @@ declare namespace Office { * Asynchronously gets the XML inside this custom XML part. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
* * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. @@ -2070,9 +2730,6 @@ declare namespace Office { * Removes an event handler for the specified event type. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
* * @param eventType Specifies the type of event to remove. For a CustomXmlPart object, the eventType parameter can be specified as `Office.EventType.NodeDeleted`, `Office.EventType.NodeInserted`, and `Office.EventType.NodeReplaced`. * @param handler The name of the handler to remove. @@ -2086,7 +2743,18 @@ declare namespace Office { * Provides information about the deleted node that raised the nodeDeleted event. * * @remarks - *
HostsWord
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this interface is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this interface. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y
*/ interface NodeDeletedEventArgs { /** @@ -2109,7 +2777,18 @@ declare namespace Office { * Provides information about the inserted node that raised the nodeInserted event. * * @remarks - *
HostsWord
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this interface is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this interface. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y
*/ interface NodeInsertedEventArgs { /** @@ -2126,6 +2805,19 @@ declare namespace Office { /** * Provides information about the replaced node that raised the nodeReplaced event. + * + * @remarks + * **Support details** + * + * A capital Y in the following matrix indicates that this interface is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this interface. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y
*/ interface NodeReplacedEventArgs { /** @@ -2150,19 +2842,24 @@ declare namespace Office { * Represents a collection of CustomXmlPart objects. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
+ *
Requirement SetsCustomXmlParts
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this interface is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this interface. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y
*/ interface CustomXmlParts { /** * Asynchronously adds a new custom XML part to a file. * - * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
- * * @param xml The XML to add to the newly created custom XML part. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. @@ -2171,11 +2868,6 @@ declare namespace Office { /** * Asynchronously gets the specified custom XML part by its id. * - * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
- * * @param id The GUID of the custom XML part, including opening and closing braces. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. @@ -2184,11 +2876,6 @@ declare namespace Office { /** * Asynchronously gets the specified custom XML part(s) by its namespace. * - * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
- * * @param ns The namespace URI. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. @@ -2199,17 +2886,26 @@ declare namespace Office { * Represents a collection of CustomXmlPart objects. * * @remarks - *
HostsWord
+ * + *
Requirement SetsCustomXmlParts
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this interface is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this interface. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y
*/ interface CustomXmlPrefixMappings { /** * Asynchronously adds a prefix to namespace mapping to use when querying an item. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
- * * If no namespace is assigned to the requested prefix, the method returns an empty string (""). * * @param prefix Specifies the prefix to add to the prefix mapping list. Required. @@ -2222,9 +2918,6 @@ declare namespace Office { * Asynchronously gets the namespace mapped to the specified prefix. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
* * If the prefix already exists in the namespace manager, this method will overwrite the mapping of that prefix except when the prefix is one added or used by the data store internally, in which case it will return an error. * @@ -2237,9 +2930,6 @@ declare namespace Office { * Asynchronously gets the prefix for the specified namespace. * * @remarks - * - * - *
HostsWord
Requirement SetsCustomXmlParts
* * If no prefix is assigned to the requested namespace, the method returns an empty string (""). If there are multiple prefixes specified in the namespace manager, the method returns the first prefix that matches the supplied namespace. * @@ -2260,48 +2950,126 @@ declare namespace Office { * Gets an object that provides access to the bindings defined in the document. * * @remarks - *
HostsAccess, Excel, Word
- * * You don't instantiate the Document object directly in your script. To call members of the Document object to interact with the current document or worksheet, use `Office.context.document` in your script. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this property. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
PowerPoint Y Y Y
Word Y Y Y
*/ bindings: Bindings; /** * Gets an object that represents the custom XML parts in the document. * * @remarks - *
HostsWord
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this property. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Word Y Y
*/ customXmlParts: CustomXmlParts; /** * Gets the mode the document is in. * * @remarks - *
HostsWord
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this property. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
*/ mode: DocumentMode; /** * Gets an object that represents the saved custom settings of the content or task pane add-in for the current document. * * @remarks - *
HostsWord
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this property. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
*/ settings: Settings; /** * Gets the URL of the document that the host application currently has open. Returns null if the URL is unavailable. * * @remarks - *
HostsWord
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this property. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y
Word Y Y Y
*/ url: string; /** * Adds an event handler for a Document object event. * * @remarks - * - * - *
HostsExcel, PowerPoint, Project, Word
Requirement SetsDocumentEvents
+ *
Requirement SetsDocumentEvents
* * You can add multiple event handlers for the specified eventType as long as the name of each event handler function is unique. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Project Y
Word Y Y Y
* * @param eventType For a Document object event, the eventType parameter can be specified as `Office.EventType.Document.SelectionChanged` or `Office.EventType.Document.ActiveViewChanged`, or the corresponding text value of this enumeration. * @param handler The event handler function to add, whose only parameter is of type {@link Office.DocumentSelectionChangedEventArgs}. Required. @@ -2313,11 +3081,23 @@ declare namespace Office { * Returns the state of the current view of the presentation (edit or read). * * @remarks - * - * - *
HostsExcel, PowerPoint, Word
Requirement SetsActiveView
+ *
Requirement SetsActiveView
* * Can trigger an event when the view changes. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y
PowerPoint Y Y Y
Word Y
* * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. @@ -2327,9 +3107,7 @@ declare namespace Office { * Returns the entire document file in slices of up to 4194304 bytes (4 MB). For add-ins for iOS, file slice is supported up to 65536 (64 KB). Note that specifying file slice size of above permitted limit will result in an "Internal Error" failure. * * @remarks - * - * - *
HostsExcel, PowerPoint, Word
Requirement SetsFile
+ *
Requirement SetsFile
* * For add-ins running in Office host applications other than Office for iOS, the getFileAsync method supports getting files in slices of up to 4194304 bytes (4 MB). For add-ins running in Office for iOS apps, the getFileAsync method supports getting files in slices of up to 65536 (64 KB). * @@ -2342,6 +3120,20 @@ declare namespace Office { * Word on Windows desktop, Word on Mac, and Word Online: `Office.FileType.Compressed`, `Office.FileType.Pdf`, `Office.FileType.Text` * * Word on iPad: `Office.FileType.Compressed`, `Office.FileType.Text` + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y
PowerPoint Y Y Y
Word Y Y
* * @param fileType The format in which the file will be returned * @param options Provides options for setting the size of slices that the document will be divided into. @@ -2352,11 +3144,23 @@ declare namespace Office { * Gets file properties of the current document. * * @remarks - * - * - *
HostsExcel, PowerPoint, Word
Requirement Setsnot in a set
+ *
Requirement SetsNot in a set
* * You get the file's URL with the url property `asyncResult.value.url`. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
* * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. @@ -2366,9 +3170,7 @@ declare namespace Office { * Reads the data contained in the current selection in the document. * * @remarks - * - * - *
HostsAccess, Excel, PowerPoint, Project, Word
Requirement SetsSelection
+ *
Requirement SetsSelection
* * In the callback function that is passed to the getSelectedDataAsync method, you can use the properties of the AsyncResult object to return the following information. * @@ -2395,21 +3197,56 @@ declare namespace Office { * * * - * @param coercionType The type of data structure to return. + * The possible values for the {@link Office.CoercionType} parameter vary by the host. * - * The possible values for the {@link Office.CoercionType} parameter vary by the host: - * - * - Excel, Excel Online, PowerPoint, PowerPoint Online, Word, and Word Online only: `Office.CoercionType.Text` (string) - * - * - Excel, Word, and Word Online only: `Office.CoercionType.Matrix` (array of arrays) - * - * - Access, Excel, Word, and Word Online only: `Office.CoercionType.Table` (TableData object) - * - * - Word only: `Office.CoercionType.Html` - * - * - Word and Word Online only: `Office.CoercionType.Ooxml` (Office Open XML) - * - * - PowerPoint and PowerPoint Online only: `Office.CoercionType.SlideRange` + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
HostSupported coercionType
Excel, Excel Online, PowerPoint, PowerPoint Online, Word, and Word Online`Office.CoercionType.Text` (string)
Excel, Word, and Word Online`Office.CoercionType.Matrix` (array of arrays)
Access, Excel, Word, and Word Online`Office.CoercionType.Table` (TableData object)
Word`Office.CoercionType.Html`
Word and Word Online `Office.CoercionType.Ooxml` (Office Open XML)
PowerPoint and PowerPoint Online`Office.CoercionType.SlideRange`
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Project Y Y
Word Y Y
+ * + * @param coercionType The type of data structure to return. See the remarks section for each host's supported coercion types. * * @param options Provides options for customizing what data is returned and how it is formatted. * @@ -2420,9 +3257,7 @@ declare namespace Office { * Goes to the specified object or location in the document. * * @remarks - * - * - *
HostsExcel, PowerPoint, Word
Requirement Setsnot in a set
+ *
Requirement Setsnot in a set
* * PowerPoint doesn't support the goToByIdAsync method in Master Views. * @@ -2433,6 +3268,20 @@ declare namespace Office { * In PowerPoint: `Office.SelectionMode.Selected` selects the slide title or first textbox on the slide. `Office.SelectionMode.None` Doesn't select anything. * * In Word: `Office.SelectionMode.Selected` selects all content in the binding. Office.SelectionMode.None for text bindings, moves the cursor to the beginning of the text; for matrix bindings and table bindings, selects the first data cell (not first cell in header row for tables). + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y
* * @param id The identifier of the object or location to go to. * @param goToType The type of the location to go to. @@ -2444,9 +3293,21 @@ declare namespace Office { * Removes an event handler for the specified event type. * * @remarks - * - * - *
HostsExcel, PowerPoint, Project, Word
Requirement SetsDocumentEvents
+ *
Requirement SetsDocumentEvents
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
* * @param eventType The event type. For document can be 'Document.SelectionChanged' or 'Document.ActiveViewChanged'. * @param options Provides options to determine which event handler or handlers are removed. @@ -2457,9 +3318,7 @@ declare namespace Office { * Writes the specified data into the current selection. * * @remarks - * - * - *
HostsAccess, Excel, PowerPoint, Project, Word, Word Online
Requirement SetsSelection
+ *
Requirement SetsSelection
* * **Application-specific behaviors** * @@ -2488,21 +3347,55 @@ declare namespace Office { * PowerPointInsert imageInserted images are floating. The position imageLeft and imageTop parameters are optional but if provided, both should be present. If a single value is provided, it will be ignored. Negative imageLeft and imageTop values are allowed and can position an image outside of a slide. If no optional parameter is given and slide has a placeholder, the image will replace the placeholder in the slide. Image aspect ratio will be locked unless both imageWidth and imageHeight parameters are provided. If only one of the imageWidth and imageHeight parameter is given, the other value will be automatically scaled to keep the original aspect ratio. * * - * @param data The data to be set. Either a string or {@link Office.CoercionType} value, 2d array or TableData object. + * The possible values for the {@link Office.CoercionType} parameter vary by the host. * - * The possible CoercionTypes that can be used for the data parameter, or for the coercionType option, vary by host: - * - * - `Office.CoercionType.Text`: Excel, Word, PowerPoint - * - * - `Office.CoercionType.Matrix`: Excel, Word - * - * - `Office.CoercionType.Table`: Access, Excel, Word - * - * - `Office.CoercionType.Html`: Word - * - * - `Office.CoercionType.Ooxml`: Word - * - * - `Office.CoercionType.Image`: Excel, Word, PowerPoint + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
HostSupported coercionType
Excel, Excel Online, PowerPoint, PowerPoint Online, Word, and Word Online`Office.CoercionType.Text` (string)
Excel, Word, and Word Online`Office.CoercionType.Matrix` (array of arrays)
Access, Excel, Word, and Word Online`Office.CoercionType.Table` (TableData object)
Word`Office.CoercionType.Html`
Word and Word Online `Office.CoercionType.Ooxml` (Office Open XML)
PowerPoint and PowerPoint Online`Office.CoercionType.SlideRange`
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
+ * + * @param data The data to be set. Either a string or {@link Office.CoercionType} value, 2d array or TableData object. * * If the value passed for `data` is: * @@ -2525,6 +3418,20 @@ declare namespace Office { * @param fieldId Project level fields. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ getProjectFieldAsync(fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** @@ -2533,24 +3440,80 @@ declare namespace Office { * @param fieldId Resource Fields. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ getResourceFieldAsync(resourceId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the current selected Resource's Id. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ getSelectedResourceAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the current selected Task's Id. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ getSelectedTaskAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the current selected View Type (Ex. Gantt) and View Name. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ getSelectedViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** @@ -2558,6 +3521,20 @@ declare namespace Office { * @param taskId Either a string or value of the Task Id. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ getTaskAsync(taskId: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** @@ -2566,12 +3543,40 @@ declare namespace Office { * @param fieldId Task Fields. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ getTaskFieldAsync(taskId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Project documents only. Get the WSS Url and list name for the Tasks List, the MPP is synced too. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ getWSSUrlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** @@ -2581,6 +3586,20 @@ declare namespace Office { * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ getMaxResourceIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** @@ -2590,6 +3609,20 @@ declare namespace Office { * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ getMaxTaskIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** @@ -2600,6 +3633,20 @@ declare namespace Office { * @param resourceIndex The index of the resource in the collection of resources for the project. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ getResourceByIndexAsync(resourceIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** @@ -2610,6 +3657,20 @@ declare namespace Office { * @param taskIndex The index of the task in the collection of tasks for the project. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ getTaskByIndexAsync(taskIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** @@ -2622,6 +3683,20 @@ declare namespace Office { * @param fieldValue Value of the target field. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** @@ -2634,6 +3709,20 @@ declare namespace Office { * @param fieldValue Value of the target field. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; } @@ -2654,24 +3743,31 @@ declare namespace Office { * Represents the document file associated with an Office Add-in. * * @remarks - *
HostsPowerPoint, Word
- * * Access the File object with the AsyncResult.value property in the callback function passed to the Document.getFileAsync method. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this interface is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this interface. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
PowerPoint Y Y Y
Word Y Y Y
*/ interface File { /** * Gets the document file size in bytes. * * @remarks - * - * - *
HostsPowerPoint, Word
Requirement SetsFile
+ *
Requirement SetsFile
*/ size: number; /** * Gets the number of slices into which the file is divided. - * @remarks - *
HostsPowerPoint, Word
*/ sliceCount: number; /** @@ -2679,9 +3775,7 @@ declare namespace Office { * * @remarks * - * - * - *
HostsPowerPoint, Word
Requirement SetsFile
+ *
Requirement SetsFile
* * No more than two documents are allowed to be in memory; otherwise the Document.getFileAsync operation will fail. Use the File.closeAsync method to close the file when you are finished working with it. * @@ -2717,9 +3811,7 @@ declare namespace Office { * Returns the specified slice. * * @remarks - * - * - *
HostsPowerPoint, Word
Requirement SetsFile
+ *
Requirement SetsFile
* * In the callback function passed to the getSliceAsync method, you can use the properties of the AsyncResult object to return the following information. * @@ -2761,11 +3853,22 @@ declare namespace Office { * Represents a binding in two dimensions of rows and columns. * * @remarks - * - * - *
HostsExcel, Word
Requirement SetsMatrixBindings
+ *
Requirement SetsMatrixBindings
* * The MatrixBinding object inherits the id property, type property, getDataAsync method, and setDataAsync method from the Binding object. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this interface is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this interface. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Word Y Y Y
*/ interface MatrixBinding extends Binding { /** @@ -2811,9 +3914,7 @@ declare namespace Office { * * @remarks * - * - * - *
HostsExcel
Requirement SetsSettings
+ *
Requirement SetsSettings
* * You can add multiple event handlers for the specified eventType as long as the name of each event handler function is unique. * @@ -2844,15 +3945,40 @@ declare namespace Office { * A user-defined item of any type that is returned in the AsyncResult object without being altered. * * + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y
*/ addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Retrieves the specified setting. * * @remarks - * - * - *
HostsAccess, Excel, PowerPoint, Word
Requirement SetsSettings
+ *
Requirement SetsSettings
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
* * @param settingName The case-sensitive name of the setting to retrieve. * @returns An object that has property names mapped to JSON serialized values. @@ -2863,16 +3989,12 @@ declare namespace Office { * * @remarks * - * - * - *
HostsAccess, Excel, PowerPoint, Word
Requirement SetsSettings
+ *
Requirement SetsSettings
* - * This method is useful in Word and PowerPoint coauthoring scenarios when multiple instances of the same add-in are working against the same document. + * This method is useful in Excel, Word, and PowerPoint coauthoring scenarios when multiple instances of the same add-in are working against the same document. * Because each add-in is working against an in-memory copy of the settings loaded from the document at the time the user opened it, the settings values used by each user can get out of sync. * This can happen whenever an instance of the add-in calls the Settings.saveAsync method to persist all of that user's settings to the document. * Calling the refreshAsync method from the event handler for the settingsChanged event of the add-in will refresh the settings values for all users. - * - * The refreshAsync method can be called from add-ins created for Excel, but since it doesn't support coauthoring there is no reason to do so. * * In the callback function passed to the refreshAsync method, you can use the properties of the AsyncResult object to return the following information. * @@ -2898,6 +4020,21 @@ declare namespace Office { * A user-defined item of any type that is returned in the AsyncResult object without being altered. * * + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
* * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. When the function you passed to the callback parameter executes, it receives an AsyncResult object that you can access from the callback function's only parameter. */ @@ -2908,11 +4045,24 @@ declare namespace Office { * Important: Be aware that the Settings.remove method affects only the in-memory copy of the settings property bag. To persist the removal of the specified setting in the document, at some point after calling the Settings.remove method and before the add-in is closed, you must call the Settings.saveAsync method. * * @remarks - * - * - *
HostsAccess, Excel, PowerPoint, Word
Requirement SetsSettings
+ *
Requirement SetsSettings
* * null is a valid value for a setting. Therefore, assigning null to the setting will not remove it from the settings property bag. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y
* * @param settingName The case-sensitive name of the setting to remove. */ @@ -2921,31 +4071,43 @@ declare namespace Office { * Removes an event handler for the settingsChanged event. * * @remarks + * + *
Requirement SetsSettings
+ * * If the optional handler parameter is omitted when calling the removeHandlerAsync method, all event handlers for the specified eventType will be removed. - * - * - * - *
HostsAccess, Excel, PowerPoint
Requirement SetsSettings
+ * + * When the function you passed to the callback parameter executes, it receives an AsyncResult object that you can access from the callback function's only parameter. + * + * In the callback function passed to the removeHandlerAsync method, you can use the properties of the AsyncResult object to return the following information. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
* * @param eventType Specifies the type of event to remove. Required. * @param options Provides options to determine which event handler or handlers are removed. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. - * @remarks - * When the function you passed to the callback parameter executes, it receives an AsyncResult object that you can access from the callback function's only parameter. - * In the callback function passed to the removeHandlerAsync method, you can use the properties of the AsyncResult object to return the following information. */ removeHandlerAsync(eventType: Office.EventType, options?: RemoveHandlerOptions, callback?: (result: AsyncResult) => void): void; /** * Persists the in-memory copy of the settings property bag in the document. * - * @remarks - *
HostsAccess, Excel, PowerPoint, Word
- * + * @remarks * Any settings previously saved by an add-in are loaded when it is initialized, so during the lifetime of the session you can just use the set and get methods to work with the in-memory copy of the settings property bag. * When you want to persist the settings so that they are available the next time the add-in is used, use the saveAsync method. * - * Note: The saveAsync method persists the in-memory settings property bag into the document file; however, the changes to the document file itself are saved only when the user (or AutoRecover setting) saves the document to the file system. - * The refreshAsync method is only useful in coauthoring scenarios (which are only supported in Word) when other instances of the same add-in might change the settings and those changes should be made available to all instances. + * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file itself are saved only when the user (or AutoRecover setting) saves the document to the file system. + * The refreshAsync method is only useful in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to all instances. * * * @@ -2970,6 +4132,21 @@ declare namespace Office { * *
* + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
+ * * @param options Provides options for saving settings. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. When the function you passed to the callback parameter executes, it receives an AsyncResult object that you can access from the callback function's only parameter to return the following information. */ @@ -2981,12 +4158,26 @@ declare namespace Office { * To make sure that additions or changes to settings will be available to your add-in the next time the document is opened, at some point after calling the Settings.set method and before the add-in is closed, you must call the Settings.saveAsync method to persist settings in the document. * * @remarks - * - * - *
HostsAccess, Excel, PowerPoint, Word
Requirement SetsSettings
+ *
Requirement SetsSettings
* * The set method creates a new setting of the specified name if it does not already exist, or sets an existing setting of the specified name in the in-memory copy of the settings property bag. * After you call the Settings.saveAsync method, the value is stored in the document as the serialized JSON representation of its data type. A maximum of 2MB is available for the settings of each add-in. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
PowerPoint Y Y Y
Word Y Y Y
+ * * @param settingName The case-sensitive name of the setting to set or create. * @param value Specifies the value to be stored. */ @@ -2996,84 +4187,97 @@ declare namespace Office { * Represents a slice of a document file. * * @remarks - * - * - *
HostsPowerPoint, Word
Requirement SetsFile
+ *
Requirement SetsFile
* * The Slice object is accessed with the File.getSliceAsync method. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this interface is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this interface. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
PowerPoint Y Y Y
Word Y Y Y
*/ interface Slice { /** * Gets the raw data of the file slice in `Office.FileType.Text` ("text") or `Office.FileType.Compressed` ("compressed") format as specified by the fileType parameter of the call to the Document.getFileAsync method. * * @remarks - * - * - *
HostsPowerPoint, Word
Requirement SetsFile
* * Files in the "compressed" format will return a byte array that can be transformed to a base64-encoded string if required. */ data: any; /** * Gets the zero-based index of the file slice. - * - * @remarks - * - * - *
HostsPowerPoint, Word
Requirement SetsFile
*/ index: number; /** * Gets the size of the slice in bytes. - * - * @remarks - * - * - *
HostsPowerPoint, Word
Requirement SetsFile
*/ size: number; } /** - * Represents a binding in two dimensions of rows and columns, optionally with headers. - * - * @remarks - * - * - *
HostsAccess, Excel, PowerPoint, Project, Word
Requirement SetsTableBindings
- * - * The TableBinding object inherits the id property, type property, getDataAsync method, and setDataAsync method from the Binding object. - * - * For Excel, note that after you establish a table binding in Excel, each new row a user adds to the table is automatically included in the binding and rowCount increases. - */ + * Represents a binding in two dimensions of rows and columns, optionally with headers. + * + * @remarks + *
Requirement SetsTableBindings
+ * + * The TableBinding object inherits the id property, type property, getDataAsync method, and setDataAsync method from the Binding object. + * + * For Excel, note that after you establish a table binding in Excel, each new row a user adds to the table is automatically included in the binding and rowCount increases. + */ interface TableBinding extends Binding { /** * Gets the number of columns in the TableBinding, as an integer value. * * @remarks - * - * - *
HostsAccess, Excel,Word
Requirement SetsTableBindings
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this property. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
*/ columnCount: number; /** * True, if the table has headers; otherwise false. * * @remarks - * - * - *
HostsAccess, Excel, PowerPoint, Project, Word
Requirement SetsTableBindings
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this property. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
*/ hasHeaders: boolean; /** * Gets the number of rows in the TableBinding, as an integer value. * * @remarks - * - * - *
HostsAccess, Excel,Word
Requirement SetsTableBindings
- * * When you insert an empty table by selecting a single row in Excel 2013 and Excel Online (using Table on the Insert tab), both Office host applications create a single row of headers followed by a single blank row. However, if your add-in's script creates a binding for this newly inserted table (for example, by using the addFromSelectionAsync method), and then checks the value of the rowCount property, the value returned will differ depending whether the spreadsheet is open in Excel 2013 or Excel Online. - * - In Excel on the desktop, rowCount will return 0 (the blank row following the headers is not counted). * * - In Excel Online, rowCount will return 1 (the blank row following the headers is counted). @@ -3081,15 +4285,26 @@ declare namespace Office { * You can work around this difference in your script by checking if rowCount == 1, and if so, then checking if the row contains all empty strings. * * In content add-ins for Access, for performance reasons the rowCount property always returns -1. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this property. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
*/ rowCount: number; /** * Adds the specified data to the table as additional columns. * * @remarks - * - * - *
HostsExcel, Word
Requirement SetsTableBindings
* * To add one or more columns specifying the values of the data and headers, pass a TableData object as the data parameter. To add one or more columns specifying only the data, pass an array of arrays ("matrix") as the data parameter. * @@ -3102,6 +4317,19 @@ declare namespace Office { * - If you pass a TableData object as the data argument, the number of header rows must match that of the table being updated. * * Additional remark for Excel Online: The total number of cells in the TableData object passed to the data parameter can't exceed 20,000 in a single call to this method. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Word Y Y Y
* * @param tableData An array of arrays ("matrix") or a TableData object that contains one or more columns of data to add to the table. Required. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3112,9 +4340,6 @@ declare namespace Office { * Adds the specified data to the table as additional rows. * * @remarks - * - * - *
HostsAccess, Excel, Word
Requirement SetsTableBindings
* * To add one or more columns specifying the values of the data and headers, pass a TableData object as the data parameter. To add one or more columns specifying only the data, pass an array of arrays ("matrix") as the data parameter. * @@ -3127,6 +4352,20 @@ declare namespace Office { * - If you pass a TableData object as the data argument, the number of header rows must match that of the table being updated. * * Additional remark for Excel Online: The total number of cells in the TableData object passed to the data parameter can't exceed 20,000 in a single call to this method. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
* * @param rows An array of arrays ("matrix") or a TableData object that contains one or more rows of data to add to the table. Required. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3137,11 +4376,22 @@ declare namespace Office { * Deletes all non-header rows and their values in the table, shifting appropriately for the host application. * * @remarks - * - * - *
HostsAccess, Excel, Word
Requirement SetsTableBindings
* * In Excel, if the table has no header row, this method will delete the table itself. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Access Y
Excel Y Y Y
Word Y Y Y
* * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. @@ -3151,11 +4401,19 @@ declare namespace Office { * Clears formatting on the bound table. * * @remarks - * - * - *
HostsExcel
Requirement SetsNot in a set
- * * See {@link https://docs.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-tables#format-a-table | Format tables in add-ins for Excel} for more information. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
* * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type AsyncResult. @@ -3173,9 +4431,6 @@ declare namespace Office { * Sets formatting on specified items and data in the table. * * @remarks - * - * - *
HostsExcel
Requirement SetsNot in a set
* * **Specifying the cellFormat parameter** * @@ -3284,6 +4539,18 @@ declare namespace Office { * A user-defined item of any type that is returned in the AsyncResult object without being altered. * * + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
* * @param cellFormat An array that contains one or more JavaScript objects that specify which cells to target and the formatting to apply to them. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3322,6 +4589,18 @@ declare namespace Office { * A user-defined item of any type that is returned in the AsyncResult object without being altered. * * + * + * **Support details** + * + * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this method. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
* * @param tableOptions An object literal containing a list of property name-value pairs that define the table options to apply. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3378,10 +4657,21 @@ declare namespace Office { rows: any[][]; } /** - * Specifies enumerated values for the cells: property in the cellFormat parameter of {@link https://docs.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-tables#format-a-table | table formatting methods}. + * Specifies enumerated values for the `cells` property in the cellFormat parameter of {@link https://docs.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-tables#format-a-table | table formatting methods}. * * @remarks - *
HostsExcel
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
*/ enum Table { /** @@ -3398,23 +4688,45 @@ declare namespace Office { Headers } /** - * Represents a bound text selection in the document. - * - * @remarks - * - * - *
HostsAccess, Excel, PowerPoint, Project, Word
Requirement SetsTextBindings
- * - * The TextBinding object inherits the id property, type property, getDataAsync method, and setDataAsync method from the {@link Office.Binding} object. It does not implement any additional properties or methods of its own. - */ - interface TextBinding extends Binding { } - /** - * Specifies the project fields that are available as a parameter for the getProjectFieldAsync method. + * Represents a bound text selection in the document. * * @remarks - *
HostsProject
+ *
Requirement SetsTextBindings
+ * + * The TextBinding object inherits the id property, type property, getDataAsync method, and setDataAsync method from the {@link Office.Binding} object. It does not implement any additional properties or methods of its own. * - * A ProjectProjectFields constant can be used as a parameter of the getProjectFieldAsync method. + * **Support details** + * + * A capital Y in the following matrix indicates that this interface is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this interface. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + * + *
Office for Windows desktop Office Online (in browser) Office for iPad
Excel Y Y Y
Word Y Y Y
+ */ + interface TextBinding extends Binding { } + /** + * Specifies the project fields that are available as a parameter for the {@link Office.Document | Document}.getProjectFieldAsync method. + * + * @remarks + * + * A ProjectProjectFields constant can be used as a parameter of the {@link Office.Document | Document}.getProjectFieldAsync method. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectProjectFields { /** @@ -3468,12 +4780,24 @@ declare namespace Office { WSSList } /** - * Specifies the resource fields that are available as a parameter for the getResourceFieldAsync method. + * Specifies the resource fields that are available as a parameter for the {@link Office.Document | Document}.getResourceFieldAsync method. * * @remarks - * A ProjectResourceFields constant can be used as a parameter of the getResourceFieldAsync method. + * A ProjectResourceFields constant can be used as a parameter of the {@link Office.Document | Document}.getResourceFieldAsync method. * * For more information about working with fields in Project, see {@link https://support.office.com/article/Available-fields-reference-615a4563-1cc3-40f4-b66f-1b17e793a460 | Available fields} reference. In Project Help, search for Available fields. + * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectResourceFields { /** @@ -4278,14 +5602,24 @@ declare namespace Office { Text9 } /** - * Specifies the task fields that are available as a parameter for the getTaskFieldAsync method. + * Specifies the task fields that are available as a parameter for the {@link Office.Document | Document}.getTaskFieldAsync method. * * @remarks - * A ProjectTaskFields constant can be used as a parameter of the getTaskFieldAsync method. + * A ProjectTaskFields constant can be used as a parameter of the {@link Office.Document | Document}.getTaskFieldAsync method. * * For more information about working with fields in Project, see the {@link https://support.office.com/article/Available-fields-reference-615a4563-1cc3-40f4-b66f-1b17e793a460 | Available fields} reference. In Project Help, search for Available fields. - * - *
HostsProject
+ * + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectTaskFields { /** @@ -5416,12 +6750,22 @@ declare namespace Office { WSSID } /** - * Specifies the types of views that the getSelectedViewAsync method can recognize. + * Specifies the types of views that the {@link Office.Document | Document}.getSelectedViewAsync method can recognize. * * @remarks - *
HostsProject
+ * The {@link Office.Document | Document}.getSelectedViewAsync method returns the ProjectViewTypes constant value and name that corresponds to the active view. * - * The getSelectedViewAsync method returns the ProjectViewTypes constant value and name that corresponds to the active view. + * **Support details** + * + * A capital Y in the following matrix indicates that this enumeration is supported in the corresponding Office host application. An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * + * + *
Office for Windows desktop Office Online (in browser)
Project Y
*/ enum ProjectViewTypes { /** @@ -5730,6 +7074,23 @@ declare namespace Office { */ Dec = "dec" } + /** + * Represents the current view of Outlook Web App. + */ + enum OWAView { + /** + * One column view. Displayed when the screen is narrow. Outlook Web App uses this single-column layout on the entire screen of a smartphone. + */ + OneColumn = "OneColumn", + /** + * Two column view. Displayed when the screen is wider. Outlook Web App uses this view on most tablets. + */ + TwoColumns = "TwoColumns", + /** + Three column view. Displayed when the screen is wide. For example, Outlook Web App uses this view in a full screen window on a desktop computer. + */ + ThreeColumns = "ThreeColumns" + } /** * Specifies the type of recipient for an appointment. * @@ -7165,7 +8526,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read */ - OWAView: "string"; + OWAView: MailboxEnums.OWAView | "OneColumn" | "TwoColumns" | "ThreeColumns"; } /** * Provides the email properties of the sender or specified recipients of an email message or appointment. @@ -7804,7 +9165,9 @@ declare namespace Office { * * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ @@ -8623,7 +9986,9 @@ declare namespace Office { * * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ @@ -8641,13 +10006,15 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Attendee * - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ getInitializationContextAsync(callback?: (result: AsyncResult) => void): void; /** - * Gets the entities found in the selected item. + * Gets the entities found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -8661,7 +10028,7 @@ declare namespace Office { */ getEntities(): Entities; /** - * Gets an array of all the entities of the specified entity type found in the selected item. + * Gets an array of all the entities of the specified entity type found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -8670,7 +10037,7 @@ declare namespace Office { * @param entityType One of the EntityType enumeration values. * * @returns - * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present on the item, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. + * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present in the item's body, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. * * @remarks * @@ -9382,7 +10749,9 @@ declare namespace Office { * * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ @@ -9898,7 +11267,9 @@ declare namespace Office { * * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ @@ -9916,13 +11287,15 @@ declare namespace Office { * *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}Restricted
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Read
* - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ getInitializationContextAsync(callback?: (result: AsyncResult) => void): void; /** - * Gets the entities found in the selected item. + * Gets the entities found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -9936,7 +11309,7 @@ declare namespace Office { */ getEntities(): Entities; /** - * Gets an array of all the entities of the specified entity type found in the selected item. + * Gets an array of all the entities of the specified entity type found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -9945,7 +11318,7 @@ declare namespace Office { * @param entityType One of the EntityType enumeration values. * * @returns - * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present on the item, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. + * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present in the item's body, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. * * @remarks * @@ -10603,7 +11976,9 @@ declare namespace Office { * * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ @@ -11426,7 +12801,9 @@ declare namespace Office { * * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ @@ -11444,13 +12821,15 @@ declare namespace Office { * *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}Restricted
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Read
* - * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. On success, the initialization data is provided in the asyncResult.value property as a string. If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, asyncResult, which is an AsyncResult object. + * On success, the initialization data is provided in the asyncResult.value property as a string. + * If there is no initialization context, the asyncResult object will contain an Error object with its code property set to 9020 and its name property set to GenericResponseError. * * @beta */ getInitializationContextAsync(callback?: (result: AsyncResult) => void): void; /** - * Gets the entities found in the selected item. + * Gets the entities found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -11464,7 +12843,7 @@ declare namespace Office { */ getEntities(): Entities; /** - * Gets an array of all the entities of the specified entity type found in the selected item. + * Gets an array of all the entities of the specified entity type found in the selected item's body. * * Note: This method is not supported in Outlook for iOS or Outlook for Android. * @@ -11473,7 +12852,7 @@ declare namespace Office { * @param entityType One of the EntityType enumeration values. * * @returns - * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present on the item, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. + * If the value passed in entityType is not a valid member of the EntityType enumeration, the method returns null. If no entities of the specified type are present in the item's body, the method returns an empty array. Otherwise, the type of the objects in the returned array depends on the type of entity requested in the entityType parameter. * * @remarks * @@ -11898,7 +13277,7 @@ declare namespace Office { * * - hostVersion (string): A string that represents the version of either the host application or the Exchange Server. If the mail add-in is running on the Outlook desktop client or Outlook for iOS, the hostVersion property returns the version of the host application, Outlook. In Outlook Web App, the property returns the version of the Exchange Server. An example is the string 15.0.468.0. * - * - OWAView (string): A string that represents the current view of Outlook Web App. If the host application is not Outlook Web App, then accessing this property results in undefined. Outlook Web App has three views (OneColumn - displayed when the screen is narrow, TwoColumns - displayed when the screen is wider, and ThreeColumns - displayed when the screen is wide.) that correspond to the width of the screen and the window, and the number of columns that can be displayed. + * - OWAView (MailboxEnums.OWAView or string): An enum (or string literal) that represents the current view of Outlook Web App. If the host application is not Outlook Web App, then accessing this property results in undefined. Outlook Web App has three views (OneColumn - displayed when the screen is narrow, TwoColumns - displayed when the screen is wider, and ThreeColumns - displayed when the screen is wide) that correspond to the width of the screen and the window, and the number of columns that can be displayed. * * More information is under {@link Office.Diagnostics}. * @@ -18357,7 +19736,7 @@ declare namespace Excel { * @param sourceData The Range object corresponding to the source data. * @param seriesBy Optional. Specifies the way columns or rows are used as data series on the chart. See Excel.ChartSeriesBy for details. */ - add(type: Excel.ChartType, sourceData: Range | string, seriesBy?: Excel.ChartSeriesBy): Excel.Chart; + add(type: Excel.ChartType, sourceData: Range, seriesBy?: Excel.ChartSeriesBy): Excel.Chart; /** * * Creates a new chart. @@ -18368,7 +19747,7 @@ declare namespace Excel { * @param sourceData The Range object corresponding to the source data. * @param seriesBy Optional. Specifies the way columns or rows are used as data series on the chart. See Excel.ChartSeriesBy for details. */ - add(type: "Invalid" | "ColumnClustered" | "ColumnStacked" | "ColumnStacked100" | "3DColumnClustered" | "3DColumnStacked" | "3DColumnStacked100" | "BarClustered" | "BarStacked" | "BarStacked100" | "3DBarClustered" | "3DBarStacked" | "3DBarStacked100" | "LineStacked" | "LineStacked100" | "LineMarkers" | "LineMarkersStacked" | "LineMarkersStacked100" | "PieOfPie" | "PieExploded" | "3DPieExploded" | "BarOfPie" | "XYScatterSmooth" | "XYScatterSmoothNoMarkers" | "XYScatterLines" | "XYScatterLinesNoMarkers" | "AreaStacked" | "AreaStacked100" | "3DAreaStacked" | "3DAreaStacked100" | "DoughnutExploded" | "RadarMarkers" | "RadarFilled" | "Surface" | "SurfaceWireframe" | "SurfaceTopView" | "SurfaceTopViewWireframe" | "Bubble" | "Bubble3DEffect" | "StockHLC" | "StockOHLC" | "StockVHLC" | "StockVOHLC" | "CylinderColClustered" | "CylinderColStacked" | "CylinderColStacked100" | "CylinderBarClustered" | "CylinderBarStacked" | "CylinderBarStacked100" | "CylinderCol" | "ConeColClustered" | "ConeColStacked" | "ConeColStacked100" | "ConeBarClustered" | "ConeBarStacked" | "ConeBarStacked100" | "ConeCol" | "PyramidColClustered" | "PyramidColStacked" | "PyramidColStacked100" | "PyramidBarClustered" | "PyramidBarStacked" | "PyramidBarStacked100" | "PyramidCol" | "3DColumn" | "Line" | "3DLine" | "3DPie" | "Pie" | "XYScatter" | "3DArea" | "Area" | "Doughnut" | "Radar" | "Histogram" | "Pareto" | "RegionMap", sourceData: Range | string, seriesBy?: "Auto" | "Columns" | "Rows"): Excel.Chart; + add(type: "Invalid" | "ColumnClustered" | "ColumnStacked" | "ColumnStacked100" | "3DColumnClustered" | "3DColumnStacked" | "3DColumnStacked100" | "BarClustered" | "BarStacked" | "BarStacked100" | "3DBarClustered" | "3DBarStacked" | "3DBarStacked100" | "LineStacked" | "LineStacked100" | "LineMarkers" | "LineMarkersStacked" | "LineMarkersStacked100" | "PieOfPie" | "PieExploded" | "3DPieExploded" | "BarOfPie" | "XYScatterSmooth" | "XYScatterSmoothNoMarkers" | "XYScatterLines" | "XYScatterLinesNoMarkers" | "AreaStacked" | "AreaStacked100" | "3DAreaStacked" | "3DAreaStacked100" | "DoughnutExploded" | "RadarMarkers" | "RadarFilled" | "Surface" | "SurfaceWireframe" | "SurfaceTopView" | "SurfaceTopViewWireframe" | "Bubble" | "Bubble3DEffect" | "StockHLC" | "StockOHLC" | "StockVHLC" | "StockVOHLC" | "CylinderColClustered" | "CylinderColStacked" | "CylinderColStacked100" | "CylinderBarClustered" | "CylinderBarStacked" | "CylinderBarStacked100" | "CylinderCol" | "ConeColClustered" | "ConeColStacked" | "ConeColStacked100" | "ConeBarClustered" | "ConeBarStacked" | "ConeBarStacked100" | "ConeCol" | "PyramidColClustered" | "PyramidColStacked" | "PyramidColStacked100" | "PyramidBarClustered" | "PyramidBarStacked" | "PyramidBarStacked100" | "PyramidCol" | "3DColumn" | "Line" | "3DLine" | "3DPie" | "Pie" | "XYScatter" | "3DArea" | "Area" | "Doughnut" | "Radar" | "Histogram" | "Pareto" | "RegionMap", sourceData: Range, seriesBy?: "Auto" | "Columns" | "Rows"): Excel.Chart; /** * * Returns the number of charts in the worksheet. @@ -18590,7 +19969,7 @@ declare namespace Excel { * @param sourceData The range corresponding to the source data. * @param seriesBy Specifies the way columns or rows are used as data series on the chart. Can be one of the following: Auto (default), Rows, and Columns. See Excel.ChartSeriesBy for details. */ - setData(sourceData: Range | string, seriesBy?: Excel.ChartSeriesBy): void; + setData(sourceData: Range, seriesBy?: Excel.ChartSeriesBy): void; /** * * Resets the source data for the chart. @@ -18600,7 +19979,7 @@ declare namespace Excel { * @param sourceData The range corresponding to the source data. * @param seriesBy Specifies the way columns or rows are used as data series on the chart. Can be one of the following: Auto (default), Rows, and Columns. See Excel.ChartSeriesBy for details. */ - setData(sourceData: Range | string, seriesBy?: "Auto" | "Columns" | "Rows"): void; + setData(sourceData: Range, seriesBy?: "Auto" | "Columns" | "Rows"): void; /** * * Positions the chart relative to cells on the worksheet. @@ -52959,7 +54338,7 @@ declare namespace OneNote { } /** * - * Represents data obtained by OCR (optical character recognition) of an image + * Represents data obtained by OCR (optical character recognition) of an image. * * [Api set: OneNoteApi 1.1] */ @@ -52981,7 +54360,7 @@ declare namespace OneNote { } /** * - * Weak reference to an ink stroke object and its content parent + * Weak reference to an ink stroke object and its content parent. * * [Api set: OneNoteApi 1.1] */ diff --git a/types/openlayers/index.d.ts b/types/openlayers/index.d.ts index a6122c8477..37cac7e65d 100644 --- a/types/openlayers/index.d.ts +++ b/types/openlayers/index.d.ts @@ -10135,6 +10135,13 @@ export namespace style { */ getLineDash(): number[]; + /** + * Get the line dash offset style for the stroke. + * @return Line dash offset + * @api + */ + getLineDashOffset(): number; + /** * Get the line join type for the stroke. * @return Line join. @@ -10186,6 +10193,14 @@ export namespace style { */ setLineDash(lineDash: number[]): void; + /** + * Set the line dash offset. + * + * @param lineDashOffset Line dash offset. + * @api + */ + setLineDashOffset(lineDashOffset: number): void; + /** * Set the line join. * @@ -12347,6 +12362,7 @@ export namespace olx { lineCap?: string; lineJoin?: string; lineDash?: number[]; + lineDashOffset?: number; miterLimit?: number; width?: number; } diff --git a/types/openlayers/openlayers-tests.ts b/types/openlayers/openlayers-tests.ts index fcf925886d..6e28ad4cd2 100644 --- a/types/openlayers/openlayers-tests.ts +++ b/types/openlayers/openlayers-tests.ts @@ -74,6 +74,7 @@ const style = new ol.style.Style(); const styleArray: ol.style.Style[] = []; const styleFunction: ol.StyleFunction = (feature, resolution) => style; let styleRegularShape: ol.style.RegularShape; +let styleStroke: ol.style.Stroke; const tilegrid = new ol.tilegrid.TileGrid({resolutions: numberArray}); const transformFn: ol.TransformFunction = (array, out, dimension) => numberArray; let units: ol.proj.Units; @@ -1111,6 +1112,35 @@ styleRegularShape = new ol.style.RegularShape({ points: 4, }); +// +// ol.style.Stroke +// + +styleStroke = new ol.style.Stroke(); +styleStroke.setColor('#FF0000'); +styleStroke.setColor('red'); +styleStroke.setColor('#CCC'); +styleStroke.setColor('rgb(255, 255, 255)'); +styleStroke.setColor('rgb(255, 255, 255, 0.7)'); +styleStroke.setLineCap('butt'); +styleStroke.setLineCap('round'); +styleStroke.setLineCap('square'); +styleStroke.setLineJoin('bevel'); +styleStroke.setLineJoin('round'); +styleStroke.setLineJoin('miter'); +styleStroke.setLineDash([10, 5]); +styleStroke.setLineDashOffset(10); +styleStroke.setMiterLimit(20); +styleStroke.setWidth(5); + +const strokeColor: ol.Color|ol.ColorLike = styleStroke.getColor(); +const strokeLineCap: string = styleStroke.getLineCap(); +const strokeLineJoin: string = styleStroke.getLineJoin(); +const strokeLineDash: number[] = styleStroke.getLineDash(); +const strokeLineDashOffset: number = styleStroke.getLineDashOffset(); +const strokeMiterLimit: number = styleStroke.getMiterLimit(); +const strokeWidth: number = styleStroke.getWidth(); + // // ol.proj // diff --git a/types/owl.carousel/index.d.ts b/types/owl.carousel/index.d.ts index b1b093ef77..9b4fbe5e89 100644 --- a/types/owl.carousel/index.d.ts +++ b/types/owl.carousel/index.d.ts @@ -61,6 +61,7 @@ declare namespace OwlCarousel { dotsContainer?: string | boolean; checkVisible?: boolean; slideTransition?: string; + autoHeight?: boolean; // CLASSES refreshClass?: string; loadingClass?: string; diff --git a/types/parse-git-config/index.d.ts b/types/parse-git-config/index.d.ts index b3302106b0..3ca55b897a 100644 --- a/types/parse-git-config/index.d.ts +++ b/types/parse-git-config/index.d.ts @@ -39,7 +39,7 @@ interface Parse { /** * Returns an object with only the properties that had ini-style keys converted to objects. */ - keys(config: Config): Config; + expandKeys(config: Config): Config; } // no-empty-interface is disabled for a better debugging experience. Empty interfaces are used to alias a type alias. @@ -49,6 +49,8 @@ interface Options extends Pick<_Options, keyof _Options> { } interface _Options { cwd: string; path: string; + include?: boolean; + expandKeys?: boolean; } type ParseCallback = ((err: Error | null, config: Config) => void); diff --git a/types/parse-git-config/parse-git-config-tests.ts b/types/parse-git-config/parse-git-config-tests.ts index c5ce43040a..a6d2a4c983 100644 --- a/types/parse-git-config/parse-git-config-tests.ts +++ b/types/parse-git-config/parse-git-config-tests.ts @@ -99,12 +99,12 @@ function test_sync() { } } -function test_keys() { +function test_expandKeys() { const config = { 'foo "bar"': { doStuff: true }, 'foo "baz"': { doStuff: true } }; - const keys = parse.keys(config); + const keys = parse.expandKeys(config); keys.foo.bar.doStuff === true; keys.foo.baz.doStuff === true; diff --git a/types/passport-saml/index.d.ts b/types/passport-saml/index.d.ts index 5e24211008..d9c86a9b23 100644 --- a/types/passport-saml/index.d.ts +++ b/types/passport-saml/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for passport-saml 0.15 // Project: https://github.com/bergie/passport-saml // Definitions by: Chris Barth +// Damian Assennato // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -62,6 +63,7 @@ export interface SamlConfig { cacheProvider?: CacheProvider; // Passport + name?: string; passReqToCallback?: boolean; // Logout diff --git a/types/passport-saml/passport-saml-tests.ts b/types/passport-saml/passport-saml-tests.ts index 45a3d18923..615c1b7320 100644 --- a/types/passport-saml/passport-saml-tests.ts +++ b/types/passport-saml/passport-saml-tests.ts @@ -5,6 +5,7 @@ import fs = require('fs'); const samlStrategy = new SamlStrategy.Strategy( { + name: 'samlCustomName', path: '/login/callback', entryPoint: 'https://openidp.feide.no/simplesaml/saml2/idp/SSOService.php', issuer: 'passport-saml', @@ -29,6 +30,6 @@ const samlStrategy = new SamlStrategy.Strategy( ); passport.use(samlStrategy); -passport.authenticate('saml', {failureRedirect: '/', failureFlash: true}); +passport.authenticate('samlCustomName', {failureRedirect: '/', failureFlash: true}); const metadata = samlStrategy.generateServiceProviderMetadata("decryptionCert"); diff --git a/types/phonegap-nfc/index.d.ts b/types/phonegap-nfc/index.d.ts index ff980eea33..abc460947d 100644 --- a/types/phonegap-nfc/index.d.ts +++ b/types/phonegap-nfc/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/chariotsolutions/phonegap-nfc // Definitions by: Michael Desigaud // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 interface Document { addEventListener(type: 'deviceready', listener: (ev: Event) => any, useCapture?: boolean): void; diff --git a/types/phonegap-nfc/phonegap-nfc-tests.ts b/types/phonegap-nfc/phonegap-nfc-tests.ts index b61009a7da..1e5a16010f 100644 --- a/types/phonegap-nfc/phonegap-nfc-tests.ts +++ b/types/phonegap-nfc/phonegap-nfc-tests.ts @@ -97,30 +97,5 @@ let eventTarget: EventTarget = { removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean) { return; } } -let ndefTagEvent = { - bubbles: false, - cancelBubble: false, - cancelable: false, - currentTarget: eventTarget, - defaultPrevented: false, - eventPhase: 2, - isTrusted: true, - returnValue: true, - srcElement: new Element(), - target: eventTarget, - timeStamp: 1394448136236, - type: "ndef", - initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean) { return; }, - preventDefault() { return; }, - stopImmediatePropagation() { return; }, - stopPropagation() { return; }, - AT_TARGET: 0, - BUBBLING_PHASE: 0, - CAPTURING_PHASE: 0, - NONE: 0, - scoped: false, - deepPath(): any { }, - tag: ndefTag -}; - -let event: NdefTagEvent = ndefTagEvent; \ No newline at end of file +let ndefTagEvent = { ...(undefined as Event), tag: ndefTag }; +let event: NdefTagEvent = ndefTagEvent; diff --git a/types/pino/index.d.ts b/types/pino/index.d.ts index 0f98e0a622..27d0f51fc6 100644 --- a/types/pino/index.d.ts +++ b/types/pino/index.d.ts @@ -19,7 +19,7 @@ export = P; * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform): P.Logger; +declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; /** * @param [options]: an options object @@ -27,7 +27,7 @@ declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream. * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform): P.Logger; +declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; declare namespace P { /** diff --git a/types/pino/pino-tests.ts b/types/pino/pino-tests.ts index 6d226a1d92..6959a6cd97 100644 --- a/types/pino/pino-tests.ts +++ b/types/pino/pino-tests.ts @@ -93,3 +93,6 @@ log.level = 'info'; pino.levels.values.error === 50; pino.levels.labels[50] === 'error'; + +const logstderr: pino.Logger = pino(process.stderr); +logstderr.error('on stderr instead of stdout'); diff --git a/types/playcanvas/engine/framework/components/animation/component.d.ts b/types/playcanvas/engine/framework/components/animation/component.d.ts index ca0547b6fe..7be1b5ea3b 100644 --- a/types/playcanvas/engine/framework/components/animation/component.d.ts +++ b/types/playcanvas/engine/framework/components/animation/component.d.ts @@ -46,6 +46,6 @@ declare namespace pc { * @param {String} name The name of the animation asset * @returns {pc.Animation} An Animation */ - getAnimation(name: string): void; + getAnimation(name: string): pc.Animation; } } diff --git a/types/pouchdb-core/index.d.ts b/types/pouchdb-core/index.d.ts index ddecfe843b..0dbf5def5b 100644 --- a/types/pouchdb-core/index.d.ts +++ b/types/pouchdb-core/index.d.ts @@ -626,7 +626,7 @@ declare namespace PouchDB { }; } - interface Database { + interface Database extends EventEmitter { /** The name passed to the PouchDB constructor and unique identifier of the database. */ name: string; diff --git a/types/pouchdb-core/pouchdb-core-tests.ts b/types/pouchdb-core/pouchdb-core-tests.ts index fe79997461..f8accd1c3a 100644 --- a/types/pouchdb-core/pouchdb-core-tests.ts +++ b/types/pouchdb-core/pouchdb-core-tests.ts @@ -114,6 +114,8 @@ function testBasics() { const db = new PouchDB(); + db.on("closed", () => {}); + db.post(model).then((result) => { isString(result.id); }); diff --git a/types/pretty-ms/index.d.ts b/types/pretty-ms/index.d.ts index e23b26826b..b1e151cd65 100644 --- a/types/pretty-ms/index.d.ts +++ b/types/pretty-ms/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for pretty-ms 3.0 +// Type definitions for pretty-ms 3.2 // Project: https://github.com/sindresorhus/pretty-ms#readme // Definitions by: BendingBender +// ocboogie // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = prettyMs; @@ -11,6 +12,7 @@ declare namespace prettyMs { interface PrettyMsOptions { secDecimalDigits?: number; msDecimalDigits?: number; + keepDecimalsOnWholeSeconds?: boolean; compact?: boolean; verbose?: boolean; } diff --git a/types/pretty-ms/pretty-ms-tests.ts b/types/pretty-ms/pretty-ms-tests.ts index 14bff61304..ae5e8120b2 100644 --- a/types/pretty-ms/pretty-ms-tests.ts +++ b/types/pretty-ms/pretty-ms-tests.ts @@ -4,6 +4,7 @@ let str: string; str = prettyMs(133); str = prettyMs(1337, {compact: true}); str = prettyMs(1335669000, {verbose: true}); +str = prettyMs(1335669000, {keepDecimalsOnWholeSeconds: true}); str = prettyMs(1335669000, {secDecimalDigits: 1}); str = prettyMs(1335669000, {msDecimalDigits: 2}); str = prettyMs(new Date(2014, 0, 1, 10, 40).getTime() - new Date(2014, 0, 1, 10, 5).getTime()); diff --git a/types/proton-native/index.d.ts b/types/proton-native/index.d.ts index 62aa0dce25..e191c00698 100644 --- a/types/proton-native/index.d.ts +++ b/types/proton-native/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/kusti8/proton-native // Definitions by: Nguyen Xuan Khanh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/ptomasroos__react-native-multi-slider/index.d.ts b/types/ptomasroos__react-native-multi-slider/index.d.ts index 572307b219..67c9106670 100644 --- a/types/ptomasroos__react-native-multi-slider/index.d.ts +++ b/types/ptomasroos__react-native-multi-slider/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ptomasroos/react-native-multi-slider#readme // Definitions by: Edward Sammut Alessi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; import { ViewStyle } from "react-native"; diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index 4859b86fc1..a5e85f802e 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for puppeteer 1.5 +// Type definitions for puppeteer 1.6 // Project: https://github.com/GoogleChrome/puppeteer#readme // Definitions by: Marvin Hagemeister // Christopher Deutsch @@ -727,6 +727,10 @@ export interface ElementHandle extends JSHandle, Ev * If the element is detached from DOM, the method throws an error. */ hover(): Promise; + /** + * Resolves to true if the element is visible in the current viewport. + */ + isIntersectingViewport(): Promise; /** * Focuses the element, and then uses keyboard.down and keyboard.up. * @param key Name of key to press, such as ArrowLeft. See USKeyboardLayout for a list of all key names. @@ -860,6 +864,8 @@ export type ErrorCode = | "aborted" | "accessdenied" | "addressunreachable" + | "blockedbyclient" + | "blockedbyresponse" | "connectionaborted" | "connectionclosed" | "connectionfailed" @@ -1107,16 +1113,6 @@ export interface FrameBase extends Evalable { ...args: any[] ): Promise; - waitForRequest( - urlOrPredicate: string | ((req: Request) => boolean), - options?: { timeout?: number } - ): Promise; - - waitForResponse( - urlOrPredicate: string | ((res: Response) => boolean), - options?: { timeout?: number } - ): Promise; - waitForSelector( selector: string, options?: { visible?: boolean; hidden?: boolean; timeout?: number } @@ -1447,6 +1443,16 @@ export interface Page extends EventEmitter, FrameBase { */ waitForNavigation(options?: NavigationOptions): Promise; + waitForRequest( + urlOrPredicate: string | ((req: Request) => boolean), + options?: { timeout?: number } + ): Promise; + + waitForResponse( + urlOrPredicate: string | ((res: Response) => boolean), + options?: { timeout?: number } + ): Promise; + /** This method returns all of the dedicated WebWorkers associated with the page. */ workers(): Worker[]; } @@ -1705,6 +1711,8 @@ export interface Coverage { export interface StartCoverageOptions { /** Whether to reset coverage on every navigation. Defaults to `true`. */ resetOnNavigation?: boolean; + /** Whether anonymous scripts generated by the page should be reported. Defaults to `false`. */ + reportAnonymousScripts?: boolean; } export interface CoverageEntry { diff --git a/types/qhistory/index.d.ts b/types/qhistory/index.d.ts index 301f6b4391..84bd4e6d83 100644 --- a/types/qhistory/index.d.ts +++ b/types/qhistory/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/pshrmn/qhistory#readme // Definitions by: Diogo Franco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 export as namespace qhistory; diff --git a/types/qrcode.react/index.d.ts b/types/qrcode.react/index.d.ts index d38d8ce89b..01e8ef18af 100644 --- a/types/qrcode.react/index.d.ts +++ b/types/qrcode.react/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/zpao/qrcode.react // Definitions by: Mleko // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/quill/index.d.ts b/types/quill/index.d.ts index afbdfa9222..0eda9a4eff 100644 --- a/types/quill/index.d.ts +++ b/types/quill/index.d.ts @@ -4,6 +4,7 @@ // Guillaume // James Garbutt // Aniello Falcone +// Mohammad Hossein Amri // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import { Blot } from 'parchment/dist/src/blot/abstract/blot'; @@ -42,6 +43,7 @@ export interface KeyboardStatic { } export interface ClipboardStatic { + convert(html?: string): DeltaStatic; addMatcher(selectorOrNodeType: string|number, callback: (node: any, delta: DeltaStatic) => DeltaStatic): void; dangerouslyPasteHTML(html: string, source?: Sources): void; dangerouslyPasteHTML(index: number, html: string, source?: Sources): void; diff --git a/types/quill/quill-tests.ts b/types/quill/quill-tests.ts index d0bc3a2189..073e68f115 100644 --- a/types/quill/quill-tests.ts +++ b/types/quill/quill-tests.ts @@ -129,7 +129,7 @@ function test_updateContents() { })); } -function test_setContents() { +function test_setDeltaContents() { const quillEditor = new Quill('#editor'); quillEditor.setContents(new Delta({ ops: [ { insert: 'Hello ' }, @@ -138,11 +138,19 @@ function test_setContents() { ]})); } -function test_setText() { +function test_setTextContents() { const quillEditor = new Quill('#editor'); quillEditor.setText('Hello\n'); } +function test_setHtmlContents() { + const quillEditor = new Quill('#editor'); + const html = "this is a bold text"; + const delta = quillEditor.clipboard.convert(html); + quillEditor.setContents(delta); + quillEditor.clipboard.convert(); +} + function test_getSelection() { const quillEditor = new Quill('#editor'); const range = quillEditor.getSelection(); diff --git a/types/qunit/index.d.ts b/types/qunit/index.d.ts index 2b7eb586ff..c5e677d187 100644 --- a/types/qunit/index.d.ts +++ b/types/qunit/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for QUnit v2.5.0 // Project: http://qunitjs.com/ // Definitions by: James Bracy +// Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Assert { @@ -234,6 +235,32 @@ interface Assert { */ throws(block: () => void, expected?: any, message?: any): void; raises(block: () => void, expected?: any, message?: any): void; + + /** + * A marker for progress in a given test. + * + * The `step()` assertion registers a passing assertion with a provided message. This makes + * it easy to check that specific portions of code are being executed, especially in + * asynchronous test cases and when used with `verifySteps()`. + * + * Together with the `verifySteps()` method, `step()` assertions give you an easy way + * to verify both the count and order of code execution. + * + * @param message Message to display for the step + */ + step(message: string): void; + + /** + * A helper assertion to verify the order and number of steps in a test. + * + * The assert.verifySteps() assertion compares a given array of string values (representing steps) + * with the order and values of previous step() calls. This assertion is helpful for verifying + * the order and count of portions of code paths, especially asynchronous ones. + * + * @param steps Array of strings representing steps to verify + * @param message A short description of the assertion + */ + verifySteps(steps: string[], message?: string): void; } @@ -313,6 +340,38 @@ interface NestedHooks { } +declare namespace QUnit { + interface BeginDetails { totalTests: number } + interface DoneDetails { failed: number, passed: number, total: number, runtime: number } + interface LogDetails { + result: boolean, + actual: any; + expected: any; + message: string; + source: string; + module: string; + name: string; + runtime: number; + } + interface ModuleDoneDetails { + name: string; + failed: number; + passed: number; + total: number; + runtime: number; + } + interface ModuleStartDetails { name: string } + interface TestDoneDetails { + name: string; + module: string; + failed: number; + passed: number; + total: number; + runtime: number; + } + interface TestStartDetails { name: string; module: string; } +} + interface QUnit { /** @@ -333,7 +392,7 @@ interface QUnit { * * @callback callback Callback to execute. */ - begin(callback: (details: { totalTests: number }) => void): void; + begin(callback: (details: QUnit.BeginDetails) => void): void; /** * Configuration for QUnit @@ -348,7 +407,7 @@ interface QUnit { * * @param callback Callback to execute */ - done(callback: (details: { failed: number, passed: number, total: number, runtime: number }) => void): void; + done(callback: (details: QUnit.DoneDetails) => void): void; /** * Advanced and extensible data dumping for JavaScript. @@ -392,16 +451,7 @@ interface QUnit { * * @param callback Callback to execute */ - log(callback: (details: { - result: boolean, - actual: any; - expected: any; - message: string; - source: string; - module: string; - name: string; - runtime: number; - }) => void): void; + log(callback: (details: QUnit.LogDetails) => void): void; /** * Group related tests under a single label. @@ -449,20 +499,14 @@ interface QUnit { * * @param callback Callback to execute */ - moduleDone(callback: (details: { - name: string; - failed: number; - passed: number; - total: number; - runtime: number; - }) => void): void; + moduleDone(callback: (details: QUnit.ModuleDoneDetails) => void): void; /** * Register a callback to fire whenever a module begins. * * @param callback Callback to execute */ - moduleStart(callback: (details: { name: string }) => void): void; + moduleStart(callback: (details: QUnit.ModuleStartDetails) => void): void; /** * Adds a test to exclusively run, preventing all other tests from running. @@ -578,7 +622,7 @@ interface QUnit { * * @param callback Callback to execute */ - testStart(callback: (details: { name: string; module: string;}) => void): void; + testStart(callback: (details: QUnit.TestStartDetails) => void): void; /** * Adds a test which expects at least one failing assertion during its run. diff --git a/types/qunit/qunit-tests.ts b/types/qunit/qunit-tests.ts index e726113604..ae519cd0bc 100644 --- a/types/qunit/qunit-tests.ts +++ b/types/qunit/qunit-tests.ts @@ -214,13 +214,33 @@ QUnit.log(function( details ) { console.log( output ); }); -QUnit.moduleDone(function( details ) { - console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total ); +QUnit.log(function( details: QUnit.LogDetails ) { + let x: { actual: number; expected: number; message: string; module: string; name: string; result: boolean; runtime: number; source: string } = details; + x = details; }); -QUnit.moduleStart(function( details ) { +QUnit.begin(function( details: QUnit.BeginDetails ) { + console.log( "Total tests running: ", details.totalTests); +}); + +QUnit.done(function( details: QUnit.DoneDetails ) { + console.log( "Finished. Failed/total: ", details.failed, details.total, details.passed, details.runtime ); +}); + +QUnit.moduleDone(function( details: QUnit.ModuleDoneDetails ) { + console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total, details.passed, details.runtime ); +}); + +QUnit.moduleStart(function( details: QUnit.ModuleStartDetails ) { console.log( "Now running: ", details.name ); }); +QUnit.testDone(function( details: QUnit.TestDoneDetails ) { + console.log( "Finished running: ", details.name, "Failed/total: ", details.failed, details.total, details.passed, details.runtime); +}); + +QUnit.testStart(function( details: QUnit.TestStartDetails ) { + console.log( "Now running: ", details.name, ' from module ', details.module ); +}); let Robot: any = () => {}; @@ -562,3 +582,11 @@ equivResult = QUnit.equiv({}, {}); equivResult = QUnit.equiv(1, 2); equivResult = QUnit.equiv('foo', 'bar'); equivResult = QUnit.equiv(['foo'], ['bar']); + + +QUnit.test('steps', assert => { + assert.step('one'); + assert.step('two'); + assert.step('three'); + assert.verifySteps(['one', 'two', 'three'], 'Counting to three correctly'); +}); diff --git a/types/radium/index.d.ts b/types/radium/index.d.ts index ce5ae3776a..d8d56caf26 100644 --- a/types/radium/index.d.ts +++ b/types/radium/index.d.ts @@ -1,8 +1,8 @@ // Type definitions for radium 0.24.0 // Project: https://github.com/formidablelabs/radium -// Definitions by: Alex Gorbatchev , Philipp Holzer , Alexey Svetliakov , Mikael Hermansson +// Definitions by: Alex Gorbatchev , Philipp Holzer , Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index ad57afda3f..66d3707d2b 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -9,7 +9,6 @@ // Vítor Castro // Jordan Quagliatini // Simon Højberg -// Charles-Philippe Clermont // Samson Keung // Angelo Ocana // Rayner Pupo diff --git a/types/rc-select/index.d.ts b/types/rc-select/index.d.ts index 5fdae43949..b78fc03837 100644 --- a/types/rc-select/index.d.ts +++ b/types/rc-select/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/react-component/select // Definitions by: Denis Tirilis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/rc-slider/index.d.ts b/types/rc-slider/index.d.ts index 139f4e2ef0..707f5425c5 100644 --- a/types/rc-slider/index.d.ts +++ b/types/rc-slider/index.d.ts @@ -5,9 +5,10 @@ // Austin Turner // Jacob Froman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; +import { RCTooltip } from 'rc-tooltip'; export interface Marks { [number: number]: @@ -178,9 +179,14 @@ export interface HandleProps extends CommonApiProps { offset: number; } +export interface WithTooltipProps { + tipFormatter?: (value: number) => React.ReactNode; + tipProps?: Partial; +} + export default class Slider extends React.Component { } export class Range extends React.Component { } export class Handle extends React.Component { } -export function createSliderWithTooltip(slider: typeof Slider): new() => Slider; -export function createSliderWithTooltip(range: typeof Range): new() => Range; +export function createSliderWithTooltip(slider: typeof Slider): new() => React.Component; +export function createSliderWithTooltip(range: typeof Range): new() => React.Component; diff --git a/types/rc-slider/rc-slider-tests.tsx b/types/rc-slider/rc-slider-tests.tsx index e08a674dca..2de87bc4e2 100644 --- a/types/rc-slider/rc-slider-tests.tsx +++ b/types/rc-slider/rc-slider-tests.tsx @@ -62,3 +62,8 @@ ReactDOM.render( , document.querySelector('.app') ); + +ReactDOM.render( + , + document.querySelector('.app') +); diff --git a/types/rc-tooltip/index.d.ts b/types/rc-tooltip/index.d.ts index 9222d9f149..e752404f21 100644 --- a/types/rc-tooltip/index.d.ts +++ b/types/rc-tooltip/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: rhysd // ahstro // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/rc-tree/index.d.ts b/types/rc-tree/index.d.ts index 206f8abeaa..e2ac50d20d 100644 --- a/types/rc-tree/index.d.ts +++ b/types/rc-tree/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/react-component/tree // Definitions by: John Reilly , Methuselah96 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.7 +// TypeScript Version: 2.8 import { Component } from "react"; diff --git a/types/rdflib/index.d.ts b/types/rdflib/index.d.ts new file mode 100644 index 0000000000..f6e1c82ba7 --- /dev/null +++ b/types/rdflib/index.d.ts @@ -0,0 +1,1169 @@ +// Type definitions for rdflib 0.17 +// Project: https://github.com/linkeddata/rdflib.js +// Definitions by: Cénotélie +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Acknowledgements: This work has been financed by Logilab SA, FRANCE, logilab.fr + +/** + * Class orders + */ +export const ClassOrder: { + [id: string]: number; +}; +/** + * A type for values that serves as inputs + */ +export type ValueType = Node | Date | string | number | boolean | undefined; +/** + * The superclass of all RDF Statement objects, that is NamedNode, Literal, BlankNode, etc. + */ +export class Node { + /** + * The type of node + */ + termType: string; + /** + * Whether this node is a variable + */ + isVar: boolean; + /** + * The class order for this node + */ + classOrder: number; + /** + * The nod's value + */ + value: string; + /** + * Gets the substituted node for this one, according to the specified bindings + * @param bindings Bindings of identifiers to nodes + */ + substitute(bindings: { [id: string]: Node }): Node; + /** + * Compares this node with another + * @param term The other node + */ + compareTerm(term: Node): number; + /** + * Gets whether the two nodes are equal + * @param other The other node + */ + equals(other: Node): boolean; + /** + * Gets a hash for this node + */ + hashString(): string; + /** + * Gets whether this node is the same as the other one + * @param other Another node + */ + sameTerm(other: Node): boolean; + /** + * Gets the canonical string representation of this node + */ + toCanonical(): string; + /** + * Gets the n-triples string representation of this node + */ + toNT(): string; + /** + * Gets the string representation of this node + */ + toString(): string; + /** + * Gets a node for the specifed input + * @param value An input value + */ + static fromValue(value: ValueType): Node | ValueType; + /** + * Gets the javascript object equivalent to a node + * @param term The RDF node + */ + static toJS(term: Node): any; +} +/** + * An empty node + */ +export class Empty extends Node { + constructor(); + static termType: string; +} +/** + * A collection of other RDF nodes + */ +export class Collection extends Node { + /** + * The identifier for this collection + */ + id: string; + /** + * The nodes in this collection + */ + elements: Node[]; + /** + * Whether this collection is closed + */ + closed: boolean; + /** + * Initializes this collection + * @param initial The initial elements + */ + constructor(initial: ReadonlyArray); + /** + * Appends an element to this collection + * @param element The new element + */ + append(element: Node): number; + /** + * Closes this collection + */ + close(): boolean; + /** + * Removes the first element from the collection (and return it) + */ + shift(): Node; + /** + * Preprends the specified element to the colelction's front + * @param element The element to preprend + */ + unshift(element: Node): number; + static termType: string; +} +/** + * An RDF blank node + */ +export class BlankNode extends Node { + /** + * The identifier for the blank node + */ + id: string; + /** + * Whether this is a blank node + */ + isBlank: boolean; + /** + * Initializes this node + * @param id The identifier for the blank node + */ + constructor(id: string); + /** + * Gets a copy of this blank node in the specified formula + * @param formula The formula + */ + copy(formula: Formula): BlankNode; + /** + * The next unique identifier for blank nodes + */ + static nextId: number; + static termType: string; + static NTAnonymousNodePrefix: string; +} +/** + * A named (IRI) RDF node + */ +export class NamedNode extends Node { + /** + * The URI for this node + */ + uri: string; + /** + * Initializes this node + * @param iri The IRI for this node + */ + constructor(iri: NamedNode | string); + /** + * Returns an RDF node for the containing directory, ending in slash. + */ + dir(): NamedNode; + /** + * Returns an named node for the whole web site, ending in slash. + * Contrast with the "origin" which does NOT have a trailing slash + */ + site(): NamedNode; + /** + * Gets the named node for the document + */ + doc(): NamedNode; + static termType: string; + /** + * Gets a named node from the specified input value + * @param value An input value + */ + static fromValue(value: ValueType): NamedNode | ValueType; +} +/** + * A RDF literal node + */ +export class Literal extends Node { + /** + * The language for the literal + */ + lang: string; + /** + * The language for the literal + */ + language: string; + /** + * The literal's datatype as a named node + */ + datatype: NamedNode; + /** + * Initializes this literal + * @param value The literal's lexical value + * @param language The language for the literal + * @param datatype The literal's datatype as a named node + */ + constructor(value: string, language: string, datatype: NamedNode); + /** + * Gets a copy of this literal + */ + copy(): Literal; + static termType: string; + /** + * Builds a literal node from a boolean value + * @param value The value + */ + static fromBoolean(value: boolean): Literal; + /** + * Builds a literal node from a date value + * @param value The value + */ + static fromDate(value: Date): Literal; + /** + * Builds a literal node from a number value + * @param value The value + */ + static fromNumber(value: number): Literal; + /** + * Builds a literal node from an input value + * @param value The input value + */ + static fromValue(value: ValueType): Literal | ValueType; +} +/** + * Variables are placeholders used in patterns to be matched. + * In cwm they are symbols which are the formula's list of quantified variables. + * In sparql they are not visibly URIs. Here we compromise, by having + * a common special base URI for variables. Their names are uris, + * but the ? notation has an implicit base uri of 'varid:' + */ +export class Variable extends Node { + /** + * The base string for a variable's name + */ + base: string; + /** + * The unique identifier of this variable + */ + uri: string; + /** + * Initializes this variable + * @param name The variable's name + */ + constructor(name: string); + static termType: string; +} +/** + * The RDF default graph + */ +export class DefaultGraph extends Node { + /** + * Initializes this graph + */ + constructor(); +} +export namespace uri { + /** + * Gets the document part of an URI + * @param uri The URI + */ + function docpart(uri: string): string; + /** + * Gets the document part of an URI as a named node + * @param x The URI + */ + function document(x: string): NamedNode; + /** + * Gets the hostname in an URI + * @param u The URI + */ + function hostpart(u: string): string; + /** + * Joins an URI with a base + * @param given The relative part + * @param base The base URI + */ + function join(given: string, base: string): string; + /** + * Gets the protocol part of an URI + * @param uri The URI + */ + function protocol(uri: string): string; + /** + * Gets a relative uri + * @param base The base URI + * @param uri The absolute URI + */ + function refTo(base: string, uri: string): string; +} +export namespace log { + /** + * Logs a debug event + * @param x The event + */ + function debug(x: any): void; + /** + * Logs a warning event + * @param x The event + */ + function warn(x: any): void; + /** + * Logs an information event + * @param x The event + */ + function info(x: any): void; + /** + * Logs an error event + * @param x The event + */ + function error(x: any): void; + /** + * Logs a success event + * @param x The event + */ + function success(x: any): void; + /** + * Logs a message event + * @param x The event + */ + function msg(x: any): void; +} +/** + * An RDF statement (subject, predicate, object) + */ +export class Statement { + /** + * The statement's subject + */ + subject: Node; + /** + * The statement's predicate + */ + predicate: Node; + /** + * The statement's object + */ + object: Node; + /** + * The origin of this statement + */ + why: ValueType; + /** + * The graph the contains this statement + */ + graph: ValueType; + /** + * Initializes this statement + * @param subject The statement's subject + * @param predicate The statement's predicate + * @param object The statement's object + * @param graph The graph the contains this statement + */ + constructor( + subject: ValueType, + predicate: ValueType, + object: ValueType, + graph: ValueType + ); + /** + * Gets whether two statements are the same + * @param other The other statement + */ + equals(other: Statement): boolean; + /** + * Gets this statement with the bindings substituted + * @param bindings The bindings + */ + substitute(bindings: { [id: string]: Node }): Statement; + /** + * Gets the canonical string representation of this statement + */ + toCanonical(): string; + /** + * Gets the n-triples string representation of this statement + */ + toNT(): string; + /** + * Gets the string representation of this statement + */ + toString(): string; +} +export namespace convert { + /** + * Converts an n3 string to JSON + * @param n3String The n3 string + * @param jsonCallback Callback when the operation terminated + */ + function convertToJson( + n3String: string, + jsonCallback: (err: string, jsonString: string) => void + ): void; + /** + * Converts an n3 string to n-quads + * @param n3String The n3 string + * @param nquadCallback Callback when the operation terminated + */ + function convertToNQuads( + n3String: string, + nquadCallback: (err: string, nquadString: string) => void + ): void; +} +/** + * A formula, or store of RDF statements + */ +export class Formula extends Node { + /** + * The stored statements + */ + statements: Statement[]; + /** + * Initializes this formula + * @param statements The initial statements in this formulat + * @param constraints The additional constraints + * @param initBindings The initial bindings + * @param optional + */ + constructor( + statements: ReadonlyArray, + constraints: ReadonlyArray, + initBindings: { + [id: string]: Node; + }, + optional: ReadonlyArray + ); + /** + * Adds a statement to this formula + * @param s The subject + * @param p The predicate + * @param o The object + * @param g The graph that contains the statement + */ + add(s: ValueType, p: ValueType, o: ValueType, g: ValueType): number; + /** + * Adds a statement to this formula + * @param st The statement to add + */ + addStatement(st: Statement): number; + /** + * Gets a node that matches the specified pattern + * @param s The subject + * @param p The predicate + * @param o The object + * @param g The graph that contains the statement + */ + any(s: ValueType, p: ValueType, o: ValueType, g: ValueType): Node; + /** + * Gets a blank node + * @param id The node's identifier + */ + bnode(id: string): BlankNode; + /** + * Finds the types in the list which have no *stored* subtypes + * These are a set of classes which provide by themselves complete + * information -- the other classes are redundant for those who + * know the class DAG. + * @param types A map of the types + */ + bottomTypeURIs(types: { + [id: string]: string | NamedNode; + }): { + [id: string]: string | NamedNode; + }; + /** + * Gets a new collection + */ + collection(): Collection; + /** + * Gets each node that matches the specified pattern + * @param s The subject + * @param p The predicate + * @param o The object + * @param g The graph that contains the statement + */ + each(s: ValueType, p: ValueType, o: ValueType, g: ValueType): Node[]; + /** + * Gets whether this formula is equals to the other one + * @param other The other formula + */ + equals(other: Formula): boolean; + /** + * For thisClass or any subclass, anything which has it is its type + * or is the object of something which has the type as its range, or subject + * of something which has the type as its domain + * We don't bother doing subproperty (yet?)as it doesn't seeem to be used + * much. + * Get all the Classes of which we can RDFS-infer the subject is a member + * @param thisClass A named node + */ + findMembersNT( + thisClass: Node + ): { + [uri: string]: Statement; + }; + /** + * For thisClass or any subclass, anything which has it is its type + * or is the object of something which has the type as its range, or subject + * of something which has the type as its domain + * We don't bother doing subproperty (yet?)as it doesn't seeem to be used + * much. + * Get all the Classes of which we can RDFS-infer the subject is a member + * @param subject A named node + */ + findMemberURIs( + subject: Node + ): { + [uri: string]: Statement; + }; + /** + * Get all the Classes of which we can RDFS-infer the subject is a superclass + * Returns a hash table where key is NT of type and value is statement why we + * think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + * @param subject A subject node + */ + findSubClassesNT( + subject: Node + ): { + [uri: string]: boolean; + }; + /** + * Get all the Classes of which we can RDFS-infer the subject is a subclass + * Returns a hash table where key is NT of type and value is statement why we + * think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + * @param subject A subject node + */ + findSuperClassesNT( + subject: Node + ): { + [uri: string]: boolean; + }; + /** + * Get all the Classes of which we can RDFS-infer the subject is a member + * todo: This will loop is there is a class subclass loop (Sublass loops are + * not illegal) + * Returns a hash table where key is NT of type and value is statement why we + * think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + * @param subject A subject node + */ + findTypesNT( + subject: Node + ): { + [uri: string]: boolean; + }; + /** + * Get all the Classes of which we can RDFS-infer the subject is a member + * todo: This will loop is there is a class subclass loop (Sublass loops are + * not illegal) + * Returns a hash table where key is NT of type and value is statement why we + * think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + * @param subject A subject node + */ + findTypeURIs( + subject: Node + ): { + [uri: string]: boolean; + }; + /** + * Trace the statements which connect directly, or through bnodes + * Returns an array of statements + * doc param may be null to search all documents in store + * @param subject A subject node + * @param doc A document (the graph that contains statements) + * @param excludePredicateURIs The predicate URIs to exclude + */ + connectedStatements( + subject: Node, + doc: ValueType, + excludePredicateURIs: ReadonlyArray + ): Statement[]; + /** + * Creates a new empty formula + */ + formula(): Formula; + /** + * Creates a new empty indexed formulat + * @param features The list of features + */ + formula(features: ReadonlyArray): IndexedFormula; + /** + * Transforms an NTriples string format into a Node. + * The bnode bit should not be used on program-external values; designed + * for internal work such as storing a bnode id in an HTML attribute. + * This will only parse the strings generated by the vaious toNT() methods. + * @param str A string representation + */ + fromNT(str: string): Node; + /** + * Gets whether this formula holds the specified statement + * @param s A subject + * @param p A predicate + * @param o An object + * @param g A containing graph + */ + holds(s: ValueType, p: ValueType, o: ValueType, g: ValueType): boolean; + /** + * Gets whether this formula holds the specified statement + * @param s A statement + */ + holds(s: Statement | ReadonlyArray): boolean; + /** + * Gets whether this formula holds the specified statement + * @param st A statement + */ + holdsStatement(st: Statement): boolean; + /** + * Gets a collection from a list of values + * @param values The values + */ + list(values: Iterable): Collection; + /** + * Gets a literal node + * @param val The literal's lexical value + * @param lang The language + * @param dt The datatype as a named node + */ + literal(val: string, lang: string, dt: NamedNode): Literal; + /** + * Transform a collection of NTriple URIs into their URI strings + * @param t some iterable colletion of NTriple URI strings + * @return a collection of the URIs as strings + */ + NTtoURI(t: { + [uri: string]: any; + }): { + [uri: string]: any; + }; + /** + * Serializes this formula + * @param base The base string + * @param contentType The content type of the syntax to use + * @param provenance The provenance URI + */ + serialize(base: string, contentType: string, provenance: string): string; + /** + * Gets a new formula with the substituting bindings applied + * @param bindings The bindings to substitute + */ + substitute(bindings: { [id: string]: Node }): Formula; + /** + * Gets an named node for an URI + * @param uri The URI + */ + sym(uri: string | NamedNode): NamedNode; + /** + * Gets the node matching the specified pattern + * @param s The subject + * @param p The predicate + * @param o The object + * @param g The graph that contains the statement + */ + the(s: ValueType, p: ValueType, o: ValueType, g: ValueType): Node; + /** + * RDFS Inference + * These are hand-written implementations of a backward-chaining reasoner + * over the RDFS axioms. + * @param seeds A hash of NTs of classes to start with + * @param predicate The property to trace though + * @param inverse Trace inverse direction + */ + transitiveClosure( + seeds: { + [uri: string]: boolean; + }, + predicate: Node, + inverse: Node + ): { + [uri: string]: boolean; + }; + /** + * Finds the types in the list which have no *stored* supertypes + * We exclude the universal class, owl:Things and rdf:Resource, as it is + * information-free. + * @param types The types + */ + topTypeURIs(types: { + [id: string]: string | NamedNode; + }): { + [id: string]: string | NamedNode; + }; + /** + * Gets the number of statements in this formulat that matches the specified pattern + * @param s The subject + * @param p The predicate + * @param o The object + * @param g The graph that contains the statement + */ + whether(s: ValueType, p: ValueType, o: ValueType, g: ValueType): number; + /** + * Serializes this formulat to a string + */ + toString(): string; + /** + * Gets a namespace for the specified namespace's URI + * @param nsuri The URI for the namespace + */ + ns(nsuri: string): (ln: string) => NamedNode; + /** + * Gets a new variable + * @param name The variable's name + */ + variable(name: string): Variable; + static termType: string; +} +/** + * A formula (set of triples) which indexes by predicate, subject and object. + * It "smushes" (merges into a single node) things which are identical + * according to owl:sameAs or an owl:InverseFunctionalProperty + * or an owl:FunctionalProperty + */ +export class IndexedFormula extends Formula { + /** + * The number of statements in this formula + */ + length: number; + /** + * Creates a new formula + * @param features The list of features to support + */ + constructor(features: ReadonlyArray); + /** + * Gets the URI of the default graph + */ + static defaultGraphURI(): string; + /** + * Gets the statements matching the specified pattern + * @param subj The subject + * @param pred The predicate + * @param obj The object + * @param why The graph that contains the statement + * @param justOne Whether to only get one statement + */ + statementsMatching( + subj: Node, + pred: Node, + obj: Node, + why: Node, + justOne: boolean + ): Statement[]; + /** + * Adds all the statements to this formula + * @param statements A collection of statements + */ + addAll(statements: Iterable): void; + /** + * Gets the value of a node that matches the specified pattern + * @param s The subject + * @param p The predicate + * @param o The object + * @param g The graph that contains the statement + */ + anyValue(s: ValueType, p: ValueType, o: ValueType, g: ValueType): string; + /** + * Returns the symbol with canonical URI as smushed + * @param term A RDF node + */ + canon(term: Node): Node; + /** + * Checks this formula for consistency + */ + check(): void; + /** + * Checks a list of statements for consistency + * @param sts The list of statements to check + * @param from An index with the array ['subject', 'predicate', 'object', 'why'] + */ + checkStatementList(sts: ReadonlyArray, from: number): boolean; + /** + * Closes this formula (and return it) + */ + close(): IndexedFormula; + /** + * Simplify graph in store when we realize two identifiers are equivalent + * We replace the bigger with the smaller. + * @param u1 The first node + * @param u2 The second node + */ + equate(u1: Node, u2: Node): boolean; + /** + * eturns any quads matching the given arguments. + * Standard RDFJS Taskforce method for Source objects, implemented as an + * alias to `statementsMatching()` + * @param subject The subject + * @param predicate The predicate + * @param object The object + * @param graph The graph that contains the statement + */ + match( + subject: ValueType, + predicate: ValueType, + object: ValueType, + graph: ValueType + ): Statement[]; + /** + * Find out whether a given URI is used as symbol in the formula + * @param uri The URI to look for + */ + mentionsURI(uri: string): boolean; + /** + * Existentials are BNodes - something exists without naming + * @param uri An URI + */ + newExistential(uri: string): Node; + /** + * Creates a new universal node + * Universals are Variables + * @param uri An URI + */ + newUniversal(uri: string): Node; + /** + * Find an unused id for a file being edited: return a symbol + * (Note: Slow iff a lot of them -- could be O(log(k)) ) + * @param doc A document named node + */ + nextSymbol(doc: NamedNode): NamedNode; + /** + * Removes a statement from this formula + * @param st A statement to remove + */ + remove(st: Statement): IndexedFormula; + /** + * Removes all statemnts in a doc + * @param doc The document + */ + removeDocument(doc: NamedNode): IndexedFormula; + /** + * Remove all statements matching args (within limit) * + * @param subj The subject + * @param pred The predicate + * @param obj The object + * @param why The graph that contains the statement + * @param limit The number of statements to remove + */ + removeMany( + subj: Node, + pred: Node, + obj: Node, + why: Node, + limit: number + ): void; + /** + * Remove all matching statements + * @param subject The subject + * @param predicate The predicate + * @param object The object + * @param graph The graph that contains the statement + */ + removeMatches( + subject: ValueType, + predicate: ValueType, + object: ValueType, + graph: ValueType + ): void; + /** + * Removes a statement + * @param st The statement to remove + */ + removeStatement(st: Statement): Formula; + /** + * Removes statements + * @param sts The statements to remove + */ + removeStatements(sts: ReadonlyArray): Formula; + /** + * Return all equivalent URIs by which this is known + * @param x A named node + */ + allAliases(x: NamedNode): NamedNode[]; + /** + * Compare by canonical URI as smushed + * @param x A named node + * @param y Another named node + */ + sameThings(x: NamedNode, y: NamedNode): boolean; + /** + * A list of all the URIs by which this thing is known + * @param term + */ + uris(term: NamedNode): string[]; +} +export namespace DataFactory { + /** + * Creates a new blank node + * @param value The blank node's identifier + */ + function blankNode(value: string): BlankNode; + /** + * Creates a new collection + * @param elements The initial element + */ + function collection(elements: ReadonlyArray): Collection; + /** + * Gets the default graph + */ + function defaultGraph(): DefaultGraph; + /** + * Creates a new fetcher + * @param store The store to use + * @param options The options + */ + function fetcher(store: Formula, options: any): Fetcher; + /** + * Creates a new graph (store) + */ + function graph(): IndexedFormula; + /** + * Creates a new literal node + * @param val The lexical value + * @param lang The language + * @param dt The datatype + */ + function lit(val: string, lang: string, dt: NamedNode): Literal; + /** + * Creates a new literal node + * @param value The lexical value + * @param languageOrDatatype Either the language or the datatype + */ + function literal( + value: string, + languageOrDatatype: string | NamedNode + ): Literal; + /** + * Creates a new named node + * @param value The new named node + */ + function namedNode(value: string): NamedNode; + /** + * Creates a new statement + * @param subject The subject + * @param predicate The predicate + * @param object The object + * @param graph The containing graph + */ + function quad( + subject: Node, + predicate: Node, + object: Node, + graph: Node + ): Statement; + /** + * Creates a new statement + * @param subject The subject + * @param predicate The predicate + * @param object The object + * @param graph The containing graph + */ + function st( + subject: Node, + predicate: Node, + object: Node, + graph: Node + ): Statement; + /** + * Creates a new statement + * @param subject The subject + * @param predicate The predicate + * @param object The object + */ + function triple(subject: Node, predicate: Node, object: Node): Statement; + /** + * Creates a new variable + * @param name The name for the variable + */ + function variable(name: string): Variable; +} +export namespace Util { + /** + * Gets a named node for a media type + * @param mediaType A media type + */ + function mediaTypeClass(mediaType: string): NamedNode; + /** + * Gets a named node from the name of a relation + * @param relation The name of a relation + */ + function linkRelationProperty(relation: string): NamedNode; + /** + * Loads ontologies of the data we load (this is the callback from the kb to + * the fetcher). Exports as `AJAR_handleNewTerm` + * @param kb The store + * @param p A property + * @param requestedBy + */ + function AJAR_handleNewTerm( + kb: Formula, + p: NamedNode, + requestedBy: string + ): Promise; +} +/** + * A datatype-specific handler for fetching data + */ +export interface Handler { + response: any; + dom: any; +} +/** + * Responsible for fetching RDF data + */ +export class Fetcher { + store: any; + timeout: number; + appNode: BlankNode; + requested: { + [uri: string]: any; + }; + timeouts: any; + redirectedTo: any; + constructor(store: any, options: any); + static HANDLERS: { + RDFXMLHandler: Handler; + XHTMLHandler: Handler; + XMLHandler: Handler; + HTMLHandler: Handler; + TextHandler: Handler; + N3Handler: Handler; + }; + static CONTENT_TYPE_BY_EXT: { + [ext: string]: string; + }; +} +/** + * Gets a node for the specified input + * @param value An input value + */ +export function term(value: ValueType): Node | Collection | ValueType; +/** + * Gets a namespace + * @param nsuri The URI for the namespace + */ +export function Namespace(nsuri: string): (ln: string) => NamedNode; +/** + * Transforms an NTriples string format into a Node. + * The bnode bit should not be used on program-external values; designed + * for internal work such as storing a bnode id in an HTML attribute. + * This will only parse the strings generated by the vaious toNT() methods. + * @param str A string representation + */ +export function fromNT(str: string): Node; +/** + * Creates a new fetcher + * @param store The store to use + * @param options The options + */ +export function fetcher(store: Formula, options: any): Fetcher; +/** + * Creates a new graph (store) + */ +export function graph(): IndexedFormula; +/** + * Creates a new literal node + * @param val The lexical value + * @param lang The language + * @param dt The datatype + */ +export function lit(val: string, lang: string, dt: NamedNode): Literal; +/** + * Creates a new statement + * @param subject The subject + * @param predicate The predicate + * @param object The object + * @param graph The containing graph + */ +export function st( + subject: Node, + predicate: Node, + object: Node, + graph: Node +): Statement; +/** + * Creates a new named node + * @param value The new named node + */ +export function sym(value: string): NamedNode; +/** + * Creates a new variable + * @param name The name for the variable + */ +export function variable(name: string): Variable; +/** + * Creates a new blank node + * @param value The blank node's identifier + */ +export function blankNode(value: string): BlankNode; +/** + * Gets the default graph + */ +export function defaultGraph(): DefaultGraph; +/** + * Creates a new literal node + * @param value The lexical value + * @param languageOrDatatype Either the language or the datatype + */ +export function literal( + value: string, + languageOrDatatype: string | NamedNode +): Literal; +/** + * Creates a new named node + * @param value The new named node + */ +export function namedNode(value: string): NamedNode; +/** + * Creates a new statement + * @param subject The subject + * @param predicate The predicate + * @param object The object + * @param graph The containing graph + */ +export function quad( + subject: Node, + predicate: Node, + object: Node, + graph: Node +): Statement; +/** + * Creates a new statement + * @param subject The subject + * @param predicate The predicate + * @param object The object + */ +export function triple(subject: Node, predicate: Node, object: Node): Statement; +/** + * Parse a string and put the result into the graph kb. + * Normal method is sync. + * Unfortunately jsdonld is currently written to need to be called async. + * Hence the mess below with executeCallback. + * @param str The input string to parse + * @param kb The store to use + * @param base The base URI to use + * @param contentType The content type for the input + * @param callback The callback to call when the data has been loaded + */ +export function parse( + str: string, + kb: Formula, + base: string, + contentType: string, + callback: (error: any, kb: Formula) => void +): void; +/** + * Get the next available unique identifier + */ +export let NextId: number; diff --git a/types/rdflib/rdflib-tests.ts b/types/rdflib/rdflib-tests.ts new file mode 100644 index 0000000000..fecd177d47 --- /dev/null +++ b/types/rdflib/rdflib-tests.ts @@ -0,0 +1,17 @@ +import * as $rdf from "rdflib"; + +const store = $rdf.graph(); +$rdf.parse( + "some inline rdf data", + store, + "http://example.com", + "text/n3", + (x, y) => {} +); +const node = store.any( + $rdf.sym("http://example.com/subject"), + $rdf.sym("http://example.com/property"), + undefined, + undefined +); +const value = node.value; diff --git a/types/rdflib/tsconfig.json b/types/rdflib/tsconfig.json new file mode 100644 index 0000000000..6c84dd0e59 --- /dev/null +++ b/types/rdflib/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", + "rdflib-tests.ts" + ] +} \ No newline at end of file diff --git a/types/rdflib/tslint.json b/types/rdflib/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rdflib/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-adal/index.d.ts b/types/react-adal/index.d.ts new file mode 100644 index 0000000000..40a8d5d3bc --- /dev/null +++ b/types/react-adal/index.d.ts @@ -0,0 +1,411 @@ +// Type definitions for react-adal 0.4 +// Project: https://github.com/salvoravida/react-adal#readme +// Definitions by: Dmitry Korolev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +export type TokenCallback = ( + errorDesc: string | null, + token: string | null, + error: any +) => void; + +export type UserCallback = ( + errorDesc: string | null, + user: UserInfo | null +) => void; + +export interface AdalConfig { + /** + * Client ID assigned to your app by Azure Active Directory. + */ + clientId: string; + /** + * Endpoint at which you expect to receive tokens.Defaults to `window.location.href`. + */ + redirectUri?: string; + /** + * Azure Active Directory instance. Defaults to `https://login.microsoftonline.com/`. + */ + instance?: string; + /** + * Your target tenant. Defaults to `common`. + */ + tenant?: string; + /** + * Query parameters to add to the authentication request. + */ + extraQueryParameter?: string; + /** + * Unique identifier used to map the request with the response. Defaults to RFC4122 version 4 guid (128 bits). + */ + correlationId?: string; + /** + * User defined function of handling the navigation to Azure AD authorization endpoint in case of login. + */ + displayCall?: (url: string) => void; + /** + * Set this to true to enable login in a popup winodow instead of a full redirect. Defaults to `false`. + */ + popUp?: boolean; + /** + * Set this to the resource to request on login. Defaults to `clientId`. + */ + loginResource?: string; + /** + * Set this to redirect the user to a custom login page. + */ + localLoginUrl?: string; + /** + * Redirects to start page after login. Defaults to `true`. + */ + navigateToLoginRequestUrl?: boolean; + /** + * Set this to redirect the user to a custom logout page. + */ + logOutUri?: string; + /** + * Redirects the user to postLogoutRedirectUri after logout. Defaults to `redirectUri`. + */ + postLogoutRedirectUri?: string; + /** + * Sets browser storage to either 'localStorage' or sessionStorage'. Defaults to `sessionStorage`. + */ + cacheLocation?: "localStorage" | "sessionStorage"; + /** + * Array of keywords or URIs. Adal will attach a token to outgoing requests that have these keywords or URIs. + */ + endpoints?: { [resource: string]: string }; + /** + * Array of keywords or URIs. Adal will not attach a token to outgoing requests that have these keywords or URIs. + */ + anonymousEndpoints?: string[]; + /** + * If the cached token is about to be expired in the expireOffsetSeconds (in seconds), Adal will renew the token instead of using the cached token. Defaults to 300 seconds. + */ + expireOffsetSeconds?: number; + /** + * The number of milliseconds of inactivity before a token renewal response from AAD should be considered timed out. Defaults to 6 seconds. + */ + loadFrameTimeout?: number; + /** + * Callback to be invoked when a token is acquired. + */ + callback?: TokenCallback; +} + +export type LoggingLevel = 0 | 1 | 2 | 3; + +export interface RequestInfo { + /** + * Object comprising of fields such as id_token/error, session_state, state, e.t.c. + */ + parameters: any; + /** + * Request type. + */ + requestType: RequestType; + /** + * Whether state is valid. + */ + stateMatch: boolean; + /** + * Unique guid used to match the response with the request. + */ + stateResponse: string; + /** + * Whether `requestType` contains `id_token`, `access_token` or error. + */ + valid: boolean; +} + +export type RequestType = "LOGIN" | "RENEW_TOKEN" | "UNKNOWN"; + +export type ResponseType = "id_token token" | "token"; + +export interface UserInfo { + /** + * Username assigned from UPN or email. + */ + userName: string; + /** + * Properties parsed from `id_token`. + */ + profile: any; +} + +export interface Constants { + ACCESS_TOKEN: 'access_token'; + EXPIRES_IN: 'expires_in'; + ID_TOKEN: 'id_token'; + ERROR_DESCRIPTION: 'error_description'; + SESSION_STATE: 'session_state'; + STORAGE: { + TOKEN_KEYS: 'adal.token.keys'; + ACCESS_TOKEN_KEY: 'adal.access.token.key'; + EXPIRATION_KEY: 'adal.expiration.key'; + STATE_LOGIN: 'adal.state.login'; + STATE_RENEW: 'adal.state.renew'; + NONCE_IDTOKEN: 'adal.nonce.idtoken'; + SESSION_STATE: 'adal.session.state'; + USERNAME: 'adal.username'; + IDTOKEN: 'adal.idtoken'; + ERROR: 'adal.error'; + ERROR_DESCRIPTION: 'adal.error.description'; + LOGIN_REQUEST: 'adal.login.request'; + LOGIN_ERROR: 'adal.login.error'; + RENEW_STATUS: 'adal.token.renew.status'; + }; + RESOURCE_DELIMETER: '|'; + LOADFRAME_TIMEOUT: '6000'; + TOKEN_RENEW_STATUS_CANCELED: 'Canceled'; + TOKEN_RENEW_STATUS_COMPLETED: 'Completed'; + TOKEN_RENEW_STATUS_IN_PROGRESS: 'In Progress'; + LOGGING_LEVEL: { + ERROR: 0; + WARN: 1; + INFO: 2; + VERBOSE: 3; + }; + LEVEL_STRING_MAP: { + 0: 'ERROR:'; + 1: 'WARNING:'; + 2: 'INFO:'; + 3: 'VERBOSE:'; + }; + POPUP_WIDTH: 483; + POPUP_HEIGHT: 600; +} + +export class AuthenticationContext { + instance: string; + config: AdalConfig; + callback: TokenCallback; + popUp: boolean; + isAngular: boolean; + + /** + * Enum for request type + */ + REQUEST_TYPE: RequestType; + RESPONSE_TYPE: ResponseType; + CONSTANTS: Constants; + + constructor(options: AdalConfig); + /** + * Initiates the login process by redirecting the user to Azure AD authorization endpoint. + */ + login(): void; + /** + * Returns whether a login is in progress. + */ + loginInProgress(): boolean; + /** + * Gets token for the specified resource from the cache. + * @param resource A URI that identifies the resource for which the token is requested. + */ + getCachedToken(resource: string): string; + /** + * If user object exists, returns it. Else creates a new user object by decoding `id_token` from the cache. + */ + getCachedUser(): UserInfo; + /** + * Adds the passed callback to the array of callbacks for the specified resource. + * @param resource A URI that identifies the resource for which the token is requested. + * @param expectedState A unique identifier (guid). + * @param callback The callback provided by the caller. It will be called with token or error. + */ + registerCallback( + expectedState: string, + resource: string, + callback: TokenCallback + ): void; + /** + * Acquires token from the cache if it is not expired. Otherwise sends request to AAD to obtain a new token. + * @param resource Resource URI identifying the target resource. + * @param callback The callback provided by the caller. It will be called with token or error. + */ + acquireToken(resource: string, callback: TokenCallback): void; + /** + * Acquires token (interactive flow using a popup window) by sending request to AAD to obtain a new token. + * @param resource Resource URI identifying the target resource. + * @param extraQueryParameters Query parameters to add to the authentication request. + * @param claims Claims to add to the authentication request. + * @param callback The callback provided by the caller. It will be called with token or error. + */ + acquireTokenPopup( + resource: string, + extraQueryParameters: string | null | undefined, + claims: string | null | undefined, + callback: TokenCallback + ): void; + /** + * Acquires token (interactive flow using a redirect) by sending request to AAD to obtain a new token. In this case the callback passed in the authentication request constructor will be called. + * @param resource Resource URI identifying the target resource. + * @param extraQueryParameters Query parameters to add to the authentication request. + * @param claims Claims to add to the authentication request. + */ + acquireTokenRedirect( + resource: string, + extraQueryParameters?: string | null, + claims?: string | null + ): void; + /** + * Redirects the browser to Azure AD authorization endpoint. + * @param urlNavigate URL of the authorization endpoint. + */ + promptUser(urlNavigate: string): void; + /** + * Clears cache items. + */ + clearCache(): void; + /** + * Clears cache items for a given resource. + * @param resource Resource URI identifying the target resource. + */ + clearCacheForResource(resource: string): void; + /** + * Redirects user to logout endpoint. After logout, it will redirect to `postLogoutRedirectUri` if added as a property on the config object. + */ + logOut(): void; + /** + * Calls the passed in callback with the user object or error message related to the user. + * @param callback The callback provided by the caller. It will be called with user or error. + */ + getUser(callback: UserCallback): void; + /** + * Checks if the URL fragment contains access token, id token or error description. + * @param hash Hash passed from redirect page. + */ + isCallback(hash: string): boolean; + /** + * Gets login error. + */ + getLoginError(): string; + /** + * Creates a request info object from the URL fragment and returns it. + */ + getRequestInfo(hash: string): RequestInfo; + /** + * Saves token or error received in the response from AAD in the cache. In case of `id_token`, it also creates the user object. + */ + saveTokenFromHash(requestInfo: RequestInfo): void; + /** + * Gets resource for given endpoint if mapping is provided with config. + * @param endpoint Resource URI identifying the target resource. + */ + getResourceForEndpoint(resource: string): string; + /** + * This method must be called for processing the response received from AAD. It extracts the hash, processes the token or error, saves it in the cache and calls the callbacks with the result. + * @param hash Hash fragment of URL. Defaults to `window.location.hash`. + */ + handleWindowCallback(hash?: string): void; + + /** + * Checks the logging Level, constructs the log message and logs it. Users need to implement/override this method to turn on logging. + * @param level Level can be set 0, 1, 2 and 3 which turns on 'error', 'warning', 'info' or 'verbose' level logging respectively. + * @param message Message to log. + * @param error Error to log. + */ + log(level: LoggingLevel, message: string, error: any): void; + /** + * Logs messages when logging level is set to 0. + * @param message Message to log. + * @param error Error to log. + */ + error(message: string, error: any): void; + /** + * Logs messages when logging level is set to 1. + * @param message Message to log. + */ + warn(message: string): void; + /** + * Logs messages when logging level is set to 2. + * @param message Message to log. + */ + info(message: string): void; + /** + * Logs messages when logging level is set to 3. + * @param message Message to log. + */ + verbose(message: string): void; + + /** + * Logs Pii messages when Logging Level is set to 0 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + * @param error Error to log. + */ + errorPii(message: string, error: any): void; + + /** + * Logs Pii messages when Logging Level is set to 1 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + */ + warnPii(message: string): void; + + /** + * Logs messages when Logging Level is set to 2 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + */ + infoPii(message: string): void; + + /** + * Logs messages when Logging Level is set to 3 and window.piiLoggingEnabled is set to true. + * @param message Message to log. + */ + verbosePii(message: string): void; +} + +/** + * Return user token + * @param authContext Authentication context + * @param resource Resource GUID ot URI identifying the target resource. + */ +export function adalGetToken( + authContext: AuthenticationContext, + resourceUrl: string +): Promise; + +/** + * Allows to make requests with adal token + * @param authContext Authentication context + * @param resource Resource GUID ot URI identifying the target resource. + * @param fetch Fetch client + * @param url Request url + * @param options Fetch options + */ +export function adalFetch( + authContext: AuthenticationContext, + resource: string, + fetch: (input: string, init: any) => Promise, + url: string, + options: any +): Promise; + +/** + * Wrap for the app + * @param authContext Authentication context + * @param app Render app callback + * @param doNotLogin Don`t need to login? + */ +export function runWithAdal( + authContext: AuthenticationContext, + app: () => void, + doNotLogin: boolean +): void; + +/** + * Creates a HOC that can be used to manage authentication for the certain components + * @param authContext Authentication context + * @param resource Resource GUID ot URI identifying the target resource. + */ +export function withAdalLogin( + authContext: AuthenticationContext, + resource: string +): ( + wrappedComponent: React.ComponentClass | React.StatelessComponent, + renderLoading: () => JSX.Element | null, + renderError: (error: any) => JSX.Element | null +) => React.ComponentClass; diff --git a/types/react-adal/react-adal-tests.tsx b/types/react-adal/react-adal-tests.tsx new file mode 100644 index 0000000000..961246560f --- /dev/null +++ b/types/react-adal/react-adal-tests.tsx @@ -0,0 +1,75 @@ +import * as React from 'react'; +import { AuthenticationContext, adalFetch, adalGetToken, runWithAdal, withAdalLogin, AdalConfig } from 'react-adal'; + +const resourceUrl = 'https://graph.microsoft.net'; + +const adalConfig: AdalConfig = { + cacheLocation: "localStorage", + clientId: '9ha8cqc6-4668-459a-9272-f48c80a053y5', + endpoints: { + api: resourceUrl + }, + postLogoutRedirectUri: 'https://localhost:3000', + tenant: 'tenantname.onmicrosoft.com' + }; + +const authContext = new AuthenticationContext(adalConfig); + +const adalApiFetch = (fetch: any, url: string, options: any) => { + return adalFetch(authContext, resourceUrl, fetch, url, options); +}; + +const getToken = () => adalGetToken(authContext, resourceUrl); + +class App extends React.Component { + render() { + return null; + } +} + +// user must login to use the app +runWithAdal(authContext, () => { + // ReactDOM.render(, document.getElementById('react-app') as HTMLElement); +}, false); + +const withAdalLoginApi = withAdalLogin(authContext, resourceUrl); + +const Loading: React.SFC = (props) => { + return null; +}; + +const ErrorPage: React.SFC = (props) => { + return null; +}; + +class SignInPage extends React.Component { + render() { + return null; + } +} + +class ProtectedPage1 extends React.Component { + render() { + return null; + } +} + +const ProtectedPage2: React.SFC = (props) => { + return null; +}; + +const AdalProtectedPage1 = withAdalLoginApi(ProtectedPage1, () => , () => ); +const AdalProtectedPage2 = withAdalLoginApi(ProtectedPage2, () =>

loading...

, () =>

It seems something went wrong...

); + +// user must login to use only specific pages +runWithAdal(authContext, () => { + const routes =
+ // $ExpectError + // $ExpectError + // $ExpectError +
; + // $ExpectError + const App = ; + // $ExpectError + ReactDOM.render(, document.getElementById('react-app') as HTMLElement); +}, true); diff --git a/types/react-svg/tsconfig.json b/types/react-adal/tsconfig.json similarity index 93% rename from types/react-svg/tsconfig.json rename to types/react-adal/tsconfig.json index 43b8246d54..b77e4dffc1 100644 --- a/types/react-svg/tsconfig.json +++ b/types/react-adal/tsconfig.json @@ -4,21 +4,21 @@ "lib": [ "es6" ], + "jsx": "react", "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": true, "strictFunctionTypes": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" ], - "jsx": "react", "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", - "react-svg-tests.tsx" + "react-adal-tests.tsx" ] } diff --git a/types/react-adal/tslint.json b/types/react-adal/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-adal/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-addons-create-fragment/index.d.ts b/types/react-addons-create-fragment/index.d.ts index 1e46046ec4..25e4ba9b43 100644 --- a/types/react-addons-create-fragment/index.d.ts +++ b/types/react-addons-create-fragment/index.d.ts @@ -2,7 +2,7 @@ // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-addons-css-transition-group/index.d.ts b/types/react-addons-css-transition-group/index.d.ts index 33d43b4cd1..03cdc48303 100644 --- a/types/react-addons-css-transition-group/index.d.ts +++ b/types/react-addons-css-transition-group/index.d.ts @@ -2,7 +2,7 @@ // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import 'react-addons-transition-group'; import { ComponentClass, CSSTransitionGroupProps } from 'react'; diff --git a/types/react-addons-linked-state-mixin/index.d.ts b/types/react-addons-linked-state-mixin/index.d.ts index 6358dde535..1c590e333f 100644 --- a/types/react-addons-linked-state-mixin/index.d.ts +++ b/types/react-addons-linked-state-mixin/index.d.ts @@ -2,7 +2,7 @@ // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Mixin } from 'react'; diff --git a/types/react-addons-pure-render-mixin/index.d.ts b/types/react-addons-pure-render-mixin/index.d.ts index 565a108721..a154dbe594 100644 --- a/types/react-addons-pure-render-mixin/index.d.ts +++ b/types/react-addons-pure-render-mixin/index.d.ts @@ -2,7 +2,7 @@ // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Mixin } from 'react'; diff --git a/types/react-addons-shallow-compare/index.d.ts b/types/react-addons-shallow-compare/index.d.ts index ff4e5dbdc9..5d6942ed24 100644 --- a/types/react-addons-shallow-compare/index.d.ts +++ b/types/react-addons-shallow-compare/index.d.ts @@ -2,7 +2,7 @@ // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component } from 'react'; diff --git a/types/react-addons-test-utils/index.d.ts b/types/react-addons-test-utils/index.d.ts index 9282f95f4e..0531c5e3f6 100644 --- a/types/react-addons-test-utils/index.d.ts +++ b/types/react-addons-test-utils/index.d.ts @@ -2,7 +2,7 @@ // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { AbstractView, Component, ComponentClass, ReactElement, ReactInstance, ClassType, diff --git a/types/react-addons-transition-group/index.d.ts b/types/react-addons-transition-group/index.d.ts index 933533df28..79f76bf84e 100644 --- a/types/react-addons-transition-group/index.d.ts +++ b/types/react-addons-transition-group/index.d.ts @@ -2,7 +2,7 @@ // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { ComponentClass, TransitionGroupProps } from 'react'; diff --git a/types/react-addons-update/index.d.ts b/types/react-addons-update/index.d.ts index 874549b7a1..5a1018d2c2 100644 --- a/types/react-addons-update/index.d.ts +++ b/types/react-addons-update/index.d.ts @@ -2,7 +2,7 @@ // Project: http://facebook.github.io/react/ // Definitions by: Asana , AssureSign , Microsoft // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-albus/index.d.ts b/types/react-albus/index.d.ts index dabdb4b81a..d9d6b5ff99 100644 --- a/types/react-albus/index.d.ts +++ b/types/react-albus/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/americanexpress/react-albus#readme // Definitions by: Sindre Seppola // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; import { History } from "history"; diff --git a/types/react-alert/index.d.ts b/types/react-alert/index.d.ts index 9150bf28b4..3814b7f29f 100644 --- a/types/react-alert/index.d.ts +++ b/types/react-alert/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/schiehll/react-alert // Definitions by: Steve Syrell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-alice-carousel/index.d.ts b/types/react-alice-carousel/index.d.ts index 2d40293003..e3002f1193 100644 --- a/types/react-alice-carousel/index.d.ts +++ b/types/react-alice-carousel/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/maxmarinich/react-alice-carousel // Definitions by: endigo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-animate-on-scroll/index.d.ts b/types/react-animate-on-scroll/index.d.ts index 6584833cbe..6750cd8200 100644 --- a/types/react-animate-on-scroll/index.d.ts +++ b/types/react-animate-on-scroll/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/dbramwell/react-animate-on-scroll // Definitions by: Ricardo Albuquerque // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-app/index.d.ts b/types/react-app/index.d.ts index 7c5e00f57a..5315874ddd 100644 --- a/types/react-app/index.d.ts +++ b/types/react-app/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/kriasoft/react-app#readme // Definitions by: Prakarsh Pandey // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-aria-menubutton/index.d.ts b/types/react-aria-menubutton/index.d.ts index f7a4ef7de0..3bfc68259e 100644 --- a/types/react-aria-menubutton/index.d.ts +++ b/types/react-aria-menubutton/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Muhammad Fawwaz Orabi // Chris Rohlfs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-aria-modal/index.d.ts b/types/react-aria-modal/index.d.ts index 83ca6d3a34..4083d08473 100644 --- a/types/react-aria-modal/index.d.ts +++ b/types/react-aria-modal/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/davidtheclark/react-aria-modal#readme // Definitions by: forabi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import React = require('react'); diff --git a/types/react-autocomplete/index.d.ts b/types/react-autocomplete/index.d.ts index 0de7cd7eac..fd0bdc8b8a 100644 --- a/types/react-autocomplete/index.d.ts +++ b/types/react-autocomplete/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/reactjs/react-autocomplete // Definitions by: Lee Standen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, ChangeEvent, ReactNode, CSSProperties, HTMLProps } from 'react'; diff --git a/types/react-autosuggest/index.d.ts b/types/react-autosuggest/index.d.ts index ab91481925..bd20cc3c0a 100644 --- a/types/react-autosuggest/index.d.ts +++ b/types/react-autosuggest/index.d.ts @@ -7,7 +7,7 @@ // Christopher Deutsch // Kevin Ross // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-avatar-editor/index.d.ts b/types/react-avatar-editor/index.d.ts index 9f9ede1ea3..c2aebc5e63 100644 --- a/types/react-avatar-editor/index.d.ts +++ b/types/react-avatar-editor/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Diogo Corrêa // Gabriel Prates // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-beautiful-dnd/index.d.ts b/types/react-beautiful-dnd/index.d.ts index 3cb5e026f8..780a854751 100644 --- a/types/react-beautiful-dnd/index.d.ts +++ b/types/react-beautiful-dnd/index.d.ts @@ -5,7 +5,7 @@ // Austin Turner // Mark Nelissen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index b73ffcc0d9..60db9a20f9 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -5,7 +5,7 @@ // Krzysztof Bezrąk // Sebastian Silbermann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.7 +// TypeScript Version: 2.8 import * as React from 'react'; @@ -86,11 +86,23 @@ export interface Format { eventTimeRangeEndFormat?: string; } +export interface HeaderProps { + culture: BigCalendarProps['culture']; + date: Date; + format: string; + label: string; + localizer: object; +} + export interface Components { event?: React.SFC | React.Component | React.ComponentClass | JSX.Element; eventWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dayWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dateCellWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; + /** + * component used as a header for each column in the TimeGridHeader + */ + header?: React.ComponentType; toolbar?: React.SFC | React.Component | React.ComponentClass | JSX.Element; agenda?: { date?: React.SFC | React.Component | React.ComponentClass | JSX.Element; diff --git a/types/react-body-classname/index.d.ts b/types/react-body-classname/index.d.ts index 23aa8d6f78..11dd7febeb 100644 --- a/types/react-body-classname/index.d.ts +++ b/types/react-body-classname/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/PactCoffee/react-body-classname // Definitions by: Mohamed Hegazy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-bootstrap-date-picker/index.d.ts b/types/react-bootstrap-date-picker/index.d.ts index 96971cc0bb..9fdd94f2fb 100644 --- a/types/react-bootstrap-date-picker/index.d.ts +++ b/types/react-bootstrap-date-picker/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/pushtell/react-bootstrap-date-picker#readme // Definitions by: Karol Janyst , Antal Bodnar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { ComponentClass, StatelessComponent, ReactNode, FocusEventHandler, HTMLAttributes } from "react"; diff --git a/types/react-bootstrap-daterangepicker/index.d.ts b/types/react-bootstrap-daterangepicker/index.d.ts index 26fb15f45a..b9ef9a955b 100644 --- a/types/react-bootstrap-daterangepicker/index.d.ts +++ b/types/react-bootstrap-daterangepicker/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/skratchdot/react-bootstrap-daterangepicker // Definitions by: Ian Ker-Seymer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// /// diff --git a/types/react-bootstrap-table/index.d.ts b/types/react-bootstrap-table/index.d.ts index d98dac1c44..1284162778 100644 --- a/types/react-bootstrap-table/index.d.ts +++ b/types/react-bootstrap-table/index.d.ts @@ -6,7 +6,7 @@ // Janeene Beeforth // Oscar Andersson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 // documentation taken from http://allenfang.github.io/react-bootstrap-table/docs.html diff --git a/types/react-bootstrap-table/v2/index.d.ts b/types/react-bootstrap-table/v2/index.d.ts index 5ac31a4a77..07d7da53d9 100644 --- a/types/react-bootstrap-table/v2/index.d.ts +++ b/types/react-bootstrap-table/v2/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/AllenFang/react-bootstrap-table // Definitions by: Frank Laub , Aleksander Lode , Josué Us // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-bootstrap-typeahead/index.d.ts b/types/react-bootstrap-typeahead/index.d.ts index 005a7633ed..fa970bc5b3 100644 --- a/types/react-bootstrap-typeahead/index.d.ts +++ b/types/react-bootstrap-typeahead/index.d.ts @@ -1,10 +1,10 @@ -// Type definitions for react-bootstrap-typeahead 3.1 +// Type definitions for react-bootstrap-typeahead 3.2 // Project: https://github.com/ericgio/react-bootstrap-typeahead // Definitions by: Guymestef // Rajab Shakirov // Paito Anderson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 // TODO: , , , components import * as React from 'react'; @@ -70,9 +70,15 @@ export interface TypeaheadProps { /* Props to be applied directly to the input. onBlur, onChange, onFocus, and onKeyDown are ignored. */ inputProps?: object; + /* Bootstrap 4 only. Adds the `is-invalid` classname to the `form-control`. */ + isInvalid?: boolean; + /* Indicate whether an asynchronous data fetch is happening. */ isLoading?: boolean; + /* Bootstrap 4 only. Adds the `is-valid` classname to the `form-control`. */ + isValid?: boolean; + /* Specify which option key to use for display or a render function. By default, the selector will use the label key. */ labelKey?: string | ((option: T | string) => string); diff --git a/types/react-breadcrumbs-dynamic/index.d.ts b/types/react-breadcrumbs-dynamic/index.d.ts index ed0521ec28..491157b655 100644 --- a/types/react-breadcrumbs-dynamic/index.d.ts +++ b/types/react-breadcrumbs-dynamic/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/oklas/react-breadcrumbs-dynamic // Definitions by: mitsuruog // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-breadcrumbs/index.d.ts b/types/react-breadcrumbs/index.d.ts index d43b5ba81c..3aa1cc3670 100644 --- a/types/react-breadcrumbs/index.d.ts +++ b/types/react-breadcrumbs/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/svenanders/react-breadcrumbs // Definitions by: Kostya Esmukov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; import * as ReactRouter from "react-router"; diff --git a/types/react-broadcast/index.d.ts b/types/react-broadcast/index.d.ts index 8a9a3bf47b..11b2312570 100644 --- a/types/react-broadcast/index.d.ts +++ b/types/react-broadcast/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ReactTraining/react-broadcast // Definitions by: Jaga Santagostino // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-burger-menu/index.d.ts b/types/react-burger-menu/index.d.ts index 51aec4fcd1..85d49494c2 100644 --- a/types/react-burger-menu/index.d.ts +++ b/types/react-burger-menu/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/negomi/react-burger-menu // Definitions by: Rajab Shakirov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-bytesize-icons/index.d.ts b/types/react-bytesize-icons/index.d.ts index d9dd1a50f7..de9d8e0f69 100644 --- a/types/react-bytesize-icons/index.d.ts +++ b/types/react-bytesize-icons/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/abdelhai/react-bytesize-icons // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-calendar-heatmap/index.d.ts b/types/react-calendar-heatmap/index.d.ts index 9f85b5bd2f..a4dbf402a5 100644 --- a/types/react-calendar-heatmap/index.d.ts +++ b/types/react-calendar-heatmap/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/patientslikeme/react-calendar-heatmap // Definitions by: Keisuke Kan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-calendar-timeline/index.d.ts b/types/react-calendar-timeline/index.d.ts index 2ff17f6a82..cf97e70f50 100644 --- a/types/react-calendar-timeline/index.d.ts +++ b/types/react-calendar-timeline/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Rajab Shakirov // Alex Maclean // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-cartographer/index.d.ts b/types/react-cartographer/index.d.ts index 918fcbef81..646ca5de0e 100644 --- a/types/react-cartographer/index.d.ts +++ b/types/react-cartographer/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/yahoo/react-cartographer // Definitions by: Tre`Von McKay // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import Map from './lib/components/Map'; export { diff --git a/types/react-circular-progressbar/index.d.ts b/types/react-circular-progressbar/index.d.ts index dc6e1a1950..f93a64c8e9 100644 --- a/types/react-circular-progressbar/index.d.ts +++ b/types/react-circular-progressbar/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/iqnivek/react-circular-progressbar#readme // Definitions by: Lee Standen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, CSSProperties } from 'react'; diff --git a/types/react-click-outside/index.d.ts b/types/react-click-outside/index.d.ts index 5a1ce6d220..c09dccb155 100644 --- a/types/react-click-outside/index.d.ts +++ b/types/react-click-outside/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/kentor/react-click-outside // Definitions by: Christian Rackerseder // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; declare function enhanceWithClickOutside

(wrappedComponent: React.ComponentClass

): React.ComponentClass

; diff --git a/types/react-codemirror/index.d.ts b/types/react-codemirror/index.d.ts index 607554b269..1afe6362c9 100644 --- a/types/react-codemirror/index.d.ts +++ b/types/react-codemirror/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Vicky Lai // Rudi Chen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// /// diff --git a/types/react-collapse/index.d.ts b/types/react-collapse/index.d.ts index a4061860ba..c960fcd825 100644 --- a/types/react-collapse/index.d.ts +++ b/types/react-collapse/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/nkbt/react-collapse // Definitions by: Adam Binford // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; export interface CollapseProps extends React.HTMLProps { diff --git a/types/react-collapsible/index.d.ts b/types/react-collapsible/index.d.ts index ad56aba34e..def932f6ba 100644 --- a/types/react-collapsible/index.d.ts +++ b/types/react-collapsible/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/glennflanagan/react-collapsible#readme // Definitions by: knegusen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; export interface CollapsibleProp { diff --git a/types/react-color/index.d.ts b/types/react-color/index.d.ts index a1fbbad698..a49d7b6035 100644 --- a/types/react-color/index.d.ts +++ b/types/react-color/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/casesandberg/react-color/ // Definitions by: Karol Janyst , Marks Polakovs , Matthieu Montaudouin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { ComponentClass, ClassAttributes, StatelessComponent, ReactNode } from "react"; diff --git a/types/react-confirm/index.d.ts b/types/react-confirm/index.d.ts index d07a367eab..532ac1768b 100644 --- a/types/react-confirm/index.d.ts +++ b/types/react-confirm/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/haradakunihiko/react-confirm // Definitions by: santiagodoldan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-content-loader/index.d.ts b/types/react-content-loader/index.d.ts index 23b0ad02c3..c395fc8a34 100644 --- a/types/react-content-loader/index.d.ts +++ b/types/react-content-loader/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Alaa Masoud // Sam Walsh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-copy-to-clipboard/index.d.ts b/types/react-copy-to-clipboard/index.d.ts index 33e9549d30..a09d7bc8be 100644 --- a/types/react-copy-to-clipboard/index.d.ts +++ b/types/react-copy-to-clipboard/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Meno Abels // Bernabe // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-credit-cards/index.d.ts b/types/react-credit-cards/index.d.ts index bc9a8fbf51..da41f6f05e 100644 --- a/types/react-credit-cards/index.d.ts +++ b/types/react-credit-cards/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/amarofashion/react-credit-cards // Definitions by: Vytautas Strimaitis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.7 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-cropper/index.d.ts b/types/react-cropper/index.d.ts index 3ab1106754..843cd50683 100644 --- a/types/react-cropper/index.d.ts +++ b/types/react-cropper/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/roadmanfong/react-cropper // Definitions by: Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as cropperjs from 'cropperjs'; import * as React from 'react'; diff --git a/types/react-css-modules/index.d.ts b/types/react-css-modules/index.d.ts index 955f76efa5..56b219728e 100644 --- a/types/react-css-modules/index.d.ts +++ b/types/react-css-modules/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/gajus/react-css-modules // Definitions by: Kostya Esmukov , Tadas Dailyda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 interface TypeOptions { allowMultiple?: boolean; diff --git a/types/react-css-transition-replace/index.d.ts b/types/react-css-transition-replace/index.d.ts index f252707f42..b386019fc0 100644 --- a/types/react-css-transition-replace/index.d.ts +++ b/types/react-css-transition-replace/index.d.ts @@ -2,7 +2,7 @@ // Project: http://marnusw.github.io/react-css-transition-replace/ // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; import * as CSSTransitionGroup from "react-addons-css-transition-group"; diff --git a/types/react-custom-scrollbars/index.d.ts b/types/react-custom-scrollbars/index.d.ts index f21ec7adba..db2ba3eb74 100644 --- a/types/react-custom-scrollbars/index.d.ts +++ b/types/react-custom-scrollbars/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: David-LeBlanc-git // kittimiyo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-custom-scrollbars/v3/index.d.ts b/types/react-custom-scrollbars/v3/index.d.ts index c0e7c1709e..f3ca0da419 100644 --- a/types/react-custom-scrollbars/v3/index.d.ts +++ b/types/react-custom-scrollbars/v3/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/malte-wessel/react-custom-scrollbars // Definitions by: David-LeBlanc-git // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-data-grid/index.d.ts b/types/react-data-grid/index.d.ts index 9c6ca297eb..bfa4ea979f 100644 --- a/types/react-data-grid/index.d.ts +++ b/types/react-data-grid/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/adazzle/react-data-grid.git // Definitions by: Simon Gellis , Kieran Peat , Martin Novak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-data-grid/v1/index.d.ts b/types/react-data-grid/v1/index.d.ts index 81d7386dca..4db1f4042a 100644 --- a/types/react-data-grid/v1/index.d.ts +++ b/types/react-data-grid/v1/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/adazzle/react-data-grid.git // Definitions by: Simon Gellis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-datagrid/index.d.ts b/types/react-datagrid/index.d.ts index 8b8d6e4848..032a640daf 100644 --- a/types/react-datagrid/index.d.ts +++ b/types/react-datagrid/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/zippyui/react-datagrid.git // Definitions by: Stephen Jelfs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-date-range/index.d.ts b/types/react-date-range/index.d.ts index e5be9f751b..fbe74f11b5 100644 --- a/types/react-date-range/index.d.ts +++ b/types/react-date-range/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/Adphorus/react-date-range/ // Definitions by: Junbong Lee // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import * as moment from "moment-timezone"; diff --git a/types/react-datepicker/index.d.ts b/types/react-datepicker/index.d.ts index 5f48988dd4..23e542d322 100644 --- a/types/react-datepicker/index.d.ts +++ b/types/react-datepicker/index.d.ts @@ -8,7 +8,7 @@ // Koala Human // Sean Kelley // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; import * as moment from "moment"; @@ -86,6 +86,7 @@ export interface ReactDatePickerProps { startDate?: moment.Moment; startOpen?: boolean; tabIndex?: number; + timeCaption?: string; timeFormat?: string; timeIntervals?: number; title?: string; diff --git a/types/react-daterange-picker/index.d.ts b/types/react-daterange-picker/index.d.ts index dc070d64a0..86ada23508 100644 --- a/types/react-daterange-picker/index.d.ts +++ b/types/react-daterange-picker/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: UNCOVER TRUTH Inc. // MartynasZilinskas // Definitions: https://github.com/borisyankov/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; import * as moment from "moment"; diff --git a/types/react-dates/index.d.ts b/types/react-dates/index.d.ts index ac441c43cf..5e0a889384 100644 --- a/types/react-dates/index.d.ts +++ b/types/react-dates/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Artur Ampilogov // Nathan Holland // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 // Required fields are made according to 'minimum REQUIRED setup' in https://github.com/airbnb/react-dates/blob/master/README.md diff --git a/types/react-daum-postcode/index.d.ts b/types/react-daum-postcode/index.d.ts index b6d093db2d..8aca77413e 100644 --- a/types/react-daum-postcode/index.d.ts +++ b/types/react-daum-postcode/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/kimminsik-bernard/react-daum-postcode // Definitions by: Sa-ryong Kang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component } from 'react'; diff --git a/types/react-dnd-multi-backend/index.d.ts b/types/react-dnd-multi-backend/index.d.ts index 10e6662bdd..0fcfbf256e 100644 --- a/types/react-dnd-multi-backend/index.d.ts +++ b/types/react-dnd-multi-backend/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Janeene Beeforth // Adam Haglund // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { CSSProperties, PureComponent } from "react"; import { BackendFactory } from "dnd-core"; diff --git a/types/react-dnd-touch-backend/index.d.ts b/types/react-dnd-touch-backend/index.d.ts index 9560f48883..e06a4106e7 100644 --- a/types/react-dnd-touch-backend/index.d.ts +++ b/types/react-dnd-touch-backend/index.d.ts @@ -4,7 +4,7 @@ // Janeene Beeforth // Adam Haglund // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { BackendFactory } from 'dnd-core'; diff --git a/types/react-document-title/index.d.ts b/types/react-document-title/index.d.ts index 85e9f3eb48..efaef782d8 100644 --- a/types/react-document-title/index.d.ts +++ b/types/react-document-title/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/gaearon/react-document-title // Definitions by: Cleve Littlefield // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-dom-factories/index.d.ts b/types/react-dom-factories/index.d.ts index eaf04f766f..b0bcb5bfa6 100644 --- a/types/react-dom-factories/index.d.ts +++ b/types/react-dom-factories/index.d.ts @@ -2,7 +2,7 @@ // Project: https://facebook.github.io/react/ // Definitions by: John Gozde // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 export as namespace ReactDOMFactories; export = ReactDOMFactories; diff --git a/types/react-dom/index.d.ts b/types/react-dom/index.d.ts index e7a5afe59d..518c0c617c 100644 --- a/types/react-dom/index.d.ts +++ b/types/react-dom/index.d.ts @@ -6,7 +6,7 @@ // MartynasZilinskas // Josh Rutherford // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 export as namespace ReactDOM; diff --git a/types/react-dom/v15/index.d.ts b/types/react-dom/v15/index.d.ts index bd39e0a5e1..8a22fd9bc2 100644 --- a/types/react-dom/v15/index.d.ts +++ b/types/react-dom/v15/index.d.ts @@ -5,7 +5,7 @@ // Microsoft // MartynasZilinskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 export as namespace ReactDOM; diff --git a/types/react-dragtastic/index.d.ts b/types/react-dragtastic/index.d.ts new file mode 100644 index 0000000000..fbfaf42cff --- /dev/null +++ b/types/react-dragtastic/index.d.ts @@ -0,0 +1,167 @@ +// Type definitions for react-dragtastic 2.4 +// Project: https://github.com/chrisjpatty/react-dragtastic#readme +// Definitions by: Nicolás Scarcella +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { ReactNode, Component, MouseEventHandler, TouchEventHandler } from 'react'; + +export type Id = string | number; +export type Type = string | number; +export type Accepts = string | ReadonlyArray; + +export interface State { + /** The user's current horizontal position on the page. */ + x: number; + /** The user's current vertical position on the page. */ + y: number; + /** The user's initial horizontal position on the page when they started dragging. */ + startingX: number; + /** The user's initial vertical position on the page when they started dragging. */ + startingY: number; + /** A boolean representing whether the user is currently dragging. */ + isDragging: boolean; + /** The id of the currently dragging element. */ + currentlyDraggingId?: Id; + /** The id of the currently being hovered. */ + currentlyHoveredDroppableId?: Id; + /** The accepts property of the currently being hovered. */ + currentlyHoveredDroppableAccepts?: Accepts; + /** Data from the data property of the which is currently active. null if not dragging. */ + data: any; + /** The type of the component being currently dragged. null if not dragging. */ + type?: Type; +} + +// ────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +// DRAGGABLE +// ────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + +export interface DraggableProps { + /** An id which will be used in the draggable zone's target */ + id?: Id; + /** A string, or array of strings, used to limit which droppable zones will accept 's attached to this draggable. */ + type?: Type; + /** Data of any type which will be passed to the onDrop function of any which accepts this 's type. */ + data?: any; + /** A function which will be called when the zone is activated (The user started dragging). */ + onDragStart?: (data: any) => void; + /** A function which will be called when the zone is deactivated (The user stopped dragging). */ + onDragEnd?: (data: any) => void; + /** A function which will be called every time the user's cursor moves while dragging. */ + onDrag?: () => void; + /** + * An optional array of strings. For performance reasons you can limit which keys in the dragState your component subscribes to. + * For example, you may pass ['type', 'data'] to only rerender if these keys change. + */ + subscribeTo?: ReadonlyArray | null; + /** An optional int representing the distance in pixels the user's pointer must travel to activate the draggable. Defaults to 8 */ + delay?: number; + + children: (arg: State & { + /** A boolean representing if the draggable is currently active. */ + isActive: boolean; + events: { + onMouseDown: MouseEventHandler, + onTouchStart: TouchEventHandler + } + }) => ReactNode; +} + +/** + * This defines a draggable zone. At a minimum, spread the events over the element that should be draggable (usually the root element). + */ +export class Draggable extends Component { } + +// ────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +// DROPPABLE +// ────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + +export interface DroppableProps { + /** An id which will be used in the draggable zone's target */ + id?: Id; + /** A string type corresponding to the type property of the zone for which this should accept drop events. */ + accepts?: Accepts; + /** A function which will be called when a user drops a on this with an accepted type. */ + onDrop?: (data: any) => void; + /** + * A function which will be called when the user's cursor enters the while dragging. + * This function will be called regardless of whether the droppable accepts the draggable currently being dragged. + */ + onDragEnter?: () => void; + /** + * A function which will be called when the user's cursor leaves the while dragging. + * This function will be called regardless of whether the droppable accepts the draggable currently being dragged. + */ + onDragLeave?: () => void; + /** + * An optional array of strings. For performance reasons you can limit which keys in the dragState your component subscribes to. + * For example, you may pass ['type', 'data'] to only rerender if these keys change. + */ + subscribeTo?: ReadonlyArray | null; + + children: (arg: State & { + /** A boolean representing if the user is currently hovering the . */ + isOver: boolean, + /** A boolean representing if this droppable will accept the currently dragging . */ + willAccept: boolean, + events: { + onMouseEnter: () => void, + onMouseLeave: () => void, + onMouseUp: () => void, + } + }) => ReactNode; +} + +/** + * This defines a droppable zone. At a minimum, spread the events over the element that should be droppable (usually the root element). + */ +export class Droppable extends Component { } + +// ────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +// DRAG +// ────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + +export interface DragComponentProps { + /* A string corresponding to the id property of the zone that should trigger this component to start rendering. */ + for?: Id; + /** A function which will be called every time a user drags. */ + onDrag?: () => void; + /** A boolean determining whether or not the DragComponent should always render. Defaults to false. */ + alwaysRender?: boolean; + /** + * An optional array of strings. For performance reasons you can limit which keys in the dragState your component subscribes to. + * For example, you may pass ['type', 'data'] to only rerender if these keys change. + */ + subscribeTo?: ReadonlyArray | null; + + children: (arg: State & { + /** A boolean representing whether the user is currently hovering a that accepts the type of the currently active */ + isOverAccepted: boolean + }) => ReactNode; +} + +/** + * By default, children passed to this component will only render if the user is currently dragging, but this can be overridden. + */ +export class DragComponent extends Component { } + +// ────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +// DRAG STATE +// ────────────────────────────────────────────────────────────────────────────────────────────────────────────────── + +export interface DragStateProps { + /** + * An optional array of strings. For performance reasons you can limit which keys in the dragState your component subscribes to. + * For example, you may pass ['type', 'data'] to only rerender if these keys change. + */ + subscribeTo?: ReadonlyArray | null; + + children: (arg: State) => ReactNode; +} + +/** + * This component is used just like a draggable or droppable, but does not accept or trigger any drag events. + * Use it if you need to notify a component about changes in the dragState without making that component a draggable or droppable zone. + */ +export class DragState extends Component { } diff --git a/types/react-dragtastic/react-dragtastic-tests.tsx b/types/react-dragtastic/react-dragtastic-tests.tsx new file mode 100644 index 0000000000..87a8e828e1 --- /dev/null +++ b/types/react-dragtastic/react-dragtastic-tests.tsx @@ -0,0 +1,57 @@ +import * as React from 'react'; +import { Draggable, Droppable, DragComponent, DragState } from 'react-dragtastic'; + +class DraggableZone extends React.Component { + render() { + return ( + + {dragState =>

I'm a draggable zone
} + + ); + } +} + +class DroppableZone extends React.Component { + render() { + return ( + + {dragState =>
I'm a droppable zone
} +
+ ); + } +} + +class DragComponentWrapper extends React.Component { + render() { + return ( + + {dragState => ( +
+ I will render when my Draggable zone is activated +
+ )} +
+ ); + } +} + +class CompWithDragState extends React.Component { + render() { + return ( + + {dragState => ( +
+ I always render, and have access to the global dragState. +
+ )} +
+ ); + } +} diff --git a/types/react-dragtastic/tsconfig.json b/types/react-dragtastic/tsconfig.json new file mode 100644 index 0000000000..7c07bab561 --- /dev/null +++ b/types/react-dragtastic/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-dragtastic-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/react-dragtastic/tslint.json b/types/react-dragtastic/tslint.json new file mode 100644 index 0000000000..30a1bdde2e --- /dev/null +++ b/types/react-dragtastic/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/react-dropzone/index.d.ts b/types/react-dropzone/index.d.ts index 423ce38462..116fcbdb57 100644 --- a/types/react-dropzone/index.d.ts +++ b/types/react-dropzone/index.d.ts @@ -8,7 +8,7 @@ // Andris Causs , // Juraj Husar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { CSSProperties, Component, DragEvent, InputHTMLAttributes } from "react"; diff --git a/types/react-dropzone/v2/index.d.ts b/types/react-dropzone/v2/index.d.ts index 995e2cdb7d..bae20a74f6 100644 --- a/types/react-dropzone/v2/index.d.ts +++ b/types/react-dropzone/v2/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/okonet/react-dropzone // Definitions by: Mathieu Larouche Dube , Ivo Jesus , Luís Rodrigues , Ben Bayard // Definitions: https://github.com/Vooban/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-dropzone/v3/index.d.ts b/types/react-dropzone/v3/index.d.ts index 55f485203f..18955dff5f 100644 --- a/types/react-dropzone/v3/index.d.ts +++ b/types/react-dropzone/v3/index.d.ts @@ -6,7 +6,7 @@ // Ben Bayard , // Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { CSSProperties, Component, DragEvent, InputHTMLAttributes } from "react"; diff --git a/types/react-dynamic-number/index.d.ts b/types/react-dynamic-number/index.d.ts index 559d0c9d01..c885d8a54c 100644 --- a/types/react-dynamic-number/index.d.ts +++ b/types/react-dynamic-number/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/uhlryk/react-dynamic-number // Definitions by: Eugene Rodin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-easy-chart/index.d.ts b/types/react-easy-chart/index.d.ts index fa3eb07b2c..0697e0e11d 100644 --- a/types/react-easy-chart/index.d.ts +++ b/types/react-easy-chart/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/rma-consulting/react-easy-chart // Definitions by: Dave Leaver // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-event-listener/index.d.ts b/types/react-event-listener/index.d.ts index 4b343c67e4..b37566af5c 100644 --- a/types/react-event-listener/index.d.ts +++ b/types/react-event-listener/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/oliviertassinari/react-event-listener // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; @@ -125,8 +125,8 @@ export interface EventListenerProps { onMouseOverCapture?(ev: MouseEvent): any; onMouseUp?(ev: MouseEvent): any; onMouseUpCapture?(ev: MouseEvent): any; - onMouseWheel?(ev: MouseWheelEvent): any; - onMouseWheelCapture?(ev: MouseWheelEvent): any; + onMouseWheel?(ev: WheelEvent): any; + onMouseWheelCapture?(ev: WheelEvent): any; onMsGestureChange?(ev: MSGestureEvent): any; onMsGestureChangeCapture?(ev: MSGestureEvent): any; onMsGestureDoubleTap?(ev: MSGestureEvent): any; diff --git a/types/react-fa/index.d.ts b/types/react-fa/index.d.ts index 86480a197e..b5641439af 100644 --- a/types/react-fa/index.d.ts +++ b/types/react-fa/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/andreypopp/react-fa // Definitions by: Frank Laub , Pat Sissons , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, ComponentClass, HTMLProps, StatelessComponent, ReactElement } from "react"; diff --git a/types/react-facebook-login/index.d.ts b/types/react-facebook-login/index.d.ts index 2cd75419b2..82672660a8 100644 --- a/types/react-facebook-login/index.d.ts +++ b/types/react-facebook-login/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/keppelen/react-facebook-login // Definitions by: Alexandre Paré , Jan Karres // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-file-input/index.d.ts b/types/react-file-input/index.d.ts index d2aa7c70cf..0662941b44 100644 --- a/types/react-file-input/index.d.ts +++ b/types/react-file-input/index.d.ts @@ -2,7 +2,7 @@ // Project: https://www.npmjs.com/package/react-file-input // Definitions by: Dmitry Rogozhny // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-file-reader-input/index.d.ts b/types/react-file-reader-input/index.d.ts index c198d2c5f1..5dcb94ad66 100644 --- a/types/react-file-reader-input/index.d.ts +++ b/types/react-file-reader-input/index.d.ts @@ -2,7 +2,7 @@ // Project: https://www.npmjs.com/package/react-file-reader-input // Definitions by: Dmitry Rogozhny , Ali Taheri // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-flag-icon-css/index.d.ts b/types/react-flag-icon-css/index.d.ts new file mode 100644 index 0000000000..74c3e04efe --- /dev/null +++ b/types/react-flag-icon-css/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for react-flag-icon-css 1.0 +// Project: https://github.com/matteocng/react-flag-icon-css#readme +// Definitions by: Jon Freedman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as CSS from 'csstype'; +import { PureComponent, ReactNode } from 'react'; + +export type FlagIconSize = 'lg' | '2x' | '3x' | '4x' | '5x'; +export type FlagIconFlip = 'horizontal' | 'vertical'; +export type FlagIconRotate = 30 | 60 | 90 | 180 | 270; + +export interface FlagIconOptions { + /** + * Use CSS modules styles (your module bundler must be correctly setup). + */ + useCssModules?: boolean; + /** + * An object literal whose keys are your custom codes. + */ + customCodes?: { + [key: string]: string; + }; + /** + * Set this if useCssModules is true and a) you want to apply styles to FlagIcon + * using .theme-base and/or b) you are using custom flags. + */ + themeStyles?: { + [key: string]: CSS.Properties & CSS.PropertiesHyphen; + }; +} + +export interface FlagIconProps { + /** + * ISO 3166-1-alpha-2 code. + */ + code: string; + size?: FlagIconSize; + flip?: FlagIconFlip; + rotate?: FlagIconRotate; + Component?: string; + /** + * Uses the 1x1 image if true. + */ + squared?: boolean; + /** + * This is always appended as-is to class in the HTML. + */ + className?: string; + /** + * This is mapped to a CSS module and appended to class in the HTML. + */ + styleName?: string; + children?: ReactNode; +} + +export class FlagIcon extends PureComponent { +} + +export default function FlagIconFactory(react: any, opts?: Readonly): (props: FlagIconProps) => FlagIcon; + +export function CustomFlagIconFactory(react: any, opts?: Readonly): (props: FlagIconProps) => FlagIcon; diff --git a/types/react-flag-icon-css/package.json b/types/react-flag-icon-css/package.json new file mode 100644 index 0000000000..e6696d08e7 --- /dev/null +++ b/types/react-flag-icon-css/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "csstype": "^2.2.0" + } +} diff --git a/types/react-flag-icon-css/react-flag-icon-css-tests.tsx b/types/react-flag-icon-css/react-flag-icon-css-tests.tsx new file mode 100644 index 0000000000..5b656cff7b --- /dev/null +++ b/types/react-flag-icon-css/react-flag-icon-css-tests.tsx @@ -0,0 +1,88 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import FlagIconFactory, { CustomFlagIconFactory, FlagIconSize } from 'react-flag-icon-css'; + +const FlagIcon = FlagIconFactory(React, {useCssModules: false}); + +/** + * based on https://github.com/matteocng/react-flag-icon-css#basic-usage + */ +interface SimpleFlagComponentProps { + code: string; + size: FlagIconSize; +} + +export class SimpleFlagComponent extends React.PureComponent { + render() { + return ( + + ); + } +} + +const rootEL = document.getElementById('react-app') as HTMLElement; + +const appProps: SimpleFlagComponentProps = { + code: 'it', + size: '3x' +}; +ReactDOM.render(, rootEL); + +/** + * based on https://github.com/matteocng/react-flag-icon-css#exampleCustomFlagsIndex + */ +const styles = { + ['.flag-icon-ex1']: { + 'background-image': '../images/4x3/ex1.svg' + }, + ['.flag-icon-ex1.flag-icon-squared']: { + 'background-image': '../images/1x1/ex1.svg' + } +}; + +const codes = { + ex1: 'Example 1 country' +}; + +const optionsCssModules = {customCodes: codes, themeStyles: styles}; +const FlagIconCssModules = CustomFlagIconFactory(React, optionsCssModules); + +export class CustomFlagComponent extends React.PureComponent { + render() { + return ( + + ); + } +} + +const appCustomProps: SimpleFlagComponentProps = { + code: 'ex1', + size: 'lg' +}; +ReactDOM.render(, rootEL); + +/** + * based on 'props:children' test + */ +interface ChildrenFlagComponentProps { + code: string; + size: FlagIconSize; + children: React.ReactNode; +} + +export class ChildrenFlagComponent extends React.PureComponent { + render() { + return ( + + ); + } +} + +const appChildrenProps: ChildrenFlagComponentProps = { + code: 'ex1', + size: 'lg', + children: FlagIcon({ + code: 'it' + }) +}; +ReactDOM.render(, rootEL); diff --git a/types/react-flag-icon-css/tsconfig.json b/types/react-flag-icon-css/tsconfig.json new file mode 100644 index 0000000000..ac4affcceb --- /dev/null +++ b/types/react-flag-icon-css/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-flag-icon-css-tests.tsx" + ] +} diff --git a/types/react-flag-icon-css/tslint.json b/types/react-flag-icon-css/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/react-flag-icon-css/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/react-flags-select/index.d.ts b/types/react-flags-select/index.d.ts index df01a33ae4..e681e93877 100644 --- a/types/react-flags-select/index.d.ts +++ b/types/react-flags-select/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ekwonye-richard/react-flags-select#readme // Definitions by: Artur Sianiuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component } from 'react'; diff --git a/types/react-flatpickr/index.d.ts b/types/react-flatpickr/index.d.ts index 9683835e32..4586774568 100644 --- a/types/react-flatpickr/index.d.ts +++ b/types/react-flatpickr/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/coderhaoxin/react-flatpickr // Definitions by: begincalendar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component } from 'react'; import flatpickr from 'flatpickr'; diff --git a/types/react-flex/index.d.ts b/types/react-flex/index.d.ts index 50df2b6fb1..cb470bb89b 100644 --- a/types/react-flex/index.d.ts +++ b/types/react-flex/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/zippyui/react-flex // Definitions by: Jeffery Grajkowski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-flexr/index.d.ts b/types/react-flexr/index.d.ts index 31be71a93e..848dd24800 100644 --- a/types/react-flexr/index.d.ts +++ b/types/react-flexr/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/kodyl/react-flexr // Definitions by: Jeffery Grajkowski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-fontawesome/index.d.ts b/types/react-fontawesome/index.d.ts index 9fa93692b3..6c680ca907 100644 --- a/types/react-fontawesome/index.d.ts +++ b/types/react-fontawesome/index.d.ts @@ -5,7 +5,7 @@ // Vincas Stonys // Gavin Gregory // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-form/index.d.ts b/types/react-form/index.d.ts index 4ae175d83b..b0f14afd2e 100644 --- a/types/react-form/index.d.ts +++ b/types/react-form/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Cameron McAteer // Mathieu Masy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-form/v1/index.d.ts b/types/react-form/v1/index.d.ts index 41ca659a2d..0d4bdc6300 100644 --- a/types/react-form/v1/index.d.ts +++ b/types/react-form/v1/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/tannerlinsley/react-form#readme // Definitions by: Cameron McAteer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-gateway/index.d.ts b/types/react-gateway/index.d.ts index 7c90464019..d3e8f0b0e5 100644 --- a/types/react-gateway/index.d.ts +++ b/types/react-gateway/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/cloudflare/react-gateway // Definitions by: Jason Unger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import Gateway = require('./Gateway'); import { GatewayProps } from './Gateway'; diff --git a/types/react-geosuggest/index.d.ts b/types/react-geosuggest/index.d.ts index 2d31ba4d6d..6d5fd584f5 100644 --- a/types/react-geosuggest/index.d.ts +++ b/types/react-geosuggest/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ubilabs/react-geosuggest // Definitions by: Brad Menchl // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-google-maps-loader/index.d.ts b/types/react-google-maps-loader/index.d.ts index 1bea9e2a9c..6bb5978bd2 100644 --- a/types/react-google-maps-loader/index.d.ts +++ b/types/react-google-maps-loader/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/xuopled/react-google-maps-loader // Definitions by: Vasily Nesterov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// import { Component, ReactNode } from "react"; diff --git a/types/react-google-places-suggest/index.d.ts b/types/react-google-places-suggest/index.d.ts index d11139a911..5e7276974f 100644 --- a/types/react-google-places-suggest/index.d.ts +++ b/types/react-google-places-suggest/index.d.ts @@ -2,7 +2,7 @@ // Project: https://xuopled.github.io/react-google-places-suggest // Definitions by: Vasily Nesterov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// import { Component, ReactNode } from "react"; diff --git a/types/react-google-recaptcha/index.d.ts b/types/react-google-recaptcha/index.d.ts index 841b6440af..faeac20b4e 100644 --- a/types/react-google-recaptcha/index.d.ts +++ b/types/react-google-recaptcha/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/dozoisch/react-google-recaptcha // Definitions by: Koala Human // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-gravatar/index.d.ts b/types/react-gravatar/index.d.ts index e2418c2cf6..b2962edc8d 100644 --- a/types/react-gravatar/index.d.ts +++ b/types/react-gravatar/index.d.ts @@ -2,7 +2,7 @@ // Project: http://kyleamathews.github.io/react-gravatar/ // Definitions by: invliD // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-grid-layout/index.d.ts b/types/react-grid-layout/index.d.ts index ff25317a96..91c8ad1f9c 100644 --- a/types/react-grid-layout/index.d.ts +++ b/types/react-grid-layout/index.d.ts @@ -5,7 +5,7 @@ // Zheyang Song , // Andrew Hathaway // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-hamburger-menu/index.d.ts b/types/react-hamburger-menu/index.d.ts index c187a7ace3..c8ff0a1659 100644 --- a/types/react-hamburger-menu/index.d.ts +++ b/types/react-hamburger-menu/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/cameronbourke/react-hamburger-menu // Definitions by: Grzegorz Kielak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-helmet-async/index.d.ts b/types/react-helmet-async/index.d.ts index 1a240b075b..086ee1fcf0 100644 --- a/types/react-helmet-async/index.d.ts +++ b/types/react-helmet-async/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/staylor/react-helmet-async#readme // Definitions by: forabi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-helmet/index.d.ts b/types/react-helmet/index.d.ts index 93b83075fe..cecb86e12d 100644 --- a/types/react-helmet/index.d.ts +++ b/types/react-helmet/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/nfl/react-helmet // Definitions by: Evan Bremer , Isman Usoh , François Nguyen , Kok Sam , Yui T. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-helmet/v4/index.d.ts b/types/react-helmet/v4/index.d.ts index b9a813b432..4d1b0c699e 100644 --- a/types/react-helmet/v4/index.d.ts +++ b/types/react-helmet/v4/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/nfl/react-helmet // Definitions by: Evan Bremer , Isman Usoh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-highlight-words/index.d.ts b/types/react-highlight-words/index.d.ts index de71c72c17..19d5cc0960 100644 --- a/types/react-highlight-words/index.d.ts +++ b/types/react-highlight-words/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Mohamed Hegazy // Diogo Corrêa // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-highlight/index.d.ts b/types/react-highlight/index.d.ts index 2ab09ee3a9..715a25b23b 100644 --- a/types/react-highlight/index.d.ts +++ b/types/react-highlight/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/akiran/react-highlight // Definitions by: Josh Goldberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-highlighter/index.d.ts b/types/react-highlighter/index.d.ts index 022cdc911a..07a0d7b8ec 100644 --- a/types/react-highlighter/index.d.ts +++ b/types/react-highlighter/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/helior/react-highlighter // Definitions by: Pedro Pereira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-holder/index.d.ts b/types/react-holder/index.d.ts index 3fa3541786..3ab9d46182 100644 --- a/types/react-holder/index.d.ts +++ b/types/react-holder/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/Moeriki/react-holder // Definitions by: Isman Usoh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-hyperscript/index.d.ts b/types/react-hyperscript/index.d.ts index 09030de2a9..ee953d3892 100644 --- a/types/react-hyperscript/index.d.ts +++ b/types/react-hyperscript/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mlmorg/react-hyperscript // Definitions by: tock203 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { ComponentClass, StatelessComponent, ReactElement } from 'react'; diff --git a/types/react-i18next/index.d.ts b/types/react-i18next/index.d.ts index 3f019617c1..979c648f50 100644 --- a/types/react-i18next/index.d.ts +++ b/types/react-i18next/index.d.ts @@ -3,8 +3,9 @@ // Definitions by: Giedrius Grabauskas // Simon Baumann // Benedict Etzel +// Wu Haotian // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { TranslationFunction } from "i18next"; diff --git a/types/react-i18next/src/I18n.d.ts b/types/react-i18next/src/I18n.d.ts index 6bc1cf8f0f..91de868caf 100644 --- a/types/react-i18next/src/I18n.d.ts +++ b/types/react-i18next/src/I18n.d.ts @@ -15,7 +15,7 @@ export interface i18nProps { i18n?: i18n; initialI18nStore?: any; initialLanguage?: string; - children: (t: TranslationFunction, options: Options) => JSX.Element; + children: (t: TranslationFunction, options: Options) => React.ReactNode; } export default class I18n extends React.Component { } diff --git a/types/react-i18next/src/I18nextProvider.d.ts b/types/react-i18next/src/I18nextProvider.d.ts index 2cd4e333e3..2db5d0361b 100644 --- a/types/react-i18next/src/I18nextProvider.d.ts +++ b/types/react-i18next/src/I18nextProvider.d.ts @@ -6,7 +6,7 @@ export interface I18nextProviderProps { i18n: i18n; initialI18nStore?: any; initialLanguage?: string; - children: JSX.Element; + children: React.ReactNode; } export default class I18nextProvider extends React.Component { } diff --git a/types/react-i18next/src/trans.d.ts b/types/react-i18next/src/trans.d.ts index 3ef535cf5d..2b0e8e7738 100644 --- a/types/react-i18next/src/trans.d.ts +++ b/types/react-i18next/src/trans.d.ts @@ -19,6 +19,7 @@ export interface TransProps { defaults?: string; values?: Values; components?: React.ReactNode[]; + ns?: string; } export default class Trans extends React.Component { } diff --git a/types/react-i18next/test/react-i18next-tests.tsx b/types/react-i18next/test/react-i18next-tests.tsx index d3afe7643a..30b95ece24 100644 --- a/types/react-i18next/test/react-i18next-tests.tsx +++ b/types/react-i18next/test/react-i18next-tests.tsx @@ -107,6 +107,10 @@ class App extends React.Component { ; + + 123 +; + loadNamespaces({components: [App], i18n}).then(() => { }).catch(error => { }); @@ -182,6 +186,10 @@ interface CustomTranslateFunctionProps { } ; + + {t => '123'} +; + const defaults: ReactI18NextOptions = { wait: true, withRef: true, diff --git a/types/react-i18next/v1/index.d.ts b/types/react-i18next/v1/index.d.ts index 451e18c34a..0296da861c 100644 --- a/types/react-i18next/v1/index.d.ts +++ b/types/react-i18next/v1/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/i18next/react-i18next // Definitions by: Kostya Esmukov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as I18next from "i18next"; import * as React from "react"; diff --git a/types/react-i18next/v4/index.d.ts b/types/react-i18next/v4/index.d.ts index 6b87326975..14676aba7e 100644 --- a/types/react-i18next/v4/index.d.ts +++ b/types/react-i18next/v4/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/i18next/react-i18next // Definitions by: Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { TranslationFunction } from "i18next"; diff --git a/types/react-icon-base/index.d.ts b/types/react-icon-base/index.d.ts index 2103acc3c3..9264889f85 100644 --- a/types/react-icon-base/index.d.ts +++ b/types/react-icon-base/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/gorangajic/react-icon-base#readme // Definitions by: Alexandre Paré , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-icons/index.d.ts b/types/react-icons/index.d.ts index 93c531c3b4..e65de56b08 100644 --- a/types/react-icons/index.d.ts +++ b/types/react-icons/index.d.ts @@ -4,4 +4,4 @@ // John Reilly // Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 diff --git a/types/react-image-crop/index.d.ts b/types/react-image-crop/index.d.ts index afadc9d8ac..7f3637d093 100644 --- a/types/react-image-crop/index.d.ts +++ b/types/react-image-crop/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/DominicTobias/react-image-crop // Definitions by: Daniela Yassuda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, CSSProperties, ReactNode } from 'react'; diff --git a/types/react-image-gallery/index.d.ts b/types/react-image-gallery/index.d.ts index 45de6e4d0a..0082046763 100644 --- a/types/react-image-gallery/index.d.ts +++ b/types/react-image-gallery/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/xiaolin/react-image-gallery // Definitions by: Adam Webb // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-imageloader/index.d.ts b/types/react-imageloader/index.d.ts index bab7a49a34..6e569b1410 100644 --- a/types/react-imageloader/index.d.ts +++ b/types/react-imageloader/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/hzdg/react-imageloader // Definitions by: Stephen Jelfs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-infinite-calendar/index.d.ts b/types/react-infinite-calendar/index.d.ts index 0264c70d91..2110d4dbd0 100644 --- a/types/react-infinite-calendar/index.d.ts +++ b/types/react-infinite-calendar/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/clauderic/react-infinite-calendar // Definitions by: Christian Chown // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-infinite-scroll-component/index.d.ts b/types/react-infinite-scroll-component/index.d.ts index 4e2ba078f5..768ad1831b 100644 --- a/types/react-infinite-scroll-component/index.d.ts +++ b/types/react-infinite-scroll-component/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for react-infinite-scroll-component 4.1 +// Type definitions for react-infinite-scroll-component 4.2 // Project: https://github.com/ankeetmaini/react-infinite-scroll-component#readme // Definitions by: Stephanie Roy +// Bartosz Dotryw // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; @@ -61,9 +62,10 @@ declare namespace InfiniteScroll { releaseToRefreshContent?: boolean; /** - * A threshold value after that the InfiniteScroll will call next. By default it's 0.8. It means the next will be called when the user comes below 80% of the total height. + * A threshold value defining when InfiniteScroll will call next. Default value is 0.8. It means the next will be called when user comes below 80% of the total height. + * If you pass threshold in pixels (scrollThreshold="200px"), next will be called once you scroll at least (100% - scrollThreshold) pixels down. */ - scrollThreshold?: number; + scrollThreshold?: number | string; /** * A function that will listen to the scroll event on the scrolling container. Note that the scroll event is throttled, so you may not receive as many events as you would expect. diff --git a/types/react-infinite-scroller/index.d.ts b/types/react-infinite-scroller/index.d.ts index 066714344c..47c2166bc9 100644 --- a/types/react-infinite-scroller/index.d.ts +++ b/types/react-infinite-scroller/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Lauri Lavanti , // Piotr Srebniak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-infinite/index.d.ts b/types/react-infinite/index.d.ts index 80a2594464..e2149a8016 100644 --- a/types/react-infinite/index.d.ts +++ b/types/react-infinite/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/seatgeek/react-infinite // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-input-autosize/index.d.ts b/types/react-input-autosize/index.d.ts index f8f6f5b06f..0a86381736 100644 --- a/types/react-input-autosize/index.d.ts +++ b/types/react-input-autosize/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/JedWatson/react-input-autosize#readme // Definitions by: Jason Unger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.7 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-input-calendar/index.d.ts b/types/react-input-calendar/index.d.ts index c0e33783b4..09a7fe59b0 100644 --- a/types/react-input-calendar/index.d.ts +++ b/types/react-input-calendar/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/Rudeg/react-input-calendar // Definitions by: Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-input-mask/index.d.ts b/types/react-input-mask/index.d.ts index 13140b1cad..c09719f871 100644 --- a/types/react-input-mask/index.d.ts +++ b/types/react-input-mask/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/sanniassin/react-input-mask // Definitions by: Alexandre Paré // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-intl/index.d.ts b/types/react-intl/index.d.ts index d33b014e36..53b6de8a80 100644 --- a/types/react-intl/index.d.ts +++ b/types/react-intl/index.d.ts @@ -9,7 +9,7 @@ // Krister Kari // Martin Raedlinger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 declare namespace ReactIntl { type DateSource = Date | string | number; diff --git a/types/react-intl/react-intl-tests.tsx b/types/react-intl/react-intl-tests.tsx index 2ed6eb0d98..782c4de889 100644 --- a/types/react-intl/react-intl-tests.tsx +++ b/types/react-intl/react-intl-tests.tsx @@ -4,6 +4,7 @@ */ import * as React from "react"; +import * as PropTypes from "prop-types"; import * as reactMixin from "react-mixin"; import { @@ -63,8 +64,9 @@ const SomeFunctionalComponentWithIntl: React.ComponentClass }); class SomeComponent extends React.Component { - static propTypes: React.ValidationMap = { - intl: intlShape.isRequired + static propTypes: React.ValidationMap = { + intl: intlShape.isRequired, + className: PropTypes.string.isRequired }; render(): React.ReactElement<{}> { const intl = this.props.intl; diff --git a/types/react-intl/v1/index.d.ts b/types/react-intl/v1/index.d.ts index a891167f91..a5322844f3 100644 --- a/types/react-intl/v1/index.d.ts +++ b/types/react-intl/v1/index.d.ts @@ -2,7 +2,7 @@ // Project: http://formatjs.io/react/ // Definitions by: Bruno Grieder // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-is/index.d.ts b/types/react-is/index.d.ts index f088b1bcc9..b0a1fd1099 100644 --- a/types/react-is/index.d.ts +++ b/types/react-is/index.d.ts @@ -2,7 +2,7 @@ // Project: https://reactjs.org/ // Definitions by: Avi Vahl // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 export as namespace ReactIs; diff --git a/types/react-joyride/index.d.ts b/types/react-joyride/index.d.ts index 5f15d84d66..7cc118a2f0 100644 --- a/types/react-joyride/index.d.ts +++ b/types/react-joyride/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/gilbarbara/react-joyride // Definitions by: Daniel Rosenwasser , Ben Dixon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-js-pagination/index.d.ts b/types/react-js-pagination/index.d.ts index b4de877d79..00f1b26a64 100644 --- a/types/react-js-pagination/index.d.ts +++ b/types/react-js-pagination/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/vayser/react-js-pagination // Definitions by: Ernesto Cruz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.7 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-json-pretty/index.d.ts b/types/react-json-pretty/index.d.ts index 4229ff7c3b..a34cbca5df 100644 --- a/types/react-json-pretty/index.d.ts +++ b/types/react-json-pretty/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/chenckang/react-json-pretty // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { ComponentClass, HTMLProps } from "react"; diff --git a/types/react-json-tree/index.d.ts b/types/react-json-tree/index.d.ts index f275070a62..f32cc61521 100644 --- a/types/react-json-tree/index.d.ts +++ b/types/react-json-tree/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/alexkuz/react-json-tree/ // Definitions by: Grant Nestor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, diff --git a/types/react-json/index.d.ts b/types/react-json/index.d.ts index fa7eadeccc..a9ff7d6f8a 100644 --- a/types/react-json/index.d.ts +++ b/types/react-json/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/arqex/react-json // Definitions by: Christoph Spielmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-jsonschema-form/index.d.ts b/types/react-jsonschema-form/index.d.ts index ff061cfcdb..9a3b54fb4b 100644 --- a/types/react-jsonschema-form/index.d.ts +++ b/types/react-jsonschema-form/index.d.ts @@ -7,7 +7,7 @@ // Philippe Bourdages // Lucian Buzzo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 declare module "react-jsonschema-form" { import * as React from "react"; diff --git a/types/react-lazyload/index.d.ts b/types/react-lazyload/index.d.ts index a72fdd3581..3fd9b075e4 100644 --- a/types/react-lazyload/index.d.ts +++ b/types/react-lazyload/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/jasonslyvia/react-lazyload // Definitions by: m0a // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component } from "react"; diff --git a/types/react-lazylog/index.d.ts b/types/react-lazylog/index.d.ts index 57c7b623a1..7f180b425a 100644 --- a/types/react-lazylog/index.d.ts +++ b/types/react-lazylog/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mozilla-frontend-infra/react-lazylog // Definitions by: Benjamin Romano // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 export * from "./build/LazyLog"; export * from "./build/ScrollFollow"; diff --git a/types/react-list/index.d.ts b/types/react-list/index.d.ts index 77559988da..60beba5403 100644 --- a/types/react-list/index.d.ts +++ b/types/react-list/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/orgsync/react-list // Definitions by: Yifei Yan , Tom Shen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, diff --git a/types/react-loadable/index.d.ts b/types/react-loadable/index.d.ts index b673d9b480..b27a4de764 100644 --- a/types/react-loadable/index.d.ts +++ b/types/react-loadable/index.d.ts @@ -6,7 +6,7 @@ // Tomek Łaziuk // Ian Mobley // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-loader/index.d.ts b/types/react-loader/index.d.ts index 2d8f7a99a0..70fc957e2a 100644 --- a/types/react-loader/index.d.ts +++ b/types/react-loader/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/quickleft/react-loader // Definitions by: Sudarsan Balaji // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component } from 'react'; diff --git a/types/react-mailchimp-subscribe/index.d.ts b/types/react-mailchimp-subscribe/index.d.ts index 558c6a92cd..55b5c487ed 100644 --- a/types/react-mailchimp-subscribe/index.d.ts +++ b/types/react-mailchimp-subscribe/index.d.ts @@ -2,7 +2,7 @@ // Project: https://revolunet.github.io/react-mailchimp-subscribe/ // Definitions by: Omar Diab // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, ReactNode } from "react"; diff --git a/types/react-map-gl/index.d.ts b/types/react-map-gl/index.d.ts index 6209e66e81..2260644d32 100644 --- a/types/react-map-gl/index.d.ts +++ b/types/react-map-gl/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Robert Imig // Fabio Berta // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import * as MapboxGL from 'mapbox-gl'; diff --git a/types/react-maskedinput/index.d.ts b/types/react-maskedinput/index.d.ts index 3a1b4687eb..dc38064cab 100644 --- a/types/react-maskedinput/index.d.ts +++ b/types/react-maskedinput/index.d.ts @@ -4,7 +4,7 @@ // Adam Lavin // Carlos Bonetti // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-mce/index.d.ts b/types/react-mce/index.d.ts index 6f1fb978db..1db5f00286 100644 --- a/types/react-mce/index.d.ts +++ b/types/react-mce/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/janstuemmel/react-mce // Definitions by: Gavin Heise // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import * as ActualTinyMCE from 'tinymce'; diff --git a/types/react-mdl/index.d.ts b/types/react-mdl/index.d.ts index caf910d421..1b83bf7def 100644 --- a/types/react-mdl/index.d.ts +++ b/types/react-mdl/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/tleunen/react-mdl // Definitions by: Brad Zacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-measure/index.d.ts b/types/react-measure/index.d.ts index c61b22b187..9cd5853948 100644 --- a/types/react-measure/index.d.ts +++ b/types/react-measure/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/souporserious/react-measure // Definitions by: Alexey Svetliakov , Marc Fallows // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; @@ -46,7 +46,7 @@ export interface MeasuredComponentProps { type MeasuredComponent = React.ComponentType; -export interface MeasureProps { +export interface MeasureProps { client?: boolean; offset?: boolean; scroll?: boolean; @@ -60,5 +60,5 @@ export interface MeasureProps { export declare function withContentRect(types: ReadonlyArray | MeasurementType): (fn: MeasuredComponent) => React.ComponentType; -declare class Measure extends React.Component> {} +declare class Measure extends React.Component {} export default Measure; diff --git a/types/react-mixin/index.d.ts b/types/react-mixin/index.d.ts index 265794afe2..284d278ff8 100644 --- a/types/react-mixin/index.d.ts +++ b/types/react-mixin/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/brigand/react-mixin // Definitions by: Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-modal/index.d.ts b/types/react-modal/index.d.ts index 9dfbf7bdf7..237c725332 100644 --- a/types/react-modal/index.d.ts +++ b/types/react-modal/index.d.ts @@ -7,7 +7,7 @@ // Uwe Wiemer , // Peter Blazejewicz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-motion-slider/index.d.ts b/types/react-motion-slider/index.d.ts index 2e7ea921ef..a53ec42259 100644 --- a/types/react-motion-slider/index.d.ts +++ b/types/react-motion-slider/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/souporserious/react-motion-slider // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 declare module "react-motion-slider" { import * as React from "react"; diff --git a/types/react-motion-ui-pack/index.d.ts b/types/react-motion-ui-pack/index.d.ts index 0e0e518f70..477cf0e604 100644 --- a/types/react-motion-ui-pack/index.d.ts +++ b/types/react-motion-ui-pack/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/souporserious/react-motion-ui-pack // Definitions by: Jason Unger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import * as motion from 'react-motion'; diff --git a/types/react-motion/index.d.ts b/types/react-motion/index.d.ts index f4f94095a8..761c8e559f 100644 --- a/types/react-motion/index.d.ts +++ b/types/react-motion/index.d.ts @@ -4,7 +4,7 @@ // Alexey Svetliakov // Dimitar Nestorov // Definitions: https://github.com/borisyankov/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, ReactElement } from 'react'; diff --git a/types/react-native-android-taskdescription/index.d.ts b/types/react-native-android-taskdescription/index.d.ts index 0f395e91f2..172f47fe00 100644 --- a/types/react-native-android-taskdescription/index.d.ts +++ b/types/react-native-android-taskdescription/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/jwarby/react-native-android-taskdescription // Definitions by: Christian Chown // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-native-autocomplete-input/index.d.ts b/types/react-native-autocomplete-input/index.d.ts index f6c5f06eb6..9e39a47241 100644 --- a/types/react-native-autocomplete-input/index.d.ts +++ b/types/react-native-autocomplete-input/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/l-urence/react-native-autocomplete-input#readme // Definitions by: Ifiok Jr. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, ReactNode } from 'react'; import { diff --git a/types/react-native-bluetooth-serial/index.d.ts b/types/react-native-bluetooth-serial/index.d.ts index 8dc4d9c1a1..7dc49dcf83 100644 --- a/types/react-native-bluetooth-serial/index.d.ts +++ b/types/react-native-bluetooth-serial/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/rusel1989/react-native-bluetooth-serial // Definitions by: Rodrigo Weber // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; import * as ReactNative from "react-native"; diff --git a/types/react-native-calendars/index.d.ts b/types/react-native-calendars/index.d.ts new file mode 100644 index 0000000000..3784c1f628 --- /dev/null +++ b/types/react-native-calendars/index.d.ts @@ -0,0 +1,418 @@ +// Type definitions for react-native-calendars 1.20 +// Project: https://github.com/wix/react-native-calendars#readme +// Definitions by: Tyler Zhang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; +import { ViewProps, StyleProp } from 'react-native'; + +export interface DateObject { + year: number; + month: number; + day: number; + timestamp: number; + dateString: string; +} + +export interface CalendarTheme { + backgroundColor?: string; + calendarBackground?: string; + textSectionTitleColor?: string; + selectedDayBackgroundColor?: string; + selectedDayTextColor?: string; + todayTextColor?: string; + dayTextColor?: string; + textDisabledColor?: string; + dotColor?: string; + selectedDotColor?: string; + arrowColor?: string; + monthTextColor?: string; + textDayFontFamily?: string; + textMonthFontFamily?: string; + textDayHeaderFontFamily?: string; + textMonthFontWeight?: string; + textDayFontSize?: number; + textMonthFontSize?: number; + textDayHeaderFontSize?: number; +} + +export interface DayComponentProps { + state: '' | 'selected' | 'disabled' | 'today'; + theme: CalendarTheme; + onPress: () => any; + onLongPress: () => any; + date: DateObject; + marking: false | Marking[]; +} + +export interface CalendarBaseProps { + /** + * Styles for the view + */ + style?: StyleProp; + + /** + * Specify theme properties to override specific styles for calendar parts. Default = {} + */ + theme?: CalendarTheme; + + /** + * Initially visible month. Default = Date() + */ + current?: Date | string; + + /** + * Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + */ + minDate?: Date | string; + + /** + * Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + */ + maxDate?: Date | string; + + /** + * Handler which gets executed on day press. Default = undefined + */ + onDayPress?: (day: number) => void; + + /** + * Handler which gets executed on day long press. Default = undefined + */ + onDayLongPress?: (day: number) => void; + + /** + * Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + */ + monthFormat?: string; + + /** + * Handler which gets executed when visible month changes in calendar. Default = undefined + */ + onMonthChange?: (month: number) => void; + + /** + * Hide month navigation arrows. Default = false + */ + hideArrows?: boolean; + + /** + * Replace default arrows with custom ones (direction can be 'left' or 'right') + */ + renderArrow?: (direction: 'left' | 'right') => React.ReactNode; + + /** + * Do not show days of other months in month page. Default = false + */ + hideExtraDays?: boolean; + + /** + * If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + * day from another month that is visible in calendar page. Default = false + */ + disableMonthChange?: boolean; + + /** + * If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + */ + firstDay?: number; + + /** + * Hide day names. Default = false + */ + hideDayNames?: boolean; + + /** + * Show week numbers to the left. Default = false + */ + showWeekNumbers?: boolean; + + /** + * Handler which gets executed when press arrow icon left. It receive a callback can go back month + */ + onPressArrowLeft?: (month: number) => void; + + /** + * Handler which gets executed when press arrow icon left. It receive a callback can go next month + */ + onPressArrowRight?: (month: number) => void; + + /** + * Custom day renderer + */ + dayComponent?: React.Component | React.SFC; +} + +export interface DotForMultiDot { + key: string; + color: string; + selectedDotColor?: string; +} + +export interface MultiDotMarking { + dots: DotForMultiDot[]; + selected?: boolean; + selectedColor?: string; + disabled?: boolean; +} + +export interface DotMarking { + selected?: boolean; + marked?: boolean; + selectedColor?: string; + dotColor?: string; + activeOpacity?: number; + disabled?: boolean; + disableTouchEvent?: boolean; +} + +export interface PeriodMarking { + textColor?: string; + startingDay?: boolean; + color?: string; + selected?: boolean; + endingDay?: boolean; + disabled?: boolean; +} + +export interface MultiPeriodMarking { + periods: Array<{ + startingDay?: boolean; + endingDay?: boolean; + color?: string; + }>; +} + +export interface CustomMarking { + customStyles: any; +} + +export type Marking = + MultiDotMarking | + DotMarking | + PeriodMarking | + MultiPeriodMarking | + CustomMarking; + +export interface MultiDotMarkingProps { + markingType: 'multi-dot'; + markedDates: { + [date: string]: MultiDotMarking; + }; +} + +export interface DotMarkingProps { + markingType?: 'simple'; + markedDates: { + [date: string]: DotMarking; + }; +} + +export interface PeriodMarkingProps { + markingType: 'period'; + markedDates: { + [date: string]: PeriodMarking; + }; +} + +export interface CustomMarkingProps { + markingType: 'custom'; + markedDates: { + [date: string]: CustomMarking; + }; +} + +/** + * This type of marking is only fully supported by as it will expand the height + * of the component + */ +export interface MultiPeriodMarkingProps { + markingType: 'multi-period'; + markedDates: { + [date: string]: MultiPeriodMarking + }; +} + +export type CalendarMarkingProps = + MultiDotMarkingProps | + DotMarkingProps | + PeriodMarkingProps | + MultiPeriodMarkingProps | + CustomMarkingProps | + {}; + +export class Calendar extends React.Component {} + +export interface CalendarListBaseProps extends CalendarBaseProps { + /** + * Callback which gets executed when visible months change in scroll view. Default = undefined + */ + onVisibleMonthsChange?: (months: number) => void; + + /** + * Max amount of months allowed to scroll to the past. Default = 50 + */ + pastScrollRange?: number; + + /** + * Max amount of months allowed to scroll to the future. Default = 50 + */ + futureScrollRange?: number; + + /** + * Enable or disable scrolling of calendar list + */ + scrollEnabled?: boolean; + + /** + * Enable or disable vertical scroll indicator. Default = false + */ + showScrollIndicator?: boolean; + + /** + * Enable horizontal scrolling, default = false + */ + horizontal?: boolean; + + /** + * Enable paging on horizontal, default = false + */ + pagingEnabled?: boolean; + + /** + * Set custom calendarWidth. + */ + calendarWidth?: boolean; +} + +export class CalendarList extends React.Component {} + +export interface AgendaProps { + /** + * the list of items that have to be displayed in agenda. If you want to render item as empty date + * the value of date key kas to be an empty array []. If there exists no value for date key it is + * considered that the date in question is not yet loaded + */ + items: { + [key: string]: T[]; + }; + + /** + * callback that gets called when items for a certain month should be loaded (month became visible) + */ + loadItemsForMonth?: (date: DateObject) => void; + + /** + * callback that fires when the calendar is opened or closed + */ + onCalendarToggled?: (calendarOpened: boolean) => void; + + /** + * callback that gets called on day press + */ + onDayPress?: (day: number) => void; + + /** + * callback that gets called when day changes while scrolling agenda list + */ + onDayChange?: (day: number) => void; + + /** + * initially selected day + */ + selected?: Date | string; + + /** + * Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + */ + minDate?: Date | string; + + /** + * Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + */ + maxDate?: Date | string; + + /** + * Max amount of months allowed to scroll to the past. Default = 50 + */ + pastScrollRange?: number; + + /** + * Max amount of months allowed to scroll to the future. Default = 50 + */ + futureScrollRange?: number; + + /** + * specify how each item should be rendered in agenda + */ + renderItem: (item: T, firstItemInDay?: T) => React.ReactNode; + + /** + * specify how each date should be rendered. day can be undefined if the item is not first in that day. + */ + renderDay?: (day: DateObject | undefined, item: T) => React.ReactNode; + + /** + * specify how empty date content with no items should be rendered + */ + renderEmptyDate?: () => React.ReactNode; + + /** + * specify how agenda knob should look like + */ + renderKnob?: () => React.ReactNode; + + /** + * specify what should be rendered instead of ActivityIndicator + */ + renderEmptyData?: () => React.ReactNode; + + /** + * specify your item comparison function for increased performance + */ + rowHasChanged?: (r1: any, r2: any) => boolean; + + /** + * Hide knob button. Default = false + */ + hideKnob?: boolean; + + /** + * A RefreshControl component, used to provide pull-to-refresh funtionality for the ScrollView + */ + refreshControl?: React.ReactNode; + + /** + * If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. + * Make sure to also set the refreshing prop correctly. + */ + onRefresh?: () => any; + + /** + * Set this true while waiting for new data from a refresh + */ + refreshing?: boolean; + + /** + * Display loading indicator. Default = false + */ + displayLoadingIndicator?: boolean; + + /** + * agenda theme + */ + theme?: { + agendaDayTextColor?: string; + agendaDayNumColor?: string; + agendaTodayColor?: string; + agendaKnobColor?: string; + } & CalendarTheme; + + /** + * agenda container style + */ + style?: StyleProp; +} + +export class Agenda extends React.Component & CalendarMarkingProps> {} diff --git a/types/react-native-calendars/react-native-calendars-tests.tsx b/types/react-native-calendars/react-native-calendars-tests.tsx new file mode 100644 index 0000000000..5b438937e1 --- /dev/null +++ b/types/react-native-calendars/react-native-calendars-tests.tsx @@ -0,0 +1,374 @@ +import * as React from "react"; +import { Text, View } from "react-native"; +import { Calendar, CalendarList, Agenda } from "react-native-calendars"; + + { + console.log("selected day", day); + }} + // Handler which gets executed on day long press. Default = undefined + onDayLongPress={day => { + console.log("selected day", day); + }} + // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + monthFormat={"yyyy MM"} + // Handler which gets executed when visible month changes in calendar. Default = undefined + onMonthChange={month => { + console.log("month changed", month); + }} + // Hide month navigation arrows. Default = false + hideArrows={true} + // Replace default arrows with custom ones (direction can be 'left' or 'right') + renderArrow={direction =>
} + // Do not show days of other months in month page. Default = false + hideExtraDays={true} + // If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + // day from another month that is visible in calendar page. Default = false + disableMonthChange={true} + // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + firstDay={1} + // Hide day names. Default = false + hideDayNames={true} + // Show week numbers to the left. Default = false + showWeekNumbers={true} + // Handler which gets executed when press arrow icon left. It receive a callback can go back month + onPressArrowLeft={substractMonth => console.log(substractMonth)} + // Handler which gets executed when press arrow icon left. It receive a callback can go next month + onPressArrowRight={addMonth => console.log(addMonth)} +/>; + + { + console.log("selected day", day); + }} + // Handler which gets executed on day long press. Default = undefined + onDayLongPress={day => { + console.log("selected day", day); + }} + // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + monthFormat={"yyyy MM"} + // Handler which gets executed when visible month changes in calendar. Default = undefined + onMonthChange={month => { + console.log("month changed", month); + }} + // Hide month navigation arrows. Default = false + hideArrows={true} + // Replace default arrows with custom ones (direction can be 'left' or 'right') + renderArrow={direction =>
} + // Do not show days of other months in month page. Default = false + hideExtraDays={true} + // If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + // day from another month that is visible in calendar page. Default = false + disableMonthChange={true} + // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + firstDay={1} + // Hide day names. Default = false + hideDayNames={true} + // Show week numbers to the left. Default = false + showWeekNumbers={true} + // Handler which gets executed when press arrow icon left. It receive a callback can go back month + onPressArrowLeft={substractMonth => console.log(substractMonth)} + // Handler which gets executed when press arrow icon left. It receive a callback can go next month + onPressArrowRight={addMonth => console.log(addMonth)} + markedDates={{ + "2012-05-16": { selected: true, marked: true, selectedColor: "blue" }, + "2012-05-17": { marked: true }, + "2012-05-18": { marked: true, dotColor: "red", activeOpacity: 0 }, + "2012-05-19": { disabled: true, disableTouchEvent: true } + }} +/>; + +const vacation = { key: "vacation", color: "red", selectedDotColor: "blue" }; +const massage = { key: "massage", color: "blue", selectedDotColor: "blue" }; +const workout = { key: "workout", color: "green" }; + +; + +; + +; + +; + +; + + { + return ( + + + {date.day} + + + ); + }} +/>; + + { + console.log("now these months are visible", months); + }} + // Max amount of months allowed to scroll to the past. Default = 50 + pastScrollRange={50} + // Horizontal + horizontal={true} + // Max amount of months allowed to scroll to the future. Default = 50 + futureScrollRange={50} + // Enable or disable scrolling of calendar list + scrollEnabled={true} + // Enable or disable vertical scroll indicator. Default = false + showScrollIndicator={true} + // Initially visible month. Default = Date() + current={"2012-03-01"} + // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + minDate={"2012-05-10"} + // Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + maxDate={"2012-05-30"} + // Handler which gets executed on day press. Default = undefined + onDayPress={day => { + console.log("selected day", day); + }} + // Handler which gets executed on day long press. Default = undefined + onDayLongPress={day => { + console.log("selected day", day); + }} + // Month format in calendar title. Formatting values: http://arshaw.com/xdate/#Formatting + monthFormat={"yyyy MM"} + // Handler which gets executed when visible month changes in calendar. Default = undefined + onMonthChange={month => { + console.log("month changed", month); + }} + // Hide month navigation arrows. Default = false + hideArrows={true} + // Replace default arrows with custom ones (direction can be 'left' or 'right') + renderArrow={direction =>
} + // Do not show days of other months in month page. Default = false + hideExtraDays={true} + // If hideArrows=false and hideExtraDays=false do not switch month when tapping on greyed out + // day from another month that is visible in calendar page. Default = false + disableMonthChange={true} + // If firstDay=1 week starts from Monday. Note that dayNames and dayNamesShort should still start from Sunday. + firstDay={1} + // Hide day names. Default = false + hideDayNames={true} + // Show week numbers to the left. Default = false + showWeekNumbers={true} + // Handler which gets executed when press arrow icon left. It receive a callback can go back month + onPressArrowLeft={substractMonth => console.log(substractMonth)} + // Handler which gets executed when press arrow icon left. It receive a callback can go next month + onPressArrowRight={addMonth => console.log(addMonth)} +/>; + + { + console.log("trigger items loading"); + }} + // callback that fires when the calendar is opened or closed + onCalendarToggled={calendarOpened => { + console.log(calendarOpened); + }} + // callback that gets called on day press + onDayPress={day => { + console.log("day pressed"); + }} + // callback that gets called when day changes while scrolling agenda list + onDayChange={day => { + console.log("day changed"); + }} + // initially selected day + selected={"2012-05-16"} + // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined + minDate={"2012-05-10"} + // Maximum date that can be selected, dates after maxDate will be grayed out. Default = undefined + maxDate={"2012-05-30"} + // Max amount of months allowed to scroll to the past. Default = 50 + pastScrollRange={50} + // Max amount of months allowed to scroll to the future. Default = 50 + futureScrollRange={50} + // specify how each item should be rendered in agenda + renderItem={(item, firstItemInDay) => { + return ; + }} + // specify how each date should be rendered. day can be undefined if the item is not first in that day. + renderDay={(day, item) => { + return ; + }} + // specify how empty date content with no items should be rendered + renderEmptyDate={() => { + return ; + }} + // specify how agenda knob should look like + renderKnob={() => { + return ; + }} + // specify what should be rendered instead of ActivityIndicator + renderEmptyData={() => { + return ; + }} + // specify your item comparison function for increased performance + rowHasChanged={(r1, r2) => { + return r1.text !== r2.text; + }} + // Hide knob button. Default = false + hideKnob={true} + // By default, agenda dates are marked if they have at least one item, but you can override this if needed + markedDates={{ + "2012-05-16": { selected: true, marked: true }, + "2012-05-17": { marked: true }, + "2012-05-18": { disabled: true } + }} + // If provided, a standard RefreshControl will be added for "Pull to Refresh" functionality. Make sure to also set the refreshing prop correctly. + onRefresh={() => console.log("refreshing...")} + // Set this true while waiting for new data from a refresh + refreshing={false} + // Add a custom RefreshControl component, used to provide pull-to-refresh functionality for the ScrollView. + refreshControl={null} + // agenda theme + theme={{ + agendaDayTextColor: "yellow", + agendaDayNumColor: "green", + agendaTodayColor: "red", + agendaKnobColor: "blue" + }} + // agenda container style + style={{}} +/>; diff --git a/types/react-native-calendars/tsconfig.json b/types/react-native-calendars/tsconfig.json new file mode 100644 index 0000000000..e13f60597a --- /dev/null +++ b/types/react-native-calendars/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "react-native-calendars-tests.tsx" + ] +} diff --git a/types/react-native-calendars/tslint.json b/types/react-native-calendars/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-calendars/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-datepicker/index.d.ts b/types/react-native-datepicker/index.d.ts index dfc8bd5b13..929acdc375 100644 --- a/types/react-native-datepicker/index.d.ts +++ b/types/react-native-datepicker/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/xgfe/react-native-datepicker // Definitions by: Jacob Baskin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { ImageURISource } from 'react-native'; diff --git a/types/react-native-dialog/index.d.ts b/types/react-native-dialog/index.d.ts index 3a1cf94be9..10e977f420 100644 --- a/types/react-native-dialog/index.d.ts +++ b/types/react-native-dialog/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mmazzarolo/react-native-dialog // Definitions by: MrLuje // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Ref, PureComponent, ReactNode } from "react"; import { diff --git a/types/react-native-dialogflow/index.d.ts b/types/react-native-dialogflow/index.d.ts index c1b663ddb5..59ebff7cdf 100644 --- a/types/react-native-dialogflow/index.d.ts +++ b/types/react-native-dialogflow/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/innFactory/react-native-dialogflow#readme // Definitions by: Jason Merino // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 export namespace Dialogflow { const LANG_CHINESE_CHINA = 'zh-CN'; diff --git a/types/react-native-doc-viewer/index.d.ts b/types/react-native-doc-viewer/index.d.ts index 6d09e3966a..f7e28147b7 100644 --- a/types/react-native-doc-viewer/index.d.ts +++ b/types/react-native-doc-viewer/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/philipphecht/react-native-doc-viewer/blob/master/README.md // Definitions by: Kyle Roach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 export function openDoc( files: Array<{ url: string; fileName?: string }>, diff --git a/types/react-native-drawer-layout/index.d.ts b/types/react-native-drawer-layout/index.d.ts index af3a05698e..3bf4ace1db 100644 --- a/types/react-native-drawer-layout/index.d.ts +++ b/types/react-native-drawer-layout/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/react-native-community/react-native-drawer-layout // Definitions by: Justin Firth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { ViewProps } from 'react-native'; diff --git a/types/react-native-drawer/index.d.ts b/types/react-native-drawer/index.d.ts index 3a82e3363a..da3420b9a7 100644 --- a/types/react-native-drawer/index.d.ts +++ b/types/react-native-drawer/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: jnbt // suniahk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { ViewStyle, ScaledSize } from 'react-native'; diff --git a/types/react-native-elevated-view/index.d.ts b/types/react-native-elevated-view/index.d.ts index e9ac2b1103..7c538a4742 100644 --- a/types/react-native-elevated-view/index.d.ts +++ b/types/react-native-elevated-view/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/alekhurst/react-native-elevated-view // Definitions by: fhelwanger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import * as ReactNative from 'react-native'; diff --git a/types/react-native-fbsdk/index.d.ts b/types/react-native-fbsdk/index.d.ts index 8b948d6b0d..eacc05209e 100644 --- a/types/react-native-fbsdk/index.d.ts +++ b/types/react-native-fbsdk/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/facebook/react-native-fbsdk // Definitions by: Ifiok Jr. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { ComponentClass, Component } from 'react'; import { ViewStyle } from 'react-native'; diff --git a/types/react-native-fs/index.d.ts b/types/react-native-fs/index.d.ts index 17f26a5514..6c92933c44 100644 --- a/types/react-native-fs/index.d.ts +++ b/types/react-native-fs/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Paulo Cesar // Joseph Roque // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-native-google-signin/index.d.ts b/types/react-native-google-signin/index.d.ts index 862a40a35a..6cf83ed1e4 100644 --- a/types/react-native-google-signin/index.d.ts +++ b/types/react-native-google-signin/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/devfd/react-native-google-signin // Definitions by: Jacob Froman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { ViewProps } from 'react-native'; diff --git a/types/react-native-htmlview/index.d.ts b/types/react-native-htmlview/index.d.ts index b0eb2ae6a3..0f2b9d661d 100644 --- a/types/react-native-htmlview/index.d.ts +++ b/types/react-native-htmlview/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/jsdf/react-native-htmlview // Definitions by: Ifiok Jr. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, ComponentType, ReactNode } from 'react'; import { diff --git a/types/react-native-indicators/index.d.ts b/types/react-native-indicators/index.d.ts index ee4a13a4c2..1a732d8cee 100644 --- a/types/react-native-indicators/index.d.ts +++ b/types/react-native-indicators/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/n4kz/react-native-indicators#readme // Definitions by: Ifiok Jr. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component } from 'react'; import { Animated, EasingFunction } from 'react-native'; diff --git a/types/react-native-keep-awake/index.d.ts b/types/react-native-keep-awake/index.d.ts index f22d1342c6..c717e83ba3 100644 --- a/types/react-native-keep-awake/index.d.ts +++ b/types/react-native-keep-awake/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/corbt/react-native-keep-awake // Definitions by: huhuanming // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; declare class KeepAwake extends React.Component<{ children?: JSX.Element }> { diff --git a/types/react-native-keyboard-spacer/index.d.ts b/types/react-native-keyboard-spacer/index.d.ts index 0c7ec24262..49ad68de41 100644 --- a/types/react-native-keyboard-spacer/index.d.ts +++ b/types/react-native-keyboard-spacer/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/Andr3wHur5t/react-native-keyboard-spacer#readme // Definitions by: Vincent Langlet // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import * as ReactNative from 'react-native'; diff --git a/types/react-native-loading-spinner-overlay/index.d.ts b/types/react-native-loading-spinner-overlay/index.d.ts index 93d511d863..aa494b5fd4 100644 --- a/types/react-native-loading-spinner-overlay/index.d.ts +++ b/types/react-native-loading-spinner-overlay/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/joinspontaneous/react-native-loading-spinner-overlay // Definitions by: fhelwanger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; import * as ReactNative from "react-native"; diff --git a/types/react-native-material-design-searchbar/index.d.ts b/types/react-native-material-design-searchbar/index.d.ts index 23b3204c76..ed9534a38c 100644 --- a/types/react-native-material-design-searchbar/index.d.ts +++ b/types/react-native-material-design-searchbar/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ananddayalan/react-native-material-design-searchbar // Definitions by: Kyle Roach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { diff --git a/types/react-native-material-kit/index.d.ts b/types/react-native-material-kit/index.d.ts index f820d8e4cd..48c044a629 100644 --- a/types/react-native-material-kit/index.d.ts +++ b/types/react-native-material-kit/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Kyle Roach // Tim Wang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { diff --git a/types/react-native-material-textfield/index.d.ts b/types/react-native-material-textfield/index.d.ts index 5f3ffc437f..c21caa15b4 100644 --- a/types/react-native-material-textfield/index.d.ts +++ b/types/react-native-material-textfield/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Ville Venäläinen // Kyle Roach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { diff --git a/types/react-native-material-ui/index.d.ts b/types/react-native-material-ui/index.d.ts index 3c4c549504..8bb86d3cc3 100644 --- a/types/react-native-material-ui/index.d.ts +++ b/types/react-native-material-ui/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/xotahal/react-native-material-ui // Definitions by: Kyle Roach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component } from 'react'; import { ViewStyle, TextStyle, Image } from 'react-native'; diff --git a/types/react-native-modalbox/index.d.ts b/types/react-native-modalbox/index.d.ts index 84461471f2..778f953f78 100644 --- a/types/react-native-modalbox/index.d.ts +++ b/types/react-native-modalbox/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/maxs15/react-native-modalbox#readme // Definitions by: Kyle Roach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { StyleProp, ViewStyle } from 'react-native'; diff --git a/types/react-native-multi-slider/index.d.ts b/types/react-native-multi-slider/index.d.ts index a3a5f39c63..42d4856938 100644 --- a/types/react-native-multi-slider/index.d.ts +++ b/types/react-native-multi-slider/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/JackDanielsAndCode/react-native-multi-slider#readme // Definitions by: Edward Sammut Alessi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; import { ViewStyle } from "react-native"; diff --git a/types/react-native-navbar/index.d.ts b/types/react-native-navbar/index.d.ts index 5c21ea38e8..afcd7df3ed 100644 --- a/types/react-native-navbar/index.d.ts +++ b/types/react-native-navbar/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/react-native-community/react-native-navbar // Definitions by: Ryo Kikuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { ViewStyle, TextProps } from 'react-native'; diff --git a/types/react-native-photo-view/index.d.ts b/types/react-native-photo-view/index.d.ts index c3f27d78a6..c104b1c0e5 100644 --- a/types/react-native-photo-view/index.d.ts +++ b/types/react-native-photo-view/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/alwx/react-native-photo-view // Definitions by: Christian Chown // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { ImageSourcePropType, ViewProps } from 'react-native'; diff --git a/types/react-native-popup-dialog/index.d.ts b/types/react-native-popup-dialog/index.d.ts index 5ddb40e0b2..3ff12802f4 100644 --- a/types/react-native-popup-dialog/index.d.ts +++ b/types/react-native-popup-dialog/index.d.ts @@ -4,7 +4,7 @@ // connectdotz // Michele Bombardi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { GestureResponderEvent, StyleProp, ViewStyle, TextStyle } from 'react-native'; diff --git a/types/react-native-qrcode/index.d.ts b/types/react-native-qrcode/index.d.ts index 7c745aa1b6..97709c5792 100644 --- a/types/react-native-qrcode/index.d.ts +++ b/types/react-native-qrcode/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/cssivision/react-native-qrcode // Definitions by: York Yao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-native-safari-view/index.d.ts b/types/react-native-safari-view/index.d.ts index 658a6664ce..77b8aa15e8 100644 --- a/types/react-native-safari-view/index.d.ts +++ b/types/react-native-safari-view/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/naoufal/react-native-safari-view // Definitions by: Michael Randolph // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { EmitterSubscription } from 'react-native'; diff --git a/types/react-native-scrollable-tab-view/index.d.ts b/types/react-native-scrollable-tab-view/index.d.ts index 962ba8a810..9be23aa66c 100644 --- a/types/react-native-scrollable-tab-view/index.d.ts +++ b/types/react-native-scrollable-tab-view/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: CaiHuan // Egor Shulga // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { Animated, ScrollViewProps, ViewStyle, TextStyle } from 'react-native'; diff --git a/types/react-native-sensor-manager/index.d.ts b/types/react-native-sensor-manager/index.d.ts index 0b0f0bf67a..9c25be10ba 100644 --- a/types/react-native-sensor-manager/index.d.ts +++ b/types/react-native-sensor-manager/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/kprimice/react-native-sensor-manager // Definitions by: Sahin Vardar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-native-settings-list/index.d.ts b/types/react-native-settings-list/index.d.ts index 0ba14c9562..e04b856296 100644 --- a/types/react-native-settings-list/index.d.ts +++ b/types/react-native-settings-list/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/evetstech/react-native-settings-list // Definitions by: MrLuje // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, ReactNode } from "react"; import { TextStyle, StyleProp, ImageStyle, ViewStyle } from "react-native"; diff --git a/types/react-native-snap-carousel/index.d.ts b/types/react-native-snap-carousel/index.d.ts index 56b083638b..3c630bc094 100644 --- a/types/react-native-snap-carousel/index.d.ts +++ b/types/react-native-snap-carousel/index.d.ts @@ -4,7 +4,7 @@ // Jacob Froman // Nikolay Polukhin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { diff --git a/types/react-native-sortable-grid/index.d.ts b/types/react-native-sortable-grid/index.d.ts index 392e9b1b01..0551d56efe 100644 --- a/types/react-native-sortable-grid/index.d.ts +++ b/types/react-native-sortable-grid/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ollija/react-native-sortable-grid#readme // Definitions by: Jacob Froman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { StyleProp, ViewStyle, Animated } from 'react-native'; diff --git a/types/react-native-sortable-list/index.d.ts b/types/react-native-sortable-list/index.d.ts index d5466c8f68..65b34ce62f 100755 --- a/types/react-native-sortable-list/index.d.ts +++ b/types/react-native-sortable-list/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/gitim/react-native-sortable-list // Definitions by: Michael Sivolobov , Vince Maiuri // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { ViewStyle } from 'react-native'; diff --git a/types/react-native-star-rating/index.d.ts b/types/react-native-star-rating/index.d.ts index 2285134c8f..a26002bf88 100644 --- a/types/react-native-star-rating/index.d.ts +++ b/types/react-native-star-rating/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/djchie/react-native-star-rating // Definitions by: iRoachie // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { ImageURISource, StyleProp, ViewStyle } from 'react-native'; diff --git a/types/react-native-svg-uri/index.d.ts b/types/react-native-svg-uri/index.d.ts index 4529c53d5e..a47550bced 100644 --- a/types/react-native-svg-uri/index.d.ts +++ b/types/react-native-svg-uri/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/matiascba/react-native-svg-uri#readme // Definitions by: Kyle Roach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { ImageURISource } from 'react-native'; diff --git a/types/react-native-swiper/index.d.ts b/types/react-native-swiper/index.d.ts index c6616aea0c..a201bcd00b 100644 --- a/types/react-native-swiper/index.d.ts +++ b/types/react-native-swiper/index.d.ts @@ -4,7 +4,7 @@ // HuHuanming // mhcgrq // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { diff --git a/types/react-native-tab-navigator/index.d.ts b/types/react-native-tab-navigator/index.d.ts index 1f4e5e5437..1586b7279a 100644 --- a/types/react-native-tab-navigator/index.d.ts +++ b/types/react-native-tab-navigator/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/exponentjs/react-native-tab-navigator#readme // Definitions by: My Self // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { ViewStyle, TextStyle } from 'react-native'; diff --git a/types/react-native-tab-view/index.d.ts b/types/react-native-tab-view/index.d.ts index 0e5ee892ce..078247e97d 100644 --- a/types/react-native-tab-view/index.d.ts +++ b/types/react-native-tab-view/index.d.ts @@ -4,7 +4,7 @@ // Kyle Roach // Tim Wang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { PureComponent, ReactNode, ComponentType } from 'react' import { Animated, diff --git a/types/react-native-text-input-mask/index.d.ts b/types/react-native-text-input-mask/index.d.ts index 33505ccc54..4cf4b392dc 100644 --- a/types/react-native-text-input-mask/index.d.ts +++ b/types/react-native-text-input-mask/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/react-native-community/react-native-text-input-mask // Definitions by: Rodrigo Weber // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; import * as ReactNative from "react-native"; diff --git a/types/react-native-toast-native/index.d.ts b/types/react-native-toast-native/index.d.ts index 130614290b..6240441781 100644 --- a/types/react-native-toast-native/index.d.ts +++ b/types/react-native-toast-native/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/onemolegames/react-native-toast-native/blob/master/README.md // Definitions by: Michele Bombardi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Platform } from 'react-native'; diff --git a/types/react-native-vector-icons/index.d.ts b/types/react-native-vector-icons/index.d.ts index 60e6408d18..6aabaadd70 100644 --- a/types/react-native-vector-icons/index.d.ts +++ b/types/react-native-vector-icons/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Kyle Roach // Tim Wang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { Icon } from './Icon'; diff --git a/types/react-native-video/index.d.ts b/types/react-native-video/index.d.ts index 25a58a3e00..e84bcc7637 100644 --- a/types/react-native-video/index.d.ts +++ b/types/react-native-video/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/react-native-community/react-native-video // Definitions by: HuHuanming // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { @@ -67,6 +67,7 @@ export interface VideoProperties extends ViewProps { controls?: boolean; currentTime?: number; progressUpdateInterval?: number; + useTextureView?: boolean; onLoadStart?(): void; onLoad?(data: OnLoadData): void; onBuffer?(): void; diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 2d3337c96d..aff434f277 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -12,7 +12,7 @@ // Tanguy Krotoff // Alexander T. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // @@ -1009,6 +1009,54 @@ export interface TextInputIOSProps { * If false, disables spell-check style (i.e. red underlines). The default value is inherited from autoCorrect */ spellCheck?: boolean; + + + /** + * Give the keyboard and the system information about the expected + * semantic meaning for the content that users enter. + * + * For iOS 11+ you can set `textContentType` to `username` or `password` to + * enable autofill of login details from the device keychain. + * + * To disable autofill, set textContentType to `none`. + * + * Possible values for `textContentType` are: + * + * - `'none'` + * - `'URL'` + * - `'addressCity'` + * - `'addressCityAndState'` + * - `'addressState'` + * - `'countryName'` + * - `'creditCardNumber'` + * - `'emailAddress'` + * - `'familyName'` + * - `'fullStreetAddress'` + * - `'givenName'` + * - `'jobTitle'` + * - `'location'` + * - `'middleName'` + * - `'name'` + * - `'namePrefix'` + * - `'nameSuffix'` + * - `'nickname'` + * - `'organizationName'` + * - `'postalCode'` + * - `'streetAddressLine1'` + * - `'streetAddressLine2'` + * - `'sublocality'` + * - `'telephoneNumber'` + * - `'username'` + * - `'password'` + * + */ + textContentType?: "none" | "URL" | "addressCity" | "addressCityAndState" | + "addressState" | "countryName" | "creditCardNumber" | "emailAddress" | + "familyName" | "fullStreetAddress" | "givenName" | "jobTitle" | + "location" | "middleName" | "name" | "namePrefix" | "nameSuffix" | + "nickname" | "organizationName" | "postalCode" | "streetAddressLine1" | + "streetAddressLine2" | "sublocality" | "telephoneNumber" | "username" | + "password"; } /** diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 818be960c7..4921847c2b 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -547,6 +547,7 @@ class TextInputTest extends React.Component<{}, {username: string}> { this.username = input} + textContentType="username" value={this.state.username} onChangeText={this.handleUsernameChange} /> diff --git a/types/react-navigation-material-bottom-tabs/index.d.ts b/types/react-navigation-material-bottom-tabs/index.d.ts new file mode 100644 index 0000000000..e9938c7bb4 --- /dev/null +++ b/types/react-navigation-material-bottom-tabs/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for react-navigation-material-bottom-tabs 0.3 +// Project: https://github.com/react-navigation/react-navigation-material-bottom-tab-navigator#readme +// Definitions by: Kyle Roach +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { StyleProp, TextStyle, ViewStyle } from 'react-native'; +import { + NavigationContainer, + NavigationPathsConfig, + NavigationRouteConfigMap +} from 'react-navigation'; + +export interface TabConfig { + shifting?: boolean; + labeled?: boolean; + activeTintColor?: string; + inactiveTintColor?: string; + barStyle?: StyleProp; + initialRouteName?: string; + order?: string[]; + paths?: NavigationPathsConfig; + backBehavior?: 'initialRoute' | 'none'; +} + +export function createMaterialBottomTabNavigator( + routeConfigMap: NavigationRouteConfigMap, + config?: TabConfig +): NavigationContainer; diff --git a/types/react-navigation-material-bottom-tabs/react-navigation-material-bottom-tabs-tests.tsx b/types/react-navigation-material-bottom-tabs/react-navigation-material-bottom-tabs-tests.tsx new file mode 100644 index 0000000000..a0d84f12f1 --- /dev/null +++ b/types/react-navigation-material-bottom-tabs/react-navigation-material-bottom-tabs-tests.tsx @@ -0,0 +1,29 @@ +import * as React from 'react'; +import { View } from 'react-native'; +import { createMaterialBottomTabNavigator } from 'react-navigation-material-bottom-tabs'; + +const Tab1 = () => ; +const Tab2 = () => ; + +export default createMaterialBottomTabNavigator( + { + tab1: { + screen: Tab1 + }, + tab2: { + screen: Tab2 + } + }, + { + activeTintColor: 'blue', + inactiveTintColor: 'red', + labeled: false, + barStyle: { + backgroundColor: '#fff' + }, + shifting: false, + initialRouteName: 'tab2', + order: ['tab2', 'tab1'], + backBehavior: 'none' + } +); diff --git a/types/react-navigation-material-bottom-tabs/tsconfig.json b/types/react-navigation-material-bottom-tabs/tsconfig.json new file mode 100644 index 0000000000..3e6dd8c735 --- /dev/null +++ b/types/react-navigation-material-bottom-tabs/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react-native", + "strictFunctionTypes": true + }, + "files": ["index.d.ts", "react-navigation-material-bottom-tabs-tests.tsx"] +} diff --git a/types/react-navigation-material-bottom-tabs/tslint.json b/types/react-navigation-material-bottom-tabs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-navigation-material-bottom-tabs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index a736473054..6e286c2217 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -20,8 +20,9 @@ // Luca Campana // Ullrich Schaefer // Yosuke Seki +// Jake // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /** * Reference: https://github.com/react-navigation/react-navigation/tree/a37473c5e4833f48796ee6c7c9cb4a8ac49d9c06 @@ -442,6 +443,7 @@ export type NavigationStackAction = | NavigationBackAction | NavigationSetParamsAction | NavigationResetAction + | NavigationReplaceAction | NavigationPopAction | NavigationPushAction | NavigationPopToTopAction; diff --git a/types/react-navigation/v1/index.d.ts b/types/react-navigation/v1/index.d.ts index 1233ca39e3..16779c4e4e 100644 --- a/types/react-navigation/v1/index.d.ts +++ b/types/react-navigation/v1/index.d.ts @@ -17,7 +17,7 @@ // Ciaran Liedeman // Edward Sammut Alessi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /** * Reference: https://github.com/react-navigation/react-navigation/tree/3f3ef6485c8932f49fddc3dd2c508629110bf2b6 diff --git a/types/react-no-ssr/index.d.ts b/types/react-no-ssr/index.d.ts new file mode 100644 index 0000000000..9ca00149d0 --- /dev/null +++ b/types/react-no-ssr/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for react-no-ssr 1.1 +// Project: https://github.com/kadirahq/react-no-ssr +// Definitions by: Rafał Filipek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +export default class NoSSR extends React.Component<{ + onSSR?: React.ReactChild; +}> {} diff --git a/types/react-no-ssr/react-no-ssr-tests.tsx b/types/react-no-ssr/react-no-ssr-tests.tsx new file mode 100644 index 0000000000..62ad9b1989 --- /dev/null +++ b/types/react-no-ssr/react-no-ssr-tests.tsx @@ -0,0 +1,17 @@ +import * as React from 'react'; +import NoSSR from 'react-no-ssr'; + +export class NoSSRTest extends React.Component { + render() { + return ( +
+ +
+ + }> +
+ +
+ ); + } +} diff --git a/types/react-no-ssr/tsconfig.json b/types/react-no-ssr/tsconfig.json new file mode 100644 index 0000000000..23e59891d8 --- /dev/null +++ b/types/react-no-ssr/tsconfig.json @@ -0,0 +1,18 @@ +{ + "files": ["index.d.ts", "react-no-ssr-tests.tsx"], + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "experimentalDecorators": true, + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/react-no-ssr/tslint.json b/types/react-no-ssr/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-no-ssr/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-notification-system-redux/index.d.ts b/types/react-notification-system-redux/index.d.ts index d74ea35871..701bde55cf 100644 --- a/types/react-notification-system-redux/index.d.ts +++ b/types/react-notification-system-redux/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/gor181/react-notification-system-redux // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component } from "react"; import { Action } from "redux"; diff --git a/types/react-notification-system/index.d.ts b/types/react-notification-system/index.d.ts index a993f6cc4d..d172cd6b2c 100644 --- a/types/react-notification-system/index.d.ts +++ b/types/react-notification-system/index.d.ts @@ -2,7 +2,7 @@ // Project: https://www.npmjs.com/package/react-notification-system // Definitions by: Giedrius Grabauskas , Deividas Bakanas , Karol Janyst , Bartosz Szewczyk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-notify-toast/index.d.ts b/types/react-notify-toast/index.d.ts index 689d543ce8..1feb26ef61 100644 --- a/types/react-notify-toast/index.d.ts +++ b/types/react-notify-toast/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/jesusoterogomez/react-notify-toast // Definitions by: Klaas Cuvelier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-numeric-input/index.d.ts b/types/react-numeric-input/index.d.ts index b10a54cfe3..bc28d95825 100644 --- a/types/react-numeric-input/index.d.ts +++ b/types/react-numeric-input/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/vlad-ignatov/react-numeric-input#readme // Definitions by: Heather Booker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-onclickoutside/index.d.ts b/types/react-onclickoutside/index.d.ts index d97970642f..2fb5659029 100644 --- a/types/react-onclickoutside/index.d.ts +++ b/types/react-onclickoutside/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/Pomax/react-onclickoutside // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-onclickoutside/v5/index.d.ts b/types/react-onclickoutside/v5/index.d.ts index 4228697e22..82b4b21a25 100644 --- a/types/react-onclickoutside/v5/index.d.ts +++ b/types/react-onclickoutside/v5/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/Pomax/react-onclickoutside // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-onsenui/index.d.ts b/types/react-onsenui/index.d.ts index 91055d25b4..39722faa7c 100644 --- a/types/react-onsenui/index.d.ts +++ b/types/react-onsenui/index.d.ts @@ -2,7 +2,7 @@ // Project: https://onsen.io/v2/docs/guide/react/ // Definitions by: Ozytis , Salim , Jemmyw // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import Component = React.Component; diff --git a/types/react-overlays/index.d.ts b/types/react-overlays/index.d.ts index 99df3b3cbd..a8df0341be 100644 --- a/types/react-overlays/index.d.ts +++ b/types/react-overlays/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Aaron Beall // Vito Samson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-owl-carousel/index.d.ts b/types/react-owl-carousel/index.d.ts index bcd9af38b5..365ea39598 100644 --- a/types/react-owl-carousel/index.d.ts +++ b/types/react-owl-carousel/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/seal789ie/react-owl-carousel // Definitions by: T Bounsiar , Ismael Gorissen , Kenneth Ceyer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-paginate/index.d.ts b/types/react-paginate/index.d.ts index 0030028055..83d8c476c9 100644 --- a/types/react-paginate/index.d.ts +++ b/types/react-paginate/index.d.ts @@ -5,7 +5,7 @@ // pegel03 // Simon Archer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-places-autocomplete/index.d.ts b/types/react-places-autocomplete/index.d.ts index f05820bbce..62e3d93a1d 100644 --- a/types/react-places-autocomplete/index.d.ts +++ b/types/react-places-autocomplete/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Guilherme Hübner // Andrew Makarov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 // /// diff --git a/types/react-plotly.js/index.d.ts b/types/react-plotly.js/index.d.ts index ac24016496..4dfc3b0ce3 100644 --- a/types/react-plotly.js/index.d.ts +++ b/types/react-plotly.js/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/plotly/react-plotly.js#readme // Definitions by: Jon Freedman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as Plotly from 'plotly.js'; import * as React from 'react'; diff --git a/types/react-pointable/index.d.ts b/types/react-pointable/index.d.ts index 0b83bdeb1d..9c0828fc76 100644 --- a/types/react-pointable/index.d.ts +++ b/types/react-pointable/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Stefan Fochler // Dibyo Majumdar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-popover/index.d.ts b/types/react-popover/index.d.ts index fed9c4c32d..a7bc435d2e 100644 --- a/types/react-popover/index.d.ts +++ b/types/react-popover/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/littlebits/react-popover // Definitions by: Jakub Řičař // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-portal/index.d.ts b/types/react-portal/index.d.ts index 7595c5e8ad..5faff72d87 100644 --- a/types/react-portal/index.d.ts +++ b/types/react-portal/index.d.ts @@ -1,25 +1,35 @@ -// Type definitions for react-portal 3.0 +// Type definitions for react-portal 4.0 // Project: https://github.com/tajo/react-portal#readme // Definitions by: Shun Takahashi +// Horus Lugo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; -interface CallBackProps extends React.Props { - closePortal(): void; +export interface PortalProps extends React.Props { + children: React.ReactNode; + node?: Element | null; } -interface ReactPortalProps { - isOpened?: boolean; - openByClickOn?: React.ReactElement; +export const Portal: React.ComponentClass; + +export interface PortalFunctionParams { + openPortal: (event?: any) => void; + closePortal: () => void; + portal: (children: React.ReactNode) => React.ReactElement>; + isOpen: boolean; +} + +export interface PortalWithStateProps extends React.Props { + children: (params: PortalFunctionParams) => React.ReactNode; + node?: Element | null; + defaultOpen?: boolean; + openByClickOn?: React.ReactElement; closeOnEsc?: boolean; closeOnOutsideClick?: boolean; - onOpen?(node: HTMLDivElement): void; - beforeClose?(node: HTMLDivElement, resetPortalState: () => void): void; + onOpen?(): void; onClose?(): void; - onUpdate?(): void; } -declare const ReactPortal: React.ComponentClass; -export = ReactPortal; +export const PortalWithState: React.ComponentClass; diff --git a/types/react-portal/react-portal-tests.tsx b/types/react-portal/react-portal-tests.tsx index 5313b101bd..7ee7183e45 100644 --- a/types/react-portal/react-portal-tests.tsx +++ b/types/react-portal/react-portal-tests.tsx @@ -1,44 +1,79 @@ // Example from https://github.com/tajo/react-portal -import * as React from "react"; -import * as ReactDOM from "react-dom"; -import Portal = require("react-portal"); +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Portal, PortalWithState } from 'react-portal'; -export default class App extends React.Component { - render() { - const button1 = ; - - return ( -
- {}} - beforeClose={(node: HTMLDivElement, resetPortalState) => resetPortalState()} - onClose={() => {}} - onUpdate={() => {}} - > - -

Pseudo Modal

-

This react component is appended to the document body.

-
-
- -
- ); - } +interface AppState { + isPortalOneActive: boolean; + isPortalTwoActive: boolean; } -export class PseudoModal extends React.Component<{ closePortal?(): void }> { - render() { - return ( -
- {this.props.children} -

-
- ); - } +export default class App extends React.Component<{}, AppState> { + constructor(props: any) { + super(props); + + this.state = { + isPortalOneActive: false, + isPortalTwoActive: false + }; + } + + render() { + return ( +
+

React Portal Examples

+

+ + https://github.com/tajo/react-portal + +

+ +

Portal (stateless)

+ + {this.state.isPortalOneActive && ( + +

This thing was portaled!

+
+ )} + +

Portal (stateless, custom node)

+ + {this.state.isPortalTwoActive && ( + +

This thing was portaled!

+
+ )} + +

PortalWithState

+ + {({ openPortal, closePortal, isOpen, portal }) => [ + , + portal( +

+ This is more advanced Portal. It handles its own state.{' '} + , hit ESC or + click outside of me. +

+ ) + ]} +
+
+ ); + } } -ReactDOM.render(, document.getElementById('react-body')); +ReactDOM.render(, document.getElementById('root')); diff --git a/types/react-portal/v3/index.d.ts b/types/react-portal/v3/index.d.ts new file mode 100644 index 0000000000..4d869009e6 --- /dev/null +++ b/types/react-portal/v3/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for react-portal 3.0 +// Project: https://github.com/tajo/react-portal#readme +// Definitions by: Shun Takahashi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; + +interface CallBackProps extends React.Props { + closePortal(): void; +} + +interface ReactPortalProps { + isOpened?: boolean; + openByClickOn?: React.ReactElement; + closeOnEsc?: boolean; + closeOnOutsideClick?: boolean; + onOpen?(node: HTMLDivElement): void; + beforeClose?(node: HTMLDivElement, resetPortalState: () => void): void; + onClose?(): void; + onUpdate?(): void; +} + +declare const ReactPortal: React.ComponentClass; +export = ReactPortal; diff --git a/types/react-portal/v3/react-portal-tests.tsx b/types/react-portal/v3/react-portal-tests.tsx new file mode 100644 index 0000000000..ca6c0289de --- /dev/null +++ b/types/react-portal/v3/react-portal-tests.tsx @@ -0,0 +1,44 @@ +// Example from https://github.com/tajo/react-portal +import * as React from "react"; +import * as ReactDOM from "react-dom"; +import * as Portal from "react-portal"; + +export default class App extends React.Component { + render() { + const button1 = ; + + return ( +
+ {}} + beforeClose={(node: HTMLDivElement, resetPortalState) => resetPortalState()} + onClose={() => {}} + onUpdate={() => {}} + > + +

Pseudo Modal

+

This react component is appended to the document body.

+
+
+ +
+ ); + } +} + +export class PseudoModal extends React.Component<{ closePortal?(): void }> { + render() { + return ( +
+ {this.props.children} +

+
+ ); + } +} + +ReactDOM.render(, document.getElementById('react-body')); diff --git a/types/react-portal/v3/tsconfig.json b/types/react-portal/v3/tsconfig.json new file mode 100644 index 0000000000..3b6f5c966a --- /dev/null +++ b/types/react-portal/v3/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "paths": { + "react-portal": [ "react-portal/v3" ] + } + }, + "files": [ + "index.d.ts", + "react-portal-tests.tsx" + ] +} diff --git a/types/react-portal/v3/tslint.json b/types/react-portal/v3/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-portal/v3/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-primitives/index.d.ts b/types/react-primitives/index.d.ts index 881b3c6a91..7d276c6a94 100644 --- a/types/react-primitives/index.d.ts +++ b/types/react-primitives/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/lelandrichardson/react-primitives // Definitions by: Ahmed Ghoneim // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { ComponentType } from 'react'; import { diff --git a/types/react-qr-reader/index.d.ts b/types/react-qr-reader/index.d.ts new file mode 100644 index 0000000000..de426667c0 --- /dev/null +++ b/types/react-qr-reader/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for react-qr-reader 2.1 +// Project: https://github.com/JodusNodus/react-qr-reader +// Definitions by: David Kevork +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; + +export as namespace QrReader; + +export default QrReader; + +export namespace QrReader { + interface props { + onScan: (data: string | null) => void; + onError: (err: any) => void; + onLoad?: () => void; + onImageLoad?: (event: React.SyntheticEvent) => void; + delay?: number | false; + facingMode?: 'user' | 'environment'; + legacyMode?: boolean; + resolution?: number; + showViewFinder?: boolean; + style?: any; + className?: string; + } +} + +declare class QrReader extends React.Component { +} diff --git a/types/react-qr-reader/react-qr-reader-tests.tsx b/types/react-qr-reader/react-qr-reader-tests.tsx new file mode 100644 index 0000000000..20632f8029 --- /dev/null +++ b/types/react-qr-reader/react-qr-reader-tests.tsx @@ -0,0 +1,14 @@ +import * as React from "react"; +import QrReader from "react-qr-reader"; + +export class Test extends React.Component { + render() { + return ( + { console.log(err); }} + onScan={(data) => { console.log(data); }} + facingMode={'user'} + /> + ); + } +} diff --git a/types/interact.js/tsconfig.json b/types/react-qr-reader/tsconfig.json similarity index 82% rename from types/interact.js/tsconfig.json rename to types/react-qr-reader/tsconfig.json index 6d4887d0f1..89aebb0de5 100644 --- a/types/interact.js/tsconfig.json +++ b/types/react-qr-reader/tsconfig.json @@ -7,9 +7,10 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", + "jsx": "react", "typeRoots": [ "../" ], @@ -19,6 +20,6 @@ }, "files": [ "index.d.ts", - "interact.js-tests.ts" + "react-qr-reader-tests.tsx" ] } \ No newline at end of file diff --git a/types/react-qr-reader/tslint.json b/types/react-qr-reader/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-qr-reader/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-radio-group/index.d.ts b/types/react-radio-group/index.d.ts index 561599ed0a..809553e497 100644 --- a/types/react-radio-group/index.d.ts +++ b/types/react-radio-group/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/chenglou/react-radio-group // Definitions by: Jason Unger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-recaptcha/index.d.ts b/types/react-recaptcha/index.d.ts index 595cc1916e..614bc50f0f 100644 --- a/types/react-recaptcha/index.d.ts +++ b/types/react-recaptcha/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Mohamed Hegazy // Zach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component } from "react"; diff --git a/types/react-redux-epic/index.d.ts b/types/react-redux-epic/index.d.ts index f9bba811f8..a059786123 100644 --- a/types/react-redux-epic/index.d.ts +++ b/types/react-redux-epic/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/BerkeleyTrue/react-redux-epic#readme // Definitions by: forabi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { Observable } from 'rxjs/Observable'; diff --git a/types/react-redux-i18n/index.d.ts b/types/react-redux-i18n/index.d.ts index 7c133448e8..9d91ab025c 100644 --- a/types/react-redux-i18n/index.d.ts +++ b/types/react-redux-i18n/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/zoover/react-redux-i18n // Definitions by: Clément Devos // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 declare module 'react-redux-i18n' { import * as react from "react" diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index 25b3ae2668..8aa723c232 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -73,9 +73,6 @@ type Shared< // Will not pass through the injected props if they are passed in during // render. Also adds new prop requirements from TNeedsProps. export interface InferableComponentEnhancerWithProps { - ( - component: StatelessComponent - ): ComponentClass & {WrappedComponent: StatelessComponent}

>( component: ComponentType

): ComponentClass> & TNeedsProps> & {WrappedComponent: ComponentType

} diff --git a/types/react-redux/react-redux-tests.tsx b/types/react-redux/react-redux-tests.tsx index f446df9a1e..5d2395d811 100644 --- a/types/react-redux/react-redux-tests.tsx +++ b/types/react-redux/react-redux-tests.tsx @@ -832,7 +832,12 @@ namespace TestDispatchToPropsAsObject {

} -namespace TestInferredFunctionalComponent { +namespace TestInferredFunctionalComponentWithExplicitOwnProps { + type Props = { + title: string, + extraText: string, + onClick: () => void, + }; const Header = connect( ( @@ -845,7 +850,30 @@ namespace TestInferredFunctionalComponent { (dispatch) => ({ onClick: () => dispatch({ type: 'test' }) }) - )(({ title, extraText, onClick }) => { + )(({ title, extraText, onClick }: Props) => { + return

{title} {extraText}

; + }); +
+} + +namespace TestInferredFunctionalComponentWithImplicitOwnProps { + + type Props = { + title: string, + extraText: string, + onClick: () => void, + }; + + const Header = connect( + ( + { app: { title }}: { app: { title: string }}, + ) => ({ + title, + }), + (dispatch) => ({ + onClick: () => dispatch({ type: 'test' }) + }) + )(({ title, extraText, onClick }: Props) => { return

{title} {extraText}

; });
@@ -1126,4 +1154,4 @@ namespace TestFailsMoreSpecificInjectedProps { // Since it is possible the injected props could fail to satisfy the decoration props, // the following line should fail to compile. connect(mapStateToProps, mapDispatchToProps)(Component) // $ExpectError -} \ No newline at end of file +} diff --git a/types/react-redux/v5/index.d.ts b/types/react-redux/v5/index.d.ts index 0e3b6ffb88..6dc8844f1e 100644 --- a/types/react-redux/v5/index.d.ts +++ b/types/react-redux/v5/index.d.ts @@ -9,7 +9,7 @@ // Dibyo Majumdar // Prashant Deva // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 // Known Issue: // There is a known issue in TypeScript, which doesn't allow decorators to change the signature of the classes diff --git a/types/react-relay/index.d.ts b/types/react-relay/index.d.ts index f87ce26356..24993b0018 100644 --- a/types/react-relay/index.d.ts +++ b/types/react-relay/index.d.ts @@ -5,8 +5,9 @@ // Eloy Durán // Nicolas Pirotte // Cameron Knight +// Kaare Hoff Skovgaard // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 export { commitLocalUpdate, @@ -23,17 +24,17 @@ import * as RelayRuntimeTypes from "relay-runtime"; // Utility types // ~~~~~~~~~~~~~~~~~~~~~ -// Taken from https://github.com/pelotom/type-zoo -// tslint:disable-next-line:strict-export-declare-modifiers -type Omit = Pick; +export type FragmentOrRegularProp = T extends { ' $refType': infer U } ? { ' $fragmentRefs': U } : T; -export type RemoveRelayProp

= Omit

; +export type MappedFragmentProps = { [K in keyof T]: FragmentOrRegularProp }; + +export type RemoveRelayProp

= Pick>; export interface ComponentRef { componentRef?: (ref: any) => void; } -export type RelayContainer = React.ComponentType & ComponentRef>; +export type RelayContainer

= React.ComponentType> & ComponentRef>; // ~~~~~~~~~~~~~~~~~~~~~ // Maybe Fix @@ -96,10 +97,11 @@ export class QueryRenderer extends ReactRelayQueryRenderer {} // ~~~~~~~~~~~~~~~~~~~~~ // createFragmentContainer // ~~~~~~~~~~~~~~~~~~~~~ -export function createFragmentContainer( - Component: React.ComponentType, + +export function createFragmentContainer

( + Component: React.ComponentType

, fragmentSpec: RelayRuntimeTypes.GraphQLTaggedNode | GeneratedNodeMap -): RelayContainer; +): RelayContainer

; // ~~~~~~~~~~~~~~~~~~~~~ // createPaginationContainer @@ -143,11 +145,11 @@ export interface ConnectionConfig { ): RelayRuntimeTypes.Variables; query: RelayRuntimeTypes.GraphQLTaggedNode; } -export function createPaginationContainer( - Component: React.ComponentType, +export function createPaginationContainer

( + Component: React.ComponentType

, fragmentSpec: RelayRuntimeTypes.GraphQLTaggedNode | GeneratedNodeMap, - connectionConfig: ConnectionConfig -): RelayContainer; + connectionConfig: ConnectionConfig

+): RelayContainer

; // ~~~~~~~~~~~~~~~~~~~~~ // createRefetchContainer @@ -166,8 +168,8 @@ export type RelayRefetchProp = RelayProp & { options?: RefetchOptions ): RelayRuntimeTypes.Disposable; }; -export function createRefetchContainer( - Component: React.ComponentType, +export function createRefetchContainer

( + Component: React.ComponentType

, fragmentSpec: RelayRuntimeTypes.GraphQLTaggedNode | GeneratedNodeMap, taggedNode: RelayRuntimeTypes.GraphQLTaggedNode -): RelayContainer; +): RelayContainer

; diff --git a/types/react-relay/test/react-relay-tests.tsx b/types/react-relay/test/react-relay-tests.tsx index bf3e2d1475..300154678c 100644 --- a/types/react-relay/test/react-relay-tests.tsx +++ b/types/react-relay/test/react-relay-tests.tsx @@ -76,9 +76,8 @@ const MyEmptyQueryRenderer = () => ( type StoryLike = (storyID: string) => void; // Artifact produced by relay-compiler-language-typescript -// tslint:disable-next-line:no-const-enum -const enum _Story_story$ref {} -type Story_story$ref = _Story_story$ref & FragmentReference; +declare const _Story_story$ref: unique symbol; +type Story_story$ref = typeof _Story_story$ref; // tslint:disable-next-line:interface-over-type-literal type Story_story = { readonly id: string; @@ -150,8 +149,7 @@ const Story = (() => { function doesNotRequireRelayPropToBeProvided() { const onLike = (id: string) => console.log(`Liked story #${id}`); const story: { " $fragmentRefs": Story_story$ref } = {} as any; - // TODO: Fix requirement to cast fragment reference as `any`. - ; + ; } return StoryRefetchContainer; @@ -162,15 +160,14 @@ const Story = (() => { // ~~~~~~~~~~~~~~~~~~~~~ // Artifact produced by relay-compiler-language-typescript -// tslint:disable-next-line:no-const-enum -const enum _FeedStories_feed$ref {} -type FeedStories_feed$ref = _FeedStories_feed$ref & FragmentReference; +declare const _FeedStories_feed$ref: unique symbol; +type FeedStories_feed$ref = typeof _FeedStories_feed$ref; // tslint:disable-next-line:interface-over-type-literal type FeedStories_feed = { readonly edges: ReadonlyArray<{ readonly node: { readonly id: string; - readonly " $fragmentRefs": Story_story$ref; + readonly " $fragmentRefs": Story_story$ref & FeedStories_feed$ref; }; }>; readonly " $refType": FeedStories_feed$ref; @@ -189,8 +186,7 @@ const Feed = (() => { // If you have a good relavant example, please update! relay.environment; const stories = feed.edges.map(edge => { - // TODO: Fix requirement to cast fragment reference as `any`. - return ; + return ; }); return

{stories}
; }; @@ -214,8 +210,7 @@ const Feed = (() => { function doesNotRequireRelayPropToBeProvided() { const onStoryLike = (id: string) => console.log(`Liked story #${id}`); const feed: { " $fragmentRefs": FeedStories_feed$ref } = {} as any; - // TODO: Fix requirement to cast fragment reference as `any`. - ; + ; } return FeedFragmentContainer; @@ -226,9 +221,8 @@ const Feed = (() => { // ~~~~~~~~~~~~~~~~~~~~~ // Artifact produced by relay-compiler-language-typescript -// tslint:disable-next-line:no-const-enum -const enum _UserFeed_user$ref {} -type UserFeed_user$ref = _UserFeed_user$ref & FragmentReference; +declare const _UserFeed_user$ref: unique symbol; +type UserFeed_user$ref = typeof _UserFeed_user$ref; // tslint:disable-next-line:interface-over-type-literal type UserFeed_user = { readonly feed: { @@ -252,11 +246,9 @@ type UserFeed_user = { class UserFeed extends React.Component { render() { const onStoryLike = (id: string) => console.log(`Liked story #${id}`); - // TODO: Fix requirement to cast fragment reference as `any`. - const feed = this.props.user.feed as any; return (
- +
); @@ -329,8 +321,7 @@ type UserFeed_user = { function doesNotRequireRelayPropToBeProvided() { const user: { " $fragmentRefs": UserFeed_user$ref } = {} as any; - // TODO: Fix requirement to cast fragment reference as `any`. - ; + ; } }; diff --git a/types/react-resize-detector/index.d.ts b/types/react-resize-detector/index.d.ts old mode 100644 new mode 100755 index 5277109c2e..68f0382dba --- a/types/react-resize-detector/index.d.ts +++ b/types/react-resize-detector/index.d.ts @@ -1,14 +1,16 @@ -// Type definitions for react-resize-detector 2.2 +// Type definitions for react-resize-detector 3.1 // Project: https://github.com/maslianok/react-resize-detector -// Definitions by: Matthew James , James Greenleaf +// Definitions by: Matthew James +// James Greenleaf +// Remin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; interface ReactResizeDetectorProps extends React.Props { /** Function that will be invoked with width and height arguments */ - onResize: (width: number, height: number) => void; + onResize?: (width: number, height: number) => void; /** Trigger onResize on height change. Default: false */ handleHeight?: boolean; /** Trigger onResize on width change. Default: false */ @@ -18,11 +20,18 @@ interface ReactResizeDetectorProps extends React.Props { /** Id of the element we want to observe. If none provided, parentElement of the component will be used. Default: "" */ resizableElementId?: string; /** Possible values: throttle and debounce */ - refreshMode?: 'throttle' | 'debounce'; + refreshMode?: "throttle" | "debounce"; /** Makes sense only when refreshMode is set. Default: 1000. */ refreshRate?: number; + + render?: (props: any) => React.ReactNode; } declare class ReactResizeDetector extends React.PureComponent { } +export declare function withResizeDetector( + WrappedComponent: React.ReactNode, + props?: ReactResizeDetectorProps +): React.Component; + export default ReactResizeDetector; diff --git a/types/react-resize-detector/react-resize-detector-tests.tsx b/types/react-resize-detector/react-resize-detector-tests.tsx old mode 100644 new mode 100755 index 42a76d8a52..d6e471f340 --- a/types/react-resize-detector/react-resize-detector-tests.tsx +++ b/types/react-resize-detector/react-resize-detector-tests.tsx @@ -2,8 +2,11 @@ import * as React from "react"; import * as ReactDOM from "react-dom"; +import ReactResizeDetector, { withResizeDetector } from "react-resize-detector"; -import ReactResizeRouter from "react-resize-detector"; +const CustomComponent = ({ width, height }: any) => ( +
{`${width}x${height}`}
+); class App extends React.PureComponent { constructor(props: {}) { @@ -13,17 +16,38 @@ class App extends React.PureComponent { } render(): JSX.Element { - return
-
Some child content
- -
; + return ( +
+
Some child content
+ + + {(width: number, height: number) => ( +
{`${width}x${height}`}
+ )} +
+ + + + {withResizeDetector(CustomComponent)} + ( +
+ Width:{width}, Height:{height} +
+ )} + /> +
+ ); } private handleResize(width: number, height: number) { diff --git a/types/react-resolver/index.d.ts b/types/react-resolver/index.d.ts index c871426401..f8e0807fab 100644 --- a/types/react-resolver/index.d.ts +++ b/types/react-resolver/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ericclemmons/react-resolver // Definitions by: forabi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { ComponentType, StatelessComponent, Factory } from 'react'; diff --git a/types/react-responsive/index.d.ts b/types/react-responsive/index.d.ts index ad042a34c5..0fa9978c8f 100644 --- a/types/react-responsive/index.d.ts +++ b/types/react-responsive/index.d.ts @@ -4,7 +4,7 @@ // Alec Hill // Javier Gonzalez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-responsive/v1/index.d.ts b/types/react-responsive/v1/index.d.ts index f9c3bfcf83..789278508a 100644 --- a/types/react-responsive/v1/index.d.ts +++ b/types/react-responsive/v1/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/contra/react-responsive // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-rnd/index.d.ts b/types/react-rnd/index.d.ts index ff5ac2078e..ef7fb89674 100644 --- a/types/react-rnd/index.d.ts +++ b/types/react-rnd/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Ragg // fsubal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; type CSSProperties = React.CSSProperties; diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index 05d5fe30bb..6814ecf19f 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -64,9 +64,9 @@ export interface StaticContext { statusCode?: number; } -export interface RouteComponentProps { +export interface RouteComponentProps { history: H.History; - location: H.Location; + location: H.Location; match: match

; staticContext?: C; } diff --git a/types/react-router/v2/index.d.ts b/types/react-router/v2/index.d.ts index 68f9c3f38f..3f24c22c2c 100644 --- a/types/react-router/v2/index.d.ts +++ b/types/react-router/v2/index.d.ts @@ -7,7 +7,7 @@ // Alex Wendland // Kostya Esmukov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 export as namespace ReactRouter; diff --git a/types/react-router/v3/index.d.ts b/types/react-router/v3/index.d.ts index 9ca93b3a9b..ee4e01ba40 100644 --- a/types/react-router/v3/index.d.ts +++ b/types/react-router/v3/index.d.ts @@ -11,7 +11,7 @@ // Dovydas Navickas // Ross Allen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 export { ChangeHook, diff --git a/types/react-s-alert/index.d.ts b/types/react-s-alert/index.d.ts index bd014abd0a..d55aae1105 100644 --- a/types/react-s-alert/index.d.ts +++ b/types/react-s-alert/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/juliancwirko/react-s-alert // Definitions by: mitsuruog // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-scroll/index.d.ts b/types/react-scroll/index.d.ts index f04e6d86ff..bc22a9f445 100644 --- a/types/react-scroll/index.d.ts +++ b/types/react-scroll/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Ioannis Kokkinidis // Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as ReactScroll from "./modules/index"; export = ReactScroll; diff --git a/types/react-scrollbar/index.d.ts b/types/react-scrollbar/index.d.ts index f551d83ebd..ef99d8ab94 100644 --- a/types/react-scrollbar/index.d.ts +++ b/types/react-scrollbar/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/souhe/reactScrollbar // Definitions by: Stephen Jelfs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-select/index.d.ts b/types/react-select/index.d.ts index bde3c3c6a0..9c4728254c 100644 --- a/types/react-select/index.d.ts +++ b/types/react-select/index.d.ts @@ -1,646 +1,21 @@ -// Type definitions for react-select 1.3 -// Project: https://github.com/JedWatson/react-select -// Definitions by: ESQUIBET Hugo -// Gilad Gray -// Izaak Baker -// Tadas Dailyda -// Mark Vujevits -// Mike Deverell -// MartynasZilinskas -// Onat Yigit Mercan -// Ian Johnson -// Anton Novik -// David Schkalee -// Arthur Udalov -// Sebastian Silbermann -// Guillaume Chartier +// Type definitions for react-select 2.0 +// Project: https://github.com/JedWatson/react-select#readme +// Definitions by: Claas Ahlrichs +// Jon Freedman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.9 -import * as React from 'react'; +import SelectBase from './lib/Select'; +import { StateManager } from './lib/stateManager'; -export default class ReactSelectClass extends React.Component> { - focus(): void; - setValue(value: Option): void; -} -// Other components -export class Creatable extends React.Component> { } -export class Async extends React.Component> { } -export class AsyncCreatable extends React.Component> { } +export default SelectBase; +// export default StateManager; -export type OptionComponentType = React.ComponentType>; -export type ValueComponentType = React.ComponentType>; - -export type HandlerRendererResult = JSX.Element | null | false; - -// Handlers -export type FocusOptionHandler = (option: Option) => void; -export type SelectValueHandler = (option: Option) => void; -export type ArrowRendererHandler = (props: ArrowRendererProps) => HandlerRendererResult; -export type ClearRendererHandler = () => HandlerRendererResult; -export type FilterOptionHandler = (option: Option, filter: string) => boolean; -export type FilterOptionsHandler = (options: Options, filter: string, currentValues: Options) => Options; -export type InputRendererHandler = (props: { [key: string]: any }) => HandlerRendererResult; -export type MenuRendererHandler = (props: MenuRendererProps) => HandlerRendererResult; -export type OnCloseHandler = () => void; -export type OnInputChangeHandler = (inputValue: string) => string; -export type OnInputKeyDownHandler = React.KeyboardEventHandler; -export type OnMenuScrollToBottomHandler = () => void; -export type OnOpenHandler = () => void; -export type OnFocusHandler = React.FocusEventHandler; -export type OnBlurHandler = React.FocusEventHandler; -export type OptionRendererHandler = (option: Option) => HandlerRendererResult; -export type ValueRendererHandler = (option: Option, index?: number) => HandlerRendererResult; -export type OnValueClickHandler = (option: Option, event: React.MouseEvent) => void; -export type IsOptionUniqueHandler = (arg: { option: Option, options: Options, labelKey: string, valueKey: string }) => boolean; -export type IsValidNewOptionHandler = (arg: { label: string }) => boolean; -export type NewOptionCreatorHandler = (arg: { label: string, labelKey: string, valueKey: string }) => Option; -export type PromptTextCreatorHandler = (filterText: string) => string; -export type ShouldKeyDownEventCreateNewOptionHandler = (arg: { keyCode: number }) => boolean; - -export type OnChangeSingleHandler = OnChangeHandler>; -export type OnChangeMultipleHandler = OnChangeHandler>; -export type OnChangeHandler | Options> = (newValue: TOption | null) => void; -export type OnNewOptionClickHandler = (option: Option) => void; - -export type LoadOptionsHandler = LoadOptionsAsyncHandler | LoadOptionsLegacyHandler; -export type LoadOptionsAsyncHandler = (input: string) => Promise>; -export type LoadOptionsLegacyHandler = (input: string, callback: (err: any, result: AutocompleteResult) => void) => void; - -export interface AutocompleteResult { - /** The search-results to be displayed */ - options: Options; - /** - * Should be set to true, if and only if a longer query with the same prefix - * would return a subset of the results - * If set to true, more specific queries will not be sent to the server. - */ - complete: boolean; -} - -export type Options = Array>; - -export interface Option { - /** Text for rendering */ - label?: string; - /** Value for searching */ - value?: TValue; - /** - * Allow this option to be cleared - * @default true - */ - clearableValue?: boolean; - /** - * Do not allow this option to be selected - * @default false - */ - disabled?: boolean; - /** - * In the event that a custom menuRenderer is provided, Option should be able - * to accept arbitrary key-value pairs. See react-virtualized-select. - */ - [property: string]: any; -} - -export type OptionValues = string | number | boolean; - -export interface MenuRendererProps { - /** - * The currently focused option; should be visible in the menu by default. - * default {} - */ - focusedOption: Option; - - /** - * Callback to focus a new option; receives the option as a parameter. - */ - focusOption: FocusOptionHandler; - - /** - * Option labels are accessible with this string key. - */ - labelKey: string; - - /** - * Ordered array of options to render. - */ - options: Options; - - /** - * Callback to select a new option; receives the option as a parameter. - */ - selectValue: SelectValueHandler; - - /** - * Array of currently selected options. - */ - valueArray: Options; - - /** - * Callback to remove selection from option; receives the option as a parameter. - */ - removeValue: SelectValueHandler; - - /** - * function which returns a custom way to render the options in the menu - */ - optionRenderer: OptionRendererHandler; -} - -export interface OptionComponentProps { - /** - * Classname(s) to apply to the option component. - */ - className?: string; - - /** - * Currently focused option. - */ - focusOption?: Option; - - inputValue?: string; - instancePrefix?: string; - - /** - * True if this option is disabled. - */ - isDisabled?: boolean; - - /** - * True if this option is focused. - */ - isFocused?: boolean; - - /** - * True if this option is selected. - */ - isSelected?: boolean; - - /** - * Callback to be invoked when this option is focused. - */ - onFocus?: (option: Option, event: any) => void; - - /** - * Callback to be invoked when this option is selected. - */ - onSelect?: (option: Option, event: any) => void; - - /** - * Option to be rendered by this component. - */ - option: Option; - - /** - * Index of the option being rendered in the list - */ - optionIndex?: number; - - /** - * Callback to invoke when removing an option from a multi-selection. (Not necessarily the one - * being rendered) - */ - removeValue?: (value: TValue | TValue[]) => void; - - /** - * Callback to invoke to select an option. (Not necessarily the one being rendered) - */ - selectValue?: (value: TValue | TValue[]) => void; -} - -export interface ArrowRendererProps { - /** - * Arrow mouse down event handler. - */ - onMouseDown: React.MouseEventHandler; - - /** - * whether the Select is open or not. - */ - isOpen: boolean; -} - -export interface ValueComponentProps { - disabled: ReactSelectProps['disabled']; - id: string; - instancePrefix: string; - onClick: OnValueClickHandler | null; - onRemove?: SelectValueHandler; - placeholder: ReactSelectProps['placeholder']; - value: Option; - values?: Array>; -} - -export interface ReactSelectProps extends React.Props> { - /** - * text to display when `allowCreate` is true. - * @default 'Add "{label}"?' - */ - addLabelText?: string; - /** - * renders a custom drop-down arrow to be shown in the right-hand side of the select. - * @default undefined - */ - arrowRenderer?: ArrowRendererHandler; - /** - * blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices. - * @default false - */ - autoBlur?: boolean; - /** - * autofocus the component on mount - * @deprecated. Use autoFocus instead - * @default false - */ - autofocus?: boolean; - /** - * autofocus the component on mount - * @default false - */ - autoFocus?: boolean; - /** - * If enabled, the input will expand as the length of its value increases - */ - autosize?: boolean; - /** - * whether pressing backspace removes the last item when there is no input value - * @default true - */ - backspaceRemoves?: boolean; - /** - * Message to use for screenreaders to press backspace to remove the current item - * {label} is replaced with the item label - * @default "Press backspace to remove..." - */ - backspaceToRemoveMessage?: string; - /** - * CSS className for the outer element - */ - className?: string; - /** - * Prefix prepended to element default className if no className is defined - */ - classNamePrefix?: string; - /** - * title for the "clear" control when `multi` is true - * @default "Clear all" - */ - clearAllText?: string; - /** - * Renders a custom clear to be shown in the right-hand side of the select when clearable true - * @default undefined - */ - clearRenderer?: ClearRendererHandler; - /** - * title for the "clear" control - * @default "Clear value" - */ - clearValueText?: string; - /** - * whether to close the menu when a value is selected - * @default true - */ - closeOnSelect?: boolean; - /** - * whether it is possible to reset value. if enabled, an X button will appear at the right side. - * @default true - */ - clearable?: boolean; - /** - * whether backspace removes an item if there is no text input - * @default true - */ - deleteRemoves?: boolean; - /** - * delimiter to use to join multiple values - * @default "," - */ - delimiter?: string; - /** - * whether the Select is disabled or not - * @default false - */ - disabled?: boolean; - /** - * whether escape clears the value when the menu is closed - * @default true - */ - escapeClearsValue?: boolean; - /** - * method to filter a single option - */ - filterOption?: FilterOptionHandler; - /** - * method to filter the options array - */ - filterOptions?: FilterOptionsHandler; - /** - * id for the underlying HTML input element - * @default undefined - */ - id?: string; - /** - * whether to strip diacritics when filtering - * @default true - */ - ignoreAccents?: boolean; - /** - * whether to perform case-insensitive filtering - * @default true - */ - ignoreCase?: boolean; - /** - * custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'} - * @default {} - */ - inputProps?: { [key: string]: any }; - /** - * renders a custom input - */ - inputRenderer?: InputRendererHandler; - /** - * allows for synchronization of component id's on server and client. - * @see https://github.com/JedWatson/react-select/pull/1105 - */ - instanceId?: string; - /** - * whether the Select is loading externally or not (such as options being loaded). - * if true, a loading spinner will be shown at the right side. - * @default false - */ - isLoading?: boolean; - /** - * (legacy mode) joins multiple values into a single form field with the delimiter - * @default false - */ - joinValues?: boolean; - /** - * the option property to use for the label - * @default "label" - */ - labelKey?: string; - /** - * (any, start) match the start or entire string when filtering - * @default "any" - */ - matchPos?: string; - /** - * (any, label, value) which option property to filter on - * @default "any" - */ - matchProp?: string; - /** - * buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport - * @default 0 - */ - menuBuffer?: number; - /** - * optional style to apply to the menu container - */ - menuContainerStyle?: React.CSSProperties; - /** - * renders a custom menu with options - */ - menuRenderer?: MenuRendererHandler; - /** - * optional style to apply to the menu - */ - menuStyle?: React.CSSProperties; - /** - * multi-value input - * @default false - */ - multi?: boolean; - /** - * field name, for hidden `` tag - */ - name?: string; - /** - * placeholder displayed when there are no matching search results or a falsy value to hide it - * @default "No results found" - */ - noResultsText?: string | JSX.Element; - /** - * onBlur handler: function (event) {} - */ - onBlur?: OnBlurHandler; - /** - * whether to clear input on blur or not - * @default true - */ - onBlurResetsInput?: boolean; - /** - * whether the input value should be reset when options are selected. - * Also input value will be set to empty if 'onSelectResetsInput=true' and - * Select will get new value that not equal previous value. - * @default true - */ - onSelectResetsInput?: boolean; - /** - * whether to clear input when closing the menu through the arrow - * @default true - */ - onCloseResetsInput?: boolean; - /** - * onChange handler: function (newValue) {} - */ - onChange?: OnChangeHandler; - /** - * fires when the menu is closed - */ - onClose?: OnCloseHandler; - /** - * onFocus handler: function (event) {} - */ - onFocus?: OnFocusHandler; - /** - * onInputChange handler: function (inputValue) {} - */ - onInputChange?: OnInputChangeHandler; - /** - * onInputKeyDown handler: function (keyboardEvent) {} - */ - onInputKeyDown?: OnInputKeyDownHandler; - /** - * fires when the menu is scrolled to the bottom; can be used to paginate options - */ - onMenuScrollToBottom?: OnMenuScrollToBottomHandler; - /** - * fires when the menu is opened - */ - onOpen?: OnOpenHandler; - /** - * boolean to enable opening dropdown when focused - * @default false - */ - openOnClick?: boolean; - /** - * open the options menu when the input gets focus (requires searchable = true) - * @default true - */ - openOnFocus?: boolean; - /** - * className to add to each option component - */ - optionClassName?: string; - /** - * option component to render in dropdown - */ - optionComponent?: OptionComponentType; - /** - * function which returns a custom way to render the options in the menu - */ - optionRenderer?: OptionRendererHandler; - /** - * array of Select options - * @default false - */ - options?: Options; - /** - * number of options to jump when using page up/down keys - * @default 5 - */ - pageSize?: number; - /** - * field placeholder, displayed when there's no value - * @default "Select..." - */ - placeholder?: string | JSX.Element; - /** - * whether the selected option is removed from the dropdown on multi selects - * @default true - */ - removeSelected?: boolean; - /** - * applies HTML5 required attribute when needed - * @default false - */ - required?: boolean; - /** - * value to use when you clear the control - */ - resetValue?: any; - /** - * use react-select in right-to-left direction - * @default false - */ - rtl?: boolean; - /** - * whether the viewport will shift to display the entire menu when engaged - * @default true - */ - scrollMenuIntoView?: boolean; - /** - * whether to enable searching feature or not - * @default true; - */ - searchable?: boolean; - /** - * whether to select the currently focused value when the [tab] key is pressed - */ - tabSelectsValue?: boolean; - /** - * initial field value - */ - value?: Option | Options | string | string[] | number | number[] | boolean; - /** - * the option property to use for the value - * @default "value" - */ - valueKey?: string; - /** - * function which returns a custom way to render the value selected - * @default false - */ - valueRenderer?: ValueRendererHandler; - /** - * optional style to apply to the control - */ - style?: React.CSSProperties; - - /** - * optional tab index of the control - */ - tabIndex?: string | number; - - /** - * value component to render - */ - valueComponent?: ValueComponentType; - - /** - * optional style to apply to the component wrapper - */ - wrapperStyle?: React.CSSProperties; - - /** - * onClick handler for value labels: function (value, event) {} - */ - onValueClick?: OnValueClickHandler; - - /** - * pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false - */ - simpleValue?: boolean; -} - -export interface ReactCreatableSelectProps extends ReactSelectProps { - /** - * Searches for any matching option within the set of options. This function prevents - * duplicate options from being created. - */ - isOptionUnique?: IsOptionUniqueHandler; - - /** - * Determines if the current input text represents a valid option. - */ - isValidNewOption?: IsValidNewOptionHandler; - - /** - * factory to create new options - */ - newOptionCreator?: NewOptionCreatorHandler; - - /** - * Creates prompt/placeholder for option text. - */ - promptTextCreator?: PromptTextCreatorHandler; - - /** - * Decides if a keyDown event (eg its 'keyCode') should result in the creation of a new option. - */ - shouldKeyDownEventCreateNewOption?: ShouldKeyDownEventCreateNewOptionHandler; - - /** - * new option click handler: function (option) {} - */ - onNewOptionClick?: OnNewOptionClickHandler; -} - -export interface ReactAsyncSelectProps extends ReactSelectProps { - /** - * Whether to auto-load the default async options set. - */ - autoload?: boolean; - - /** - * object to use to cache results; can be null to disable cache - */ - cache?: { [key: string]: any } | boolean; - - /** - * function to call to load options asynchronously - */ - loadOptions: LoadOptionsHandler; - - /** - * replaces the placeholder while options are loading - */ - loadingPlaceholder?: string | JSX.Element; - /** - * displayed in the drop down list when the user did not type anything yet - */ - searchPromptText?: string; -} - -export type ReactAsyncCreatableSelectProps = ReactAsyncSelectProps & ReactCreatableSelectProps; +export { SelectBase }; +export { default as Async } from './lib/Async'; +export { default as AsyncCreatable } from './lib/AsyncCreatable'; +export { default as Creatable } from './lib/Creatable'; +export { createFilter } from './lib/filters'; +export { default as makeAnimated } from './lib/animated/index'; +export { components } from './lib/components/index'; +export { mergeStyles } from './lib/styles'; diff --git a/types/react-select/lib/Async.d.ts b/types/react-select/lib/Async.d.ts new file mode 100644 index 0000000000..8acc5532b7 --- /dev/null +++ b/types/react-select/lib/Async.d.ts @@ -0,0 +1,47 @@ +import * as React from 'react'; +import Select, { Props as SelectProps } from './Select'; +import { handleInputChange } from './utils'; +import manageState from './stateManager'; +import { OptionsType, InputActionMeta } from './types'; + +export interface AsyncProps { + /* The default set of options to show before the user starts searching. When + set to `true`, the results for loadOptions('') will be autoloaded. */ + defaultOptions: OptionsType | boolean; + /* Function that returns a promise, which is the set of options to be used + once the promise resolves. */ + loadOptions: (inputValue: string, callback: ((options: OptionsType) => void)) => Promise | void; + /* If cacheOptions is truthy, then the loaded data will be cached. The cache + will remain until `cacheOptions` changes value. */ + cacheOptions: any; +} + +export type Props = SelectProps & AsyncProps; + +export const defaultProps: Props; + +export interface State { + defaultOptions?: OptionsType; + inputValue: string; + isLoading: boolean; + loadedInputValue?: string; + loadedOptions: OptionsType; + passEmptyOptions: boolean; +} + +export class Async extends React.Component, State> { + static defaultProps: Props; + select: React.Ref; + lastRequest: {}; + mounted: boolean; + optionsCache: { [key: string]: OptionsType }; + + focus(): void; + blur(): void; + loadOptions(inputValue: string, callback: (options: OptionsType) => void): void; + handleInputChange: (newValue: string, actionMeta: InputActionMeta) => string; +} + +export function makeAsyncSelect(SelectComponent: React.ComponentType): Async; + +export default Async; diff --git a/types/react-select/lib/AsyncCreatable.d.ts b/types/react-select/lib/AsyncCreatable.d.ts new file mode 100644 index 0000000000..5fbdd8e52c --- /dev/null +++ b/types/react-select/lib/AsyncCreatable.d.ts @@ -0,0 +1,25 @@ +import { Component, Ref as ElementRef } from 'react'; +import { Props as AsyncProps, State as AsyncState } from './Async'; +import { Props as CreatableProps, State as CreatableState } from './Creatable'; +import { OptionsType, ValueType, ActionMeta, InputActionMeta } from './types'; +import { cleanValue } from './utils'; + +type Props = AsyncProps & CreatableProps; + +type State = AsyncState & CreatableState; + +export class AsyncCreatable extends Component, State> { + static defaultProps: Props; + select: ElementRef; + lastRequest: {}; + mounted: boolean; + optionsCache: { [key: string]: OptionsType }; + + focus(): void; + blur(): void; + loadOptions(inputValue: string, callback: (options: OptionsType) => void): void; + handleInputChange: (newValue: string, actionMeta: InputActionMeta) => string; + onChange: (newValue: ValueType, actionMeta: ActionMeta) => void; +} + +export default AsyncCreatable; diff --git a/types/react-select/lib/Creatable.d.ts b/types/react-select/lib/Creatable.d.ts new file mode 100644 index 0000000000..5cae63021c --- /dev/null +++ b/types/react-select/lib/Creatable.d.ts @@ -0,0 +1,49 @@ +import * as React from 'react'; +import Select, { Props as SelectProps } from './Select'; +import { OptionsType, ValueType, ActionMeta } from './types'; +import { cleanValue } from './utils'; +import manageState from './stateManager'; + +export interface CreatableProps { + /* Allow options to be created while the `isLoading` prop is true. Useful to + prevent the "create new ..." option being displayed while async results are + still being loaded. */ + allowCreateWhileLoading?: boolean; + /* Gets the label for the "create new ..." option in the menu. Is given the + current input value. */ + formatCreateLabel?: (inputValue: string) => React.ReactNode; + /* Determines whether the "create new ..." option should be displayed based on + the current input value, select value and options array. */ + isValidNewOption?: (inputValue: string, value: ValueType, options: OptionsType) => boolean; + /* Returns the data for the new option when it is created. Used to display the + value, and is passed to `onChange`. */ + getNewOptionData?: (inputValue: string, optionLabel: React.ReactNode) => OptionType; + /* If provided, this will be called with the input value when a new option is + created, and `onChange` will **not** be called. Use this when you need more + control over what happens when new options are created. */ + onCreateOption?: (inputValue: string) => void; + /* Sets the position of the createOption element in your options list. Defaults to 'last' */ + createOptionPosition?: 'first' | 'last'; +} + +export type Props = SelectProps & CreatableProps; + +export const defaultProps: Props; + +export interface State { + newOption: OptionType | undefined; + options: OptionsType; +} + +export class Creatable extends React.Component, State> { + static defaultProps: Props; + select: React.Ref; + + onChange: (newValue: ValueType, actionMeta: ActionMeta) => void; + focus(): void; + blur(): void; +} + +export function makeCreatableSelect(SelectComponent: React.ComponentType): Creatable; + +export default Creatable; diff --git a/types/react-select/lib/Select.d.ts b/types/react-select/lib/Select.d.ts new file mode 100644 index 0000000000..aa8524103e --- /dev/null +++ b/types/react-select/lib/Select.d.ts @@ -0,0 +1,419 @@ +import * as React from 'react'; + +import { Option } from './filters'; +import { + InstructionsContext, + ValueEventContext, +} from './accessibility/index'; + +import { + classNames, + noop, + scrollIntoView, +} from './utils'; + +import { + formatGroupLabel, + getOptionLabel, + getOptionValue, + isOptionDisabled, +} from './builtins'; + +import { + PlaceholderOrValue, + SelectComponents, + SelectComponentsConfig, +} from './components/index'; +import { StylesConfig } from './styles'; + +import { + ActionMeta, + ActionTypes, + FocusDirection, + FocusEventHandler, + GroupType, + InputActionMeta, + KeyboardEventHandler, + MenuPlacement, + MenuPosition, + OptionsType, + ValueType, + GroupedOptionsType, +} from './types'; + +export type MouseOrTouchEvent = + | React.MouseEvent + | React.TouchEvent; +export type FormatOptionLabelContext = 'menu' | 'value'; +export interface FormatOptionLabelMeta { + context: FormatOptionLabelContext; + inputValue: string; + selectValue: ValueType; +} + +export interface Props { + /* Aria label (for assistive tech) */ + 'aria-label'?: string; + /* HTML ID of an element that should be used as the label (for assistive tech) */ + 'aria-labelledby'?: string; + /* Focus the control when it is mounted */ + autoFocus?: boolean; + /* Remove the currently focused option when the user presses backspace */ + backspaceRemovesValue?: boolean; + /* Remove focus from the input when the user selects an option (handy for dismissing the keyboard on touch devices) */ + blurInputOnSelect?: boolean; + /* When the user reaches the top/bottom of the menu, prevent scroll on the scroll-parent */ + captureMenuScroll?: boolean; + /* className attribute applied to the outer component */ + className?: string; + /* classNamePrefix attribute used as a base for inner component classNames */ + classNamePrefix?: string | null; + /* Close the select menu when the user selects an option */ + closeMenuOnSelect?: boolean; + /* + If `true`, close the select menu when the user scrolls the document/body. + + If a function, takes a standard javascript `ScrollEvent` you return a boolean: + + `true` => The menu closes + + `false` => The menu stays open + + This is useful when you have a scrollable modal and want to portal the menu out, + but want to avoid graphical issues. + */ + closeMenuOnScroll?: boolean | EventListener; + /* + This complex object includes all the compositional components that are used + in `react-select`. If you wish to overwrite a component, pass in an object + with the appropriate namespace. + + If you only wish to restyle a component, we recommend using the `styles` prop + instead. For a list of the components that can be passed in, and the shape + that will be passed to them, see [the components docs](/api#components) + */ + components?: SelectComponentsConfig; + /* Whether the value of the select, e.g. SingleValue, should be displayed in the control. */ + controlShouldRenderValue?: boolean; + /* Delimiter used to join multiple values into a single HTML Input value */ + delimiter?: string; + /* Clear all values when the user presses escape AND the menu is closed */ + escapeClearsValue?: boolean; + /* Custom method to filter whether an option should be displayed in the menu */ + filterOption?: (( + option: Option, + rawInput: string + ) => boolean) | null; + /* Formats group labels in the menu as React components */ + formatGroupLabel?: typeof formatGroupLabel; + /* Formats option labels in the menu and control as React components */ + formatOptionLabel?: (option: OptionType, labelMeta: FormatOptionLabelMeta) => React.ReactNode; + /* Resolves option data to a string to be displayed as the label by components */ + getOptionLabel?: typeof getOptionLabel; + /* Resolves option data to a string to compare options and specify value attributes */ + getOptionValue?: typeof getOptionValue; + /* Hide the selected option from the menu */ + hideSelectedOptions?: boolean; + /* The id to set on the SelectContainer component. */ + id?: string; + /* The value of the search input */ + inputValue?: string; + /* The id of the search input */ + inputId?: string; + /* Define an id prefix for the select components e.g. {your-id}-value */ + instanceId?: number | string; + /* Is the select value clearable */ + isClearable?: boolean; + /* Is the select disabled */ + isDisabled?: boolean; + /* Is the select in a state of loading (async) */ + isLoading?: boolean; + /* Override the built-in logic to detect whether an option is disabled */ + isOptionDisabled?: (option: OptionType, options: OptionsType) => boolean | false; + /* Override the built-in logic to detect whether an option is selected */ + isOptionSelected?: (option: OptionType, options: OptionsType) => boolean; + /* Support multiple selected options */ + isMulti?: boolean; + /* Is the select direction right-to-left */ + isRtl?: boolean; + /* Whether to enable search functionality */ + isSearchable?: boolean; + /* Async: Text to display when loading options */ + loadingMessage?: (obj: { inputValue: string }) => string | null; + /* Minimum height of the menu before flipping */ + minMenuHeight?: number; + /* Maximum height of the menu before scrolling */ + maxMenuHeight?: number; + /* Whether the menu is open */ + menuIsOpen?: boolean; + /* Default placement of the menu in relation to the control. 'auto' will flip + when there isn't enough space below the control. */ + menuPlacement?: MenuPlacement; + /* The CSS position value of the menu, when "fixed" extra layout management is required */ + menuPosition?: MenuPosition; + /* Whether the menu should use a portal, and where it should attach */ + menuPortalTarget?: HTMLElement | null; + /* Whether to block scroll events when the menu is open */ + menuShouldBlockScroll?: boolean; + /* Whether the menu should be scrolled into view when it opens */ + menuShouldScrollIntoView?: boolean; + /* Name of the HTML Input (optional - without this, no input will be rendered) */ + name?: string; + /* Text to display when there are no options */ + noOptionsMessage?: (obj: { inputValue: string }) => string | null; + /* Handle blur events on the control */ + onBlur?: FocusEventHandler; + /* Handle change events on the select */ + onChange?: (value: ValueType, action: ActionMeta) => void; + /* Handle focus events on the control */ + onFocus?: FocusEventHandler; + /* Handle change events on the input */ + onInputChange?: (newValue: string, actionMeta: InputActionMeta) => void; + /* Handle key down events on the select */ + onKeyDown?: KeyboardEventHandler; + /* Handle the menu opening */ + onMenuOpen?: () => void; + /* Handle the menu closing */ + onMenuClose?: () => void; + /* Fired when the user scrolls to the top of the menu */ + onMenuScrollToTop?: (event: React.SyntheticEvent) => void; + /* Fired when the user scrolls to the bottom of the menu */ + onMenuScrollToBottom?: (event: React.SyntheticEvent) => void; + /* Allows control of whether the menu is opened when the Select is focused */ + openMenuOnFocus?: boolean; + /* Allows control of whether the menu is opened when the Select is clicked */ + openMenuOnClick?: boolean; + /* Array of options that populate the select menu */ + options?: GroupedOptionsType | OptionsType; + /* Number of options to jump in menu when page{up|down} keys are used */ + pageSize?: number; + /* Placeholder text for the select value */ + placeholder?: string; + /* Status to relay to screen readers */ + screenReaderStatus?: (obj: { count: number }) => string; + /* Style modifier methods */ + styles?: StylesConfig; + /* Sets the tabIndex attribute on the input */ + tabIndex?: string; + /* Select the currently focused option when the user presses tab */ + tabSelectsValue?: boolean; + /* The value of the select; reflected by the selected option */ + value?: ValueType; + + defaultInputValue?: string; + defaultMenuIsOpen?: boolean; + defaultValue?: ValueType; +} + +export const defaultProps: Props; + +export interface MenuOptions { + render: OptionType[]; + focusable: OptionType[]; +} + +export interface State { + ariaLiveSelection: string; + ariaLiveContext: string; + inputIsHidden: boolean; + isFocused: boolean; + isComposing: boolean; + focusedOption: OptionType | null; + focusedValue: OptionType | null; + menuOptions: MenuOptions; + selectValue: OptionsType; +} + +export type ElRef = React.Ref; + +export default class Select extends React.Component, State> { + static defaultProps: Props; + + // Misc. Instance Properties + // ------------------------------ + + blockOptionHover: boolean; + clearFocusValueOnUpdate: boolean; + commonProps: any; // TODO + components: SelectComponents; + hasGroups: boolean; + initialTouchX: number; + initialTouchY: number; + inputIsHiddenAfterUpdate: boolean | null; + instancePrefix: string; + openAfterFocus: boolean; + scrollToFocusedOptionOnUpdate: boolean; + userIsDragging: boolean | null; + + // Refs + // ------------------------------ + + controlRef: ElRef; + getControlRef: (ref: HTMLElement) => void; + focusedOptionRef: ElRef; + getFocusedOptionRef: (ref: HTMLElement) => void; + menuListRef: ElRef; + getMenuListRef: (ref: HTMLElement) => void; + inputRef: ElRef; + getInputRef: (ref: HTMLElement) => void; + + // Lifecycle + // ------------------------------ + + cacheComponents: (components: SelectComponents) => void; + + // ============================== + // Consumer Handlers + // ============================== + + onMenuOpen(): void; + onMenuClose(): void; + onInputChange(newValue: string, actionMeta: InputActionMeta): void; + + // ============================== + // Methods + // ============================== + + focusInput(): void; + blurInput(): void; + + // aliased for consumers + focus(): void; + blur(): void; + + openMenu(focusOption: 'first' | 'last'): void; + focusValue(direction: 'previous' | 'next'): void; + + focusOption(direction: FocusDirection): void; + setValue: ( + newValue: ValueType, + action: ActionTypes, + option?: OptionType + ) => void; + selectOption: (newValue: OptionType) => void; + removeValue: (removedValue: OptionType) => void; + clearValue: () => void; + popValue: () => void; + + // ============================== + // Getters + // ============================== + + getCommonProps(): { + cx: any; + clearValue: () => void; + getStyles: (key: string, props: {}) => {}; + getValue: () => OptionType[]; + hasValue: boolean; + isMulti: boolean; + isRtl: boolean; + options: OptionsType; + selectOption: (newValue: OptionType) => void; + setValue: (newValue: ValueType, action: ActionTypes, option?: OptionType) => void; + selectProps: Readonly<{ + children?: React.ReactNode; + }> & Readonly>; +}; + + getNextFocusedValue(nextSelectValue: OptionsType): OptionType; + + getNextFocusedOption(options: OptionsType): OptionType; + getOptionLabel: (data: OptionType) => string; + getOptionValue: (data: OptionType) => string; + getStyles: (key: string, props: {}) => {}; + getElementId: (element: 'group' | 'input' | 'listbox' | 'option') => string; + getActiveDescendentId: () => any; + + // ============================== + // Helpers + // ============================== + announceAriaLiveSelection: (props: { + event: string, + context: ValueEventContext, + }) => void; + announceAriaLiveContext: (props: { + event: string, + context?: InstructionsContext, + }) => void; + + hasValue(): boolean; + hasOptions(): boolean; + countOptions(): number; + isClearable(): boolean; + isOptionDisabled(option: OptionType, selectValue: OptionsType): boolean; + isOptionSelected(option: OptionType, selectValue: OptionsType): boolean; + filterOption(option: {}, inputValue: string): boolean; + formatOptionLabel(data: OptionType, context: FormatOptionLabelContext): React.ReactNode; + formatGroupLabel(data: GroupType): React.ReactNode; + + // ============================== + // Mouse Handlers + // ============================== + + onMenuMouseDown: (event: React.MouseEvent) => void; + onMenuMouseMove: (event: React.MouseEvent) => void; + onControlMouseDown: (event: MouseOrTouchEvent) => void; + onDropdownIndicatorMouseDown: (event: MouseOrTouchEvent) => void; + onClearIndicatorMouseDown: (event: MouseOrTouchEvent) => void; + onScroll: (event: Event) => void; + + // ============================== + // Composition Handlers + // ============================== + + startListeningComposition(): void; + stopListeningComposition(): void; + onCompositionStart: () => void; + onCompositionEnd: () => void; + + // ============================== + // Touch Handlers + // ============================== + + startListeningToTouch(): void; + stopListeningToTouch(): void; + onTouchStart: (event: TouchEvent) => void; + onTouchMove: (event: TouchEvent) => void; + onTouchEnd: (event: TouchEvent) => void; + onControlTouchEnd: (event: React.TouchEvent) => void; + onClearIndicatorTouchEnd: (event: React.TouchEvent) => void; + onDropdownIndicatorTouchEnd: (event: React.TouchEvent) => void; + + // ============================== + // Focus Handlers + // ============================== + + handleInputChange: (event: React.KeyboardEvent) => void; + onInputFocus: (event: React.FocusEvent) => void; + onInputBlur: (event: React.FocusEvent) => void; + onOptionHover: (focusedOption: OptionType) => void; + shouldHideSelectedOptions: () => boolean; + + // ============================== + // Keyboard Handlers + // ============================== + + onKeyDown: (event: React.KeyboardEvent) => void; + + // ============================== + // Menu Options + // ============================== + + buildMenuOptions(props: Props, selectValue: OptionsType): MenuOptions; + + // ============================== + // Renderers + // ============================== + constructAriaLiveMessage(): string; + + renderInput(): React.ReactNode; + renderPlaceholderOrValue(): PlaceholderOrValue | null; + renderClearIndicator(): React.ReactNode; + renderLoadingIndicator(): React.ReactNode; + renderIndicatorSeparator(): React.ReactNode; + renderDropdownIndicator(): React.ReactNode; + renderMenu(): React.ReactNode; + renderFormField(): React.ReactNode; + + renderLiveRegion(): React.ReactNode; +} diff --git a/types/react-select/lib/accessibility/index.d.ts b/types/react-select/lib/accessibility/index.d.ts new file mode 100644 index 0000000000..633aaeda72 --- /dev/null +++ b/types/react-select/lib/accessibility/index.d.ts @@ -0,0 +1,10 @@ +export interface InstructionsContext { isSearchable?: boolean; isMulti?: boolean; label?: string; } +export interface ValueEventContext { value: string; } + +export function instructionsAriaMessage(event: any, context?: InstructionsContext): string; + +export function valueEventAriaMessage(event: any, context: ValueEventContext): string; + +export function valueFocusAriaMessage({ focusedValue, getOptionLabel, selectValue }: any): string; +export function optionFocusAriaMessage({ focusedOption, getOptionLabel, options }: any): string; +export function resultsAriaMessage({ inputValue, screenReaderMessage }: any): string; diff --git a/types/react-select/lib/animated/Input.d.ts b/types/react-select/lib/animated/Input.d.ts new file mode 100644 index 0000000000..ad752a96c5 --- /dev/null +++ b/types/react-select/lib/animated/Input.d.ts @@ -0,0 +1,10 @@ +import * as React from 'react'; +import { InputProps } from '../components/Input'; +import { BaseTransition } from './transitions'; +import { PropsWithInnerRef } from '../types'; + +export type AnimatedInputProps = BaseTransition & PropsWithInnerRef & InputProps; + +export function AnimatedInput(WrappedComponent: React.ComponentType): React.ComponentType; + +export default AnimatedInput; diff --git a/types/react-select/lib/animated/MultiValue.d.ts b/types/react-select/lib/animated/MultiValue.d.ts new file mode 100644 index 0000000000..8a8f37ad16 --- /dev/null +++ b/types/react-select/lib/animated/MultiValue.d.ts @@ -0,0 +1,12 @@ +import { ComponentType } from 'react'; +import { MultiValueProps } from '../components/MultiValue'; +import { Collapse, fn } from './transitions'; + +export type AnimatedMultiValueProps = { + in: boolean, + onExited: fn, +} & MultiValueProps; + +export function AnimatedMultiValue(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedMultiValue; diff --git a/types/react-select/lib/animated/Placeholder.d.ts b/types/react-select/lib/animated/Placeholder.d.ts new file mode 100644 index 0000000000..1dbd3ba203 --- /dev/null +++ b/types/react-select/lib/animated/Placeholder.d.ts @@ -0,0 +1,9 @@ +import { ComponentType } from 'react'; +import { PlaceholderProps } from '../components/Placeholder'; +import { Fade, collapseDuration } from './transitions'; + +export type AnimatedPlaceholderProps = PlaceholderProps; + +export function AnimatedPlaceholder(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedPlaceholder; diff --git a/types/react-select/lib/animated/SingleValue.d.ts b/types/react-select/lib/animated/SingleValue.d.ts new file mode 100644 index 0000000000..6cd1bea908 --- /dev/null +++ b/types/react-select/lib/animated/SingleValue.d.ts @@ -0,0 +1,9 @@ +import { ComponentType } from 'react'; +import { SingleValueProps } from '../components/SingleValue'; +import { Fade } from './transitions'; + +export type AnimatedSingleValueProps = SingleValueProps; + +export function AnimatedSingleValue(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedSingleValue; diff --git a/types/react-select/lib/animated/ValueContainer.d.ts b/types/react-select/lib/animated/ValueContainer.d.ts new file mode 100644 index 0000000000..6bd15c0c19 --- /dev/null +++ b/types/react-select/lib/animated/ValueContainer.d.ts @@ -0,0 +1,9 @@ +import { ComponentType } from 'react'; +import { TransitionGroup } from 'react-transition-group'; +import { ValueContainerProps } from '../components/containers'; + +export type AnimatedValueContainerProps = ValueContainerProps; + +export function AnimatedValueContainer(WrappedComponent: ComponentType>): ComponentType>; + +export default AnimatedValueContainer; diff --git a/types/react-select/lib/animated/index.d.ts b/types/react-select/lib/animated/index.d.ts new file mode 100644 index 0000000000..6760d55e81 --- /dev/null +++ b/types/react-select/lib/animated/index.d.ts @@ -0,0 +1,17 @@ +import { ComponentType } from 'react'; +import { SelectComponents, defaultComponents } from '../components/index'; +import { default as AnimatedInput, AnimatedInputProps } from './Input'; +import { default as AnimatedMultiValue, AnimatedMultiValueProps } from './MultiValue'; +import { default as AnimatedPlaceholder, AnimatedPlaceholderProps } from './Placeholder'; +import { default as AnimatedSingleValue, AnimatedSingleValueProps } from './SingleValue'; +import { default as AnimatedValueContainer, AnimatedValueContainerProps } from './ValueContainer'; + +export function makeAnimated(externalComponents?: SelectComponents): SelectComponents; + +export const Input: ComponentType; +export const MultiValue: ComponentType>; +export const Placeholder: ComponentType>; +export const SingleValue: ComponentType>; +export const ValueContainer: ComponentType>; + +export default makeAnimated; diff --git a/types/react-select/lib/animated/transitions.d.ts b/types/react-select/lib/animated/transitions.d.ts new file mode 100644 index 0000000000..ee2bd3c83b --- /dev/null +++ b/types/react-select/lib/animated/transitions.d.ts @@ -0,0 +1,50 @@ +import * as React from 'react'; +import { Transition } from 'react-transition-group'; + +export type fn = () => void; +export interface BaseTransition { + /** Whether we are in a transition. */ + in: boolean; + /** Function to be called once transition finishes. */ + onExited: fn; +} + +// ============================== +// Fade Transition +// ============================== + +export type FadeProps = BaseTransition & { + component: React.ComponentType, + duration: number, +}; +export const Fade: React.ComponentType; + +// ============================== +// Collapse Transition +// ============================== + +export const collapseDuration: number; + +export type TransitionState = 'exiting' | 'exited'; +export type Width = number | 'auto'; +export interface CollapseProps { children: any; in: boolean; } +export interface CollapseState { width: Width; } + +// wrap each MultiValue with a collapse transition; decreases width until +// finally removing from DOM +export class Collapse extends React.Component { + duration: number; + transition: { + exiting: any, + exited: any, + }; + + // width must be calculated; cannot transition from `undefined` to `number` + getWidth: (ref: React.Ref) => void; + + // get base styles + getStyle: (width: Width) => any; + + // get transition styles + getTransition: (state: TransitionState) => any; +} diff --git a/types/react-select/lib/builtins.d.ts b/types/react-select/lib/builtins.d.ts new file mode 100644 index 0000000000..5d404230cd --- /dev/null +++ b/types/react-select/lib/builtins.d.ts @@ -0,0 +1,10 @@ +import { ReactNode } from 'react'; +import { GroupType } from './types'; + +export function formatGroupLabel(group: GroupType): ReactNode; + +export function getOptionLabel(option: any): string; + +export function getOptionValue(option: any): string; + +export function isOptionDisabled(option: any): boolean; diff --git a/types/react-select/lib/components/Control.d.ts b/types/react-select/lib/components/Control.d.ts new file mode 100644 index 0000000000..8a9513197b --- /dev/null +++ b/types/react-select/lib/components/Control.d.ts @@ -0,0 +1,29 @@ +import { ComponentType, ReactNode, Ref as ElementRef } from 'react'; + +import { borderRadius, colors, spacing } from '../theme'; +import { CommonProps, PropsWithStyles } from '../types'; + +interface State { + /** Whether the select is disabled. */ + isDisabled: boolean; + /** Whether the select is focused. */ + isFocused: boolean; +} + +export type ControlProps = CommonProps & + PropsWithStyles & + State & { + /** Children to render. */ + children: ReactNode, + innerRef: ElementRef, + /** The mouse down event and the innerRef to pass down to the controller element. */ + innerProps: { + onMouseDown: (event: React.MouseEvent) => void, + }, + }; + +export function css(state: State): React.CSSProperties; + +declare const Control: ComponentType>; + +export default Control; diff --git a/types/react-select/lib/components/Group.d.ts b/types/react-select/lib/components/Group.d.ts new file mode 100644 index 0000000000..39c3489bce --- /dev/null +++ b/types/react-select/lib/components/Group.d.ts @@ -0,0 +1,24 @@ +import { ReactNode, ComponentType } from 'react'; + +import { spacing } from '../theme'; +import { CommonProps } from '../types'; + +interface ComponentProps { + /** The children to be rendered. */ + children: ReactNode; + /** Component to wrap the label, recieves headingProps. */ + Heading: ComponentType; + /** Label to be displayed in the heading component. */ + label: ReactNode; +} +export type GroupProps = CommonProps & ComponentProps; + +export function groupCSS(): React.CSSProperties; + +export const Group: ComponentType>; + +export function groupHeadingCSS(): React.CSSProperties; + +export const GroupHeading: ComponentType; + +export default Group; diff --git a/types/react-select/lib/components/Input.d.ts b/types/react-select/lib/components/Input.d.ts new file mode 100644 index 0000000000..9f79ffb1e0 --- /dev/null +++ b/types/react-select/lib/components/Input.d.ts @@ -0,0 +1,23 @@ +import { ComponentType, Ref as ElementRef } from 'react'; + +import { colors, spacing } from '../theme'; + +import { PropsWithStyles, ClassNamesState } from '../types'; + +export type InputProps = PropsWithStyles & { + cx: (a: string | null, b: ClassNamesState, c: string) => string | void, + /** Reference to the internal element */ + innerRef: (element: ElementRef) => void, + /** Set whether the input should be visible. Does not affect input size. */ + isHidden: boolean, + /** Whether the input is disabled */ + isDisabled?: boolean, + className?: string, +}; + +export function inputCSS(props: InputProps): React.CSSProperties; +export function inputStyle(isHidden: boolean): React.CSSProperties; + +export const Input: ComponentType; + +export default Input; diff --git a/types/react-select/lib/components/Menu.d.ts b/types/react-select/lib/components/Menu.d.ts new file mode 100644 index 0000000000..0af2bf16c1 --- /dev/null +++ b/types/react-select/lib/components/Menu.d.ts @@ -0,0 +1,158 @@ +import { + Component, + ReactElement, + Ref as ElementRef, + ReactNode, + ComponentType +} from 'react'; +import { createPortal } from 'react-dom'; + +import { + animatedScrollTo, + getBoundingClientObj, + RectType, + getScrollParent, + getScrollTop, + scrollTo, +} from '../utils'; +import { borderRadius, colors, spacing } from '../theme'; +import { + InnerRef, + MenuPlacement, + MenuPosition, + CommonProps, +} from '../types'; + +// ============================== +// Menu +// ============================== + +// Get Menu Placement +// ------------------------------ + +interface MenuState { placement: 'bottom' | 'top' | null; maxHeight: number; } +interface PlacementArgs { + maxHeight: number; + menuEl: ElementRef; + minHeight: number; + placement: 'bottom' | 'top' | 'auto'; + shouldScroll: boolean; + isFixedPosition: boolean; +} + +export function getMenuPlacement(args: PlacementArgs): MenuState; + +// Menu Component +// ------------------------------ + +export type MenuProps = CommonProps & { + /** The children to be rendered. */ + children: ReactElement, + /** Callback to update the portal after possible flip. */ + getPortalPlacement: (state: MenuState) => void, + /** Props to be passed to the menu wrapper. */ + innerProps: object, + /** Set the maximum height of the menu. */ + maxMenuHeight: number, + /** Set whether the menu should be at the top, at the bottom. The auto options sets it to bottom. */ + menuPlacement: MenuPlacement, + /* The CSS position value of the menu, when "fixed" extra layout management is required */ + menuPosition: MenuPosition, + /** Set the minimum height of the menu. */ + minMenuHeight: number, + /** Set whether the page should scroll to show the menu. */ + menuShouldScrollIntoView: boolean, +}; + +export function menuCSS(state: MenuState): React.CSSProperties; + +export class Menu extends Component, MenuState> { + static contextTypes: { + getPortalPlacement: (state: MenuState) => void, + }; + getPlacement: (ref: ElementRef) => void; + getState: () => MenuProps & MenuState; +} + +export default Menu; + +// ============================== +// Menu List +// ============================== + +interface MenuListState { + /** Set classname for isMulti */ + isMulti: boolean; + /* Set the max height of the Menu component */ + maxHeight: number; +} + +export interface MenuListProps { + /** The children to be rendered. */ + children: ReactNode; + /** Inner ref to DOM Node */ + innerRef: InnerRef; +} +export type MenuListComponentProps = CommonProps & + MenuListProps & + MenuListState; +export function menuListCSS(state: MenuState): React.CSSProperties; +export const MenuList: ComponentType>; + +// ============================== +// Menu Notices +// ============================== + +export function noOptionsMessageCSS(): React.CSSProperties; +export function loadingMessageCSS(): React.CSSProperties; + +export type NoticeProps = CommonProps & { + /** The children to be rendered. */ + children: ReactNode, + /** Props to be passed on to the wrapper. */ + innerProps: { [key: string]: any }, +}; + +export const NoOptionsMessage: ComponentType>; +// NoOptionsMessage.defaultProps = { +// children: 'No options', +// }; + +export const LoadingMessage: ComponentType>; +// LoadingMessage.defaultProps = { +// children: 'Loading...', +// }; + +// ============================== +// Menu Portal +// ============================== + +export type MenuPortalProps = CommonProps & { + appendTo: HTMLElement, + children: ReactNode, // ideally Menu + controlElement: HTMLElement, + menuPlacement: MenuPlacement, + menuPosition: MenuPosition, +}; +interface MenuPortalState { + placement: 'bottom' | 'top' | null; +} +interface PortalStyleArgs { + offset: number; + position: MenuPosition; + rect: RectType; +} + +export function menuPortalCSS(args: PortalStyleArgs): React.CSSProperties; + +export class MenuPortal extends Component, MenuPortalState> { + static childContextTypes: { + getPortalPlacement: (state: MenuState) => void, + }; + getChildContext(): { + getPortalPlacement: (state: MenuState) => void; + }; + + // callback for occassions where the menu must "flip" + getPortalPlacement: (state: MenuState) => void; +} diff --git a/types/react-select/lib/components/MultiValue.d.ts b/types/react-select/lib/components/MultiValue.d.ts new file mode 100644 index 0000000000..59974fbc46 --- /dev/null +++ b/types/react-select/lib/components/MultiValue.d.ts @@ -0,0 +1,57 @@ +import { ComponentType, Component, ReactNode } from 'react'; + +import { borderRadius, colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +export type MultiValueProps = CommonProps &{ + children: ReactNode, + components: any, + cropWithEllipsis: boolean, + data: OptionType, + innerProps: any, + isFocused: boolean, + isDisabled: boolean, + removeProps: { + onTouchEnd: (event: any) => void, + onClick: (event: any) => void, + onMouseDown: (event: any) => void, + }, +}; + +export function multiValueCSS(): React.CSSProperties; +export function multiValueLabelCSS(props: MultiValueProps): React.CSSProperties; +export function multiValueRemoveCSS(props: MultiValueProps): React.CSSProperties; + +export interface MultiValueGenericProps { + children: ReactNode; + data: OptionType; + innerProps: { className?: string }; + selectProps: any; +} +export const MultiValueGeneric: ComponentType>; + +export const MultiValueContainer: typeof MultiValueGeneric; +export const MultiValueLabel: typeof MultiValueGeneric; +export type MultiValueRemoveProps = CommonProps & { + children: ReactNode, + innerProps: { + className: string, + onTouchEnd: (event: any) => void, + onClick: (event: any) => void, + onMouseDown: (event: any) => void, + }, + selectProps: any, +}; +export class MultiValueRemove extends Component> { + static defaultProps: { + children: ReactNode, + }; +} + +export class MultiValue extends Component> { + static defaultProps: { + cropWithEllipsis: boolean, + }; +} + +export default MultiValue; diff --git a/types/react-select/lib/components/Option.d.ts b/types/react-select/lib/components/Option.d.ts new file mode 100644 index 0000000000..defe37711a --- /dev/null +++ b/types/react-select/lib/components/Option.d.ts @@ -0,0 +1,41 @@ +import { ComponentType, ReactNode, MouseEventHandler } from 'react'; + +import { colors, spacing } from '../theme'; +import { CommonProps, PropsWithStyles, InnerRef } from '../types'; + +interface State { + /** Wether the option is disabled. */ + isDisabled: boolean; + /** Wether the option is focused. */ + isFocused: boolean; + /** Whether the option is selected. */ + isSelected: boolean; +} +interface InnerProps { + id: string; + key: string; + onClick: MouseEventHandler; + onMouseOver: MouseEventHandler; + tabIndex: number; +} +export type OptionProps = PropsWithStyles & + CommonProps & + State & { + /** The children to be rendered. */ + children: ReactNode, + /** Inner ref to DOM Node */ + innerRef: InnerRef, + /** props passed to the wrapping element for the group. */ + innerProps: InnerProps, + /* Text to be displayed representing the option. */ + label: string, + /* Type is used by the menu to determine whether this is an option or a group. + In the case of option this is always `option`. */ + type: 'option', + }; + +export function optionCSS(state: State): React.CSSProperties; + +export const Option: ComponentType>; + +export default Option; diff --git a/types/react-select/lib/components/Placeholder.d.ts b/types/react-select/lib/components/Placeholder.d.ts new file mode 100644 index 0000000000..1a72bd69a7 --- /dev/null +++ b/types/react-select/lib/components/Placeholder.d.ts @@ -0,0 +1,17 @@ +import { ComponentType, ReactNode } from 'react'; + +import { colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +export type PlaceholderProps = CommonProps & { + /** The children to be rendered. */ + children: ReactNode, + /** props passed to the wrapping element for the group. */ + innerProps: { [key: string]: any }, +}; + +export function placeholderCSS(): React.CSSProperties; + +export const Placeholder: ComponentType>; + +export default Placeholder; diff --git a/types/react-select/lib/components/SingleValue.d.ts b/types/react-select/lib/components/SingleValue.d.ts new file mode 100644 index 0000000000..c727b2242e --- /dev/null +++ b/types/react-select/lib/components/SingleValue.d.ts @@ -0,0 +1,23 @@ +import { ComponentType } from 'react'; +import { colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +interface State { + /** Whether this is disabled */ + isDisabled: boolean; +} +interface ValueProps { + /** The children to be rendered. */ + children: string; + /* The data of the selected option rendered in the Single Value componentn */ + data: OptionType; + /** Props passed to the wrapping element for the group. */ + innerProps: any; +} +export type SingleValueProps = CommonProps & ValueProps & State; + +export function css(props: SingleValueProps): React.CSSProperties; + +export const SingleValue: ComponentType>; + +export default SingleValue; diff --git a/types/react-select/lib/components/containers.d.ts b/types/react-select/lib/components/containers.d.ts new file mode 100644 index 0000000000..c72609bf31 --- /dev/null +++ b/types/react-select/lib/components/containers.d.ts @@ -0,0 +1,57 @@ +import { Component, ReactNode, ComponentType } from 'react'; +import { spacing } from '../theme'; +import { CommonProps, KeyboardEventHandler } from '../types'; + +// ============================== +// Root Container +// ============================== + +export interface ContainerState { + /** Whether the select is disabled. */ + isDisabled: boolean; + /** Whether the text in the select is indented from right to left. */ + isRtl: boolean; +} + +export type ContainerProps = CommonProps & + ContainerState & { + /** The children to be rendered. */ + children: ReactNode, + /** Inner props to be passed down to the container. */ + innerProps: { onKeyDown: KeyboardEventHandler }, + }; +export function containerCSS(state: ContainerState): React.CSSProperties; +export const SelectContainer: ComponentType>; + +// ============================== +// Value Container +// ============================== + +export type ValueContainerProps = CommonProps & { + /** Set when the value container should hold multiple values */ + isMulti: boolean, + /** Whether the value container currently holds a value. */ + hasValue: boolean, + /** The children to be rendered. */ + children: ReactNode, +}; +export function valueContainerCSS(): React.CSSProperties; +export class ValueContainer extends Component> {} + +// ============================== +// Indicator Container +// ============================== + +export interface IndicatorsState { + /** Whether the text should be rendered right to left. */ + isRtl: boolean; +} + +export type IndicatorContainerProps = CommonProps & + IndicatorsState & { + /** The children to be rendered. */ + children: ReactNode, + }; + +export function indicatorsContainerCSS(): React.CSSProperties; +export const IndicatorsContainer: ComponentType>; diff --git a/types/react-select/lib/components/index.d.ts b/types/react-select/lib/components/index.d.ts new file mode 100644 index 0000000000..d9d505b119 --- /dev/null +++ b/types/react-select/lib/components/index.d.ts @@ -0,0 +1,116 @@ +import { + ComponentType, + ReactElement as Element, +} from 'react'; +import { + IndicatorContainerProps, + ContainerProps, + ValueContainerProps, + IndicatorsContainer, + SelectContainer, + ValueContainer, +} from './containers'; +import { + IndicatorProps, + LoadingIconProps, + ClearIndicator, + DropdownIndicator, + LoadingIndicator, + IndicatorSeparator, + DownChevron, + CrossIcon, +} from './indicators'; + +import Control, { ControlProps } from './Control'; +import Group, { GroupProps, GroupHeading } from './Group'; +import Input, { InputProps } from './Input'; +import Menu, { + MenuProps, + MenuList, + MenuListComponentProps, + MenuPortal, + MenuPortalProps, + NoticeProps, + NoOptionsMessage, + LoadingMessage, +} from './Menu'; +import MultiValue, { + MultiValueProps, + MultiValueContainer, + MultiValueLabel, + MultiValueRemove, +} from './MultiValue'; +import Option, { OptionProps } from './Option'; +import Placeholder, { PlaceholderProps } from './Placeholder'; +import SingleValue, { SingleValueProps } from './SingleValue'; + +export type PlaceholderOrValue = + | Element>> + | Element>> + | Array>>>; + +export type IndicatorComponentType = ComponentType>; + +export interface SelectComponents { + ClearIndicator: IndicatorComponentType | null; + Control: ComponentType>; + DropdownIndicator: IndicatorComponentType | null; + DownChevron: ComponentType; + CrossIcon: ComponentType; + Group: ComponentType>; + GroupHeading: ComponentType; + IndicatorsContainer: ComponentType>; + IndicatorSeparator: IndicatorComponentType | null; + Input: ComponentType; + LoadingIndicator: ComponentType> | null; + Menu: ComponentType>; + MenuList: ComponentType>; + MenuPortal: ComponentType>; + LoadingMessage: ComponentType>; + NoOptionsMessage: ComponentType>; + MultiValue: ComponentType>; + MultiValueContainer: ComponentType; + MultiValueLabel: ComponentType; + MultiValueRemove: ComponentType; + Option: ComponentType>; + Placeholder: ComponentType>; + SelectContainer: ComponentType>; + SingleValue: ComponentType>; + ValueContainer: ComponentType>; +} + +export type SelectComponentsConfig = Partial>; + +export namespace components { + const ClearIndicator: IndicatorComponentType | null; + const Control: ComponentType>; + const DropdownIndicator: IndicatorComponentType | null; + const DownChevron: ComponentType; + const CrossIcon: ComponentType; + const Group: ComponentType>; + const GroupHeading: ComponentType; + const IndicatorsContainer: ComponentType>; + const IndicatorSeparator: IndicatorComponentType | null; + const Input: ComponentType; + const LoadingIndicator: ComponentType> | null; + const Menu: ComponentType>; + const MenuList: ComponentType>; + const MenuPortal: ComponentType>; + const LoadingMessage: ComponentType>; + const NoOptionsMessage: ComponentType>; + const MultiValue: ComponentType>; + const MultiValueContainer: ComponentType; + const MultiValueLabel: ComponentType; + const MultiValueRemove: ComponentType; + const Option: ComponentType>; + const Placeholder: ComponentType>; + const SelectContainer: ComponentType>; + const SingleValue: ComponentType>; + const ValueContainer: ComponentType>; +} + +export interface Props { + components: SelectComponentsConfig; +} + +export function defaultComponents(props: Props): SelectComponentsConfig; diff --git a/types/react-select/lib/components/indicators.d.ts b/types/react-select/lib/components/indicators.d.ts new file mode 100644 index 0000000000..15df6d3748 --- /dev/null +++ b/types/react-select/lib/components/indicators.d.ts @@ -0,0 +1,67 @@ +import { ComponentType, ReactElement as ElementType } from 'react'; + +import { colors, spacing } from '../theme'; +import { CommonProps } from '../types'; + +// ============================== +// Dropdown & Clear Icons +// ============================== + +export function CrossIcon(props: any): any; // TODO svg type +export function DownChevron(props: any): any; // TODO svg type + +// ============================== +// Dropdown & Clear Buttons +// ============================== + +export type IndicatorProps = CommonProps & { + /** The children to be rendered inside the indicator. */ + children: ElementType, + /** Props that will be passed on to the children. */ + innerProps: any, + /** The focused state of the select. */ + isFocused: boolean, + /** Whether the text is right to left */ + isRtl: boolean, +}; + +export type baseCSS = (props: IndicatorProps) => React.CSSProperties; + +export const dropdownIndicatorCSS: baseCSS; +export const DropdownIndicator: ComponentType>; + +export const clearIndicatorCSS: baseCSS; +export const ClearIndicator: ComponentType>; + +// ============================== +// Separator +// ============================== + +export interface SeparatorState { isDisabled: boolean; } + +export function indicatorSeparatorCSS(state: SeparatorState): React.CSSProperties; + +export const IndicatorSeparator: ComponentType>; + +// ============================== +// Loading +// ============================== + +export function loadingIndicatorCSS(state: { + isFocused: boolean, + size: number, +}): React.CSSProperties; + +export type LoadingIconProps = { + /** Props that will be passed on to the children. */ + innerProps: any, + /** The focused state of the select. */ + isFocused: boolean, + /** Whether the text is right to left */ + isRtl: boolean, +} & CommonProps & { + /** Set size of the container. */ + size: number, +}; +export const LoadingIndicator: ComponentType>; +// TODO LoadingIndicator.defaultProps: { size: number }; diff --git a/types/react-select/lib/diacritics.d.ts b/types/react-select/lib/diacritics.d.ts new file mode 100644 index 0000000000..855a0e152a --- /dev/null +++ b/types/react-select/lib/diacritics.d.ts @@ -0,0 +1 @@ +export function stripDiacritics(str: string): string; diff --git a/types/react-select/lib/filters.d.ts b/types/react-select/lib/filters.d.ts new file mode 100644 index 0000000000..33d1a7fddf --- /dev/null +++ b/types/react-select/lib/filters.d.ts @@ -0,0 +1,16 @@ +export interface Config { + ignoreCase?: boolean; + ignoreAccents?: boolean; + stringify?: (obj: any) => string; + trim?: boolean; + matchFrom?: 'any' | 'start'; +} + +import { stripDiacritics } from './diacritics'; + +export interface Option { label: string; value: string; data: any; } + +export function createFilter(config: Config | null): ( + option: Option, + rawInput: string +) => boolean; diff --git a/types/react-select/lib/stateManager.d.ts b/types/react-select/lib/stateManager.d.ts new file mode 100644 index 0000000000..07a17f52f7 --- /dev/null +++ b/types/react-select/lib/stateManager.d.ts @@ -0,0 +1,36 @@ +import { Component, ComponentType, Ref as ElementRef } from 'react'; + +import { ActionMeta, InputActionMeta, ValueType } from './types'; + +export interface Props { + defaultInputValue?: string; + defaultMenuIsOpen?: boolean; + defaultValue?: ValueType; + inputValue?: string; + menuIsOpen?: boolean; + value?: ValueType; +} +interface State { + inputValue: string; + menuIsOpen: boolean; + value: ValueType; +} + +export class StateManager extends Component, State> { + static defaultProps: Props; + + select: ElementRef; + + focus(): void; + blur(): void; + getProp(key: string): any; + callProp(name: string, ...args: any[]): any; + onChange: (value: any, actionMeta: ActionMeta) => void; + onInputChange: (value: any, actionMeta: InputActionMeta) => void; + onMenuOpen: () => void; + onMenuClose: () => void; +} + +export function manageState(SelectComponent: ComponentType): StateManager; + +export default manageState; diff --git a/types/react-select/lib/styles.d.ts b/types/react-select/lib/styles.d.ts new file mode 100644 index 0000000000..e9c63d07b8 --- /dev/null +++ b/types/react-select/lib/styles.d.ts @@ -0,0 +1,75 @@ +import { + containerCSS, + indicatorsContainerCSS, + valueContainerCSS, +} from './components/containers'; +import { css as controlCSS } from './components/Control'; +import { groupCSS, groupHeadingCSS } from './components/Group'; +import { + clearIndicatorCSS, + dropdownIndicatorCSS, + loadingIndicatorCSS, + indicatorSeparatorCSS, +} from './components/indicators'; +import { inputCSS } from './components/Input'; +import { placeholderCSS } from './components/Placeholder'; +import { optionCSS } from './components/Option'; +import { + menuCSS, + menuListCSS, + menuPortalCSS, + noOptionsMessageCSS, + loadingMessageCSS, +} from './components/Menu'; +import { css as singleValueCSS } from './components/SingleValue'; +import { + multiValueCSS, + multiValueLabelCSS, + multiValueRemoveCSS, +} from './components/MultiValue'; +import { CSSProperties } from 'react'; + +export interface Props { [key: string]: any; } + +/** + * @param base -- the component's default style + * @param state -- the component's current state e.g. `isFocused` + * @returns + */ +export type styleFn = (base: CSSProperties, state: any) => CSSProperties; + +export interface Styles { + clearIndicator?: styleFn; + container?: styleFn; + control?: styleFn; + dropdownIndicator?: styleFn; + group?: styleFn; + groupHeading?: styleFn; + indicatorsContainer?: styleFn; + indicatorSeparator?: styleFn; + input?: styleFn; + loadingIndicator?: styleFn; + // TODO loadingMessageCSS?: styleFn; + loadingMessage?: styleFn; + menu?: styleFn; + menuList?: styleFn; + menuPortal?: styleFn; + multiValue?: styleFn; + multiValueLabel?: styleFn; + multiValueRemove?: styleFn; + // TODO noOptionsMessageCSS?: styleFn; + noOptionsMessage?: styleFn; + option?: styleFn; + placeholder?: styleFn; + singleValue?: styleFn; + valueContainer: styleFn; +} +export type StylesConfig = Partial; +export type GetStyles = (a: string, b: Props) => CSSProperties; + +export const defaultStyles: Styles; + +// Merge Utility +// Allows consumers to extend a base Select with additional styles + +export function mergeStyles(source: any, target: any): CSSProperties; diff --git a/types/react-select/lib/theme.d.ts b/types/react-select/lib/theme.d.ts new file mode 100644 index 0000000000..7282dd20ad --- /dev/null +++ b/types/react-select/lib/theme.d.ts @@ -0,0 +1,53 @@ +export const borderRadius: number; + +export const colors: { + text: string; + textLight: string; + primary: string; + primary75: string; + primary50: string; + primary25: string; + danger: string; + dangerLight: string; + + neutral0: string; + neutral1: string; + neutral2: string; + neutral3: string; + neutral4: string; + neutral5: string; + neutral10: string; + neutral20: string; + neutral30: string; + neutral40: string; + neutral50: string; + neutral60: string; + neutral70: string; + neutral80: string; + neutral90: string; + neutral100: string; + + neutral1a: string; + neutral2a: string; + neutral3a: string; + neutral4a: string; + neutral5a: string; + neutral10a: string; + neutral20a: string; + neutral30a: string; + neutral40a: string; + neutral50a: string; + neutral60a: string; + neutral70a: string; + neutral80a: string; + neutral90a: string; +}; + +export const spacing: { + /* Used to calculate consistent margin/padding on elements */ + baseUnit: number, + /* The minimum height of the control */ + controlHeight: number, + /* The amount of space between the control and menu */ + menuGutter: number, +}; diff --git a/types/react-select/lib/types.d.ts b/types/react-select/lib/types.d.ts new file mode 100644 index 0000000000..08ebfae965 --- /dev/null +++ b/types/react-select/lib/types.d.ts @@ -0,0 +1,100 @@ +import * as React from 'react'; + +export type OptionsType = OptionType[]; + +export interface GroupType { + options: OptionsType; + [key: string]: any; +} + +export type GroupedOptionsType = Array>; + +export type ValueType = OptionType | OptionsType | null | undefined; + +export type FocusEventHandler = (event: React.FocusEvent) => void; +export type MouseEventHandler = (event: React.MouseEvent) => void; +export type KeyboardEventHandler = (event: React.KeyboardEvent) => void; + +export type InnerRef = React.Ref; +export interface PropsWithInnerRef { + /** The inner reference. */ + innerRef: React.Ref; +} + +export interface PropsWithStyles { + /* + Get the styles of a particular part of the select. Pass in the name of the + property as the first argument, and the current props as the second argument. + See the `styles` object for the properties available. + */ + getStyles: (name: string, props: any) => {}; +} + +export type ClassNameList = string[]; +export type ClassNamesState = { [key: string]: boolean } | undefined; + +export interface CommonProps { + clearValue: () => void; + className?: string; + cx: (a: string | null, b: ClassNamesState | undefined, c: string | undefined) => string | void; + /* + Get the styles of a particular part of the select. Pass in the name of the + property as the first argument, and the current props as the second argument. + See the `styles` object for the properties available. + */ + getStyles: (name: string, props: any) => {}; + getValue: () => ValueType; + hasValue: boolean; + isMulti: boolean; + options: OptionsType; + selectOption: (option: OptionType) => void; + selectProps: any; + setValue: (value: ValueType, action: ActionTypes) => void; +} + +export type ActionTypes = + | 'select-option' + | 'deselect-option' + | 'remove-value' + | 'pop-value' + | 'set-value' + | 'clear' + | 'create-option'; + +export interface ActionMeta { + action: ActionTypes; +} + +export type InputActionTypes = + | 'set-value' + | 'input-change' + | 'input-blur' + | 'menu-close'; + +export interface InputActionMeta { + action: InputActionTypes; +} + +export type MenuPlacement = 'auto' | 'bottom' | 'top'; +export type MenuPosition = 'absolute' | 'fixed'; + +export type FocusDirection = + | 'up' + | 'down' + | 'pageup' + | 'pagedown' + | 'first' + | 'last'; + +export type OptionProps = PropsWithInnerRef & { + data: any, + id: number, + index: number, + isDisabled: boolean, + isFocused: boolean, + isSelected: boolean, + label: string, + onClick: MouseEventHandler, + onMouseOver: MouseEventHandler, + value: any, +}; diff --git a/types/react-select/lib/utils.d.ts b/types/react-select/lib/utils.d.ts new file mode 100644 index 0000000000..c907d59c2a --- /dev/null +++ b/types/react-select/lib/utils.d.ts @@ -0,0 +1,121 @@ +import * as React from 'react'; +import { + ClassNamesState, + InputActionMeta, + OptionsType, + ValueType, +} from './types'; + +// ============================== +// NO OP +// ============================== + +export function noop(): void; +export function emptyString(): string; + +// ============================== +// Class Name Prefixer +// ============================== + +export function classNames( + prefix?: string | null, + cssKey?: string | null, + state?: ClassNamesState, + className?: string, +): string; + +// ============================== +// Clean Value +// ============================== + +export function cleanValue(value: ValueType): OptionsType; + +// ============================== +// Handle Input Change +// ============================== + +export function handleInputChange( + inputValue: string, + actionMeta: InputActionMeta, + onInputChange?: (inputValue: string, actionMeta: InputActionMeta) => string | void +): string; + +// ============================== +// Scroll Helpers +// ============================== + +export function isDocumentElement(el: Element): boolean; + +// Normalized Scroll Top +// ------------------------------ + +export function normalizedHeight(el: Element): number; + +// Normalized scrollTo & scrollTop +// ------------------------------ + +export function getScrollTop(el: Element): number; + +export function scrollTo(el: Element, top: number): void; + +// Get Scroll Parent +// ------------------------------ + +export function getScrollParent(element: React.Ref): Element; + +// Animated Scroll To +// ------------------------------ + +export function animatedScrollTo( + element: Element, + to: number, + duration: number, + callback: (element: Element) => void +): void; + +// Scroll Into View +// ------------------------------ + +export function scrollIntoView( + menuEl: HTMLElement, + focusedEl: HTMLElement +): void; + +// ============================== +// Get bounding client object +// ============================== + +// cannot get keys using array notation with DOMRect +export function getBoundingClientObj(element: HTMLElement): { + bottom: number; + height: number; + left: number; + right: number; + top: number; + width: number; +}; +export interface RectType { + left: number; + right: number; + bottom: number; + height: number; + width: number; +} + +// ============================== +// String to Key (kebabify) +// ============================== + +export function toKey(str: string): string; + +// ============================== +// Touch Capability Detector +// ============================== + +export function isTouchCapable(): boolean; + +// ============================== +// Mobile Device Detector +// ============================== + +export function isMobileDevice(): boolean; diff --git a/types/react-select/test/AtlaskitDummy.ts b/types/react-select/test/AtlaskitDummy.ts new file mode 100644 index 0000000000..e6e75e9e32 --- /dev/null +++ b/types/react-select/test/AtlaskitDummy.ts @@ -0,0 +1,11 @@ +export const Tooltip = (props: any) => null; + +export const EmojiIcon = (props: any) => null; + +export const EditorPanelIcon = (props: any) => null; + +export const Spinner = (props: any) => null; + +export const Button = (props: any) => null; + +export const Modal = (props: any) => null; diff --git a/types/react-select/test/ChronoNodeDummy.ts b/types/react-select/test/ChronoNodeDummy.ts new file mode 100644 index 0000000000..1e4aed01b0 --- /dev/null +++ b/types/react-select/test/ChronoNodeDummy.ts @@ -0,0 +1 @@ +export function parseDate(a: any): any {} diff --git a/types/react-select/test/data.ts b/types/react-select/test/data.ts new file mode 100644 index 0000000000..a4bff0225d --- /dev/null +++ b/types/react-select/test/data.ts @@ -0,0 +1,132 @@ +import { GroupedOptionsType, GroupType } from "react-select/lib/types"; + +export interface ColourOption { + value: string; + label: string; + color: string; + disabled?: boolean; +} + +export const colourOptions: ColourOption[] = [ + { value: 'ocean', label: 'Ocean', color: '#00B8D9' }, + { value: 'blue', label: 'Blue', color: '#0052CC', disabled: true }, + { value: 'purple', label: 'Purple', color: '#5243AA' }, + { value: 'red', label: 'Red', color: '#FF5630' }, + { value: 'orange', label: 'Orange', color: '#FF8B00' }, + { value: 'yellow', label: 'Yellow', color: '#FFC400' }, + { value: 'green', label: 'Green', color: '#36B37E' }, + { value: 'forest', label: 'Forest', color: '#00875A' }, + { value: 'slate', label: 'Slate', color: '#253858' }, + { value: 'silver', label: 'Silver', color: '#666666' }, +]; + +export interface FlavourOption { + value: string; + label: string; + rating: 'safe' | 'good' | 'wild' | 'crazy'; +} + +export const flavourOptions: FlavourOption[] = [ + { value: 'vanilla', label: 'Vanilla', rating: 'safe' }, + { value: 'chocolate', label: 'Chocolate', rating: 'good' }, + { value: 'strawberry', label: 'Strawberry', rating: 'wild' }, + { value: 'salted-caramel', label: 'Salted Caramel', rating: 'crazy' }, +]; + +export interface StateOption { + value: string; + label: string; +} + +export const stateOptions: StateOption[] = [ + { value: 'AL', label: 'Alabama' }, + { value: 'AK', label: 'Alaska' }, + { value: 'AS', label: 'American Samoa' }, + { value: 'AZ', label: 'Arizona' }, + { value: 'AR', label: 'Arkansas' }, + { value: 'CA', label: 'California' }, + { value: 'CO', label: 'Colorado' }, + { value: 'CT', label: 'Connecticut' }, + { value: 'DE', label: 'Delaware' }, + { value: 'DC', label: 'District Of Columbia' }, + { value: 'FM', label: 'Federated States Of Micronesia' }, + { value: 'FL', label: 'Florida' }, + { value: 'GA', label: 'Georgia' }, + { value: 'GU', label: 'Guam' }, + { value: 'HI', label: 'Hawaii' }, + { value: 'ID', label: 'Idaho' }, + { value: 'IL', label: 'Illinois' }, + { value: 'IN', label: 'Indiana' }, + { value: 'IA', label: 'Iowa' }, + { value: 'KS', label: 'Kansas' }, + { value: 'KY', label: 'Kentucky' }, + { value: 'LA', label: 'Louisiana' }, + { value: 'ME', label: 'Maine' }, + { value: 'MH', label: 'Marshall Islands' }, + { value: 'MD', label: 'Maryland' }, + { value: 'MA', label: 'Massachusetts' }, + { value: 'MI', label: 'Michigan' }, + { value: 'MN', label: 'Minnesota' }, + { value: 'MS', label: 'Mississippi' }, + { value: 'MO', label: 'Missouri' }, + { value: 'MT', label: 'Montana' }, + { value: 'NE', label: 'Nebraska' }, + { value: 'NV', label: 'Nevada' }, + { value: 'NH', label: 'New Hampshire' }, + { value: 'NJ', label: 'New Jersey' }, + { value: 'NM', label: 'New Mexico' }, + { value: 'NY', label: 'New York' }, + { value: 'NC', label: 'North Carolina' }, + { value: 'ND', label: 'North Dakota' }, + { value: 'MP', label: 'Northern Mariana Islands' }, + { value: 'OH', label: 'Ohio' }, + { value: 'OK', label: 'Oklahoma' }, + { value: 'OR', label: 'Oregon' }, + { value: 'PW', label: 'Palau' }, + { value: 'PA', label: 'Pennsylvania' }, + { value: 'PR', label: 'Puerto Rico' }, + { value: 'RI', label: 'Rhode Island' }, + { value: 'SC', label: 'South Carolina' }, + { value: 'SD', label: 'South Dakota' }, + { value: 'TN', label: 'Tennessee' }, + { value: 'TX', label: 'Texas' }, + { value: 'UT', label: 'Utah' }, + { value: 'VT', label: 'Vermont' }, + { value: 'VI', label: 'Virgin Islands' }, + { value: 'VA', label: 'Virginia' }, + { value: 'WA', label: 'Washington' }, + { value: 'WV', label: 'West Virginia' }, + { value: 'WI', label: 'Wisconsin' }, + { value: 'WY', label: 'Wyoming' }, +]; + +export const optionLength = [ + { value: 1, label: 'general' }, + { + value: 2, + label: + 'Evil is the moment when I lack the strength to be true to the Good that compels me.', + }, + { + value: 3, + label: + // tslint:disable-next-line:max-line-length + "It is now an easy matter to spell out the ethic of a truth: 'Do all that you can to persevere in that which exceeds your perseverance. Persevere in the interruption. Seize in your being that which has seized and broken you.", + }, +]; + +// let bigOptions = []; +// for (let i = 0; i < 10000; i++) { +// bigOptions = bigOptions.concat(colourOptions); +// } + +const colourGroup: GroupType = { + label: 'Colours', + options: colourOptions +}; +const flavourGroup: GroupType = { + label: 'Flavours', + options: flavourOptions, +}; + +export const groupedOptions: GroupedOptionsType = [ colourGroup, flavourGroup ]; diff --git a/types/react-select/test/examples/AccessingInternals.tsx b/types/react-select/test/examples/AccessingInternals.tsx new file mode 100644 index 0000000000..8948bc19e7 --- /dev/null +++ b/types/react-select/test/examples/AccessingInternals.tsx @@ -0,0 +1,114 @@ +import * as React from 'react'; + +import Select from 'react-select'; +import AsyncSelect from 'react-select/lib/Async'; +import CreatableSelect from 'react-select/lib/Creatable'; +import { Note } from '../styled-components'; +import { ColourOption, colourOptions } from '../data'; + +const filterColors = (inputValue: string) => + colourOptions.filter(i => + i.label.toLowerCase().includes(inputValue.toLowerCase()) + ); + +const promiseOptions = (inputValue: string) => + new Promise(resolve => { + setTimeout(() => { + resolve(filterColors(inputValue)); + }, 1000); + }); + +export default class AccessingInterals extends React.Component { + selectRef: Select; + asyncRef: AsyncSelect; + creatableRef: CreatableSelect; + focus = () => { + console.log(this.selectRef); + this.selectRef.focus(); + } + focusCreatable = () => { + console.log(this.creatableRef); + this.creatableRef.focus(); + } + focusAsync = () => { + console.log(this.asyncRef); + this.asyncRef.focus(); + } + blurAsync = () => { + this.asyncRef.blur(); + } + blurCreatable = () => { + this.creatableRef.blur(); + } + blur = () => this.selectRef.blur(); + onSelectRef = (ref: any) => { + console.log(ref); + this.selectRef = ref; + } + render() { + return ( + +

+ Creatable Select +

+ { this.creatableRef = ref; }} + isClearable + options={colourOptions} + /> + + + + + + +

+ Async Select +

+ { this.asyncRef = ref; }} + cacheOptions + defaultOptions + loadOptions={promiseOptions} + /> + + + + + + +

Select

+ +); diff --git a/types/react-select/test/examples/BasicSingle.tsx b/types/react-select/test/examples/BasicSingle.tsx new file mode 100644 index 0000000000..69697566c2 --- /dev/null +++ b/types/react-select/test/examples/BasicSingle.tsx @@ -0,0 +1,101 @@ +import * as React from 'react'; + +import Select from 'react-select'; +import { colourOptions } from '../data'; +import { Note } from '../styled-components'; + +const Checkbox = (props: any) => ; + +interface State { + isClearable: boolean; + isDisabled: boolean; + isLoading: boolean; + isRtl: boolean; + isSearchable: boolean; +} + +export default class SingleSelect extends React.Component { + state = { + isClearable: true, + isDisabled: false, + isLoading: false, + isRtl: false, + isSearchable: true, + }; + + toggleClearable = () => + this.setState(state => ({ isClearable: !state.isClearable })) + toggleDisabled = () => + this.setState(state => ({ isDisabled: !state.isDisabled })) + toggleLoading = () => + this.setState(state => ({ isLoading: !state.isLoading })) + toggleRtl = () => this.setState(state => ({ isRtl: !state.isRtl })); + toggleSearchable = () => + this.setState(state => ({ isSearchable: !state.isSearchable })) + render() { + const { + isClearable, + isSearchable, + isDisabled, + isLoading, + isRtl, + } = this.state; + return ( + + ; + +interface State { + menuIsOpen: boolean; +} + +export default class controlledMenu extends React.Component { + state = { + menuIsOpen: false, + }; + toggleMenuIsOpen = () => + this.setState(state => ({ menuIsOpen: !state.menuIsOpen })) + render() { + const { menuIsOpen } = this.state; + return ( + + ; + +interface State { + ignoreCase: boolean; + ignoreAccents: boolean; + trim: boolean; + matchFromStart: boolean; +} + +export default class SelectCreateFilter extends React.Component { + state: State = { + ignoreCase: false, + ignoreAccents: false, + trim: false, + matchFromStart: false, + }; + toggleOption = (key: string) => () => { + this.setState((state: any) => ({ ...state, [key]: !state[key] })); + } + render() { + const { + ignoreCase, + ignoreAccents, + trim, + matchFromStart, + } = this.state; + + const filterConfig = { + ignoreCase, + ignoreAccents, + trim, + matchFrom: this.state.matchFromStart ? ('start' as 'start') : ('any' as 'any'), + }; + + return ( + + + ); +} diff --git a/types/react-select/test/examples/CustomControl.tsx b/types/react-select/test/examples/CustomControl.tsx new file mode 100644 index 0000000000..3ed018e05e --- /dev/null +++ b/types/react-select/test/examples/CustomControl.tsx @@ -0,0 +1,32 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; +const controlStyles = { + borderRadius: '1px solid black', + padding: '5px', + background: colourOptions[2].color, + color: 'white' +}; + +const ControlComponent = (props: any) => ( +
+ {

Custom Control

} + +
+); + +export default class CustomControl extends React.Component { + render() { + return ( + +); diff --git a/types/react-select/test/examples/CustomFilterOptions.tsx b/types/react-select/test/examples/CustomFilterOptions.tsx new file mode 100644 index 0000000000..62a13f2a89 --- /dev/null +++ b/types/react-select/test/examples/CustomFilterOptions.tsx @@ -0,0 +1,34 @@ +import * as React from 'react'; +import Select from 'react-select'; +import { colourOptions } from '../data'; + +interface State { + ignoreCase: boolean; + ignoreAccents: boolean; + trim: boolean; + matchFrom: boolean; +} + +const filterOptions = (candidate: any, input: string) => { + if (input) { + return candidate.value === customOptions[0].value; + } + return true; +}; + +const customOptions = [{ value: 'custom', label: 'Using a custom filter to always display this option on search' }, ...colourOptions]; + +export default class SelectCreateFilter extends React.Component { + render() { + return ( + +
+ ); + } +} diff --git a/types/react-select/test/examples/CustomGroup.tsx b/types/react-select/test/examples/CustomGroup.tsx new file mode 100644 index 0000000000..7085e2901c --- /dev/null +++ b/types/react-select/test/examples/CustomGroup.tsx @@ -0,0 +1,24 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; + +const groupStyles = { + border: `2px dotted ${colourOptions[2].color}`, + borderRadius: '5px', + background: '#f2fcff' +}; + +const Group = (props: any) => ( +
+ +
+); + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ Group }} + /> +); diff --git a/types/react-select/test/examples/CustomGroupHeading.tsx b/types/react-select/test/examples/CustomGroupHeading.tsx new file mode 100644 index 0000000000..abf09de9ef --- /dev/null +++ b/types/react-select/test/examples/CustomGroupHeading.tsx @@ -0,0 +1,31 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; +import { EditorPanelIcon, Tooltip } from '../AtlaskitDummy'; + +const groupStyles = { + border: `2px dotted ${colourOptions[2].color}`, + color: 'white', + background: colourOptions[2].color, + padding: '5px 0px', + display: 'flex', +}; + +const GroupHeading = (props: any) => ( +
+ + + + +
+); + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ GroupHeading }} + styles={{ groupHeading: (base: any) => ({ ...base, flex: '1 1', color: 'white', margin: 0 }) }} + /> +); diff --git a/types/react-select/test/examples/CustomIndicatorSeparator.tsx b/types/react-select/test/examples/CustomIndicatorSeparator.tsx new file mode 100644 index 0000000000..c63d4a0f0e --- /dev/null +++ b/types/react-select/test/examples/CustomIndicatorSeparator.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import Select from 'react-select'; +import { colourOptions } from '../data'; + +const indicatorSeparatorStyle = { + alignSelf: 'stretch', + backgroundColor: colourOptions[2].color, + marginBottom: 8, + marginTop: 8, + width: 1, +}; + +const IndicatorSeparator = ({ innerProps }: any) => { + return ( + + ); +}; + +export default () => ( + +); diff --git a/types/react-select/test/examples/CustomInput.tsx b/types/react-select/test/examples/CustomInput.tsx new file mode 100644 index 0000000000..e2bd0eb7d6 --- /dev/null +++ b/types/react-select/test/examples/CustomInput.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const Input = (props: any) => { + if (props.isHidden) { + return ; + } + return ( +
+ + + +
+ ); +}; + +export default () => ( + option.rating !== 'safe'} + /> +
+ ); + } +} diff --git a/types/react-select/test/examples/CustomLoadingIndicator.tsx b/types/react-select/test/examples/CustomLoadingIndicator.tsx new file mode 100644 index 0000000000..627599d52a --- /dev/null +++ b/types/react-select/test/examples/CustomLoadingIndicator.tsx @@ -0,0 +1,47 @@ +import * as React from 'react'; +import { Spinner, Tooltip } from '../AtlaskitDummy'; +import AsyncSelect from 'react-select/lib/Async'; +import { colourOptions } from '../data'; + +const LoadingIndicator = (props: any) => { + return ( + + + + ); +}; + +interface State { + inputValue: string; +} + +const filterColors = (inputValue: string) => + colourOptions.filter(i => + i.label.toLowerCase().includes(inputValue.toLowerCase()) + ); + +const promiseOptions = (inputValue: string) => + new Promise(resolve => { + setTimeout(() => { + resolve(filterColors(inputValue)); + }, 1000); + }); + +export default class CustomLoadingIndicator extends React.Component { + state = { inputValue: '' }; + handleInputChange = (newValue: string) => { + const inputValue = newValue.replace(/\W/g, ''); + this.setState({ inputValue }); + return inputValue; + } + render() { + return ( + + ); + } +} diff --git a/types/react-select/test/examples/CustomLoadingMessage.tsx b/types/react-select/test/examples/CustomLoadingMessage.tsx new file mode 100644 index 0000000000..04776ebfd6 --- /dev/null +++ b/types/react-select/test/examples/CustomLoadingMessage.tsx @@ -0,0 +1,50 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import AsyncSelect from 'react-select/lib/Async'; +import { colourOptions } from '../data'; + +const LoadingMessage = (props: any) => { + return ( + +
+ {props.children} +
+
+ ); +}; + +interface State { + inputValue: string; +} + +const filterColors = (inputValue: string) => + colourOptions.filter(i => + i.label.toLowerCase().includes(inputValue.toLowerCase()) + ); + +const promiseOptions = (inputValue: string) => + new Promise(resolve => { + setTimeout(() => { + resolve(filterColors(inputValue)); + }, 1000); + }); + +export default class CustomLoadingIndicator extends React.Component { + state = { inputValue: '' }; + handleInputChange = (newValue: string) => { + const inputValue = newValue.replace(/\W/g, ''); + this.setState({ inputValue }); + return inputValue; + } + render() { + return ( + ({ ...base, backgroundColor: colourOptions[2].color, color: 'white' }) }} + components={{ LoadingMessage }} + /> + ); + } +} diff --git a/types/react-select/test/examples/CustomMenu.tsx b/types/react-select/test/examples/CustomMenu.tsx new file mode 100644 index 0000000000..b774a7fa1e --- /dev/null +++ b/types/react-select/test/examples/CustomMenu.tsx @@ -0,0 +1,37 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; + +function getLength(options: any) { + return options.reduce((acc: any, curr: any) => { + if (curr.options) return acc + getLength(curr.options); + return acc + 1; + }, 0); +} + +const menuHeaderStyle = { + padding: '8px 12px', +}; + +const Menu = (props: any) => { + const optionsLength = getLength(props.options); + return ( + +
+ Custom Menu with {optionsLength} options +
+ + {props.children} + +
+ ); +}; + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ Menu }} + /> +); diff --git a/types/react-select/test/examples/CustomMenuList.tsx b/types/react-select/test/examples/CustomMenuList.tsx new file mode 100644 index 0000000000..48a3cf62f7 --- /dev/null +++ b/types/react-select/test/examples/CustomMenuList.tsx @@ -0,0 +1,29 @@ +import * as React from 'react'; + +import Select, { components } from 'react-select'; +import { ColourOption, colourOptions, FlavourOption, groupedOptions } from '../data'; + +const menuHeaderStyle = { + padding: '8px 12px', + background: colourOptions[2].color, + color: 'white', +}; + +const MenuList = (props: any) => { + return ( + +
+ Custom Menu List +
+ {props.children} +
+ ); +}; + +export default () => ( + + defaultValue={colourOptions[1]} + options={groupedOptions} + components={{ MenuList }} + /> +); diff --git a/types/react-select/test/examples/CustomMultiValueContainer.tsx b/types/react-select/test/examples/CustomMultiValueContainer.tsx new file mode 100644 index 0000000000..1b556751e1 --- /dev/null +++ b/types/react-select/test/examples/CustomMultiValueContainer.tsx @@ -0,0 +1,23 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const MultiValueContainer = (props: any) => { + return ( + + + + ); +}; + +export default () => ( + ({ ...base, backgroundColor: colourOptions[2].color, color: 'white' }) }} + defaultValue={[colourOptions[4], colourOptions[5]]} + isMulti + options={colourOptions} + /> +); diff --git a/types/react-select/test/examples/CustomMultiValueRemove.tsx b/types/react-select/test/examples/CustomMultiValueRemove.tsx new file mode 100644 index 0000000000..81dfaf35e9 --- /dev/null +++ b/types/react-select/test/examples/CustomMultiValueRemove.tsx @@ -0,0 +1,25 @@ +import * as React from 'react'; +import { EmojiIcon, Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const MultiValueRemove = (props: any) => { + return ( + + + + + + ); +}; + +export default () => ( + ({ ...base, ...msgStyles }) }} + isSearchable + name="color" + options={[]} + /> + ); + } +} diff --git a/types/react-select/test/examples/CustomOption.tsx b/types/react-select/test/examples/CustomOption.tsx new file mode 100644 index 0000000000..aa115e78bf --- /dev/null +++ b/types/react-select/test/examples/CustomOption.tsx @@ -0,0 +1,22 @@ +import * as React from 'react'; +import { Tooltip } from '../AtlaskitDummy'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const Option = (props: any) => { + return ( + + + + ); +}; + +export default () => ( + ({ ...base, fontSize: '1em', color: colourOptions[2].color, fontWeight: 400 }) }} + options={colourOptions} + /> +); diff --git a/types/react-select/test/examples/CustomSelectContainer.tsx b/types/react-select/test/examples/CustomSelectContainer.tsx new file mode 100644 index 0000000000..393b8d1dd8 --- /dev/null +++ b/types/react-select/test/examples/CustomSelectContainer.tsx @@ -0,0 +1,24 @@ +import * as React from 'react'; +import Select, { components } from 'react-select'; +import { Tooltip } from '../AtlaskitDummy'; +import { colourOptions } from '../data'; + +const SelectContainer = ({ children, ...props }: any) => { + return ( + + + {children} + + + ); +}; + +export default () => ( + ({ ...base, padding: 5, borderRadius: 5, background: colourOptions[2].color, color: 'white', display: 'flex' }) }} + components={{ SingleValue }} + isSearchable + name="color" + options={colourOptions} + /> + ); + } +} diff --git a/types/react-select/test/examples/CustomValueContainer.tsx b/types/react-select/test/examples/CustomValueContainer.tsx new file mode 100644 index 0000000000..31d18ef50b --- /dev/null +++ b/types/react-select/test/examples/CustomValueContainer.tsx @@ -0,0 +1,28 @@ +import * as React from 'react'; +import Select, { components } from 'react-select'; +import { colourOptions } from '../data'; + +const ValueContainer = ({ children, ...props }: any) => ( + + {children} + +); + +export default class CustomControl extends React.Component { + render() { + return ( + v.some(i => i.date.isSame(o.date, 'day'))} + maxMenuHeight={380} + onChange={this.props.onChange} + onInputChange={this.handleInputChange} + options={options} + value={value} + /> + ); + } +} + +export default class Experimental extends React.Component { + state = { + value: defaultOptions[0], + }; + handleChange = (value: any) => { + this.setState({ value }); + } + render() { + const { value } = this.state; + const displayValue = value && value.value ? value.value.toString() : 'null'; + return ( +
+
Value: {displayValue}
+ +
+ ); + } +} diff --git a/types/react-select/test/examples/MenuPortal.tsx b/types/react-select/test/examples/MenuPortal.tsx new file mode 100644 index 0000000000..b7360e6fff --- /dev/null +++ b/types/react-select/test/examples/MenuPortal.tsx @@ -0,0 +1,90 @@ +import * as React from 'react'; +import { Modal, Button } from '../AtlaskitDummy'; +import Select from 'react-select'; +import { H1, Note } from '../styled-components'; + +import { colourOptions } from '../data'; + +interface State { + isOpen: boolean; + isFixed: boolean; + portalPlacement: 'auto' | 'bottom' | 'top'; +} + +export default class MenuPortal extends React.Component { + state: State = { + isOpen: false, + isFixed: false, + portalPlacement: 'bottom', + }; + open = () => { + console.log('menuPortal is Open'); + this.setState({ isOpen: true }); + } + close = () => { this.setState({ isOpen: false }); }; + setPlacement = ({ currentTarget }: any) => { + const portalPlacement = currentTarget && currentTarget.value; + this.setState({ portalPlacement }); + } + toggleMode = () => { + this.setState(state => ({ isFixed: !state.isFixed })); + } + render() { + const { close, open } = this; + const { isOpen, isFixed, portalPlacement } = this.state; + return ( + + + { + isOpen ? + +

Portaled Menu Element

+ + + + + + + + + Fixed + + + + Portal + +
+ : null + } +
+ ); + } +} diff --git a/types/react-select/test/examples/OnSelectResetsInput.tsx b/types/react-select/test/examples/OnSelectResetsInput.tsx new file mode 100644 index 0000000000..af1327b1bb --- /dev/null +++ b/types/react-select/test/examples/OnSelectResetsInput.tsx @@ -0,0 +1,47 @@ +import * as React from 'react'; +import Select from 'react-select'; +import { colourOptions } from '../data'; +import { InputActionMeta } from 'react-select/lib/types'; + +export default class OnSelectResetsInput extends React.Component { + state = { + inputValue: '', + menuIsOpen: undefined + }; + onInputChange = (inputValue: string, { action }: InputActionMeta) => { + console.log(inputValue, action); + switch (action) { + case 'input-change': + this.setState({ inputValue }); + return; + case 'menu-close': + console.log(this.state.inputValue); + let menuIsOpen; + if (this.state.inputValue) { + menuIsOpen = true; + } + this.setState({ + menuIsOpen + }); + return; + default: + return; + } + } + render() { + const { inputValue, menuIsOpen } = this.state; + return ( + + + ); + } +} + +// styled components + +const Menu = (props: any) => { + const shadow = colors.neutral10a; + return ( +
+ ); +}; +const Blanket = (props: any) => ( +
+); +const Dropdown = ({ children, isOpen, target, onClose }: any) => ( +
+ {target} + {isOpen ? {children} : null} + {isOpen ? : null} +
+); +const Svg = (p: any) => ( + +); +const DropdownIndicator = () => ( +
+ + + +
+); +const ChevronDown = () => ( + + + +); diff --git a/types/react-select/test/examples/StyledMulti.tsx b/types/react-select/test/examples/StyledMulti.tsx new file mode 100644 index 0000000000..a4dedb4156 --- /dev/null +++ b/types/react-select/test/examples/StyledMulti.tsx @@ -0,0 +1,53 @@ +import * as React from 'react'; +import * as chroma from 'chroma-js'; + +import { colourOptions } from '../data'; +import Select from 'react-select'; + +const colourStyles = { + control: (styles: any) => ({ ...styles, backgroundColor: 'white' }), + option: (styles: any, { data, isDisabled, isFocused, isSelected }: any) => { + const color = chroma(data.color); + return { + ...styles, + backgroundColor: isDisabled + ? null + : isSelected ? data.color : isFocused ? color.alpha(0.1).css() : null, + color: isDisabled + ? '#ccc' + : isSelected + ? chroma.contrast(color, 'white') > 2 ? 'white' : 'black' + : data.color, + cursor: isDisabled ? 'not-allowed' : 'default', + }; + }, + multiValue: (styles: any, { data }: any) => { + const color = chroma(data.color); + return { + ...styles, + backgroundColor: color.alpha(0.1).css(), + }; + }, + multiValueLabel: (styles: any, { data }: any) => ({ + ...styles, + color: data.color, + }), + multiValueRemove: (styles: any, { data }: any) => ({ + ...styles, + color: data.color, + ':hover': { + backgroundColor: data.color, + color: 'white', + }, + }), +}; + +export default () => ( + +); diff --git a/types/react-select/test/styled-components.tsx b/types/react-select/test/styled-components.tsx new file mode 100644 index 0000000000..fa18465cd8 --- /dev/null +++ b/types/react-select/test/styled-components.tsx @@ -0,0 +1,17 @@ +import * as React from 'react'; + +export const Note = ({ Tag = 'div', ...props }: any) => ( + +); + +export const H1 = (props: any) =>

; +export const H2 = (props: any) =>

; diff --git a/types/react-select/tsconfig.json b/types/react-select/tsconfig.json index 7855eceaf1..8c7a1921bd 100644 --- a/types/react-select/tsconfig.json +++ b/types/react-select/tsconfig.json @@ -1,10 +1,4 @@ { - "files": [ - "index.d.ts", - "lib/Option/index.d.ts", - "lib/utils/defaultMenuRenderer/index.d.ts", - "react-select-tests.tsx" - ], "compilerOptions": { "module": "commonjs", "lib": [ @@ -12,16 +6,99 @@ "dom" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", - "jsx": "react", "typeRoots": [ "../" ], + "jsx": "react", "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true - } + }, + "files": [ + "index.d.ts", + "lib/animated/Input.d.ts", + "lib/animated/MultiValue.d.ts", + "lib/animated/Placeholder.d.ts", + "lib/animated/SingleValue.d.ts", + "lib/animated/ValueContainer.d.ts", + "lib/animated/transitions.d.ts", + "lib/animated/index.d.ts", + "lib/components/containers.d.ts", + "lib/components/Control.d.ts", + "lib/components/Group.d.ts", + "lib/components/Input.d.ts", + "lib/components/Menu.d.ts", + "lib/components/MultiValue.d.ts", + "lib/components/Option.d.ts", + "lib/components/Placeholder.d.ts", + "lib/components/SingleValue.d.ts", + "lib/components/indicators.d.ts", + "lib/components/index.d.ts", + "lib/accessibility/index.d.ts", + "lib/theme.d.ts", + "lib/Creatable.d.ts", + "lib/Async.d.ts", + "lib/AsyncCreatable.d.ts", + "lib/filters.d.ts", + "lib/styles.d.ts", + "lib/stateManager.d.ts", + "lib/builtins.d.ts", + "lib/utils.d.ts", + "lib/diacritics.d.ts", + "lib/types.d.ts", + "lib/Select.d.ts", + "test/data.ts", + "test/styled-components.tsx", + "test/AtlaskitDummy.ts", + "test/ChronoNodeDummy.ts", + "test/examples/AccessingInternals.tsx", + "test/examples/AnimatedMulti.tsx", + "test/examples/AsyncCallbacks.tsx", + "test/examples/AsyncCreatable.tsx", + "test/examples/AsyncMulti.tsx", + "test/examples/AsyncPromises.tsx", + "test/examples/BasicGrouped.tsx", + "test/examples/BasicMulti.tsx", + "test/examples/BasicSingle.tsx", + "test/examples/ControlledMenu.tsx", + "test/examples/CreatableAdvanced.tsx", + "test/examples/CreatableInputOnly.tsx", + "test/examples/CreatableMulti.tsx", + "test/examples/CreatableSingle.tsx", + "test/examples/CreateFilter.tsx", + "test/examples/CustomClearIndicator.tsx", + "test/examples/CustomControl.tsx", + "test/examples/CustomDropdownIndicator.tsx", + "test/examples/CustomFilterOptions.tsx", + "test/examples/CustomGetOptionLabel.tsx", + "test/examples/CustomGroup.tsx", + "test/examples/CustomGroupHeading.tsx", + "test/examples/CustomIndicatorsContainer.tsx", + "test/examples/CustomIndicatorSeparator.tsx", + "test/examples/CustomInput.tsx", + "test/examples/CustomIsOptionDisabled.tsx", + "test/examples/CustomLoadingIndicator.tsx", + "test/examples/CustomLoadingMessage.tsx", + "test/examples/CustomMenu.tsx", + "test/examples/CustomMenuList.tsx", + "test/examples/CustomMultiValueContainer.tsx", + "test/examples/CustomMultiValueLabel.tsx", + "test/examples/CustomMultiValueRemove.tsx", + "test/examples/CustomNoOptionsMessage.tsx", + "test/examples/CustomOption.tsx", + "test/examples/CustomPlaceholder.tsx", + "test/examples/CustomSelectContainer.tsx", + "test/examples/CustomSingleValue.tsx", + "test/examples/CustomValueContainer.tsx", + "test/examples/Experimental.tsx", + "test/examples/MenuPortal.tsx", + "test/examples/OnSelectResetsInput.tsx", + "test/examples/Popout.tsx", + "test/examples/StyledMulti.tsx", + "test/examples/StyledSingle.tsx" + ] } diff --git a/types/react-select/tslint.json b/types/react-select/tslint.json index 3db14f85ea..f93cf8562a 100644 --- a/types/react-select/tslint.json +++ b/types/react-select/tslint.json @@ -1 +1,3 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json" +} diff --git a/types/react-select/v1/index.d.ts b/types/react-select/v1/index.d.ts new file mode 100644 index 0000000000..59bea6d815 --- /dev/null +++ b/types/react-select/v1/index.d.ts @@ -0,0 +1,654 @@ +// Type definitions for react-select 1.3 +// Project: https://github.com/JedWatson/react-select +// Definitions by: ESQUIBET Hugo +// Gilad Gray +// Izaak Baker +// Tadas Dailyda +// Mark Vujevits +// Mike Deverell +// MartynasZilinskas +// Onat Yigit Mercan +// Ian Johnson +// Anton Novik +// David Schkalee +// Arthur Udalov +// Sebastian Silbermann +// Endurance Idehen +// Guillaume Chartier +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +export default class ReactSelectClass extends React.Component> { + focus(): void; + setValue(value: Option): void; +} +// Other components +export class Creatable extends React.Component> { } +export class Async extends React.Component> { } +export class AsyncCreatable extends React.Component> { } + +export type OptionComponentType = React.ComponentType>; +export type ValueComponentType = React.ComponentType>; + +export type HandlerRendererResult = JSX.Element | null | false; + +// Handlers +export type FocusOptionHandler = (option: Option) => void; +export type SelectValueHandler = (option: Option) => void; +export type ArrowRendererHandler = (props: ArrowRendererProps) => HandlerRendererResult; +export type ClearRendererHandler = () => HandlerRendererResult; +export type FilterOptionHandler = (option: Option, filter: string) => boolean; +export type FilterOptionsHandler = (options: Options, filter: string, currentValues: Options) => Options; +export type InputRendererHandler = (props: { [key: string]: any }) => HandlerRendererResult; +export type MenuRendererHandler = (props: MenuRendererProps) => HandlerRendererResult; +export type OnCloseHandler = () => void; +export type OnInputChangeHandler = (inputValue: string) => string; +export type OnInputKeyDownHandler = React.KeyboardEventHandler; +export type OnMenuScrollToBottomHandler = () => void; +export type OnOpenHandler = () => void; +export type OnFocusHandler = React.FocusEventHandler; +export type OnBlurHandler = React.FocusEventHandler; +export type OptionRendererHandler = (option: Option) => HandlerRendererResult; +export type ValueRendererHandler = (option: Option, index?: number) => HandlerRendererResult; +export type OnValueClickHandler = (option: Option, event: React.MouseEvent) => void; +export type IsOptionUniqueHandler = (arg: { option: Option, options: Options, labelKey: string, valueKey: string }) => boolean; +export type IsValidNewOptionHandler = (arg: { label: string }) => boolean; +export type NewOptionCreatorHandler = (arg: { label: string, labelKey: string, valueKey: string }) => Option; +export type PromptTextCreatorHandler = (filterText: string) => string; +export type ShouldKeyDownEventCreateNewOptionHandler = (arg: { keyCode: number }) => boolean; + +export type OnChangeSingleHandler = OnChangeHandler>; +export type OnChangeMultipleHandler = OnChangeHandler>; +export type OnChangeHandler | Options> = (newValue: TOption | null) => void; +export type OnNewOptionClickHandler = (option: Option) => void; + +export type LoadOptionsHandler = LoadOptionsAsyncHandler | LoadOptionsLegacyHandler; +export type LoadOptionsAsyncHandler = (input: string) => Promise>; +export type LoadOptionsLegacyHandler = (input: string, callback: (err: any, result: AutocompleteResult) => void) => void; + +export interface AutocompleteResult { + /** The search-results to be displayed */ + options: Options; + /** + * Should be set to true, if and only if a longer query with the same prefix + * would return a subset of the results + * If set to true, more specific queries will not be sent to the server. + */ + complete: boolean; +} + +export type Options = Array>; + +export interface Option { + /** Text for rendering */ + label?: string; + /** Value for searching */ + value?: TValue; + /** + * Allow this option to be cleared + * @default true + */ + clearableValue?: boolean; + /** + * Do not allow this option to be selected + * @default false + */ + disabled?: boolean; + /** + * In the event that a custom menuRenderer is provided, Option should be able + * to accept arbitrary key-value pairs. See react-virtualized-select. + */ + [property: string]: any; +} + +export type OptionValues = string | number | boolean; + +export interface MenuRendererProps { + /** + * The currently focused option; should be visible in the menu by default. + * default {} + */ + focusedOption: Option; + + /** + * Callback to focus a new option; receives the option as a parameter. + */ + focusOption: FocusOptionHandler; + + /** + * Option labels are accessible with this string key. + */ + labelKey: string; + + /** + * Ordered array of options to render. + */ + options: Options; + + /** + * Callback to select a new option; receives the option as a parameter. + */ + selectValue: SelectValueHandler; + + /** + * Array of currently selected options. + */ + valueArray: Options; + + /** + * Callback to remove selection from option; receives the option as a parameter. + */ + removeValue: SelectValueHandler; + + /** + * function which returns a custom way to render the options in the menu + */ + optionRenderer: OptionRendererHandler; +} + +export interface OptionComponentProps { + /** + * Classname(s) to apply to the option component. + */ + className?: string; + + /** + * Currently focused option. + */ + focusOption?: Option; + + inputValue?: string; + instancePrefix?: string; + + /** + * True if this option is disabled. + */ + isDisabled?: boolean; + + /** + * True if this option is focused. + */ + isFocused?: boolean; + + /** + * True if this option is selected. + */ + isSelected?: boolean; + + /** + * Callback to be invoked when this option is focused. + */ + onFocus?: (option: Option, event: any) => void; + + /** + * Callback to be invoked when this option is selected. + */ + onSelect?: (option: Option, event: any) => void; + + /** + * Option to be rendered by this component. + */ + option: Option; + + /** + * Index of the option being rendered in the list + */ + optionIndex?: number; + + /** + * Callback to invoke when removing an option from a multi-selection. (Not necessarily the one + * being rendered) + */ + removeValue?: (value: TValue | TValue[]) => void; + + /** + * Callback to invoke to select an option. (Not necessarily the one being rendered) + */ + selectValue?: (value: TValue | TValue[]) => void; +} + +export interface ArrowRendererProps { + /** + * Arrow mouse down event handler. + */ + onMouseDown: React.MouseEventHandler; + + /** + * whether the Select is open or not. + */ + isOpen: boolean; +} + +export interface ValueComponentProps { + disabled: ReactSelectProps['disabled']; + id: string; + instancePrefix: string; + onClick: OnValueClickHandler | null; + onRemove?: SelectValueHandler; + placeholder: ReactSelectProps['placeholder']; + value: Option; + values?: Array>; +} + +export interface ReactSelectProps extends React.Props> { + /** + * text to display when `allowCreate` is true. + * @default 'Add "{label}"?' + */ + addLabelText?: string; + /** + * renders a custom drop-down arrow to be shown in the right-hand side of the select. + * @default undefined + */ + arrowRenderer?: ArrowRendererHandler | null; + /** + * blurs the input element after a selection has been made. Handy for lowering the keyboard on mobile devices. + * @default false + */ + autoBlur?: boolean; + /** + * autofocus the component on mount + * @deprecated. Use autoFocus instead + * @default false + */ + autofocus?: boolean; + /** + * autofocus the component on mount + * @default false + */ + autoFocus?: boolean; + /** + * If enabled, the input will expand as the length of its value increases + */ + autosize?: boolean; + /** + * whether pressing backspace removes the last item when there is no input value + * @default true + */ + backspaceRemoves?: boolean; + /** + * Message to use for screenreaders to press backspace to remove the current item + * {label} is replaced with the item label + * @default "Press backspace to remove..." + */ + backspaceToRemoveMessage?: string; + /** + * CSS className for the outer element + */ + className?: string; + /** + * Prefix prepended to element default className if no className is defined + */ + classNamePrefix?: string; + /** + * title for the "clear" control when `multi` is true + * @default "Clear all" + */ + clearAllText?: string; + /** + * Renders a custom clear to be shown in the right-hand side of the select when clearable true + * @default undefined + */ + clearRenderer?: ClearRendererHandler; + /** + * title for the "clear" control + * @default "Clear value" + */ + clearValueText?: string; + /** + * whether to close the menu when a value is selected + * @default true + */ + closeOnSelect?: boolean; + /** + * whether it is possible to reset value. if enabled, an X button will appear at the right side. + * @default true + */ + clearable?: boolean; + /** + * whether backspace removes an item if there is no text input + * @default true + */ + deleteRemoves?: boolean; + /** + * delimiter to use to join multiple values + * @default "," + */ + delimiter?: string; + /** + * whether the Select is disabled or not + * @default false + */ + disabled?: boolean; + /** + * whether escape clears the value when the menu is closed + * @default true + */ + escapeClearsValue?: boolean; + /** + * method to filter a single option + */ + filterOption?: FilterOptionHandler; + /** + * method to filter the options array + */ + filterOptions?: FilterOptionsHandler; + /** + * id for the underlying HTML input element + * @default undefined + */ + id?: string; + /** + * whether to strip diacritics when filtering + * @default true + */ + ignoreAccents?: boolean; + /** + * whether to perform case-insensitive filtering + * @default true + */ + ignoreCase?: boolean; + /** + * custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'} + * @default {} + */ + inputProps?: { [key: string]: any }; + /** + * renders a custom input + */ + inputRenderer?: InputRendererHandler; + /** + * allows for synchronization of component id's on server and client. + * @see https://github.com/JedWatson/react-select/pull/1105 + */ + instanceId?: string; + /** + * whether the Select is loading externally or not (such as options being loaded). + * if true, a loading spinner will be shown at the right side. + * @default false + */ + isLoading?: boolean; + /** + * (legacy mode) joins multiple values into a single form field with the delimiter + * @default false + */ + joinValues?: boolean; + /** + * the option property to use for the label + * @default "label" + */ + labelKey?: string; + /** + * (any, start) match the start or entire string when filtering + * @default "any" + */ + matchPos?: string; + /** + * (any, label, value) which option property to filter on + * @default "any" + */ + matchProp?: string; + /** + * buffer of px between the base of the dropdown and the viewport to shift if menu doesnt fit in viewport + * @default 0 + */ + menuBuffer?: number; + /** + * optional style to apply to the menu container + */ + menuContainerStyle?: React.CSSProperties; + /** + * renders a custom menu with options + */ + menuRenderer?: MenuRendererHandler; + /** + * optional style to apply to the menu + */ + menuStyle?: React.CSSProperties; + /** + * multi-value input + * @default false + */ + multi?: boolean; + /** + * field name, for hidden `` tag + */ + name?: string; + /** + * placeholder displayed when there are no matching search results or a falsy value to hide it + * @default "No results found" + */ + noResultsText?: string | JSX.Element; + /** + * onBlur handler: function (event) {} + */ + onBlur?: OnBlurHandler; + /** + * whether to clear input on blur or not + * @default true + */ + onBlurResetsInput?: boolean; + /** + * whether the input value should be reset when options are selected. + * Also input value will be set to empty if 'onSelectResetsInput=true' and + * Select will get new value that not equal previous value. + * @default true + */ + onSelectResetsInput?: boolean; + /** + * whether to clear input when closing the menu through the arrow + * @default true + */ + onCloseResetsInput?: boolean; + /** + * onChange handler: function (newValue) {} + */ + onChange?: OnChangeHandler; + /** + * fires when the menu is closed + */ + onClose?: OnCloseHandler; + /** + * onFocus handler: function (event) {} + */ + onFocus?: OnFocusHandler; + /** + * onInputChange handler: function (inputValue) {} + */ + onInputChange?: OnInputChangeHandler; + /** + * onInputKeyDown handler: function (keyboardEvent) {} + */ + onInputKeyDown?: OnInputKeyDownHandler; + /** + * fires when the menu is scrolled to the bottom; can be used to paginate options + */ + onMenuScrollToBottom?: OnMenuScrollToBottomHandler; + /** + * fires when the menu is opened + */ + onOpen?: OnOpenHandler; + /** + * boolean to enable opening dropdown when focused + * @default false + */ + openOnClick?: boolean; + /** + * open the options menu when the input gets focus (requires searchable = true) + * @default true + */ + openOnFocus?: boolean; + /** + * className to add to each option component + */ + optionClassName?: string; + /** + * option component to render in dropdown + */ + optionComponent?: OptionComponentType; + /** + * function which returns a custom way to render the options in the menu + */ + optionRenderer?: OptionRendererHandler; + /** + * array of Select options + * @default false + */ + options?: Options; + /** + * number of options to jump when using page up/down keys + * @default 5 + */ + pageSize?: number; + /** + * field placeholder, displayed when there's no value + * @default "Select..." + */ + placeholder?: string | JSX.Element; + /** + * whether the selected option is removed from the dropdown on multi selects + * @default true + */ + removeSelected?: boolean; + /** + * applies HTML5 required attribute when needed + * @default false + */ + required?: boolean; + /** + * value to use when you clear the control + */ + resetValue?: any; + /** + * use react-select in right-to-left direction + * @default false + */ + rtl?: boolean; + /** + * whether the viewport will shift to display the entire menu when engaged + * @default true + */ + scrollMenuIntoView?: boolean; + /** + * whether to enable searching feature or not + * @default true; + */ + searchable?: boolean; + /** + * whether to select the currently focused value when the [tab] key is pressed + */ + tabSelectsValue?: boolean; + /** + * initial field value + */ + value?: Option | Options | string | string[] | number | number[] | boolean; + /** + * the option property to use for the value + * @default "value" + */ + valueKey?: string; + /** + * function which returns a custom way to render the value selected + * @default false + */ + valueRenderer?: ValueRendererHandler; + /** + * optional style to apply to the control + */ + style?: React.CSSProperties; + + /** + * optional tab index of the control + */ + tabIndex?: string | number; + + /** + * value component to render + */ + valueComponent?: ValueComponentType; + + /** + * optional style to apply to the component wrapper + */ + wrapperStyle?: React.CSSProperties; + + /** + * onClick handler for value labels: function (value, event) {} + */ + onValueClick?: OnValueClickHandler; + + /** + * pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false + */ + simpleValue?: boolean; +} + +export interface ReactCreatableSelectProps extends ReactSelectProps { + /** + * Searches for any matching option within the set of options. This function prevents + * duplicate options from being created. + */ + isOptionUnique?: IsOptionUniqueHandler; + + /** + * Determines if the current input text represents a valid option. + */ + isValidNewOption?: IsValidNewOptionHandler; + + /** + * factory to create new options + */ + newOptionCreator?: NewOptionCreatorHandler; + + /** + * Creates prompt/placeholder for option text. + */ + promptTextCreator?: PromptTextCreatorHandler; + + /** + * Decides if a keyDown event (eg its 'keyCode') should result in the creation of a new option. + */ + shouldKeyDownEventCreateNewOption?: ShouldKeyDownEventCreateNewOptionHandler; + + /** + * new option click handler: function (option) {} + */ + onNewOptionClick?: OnNewOptionClickHandler; + + /** + * true: Show new option at top of list + * false: Show new option at bottom of list + * @default true + */ + showNewOptionAtTop?: boolean; +} + +export interface ReactAsyncSelectProps extends ReactSelectProps { + /** + * Whether to auto-load the default async options set. + */ + autoload?: boolean; + + /** + * object to use to cache results; can be null to disable cache + */ + cache?: { [key: string]: any } | boolean; + + /** + * function to call to load options asynchronously + */ + loadOptions: LoadOptionsHandler; + + /** + * replaces the placeholder while options are loading + */ + loadingPlaceholder?: string | JSX.Element; + /** + * displayed in the drop down list when the user did not type anything yet + */ + searchPromptText?: string; +} + +export type ReactAsyncCreatableSelectProps = ReactAsyncSelectProps & ReactCreatableSelectProps; diff --git a/types/react-select/lib/Option/index.d.ts b/types/react-select/v1/lib/Option/index.d.ts similarity index 100% rename from types/react-select/lib/Option/index.d.ts rename to types/react-select/v1/lib/Option/index.d.ts diff --git a/types/react-select/lib/utils/defaultMenuRenderer/index.d.ts b/types/react-select/v1/lib/utils/defaultMenuRenderer/index.d.ts similarity index 100% rename from types/react-select/lib/utils/defaultMenuRenderer/index.d.ts rename to types/react-select/v1/lib/utils/defaultMenuRenderer/index.d.ts diff --git a/types/react-select/react-select-tests.tsx b/types/react-select/v1/react-select-tests.tsx similarity index 100% rename from types/react-select/react-select-tests.tsx rename to types/react-select/v1/react-select-tests.tsx diff --git a/types/react-select/v1/tsconfig.json b/types/react-select/v1/tsconfig.json new file mode 100644 index 0000000000..e01d55ae8a --- /dev/null +++ b/types/react-select/v1/tsconfig.json @@ -0,0 +1,35 @@ +{ + "files": [ + "index.d.ts", + "lib/Option/index.d.ts", + "lib/utils/defaultMenuRenderer/index.d.ts", + "react-select-tests.tsx" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "jsx": "react", + "typeRoots": [ + "../../" + ], + "paths": { + "react-select": [ + "react-select/v1" + ], + "react-select/*": [ + "react-select/v1/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/react-select/v1/tslint.json b/types/react-select/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-select/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-share/index.d.ts b/types/react-share/index.d.ts index 756b917014..6fe45b124c 100644 --- a/types/react-share/index.d.ts +++ b/types/react-share/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/nygardk/react-share#readme // Definitions by: icopp // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-show-more/index.d.ts b/types/react-show-more/index.d.ts index e411726c52..efa2459148 100644 --- a/types/react-show-more/index.d.ts +++ b/types/react-show-more/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/One-com/react-show-more // Definitions by: Naor Torgeman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-side-effect/index.d.ts b/types/react-side-effect/index.d.ts index 1f15038c4b..977db41611 100644 --- a/types/react-side-effect/index.d.ts +++ b/types/react-side-effect/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Remo H. Jansen // Martin Charles // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-sidebar/index.d.ts b/types/react-sidebar/index.d.ts index da6d9e0f79..1aec2497da 100644 --- a/types/react-sidebar/index.d.ts +++ b/types/react-sidebar/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/balloob/react-sidebar#readme // Definitions by: Jeroen Vervaeke // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component } from "react"; diff --git a/types/react-sketchapp/index.d.ts b/types/react-sketchapp/index.d.ts index 67ade07673..6152bd7b07 100644 --- a/types/react-sketchapp/index.d.ts +++ b/types/react-sketchapp/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Rico Kahler // DomiR // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-slick/index.d.ts b/types/react-slick/index.d.ts index e9f03b80fa..d20aef9a02 100644 --- a/types/react-slick/index.d.ts +++ b/types/react-slick/index.d.ts @@ -4,7 +4,7 @@ // Giedrius Grabauskas // Andrew Makarov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-slider/index.d.ts b/types/react-slider/index.d.ts index 446f3159e3..25cbb5c9b8 100644 --- a/types/react-slider/index.d.ts +++ b/types/react-slider/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mpowaga/react-slider // Definitions by: Jason Unger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.7 +// TypeScript Version: 2.8 import * as React from 'react'; import * as motion from 'react-motion'; diff --git a/types/react-smooth-scrollbar/index.d.ts b/types/react-smooth-scrollbar/index.d.ts index c0aa21a0ff..85b4a736c3 100644 --- a/types/react-smooth-scrollbar/index.d.ts +++ b/types/react-smooth-scrollbar/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/idiotWu/react-smooth-scrollbar // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; import SmoothScrollbar from "smooth-scrollbar"; diff --git a/types/react-sortable-hoc/index.d.ts b/types/react-sortable-hoc/index.d.ts index 9963ebd69e..6a89c766e5 100644 --- a/types/react-sortable-hoc/index.d.ts +++ b/types/react-sortable-hoc/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/clauderic/react-sortable-hoc // Definitions by: Ivo Stratev , Charles Rey // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-sortable-pane/index.d.ts b/types/react-sortable-pane/index.d.ts index f8d3eba15f..16e14eaff2 100644 --- a/types/react-sortable-pane/index.d.ts +++ b/types/react-sortable-pane/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/bokuweb/react-sortable-pane // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-sortable-tree/package.json b/types/react-sortable-tree/package.json new file mode 100644 index 0000000000..2e009d2f82 --- /dev/null +++ b/types/react-sortable-tree/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "react-dnd": "^5.0.0" + } +} diff --git a/types/react-spinkit/index.d.ts b/types/react-spinkit/index.d.ts index 9e4a5f0cff..9d723ccc11 100644 --- a/types/react-spinkit/index.d.ts +++ b/types/react-spinkit/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/KyleAMathews/react-spinkit // Definitions by: Qubo , Mleko , Tom Crockett , zzanol // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-spinkit/v1/index.d.ts b/types/react-spinkit/v1/index.d.ts index ec841afd4b..2e616371e8 100644 --- a/types/react-spinkit/v1/index.d.ts +++ b/types/react-spinkit/v1/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/KyleAMathews/react-spinkit // Definitions by: Qubo , Mleko , Tom Crockett // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-sticky-el/index.d.ts b/types/react-sticky-el/index.d.ts index b41d48c454..da831c9d61 100644 --- a/types/react-sticky-el/index.d.ts +++ b/types/react-sticky-el/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/gm0t/react-sticky-el // Definitions by: Justin Braithwaite // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-sticky/index.d.ts b/types/react-sticky/index.d.ts index 86091531e9..0bc4e2c0f2 100644 --- a/types/react-sticky/index.d.ts +++ b/types/react-sticky/index.d.ts @@ -4,7 +4,7 @@ // Curtis Warren , // Andrew Hyndman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-stripe-elements/index.d.ts b/types/react-stripe-elements/index.d.ts index 27d124f78a..32a94b0639 100644 --- a/types/react-stripe-elements/index.d.ts +++ b/types/react-stripe-elements/index.d.ts @@ -6,7 +6,7 @@ // Andrew Goh Yisheng // Thomas Chia // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// import * as React from 'react'; diff --git a/types/react-svg-inline/index.d.ts b/types/react-svg-inline/index.d.ts index 8e85be5b1a..849d5772b0 100644 --- a/types/react-svg-inline/index.d.ts +++ b/types/react-svg-inline/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/MoOx/react-svg-inline // Definitions by: kiyopikko // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-svg-pan-zoom/index.d.ts b/types/react-svg-pan-zoom/index.d.ts index f825694915..c2636a8d6d 100644 --- a/types/react-svg-pan-zoom/index.d.ts +++ b/types/react-svg-pan-zoom/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/chrvadala/react-svg-pan-zoom#readme // Definitions by: Huy Nguyen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-svg/index.d.ts b/types/react-svg/index.d.ts deleted file mode 100644 index 5484191442..0000000000 --- a/types/react-svg/index.d.ts +++ /dev/null @@ -1,37 +0,0 @@ -// Type definitions for react-svg 3.0 -// Project: https://github.com/atomic-app/react-svg -// Definitions by: Chen Junda -// Chris Garber -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 - -import * as React from "react"; - -declare class ReactSVG extends React.Component, HTMLDivElement>> {} - -export = ReactSVG; - -declare namespace ReactSVG { - interface ReactSVGProps { - /** - * Path to the SVG. - */ - path: string; - /** - * Run any script blocks found in the SVG (always, once, or never). Defaults to never. - */ - evalScripts?: 'always' | 'once' | 'never'; - /** - * Function to call after the SVG is injected. Receives the newly injected SVG DOM element as a parameter. Defaults to null. - */ - onInjected?: (dom: SVGSVGElement) => void; - /** - * Class name to be added to the SVG. Defaults to ''. - */ - svgClassName?: string; - /** - * Inline styles to be added to the SVG. Defaults to {}. - */ - svgStyle?: any; - } -} diff --git a/types/react-svg/react-svg-tests.tsx b/types/react-svg/react-svg-tests.tsx deleted file mode 100644 index 676e1e5663..0000000000 --- a/types/react-svg/react-svg-tests.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import * as React from 'react'; -import * as ReactDOM from 'react-dom'; -import ReactSVG = require("react-svg"); - -const complete = {}} - className="wrapper-class-name" - svgClassName="svg-class-name" - onClick={() => {}} - evalScripts="once" - svgStyle={{}} - />; - -const minimal = ; diff --git a/types/react-swf/index.d.ts b/types/react-swf/index.d.ts index c37aff3d69..119b566ad8 100644 --- a/types/react-swf/index.d.ts +++ b/types/react-swf/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/syranide/react-swf // Definitions by: Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; export as namespace ReactSWF; diff --git a/types/react-swipe/index.d.ts b/types/react-swipe/index.d.ts index fb7d02055f..8b5c2d2a2d 100644 --- a/types/react-swipe/index.d.ts +++ b/types/react-swipe/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/voronianski/react-swipe // Definitions by: Deividas Bakanas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-swipeable-views/index.d.ts b/types/react-swipeable-views/index.d.ts index dedc165871..68545673e6 100644 --- a/types/react-swipeable-views/index.d.ts +++ b/types/react-swipeable-views/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Michael Ledin // Deividas Bakanas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-swipeable/index.d.ts b/types/react-swipeable/index.d.ts index b39a7b29ea..643d053b40 100644 --- a/types/react-swipeable/index.d.ts +++ b/types/react-swipeable/index.d.ts @@ -4,7 +4,7 @@ // Konstantin Vasilev // Hiroki Horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-syntax-highlighter/index.d.ts b/types/react-syntax-highlighter/index.d.ts index b751e75bf1..c9590f15a4 100644 --- a/types/react-syntax-highlighter/index.d.ts +++ b/types/react-syntax-highlighter/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/conorhastings/react-syntax-highlighter // Definitions by: Ivo Stratev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 declare module 'react-syntax-highlighter' { import SyntaxHighlighter from 'react-syntax-highlighter/light'; diff --git a/types/react-table/index.d.ts b/types/react-table/index.d.ts index ebe531ecfa..c58f54eefc 100644 --- a/types/react-table/index.d.ts +++ b/types/react-table/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/react-tools/react-table // Definitions by: Roy Xue , Pavel Sakalo , Krzysztof Porębski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; export type ReactTableFunction = (value?: any) => void; diff --git a/types/react-tabs/index.d.ts b/types/react-tabs/index.d.ts index 9c053d465e..9740d1366e 100644 --- a/types/react-tabs/index.d.ts +++ b/types/react-tabs/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/reactjs/react-tabs/ // Definitions by: Yuu Igarashi , Daniel Tschinder // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-tag-input/index.d.ts b/types/react-tag-input/index.d.ts index 54ae20b8c9..c6f905788f 100644 --- a/types/react-tag-input/index.d.ts +++ b/types/react-tag-input/index.d.ts @@ -4,7 +4,7 @@ // Jan Karres // Matthew Berryman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-tagcloud/index.d.ts b/types/react-tagcloud/index.d.ts index 4f6987cb5f..61725d0b2c 100644 --- a/types/react-tagcloud/index.d.ts +++ b/types/react-tagcloud/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/madox2/react-tagcloud // Definitions by: wassname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-tagsinput/index.d.ts b/types/react-tagsinput/index.d.ts index 4de3a4b8ac..d234a19c12 100644 --- a/types/react-tagsinput/index.d.ts +++ b/types/react-tagsinput/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/olahol/react-tagsinput // Definitions by: Michael Macnair // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-test-renderer/index.d.ts b/types/react-test-renderer/index.d.ts index d069686903..834664c11d 100644 --- a/types/react-test-renderer/index.d.ts +++ b/types/react-test-renderer/index.d.ts @@ -5,7 +5,7 @@ // John Reilly // John Gozde // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { ReactElement, ReactType } from "react"; diff --git a/types/react-test-renderer/v15/index.d.ts b/types/react-test-renderer/v15/index.d.ts index 753f4ef19d..9c65a34140 100644 --- a/types/react-test-renderer/v15/index.d.ts +++ b/types/react-test-renderer/v15/index.d.ts @@ -2,7 +2,7 @@ // Project: https://facebook.github.io/react/ // Definitions by: Arvitaly , Lochbrunner , Lochbrunner , John Reilly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { ReactElement } from "react"; diff --git a/types/react-test-renderer/v15/tsconfig.json b/types/react-test-renderer/v15/tsconfig.json index 4be2e2797f..0c98103ec8 100644 --- a/types/react-test-renderer/v15/tsconfig.json +++ b/types/react-test-renderer/v15/tsconfig.json @@ -9,6 +9,9 @@ "react": [ "react/v15" ], + "react-dom": [ + "react-dom/v15" + ], "react-test-renderer": [ "react-test-renderer/v15" ] @@ -30,4 +33,4 @@ "shallow/index.d.ts", "react-test-renderer-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/react-tether/index.d.ts b/types/react-tether/index.d.ts index 1012c8254b..8268550eb5 100644 --- a/types/react-tether/index.d.ts +++ b/types/react-tether/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/souporserious/react-tether // Definitions by: Ryan Price // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 export default TetherComponent; export as namespace ReactTether; diff --git a/types/react-text-mask/index.d.ts b/types/react-text-mask/index.d.ts index d598fcf711..f59878e83f 100644 --- a/types/react-text-mask/index.d.ts +++ b/types/react-text-mask/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/text-mask/text-mask // Definitions by: Guilherme Hübner , Deividi Cavarzan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-textarea-autosize/index.d.ts b/types/react-textarea-autosize/index.d.ts index de52335683..90fa858dfb 100644 --- a/types/react-textarea-autosize/index.d.ts +++ b/types/react-textarea-autosize/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/andreypopp/react-textarea-autosize // Definitions by: Alexey Svetliakov , Jerry Zou // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 declare module "react-textarea-autosize" { import * as React from "react"; diff --git a/types/react-timeout/index.d.ts b/types/react-timeout/index.d.ts index b214318a23..a360b47c5a 100644 --- a/types/react-timeout/index.d.ts +++ b/types/react-timeout/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/plougsgaard/react-timeout // Definitions by: Kerwyn Rojas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-toastify/index.d.ts b/types/react-toastify/index.d.ts index e77ef01837..0bde299cd4 100644 --- a/types/react-toastify/index.d.ts +++ b/types/react-toastify/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/fkhadra/react-toastify#readme // Definitions by: icopp // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { Transition } from 'react-transition-group'; diff --git a/types/react-toastr/index.d.ts b/types/react-toastr/index.d.ts index 8320244d7f..7b822ad601 100644 --- a/types/react-toastr/index.d.ts +++ b/types/react-toastr/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/tomchentw/react-toastr // Definitions by: Josh Holmer , Dan Regazzi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, ReactHTML } from 'react'; diff --git a/types/react-toggle/index.d.ts b/types/react-toggle/index.d.ts index 015daff31e..0d625cff55 100644 --- a/types/react-toggle/index.d.ts +++ b/types/react-toggle/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/aaronshaf/react-toggle // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, InputHTMLAttributes, ReactNode } from "react"; diff --git a/types/react-toggle/v2/index.d.ts b/types/react-toggle/v2/index.d.ts index 2b0774de2d..388121e5a8 100644 --- a/types/react-toggle/v2/index.d.ts +++ b/types/react-toggle/v2/index.d.ts @@ -1,20 +1,24 @@ // Type definitions for react-toggle 2.2 // Project: https://github.com/aaronshaf/react-toggle // Definitions by: Karol Janyst +// Jason Unger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 -import { Component, HTMLAttributes, ReactNode } from "react"; +import { ComponentClass, InputHTMLAttributes, ReactNode } from "react"; -export interface ToggleIcons { - checked?: ReactNode; - unchecked?: ReactNode; +declare namespace Toggle { + interface ToggleIcons { + checked?: ReactNode; + unchecked?: ReactNode; + } + + interface ToggleProps extends InputHTMLAttributes { + icons?: boolean | ToggleIcons; + defaultChecked?: boolean; + } } -export interface ToggleProps extends HTMLAttributes { - "aria-labelledby"?: string; - "aria-label"?: string; - icons?: boolean | ToggleIcons; -} +declare const Toggle: ComponentClass; -export default class Toggle extends Component {} +export = Toggle; diff --git a/types/react-toggle/v2/react-toggle-tests.tsx b/types/react-toggle/v2/react-toggle-tests.tsx index f02cf447e4..ac86a3ea7e 100644 --- a/types/react-toggle/v2/react-toggle-tests.tsx +++ b/types/react-toggle/v2/react-toggle-tests.tsx @@ -8,3 +8,15 @@ class Test extends React.Component { ); } } + +class TestControlled extends React.Component<{}, {checked: boolean}> { + state = { + checked: false + }; + + render() { + return ( + this.setState({ checked: e.target.checked })} /> + ); + } +} diff --git a/types/react-toggle/v2/tsconfig.json b/types/react-toggle/v2/tsconfig.json index 996290fe7b..122fd7a4b3 100644 --- a/types/react-toggle/v2/tsconfig.json +++ b/types/react-toggle/v2/tsconfig.json @@ -21,10 +21,11 @@ }, "noEmit": true, "forceConsistentCasingInFileNames": true, - "jsx": "react" + "jsx": "react", + "esModuleInterop": true }, "files": [ "index.d.ts", "react-toggle-tests.tsx" ] -} \ No newline at end of file +} diff --git a/types/react-tooltip/index.d.ts b/types/react-tooltip/index.d.ts index 044e737402..868e49e4ca 100644 --- a/types/react-tooltip/index.d.ts +++ b/types/react-tooltip/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/wwayne/react-tooltip // Definitions by: Deividas Bakanas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-touch/index.d.ts b/types/react-touch/index.d.ts index 3e714b2b6c..16ba4f39ba 100644 --- a/types/react-touch/index.d.ts +++ b/types/react-touch/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/leonaves/react-touch // Definitions by: Grzegorz Kielak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-tracking/index.d.ts b/types/react-tracking/index.d.ts index 8705a32781..c0e4571bd5 100644 --- a/types/react-tracking/index.d.ts +++ b/types/react-tracking/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/NYTimes/react-tracking // Definitions by: Eloy Durán // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-transition-group/Transition.d.ts b/types/react-transition-group/Transition.d.ts index 66ab782d1e..f8722a41d8 100644 --- a/types/react-transition-group/Transition.d.ts +++ b/types/react-transition-group/Transition.d.ts @@ -16,6 +16,13 @@ export interface TransitionActions { exit?: boolean; } +type TransitionStatus = + typeof ENTERING | + typeof ENTERED | + typeof EXITING | + typeof EXITED | + typeof UNMOUNTED; +export type TransitionChildren = React.ReactNode | ((status: TransitionStatus) => React.ReactNode); export interface TransitionProps extends TransitionActions { in?: boolean; mountOnEnter?: boolean; @@ -29,6 +36,7 @@ export interface TransitionProps extends TransitionActions { onExiting?: ExitHandler; onExited?: ExitHandler; [prop: string]: any; + children?: TransitionChildren; } /** diff --git a/types/react-transition-group/index.d.ts b/types/react-transition-group/index.d.ts index dbe906f679..2d97f64ce6 100644 --- a/types/react-transition-group/index.d.ts +++ b/types/react-transition-group/index.d.ts @@ -2,8 +2,9 @@ // Project: https://github.com/reactjs/react-transition-group // Definitions by: Karol Janyst // Epskampie +// Masafumi Koba // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import CSSTransition = require("./CSSTransition"); import Transition from "./Transition"; diff --git a/types/react-transition-group/react-transition-group-tests.tsx b/types/react-transition-group/react-transition-group-tests.tsx index 1441027481..172d91ce54 100644 --- a/types/react-transition-group/react-transition-group-tests.tsx +++ b/types/react-transition-group/react-transition-group-tests.tsx @@ -51,6 +51,18 @@ const Test: React.StatelessComponent = () => { >
{ "test" }
+ + {(status) => { + switch (status) { + case ENTERING: + case ENTERED: + case EXITING: + case EXITED: + case UNMOUNTED: + return
{status}
; + } + }} +
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { HTMLAttributes, ReactElement, ReactType } from "react"; diff --git a/types/react-treeview/index.d.ts b/types/react-treeview/index.d.ts index 2bfacc3eee..83f60eb5f2 100644 --- a/types/react-treeview/index.d.ts +++ b/types/react-treeview/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/chenglou/react-treeview // Definitions by: Jay Anslow // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, HTMLAttributes } from 'react'; diff --git a/types/react-truncate/index.d.ts b/types/react-truncate/index.d.ts index 15c72616c0..13de471a93 100644 --- a/types/react-truncate/index.d.ts +++ b/types/react-truncate/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/One-com/react-truncate // Definitions by: Matt Perry // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-twitter-auth/index.d.ts b/types/react-twitter-auth/index.d.ts index 46dc5e7aa7..962693997c 100644 --- a/types/react-twitter-auth/index.d.ts +++ b/types/react-twitter-auth/index.d.ts @@ -1,8 +1,9 @@ // Type definitions for react-twitter-auth 0.0 // Project: https://github.com/GenFirst/react-twitter-auth // Definitions by: Paul Fasola +// Dmytro Savchenko // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 interface TwitterLoginProps { tag?: React.ReactType; @@ -17,6 +18,9 @@ interface TwitterLoginProps { dialogHeight?: number; showIcon?: boolean; credentials?: "omit" | "same-origin" | "include"; + customHeaders?: HeadersInit; + children?: React.ReactNode; + forceLogin?: boolean; } declare var TwitterLogin: React.StatelessComponent; diff --git a/types/react-twitter-auth/react-twitter-auth-tests.tsx b/types/react-twitter-auth/react-twitter-auth-tests.tsx index 3bb1e8812d..abed3577d8 100644 --- a/types/react-twitter-auth/react-twitter-auth-tests.tsx +++ b/types/react-twitter-auth/react-twitter-auth-tests.tsx @@ -6,17 +6,47 @@ const ReactTwitterAuth: React.StatelessComponent = () => { function handleFailure(msg: string) {} return ( - +
+ + + + Login with twitter + +
); }; diff --git a/types/react-user-tour/index.d.ts b/types/react-user-tour/index.d.ts index 6fdbc2da13..1e704d5306 100644 --- a/types/react-user-tour/index.d.ts +++ b/types/react-user-tour/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/socialtables/react-user-tour // Definitions by: Carlo Cancellieri // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/react-virtual-keyboard/index.d.ts b/types/react-virtual-keyboard/index.d.ts index 03597e82e6..705dfc5682 100644 --- a/types/react-virtual-keyboard/index.d.ts +++ b/types/react-virtual-keyboard/index.d.ts @@ -2,7 +2,7 @@ // Project: https://www.npmjs.com/package/react-virtual-keyboard // Definitions by: Bogdan Surai // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component } from "react"; import { KeyboardOptions, NavigateOptions } from "virtual-keyboard"; diff --git a/types/react-virtualized-select/tsconfig.json b/types/react-virtualized-select/tsconfig.json index b544360da3..42387bc3e0 100644 --- a/types/react-virtualized-select/tsconfig.json +++ b/types/react-virtualized-select/tsconfig.json @@ -10,11 +10,18 @@ "noImplicitThis": true, "strictFunctionTypes": true, "strictNullChecks": true, - "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], + "paths": { + "react-select": [ + "react-select/v1" + ], + "react-select/*": [ + "react-select/v1/*" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/react-virtualized/dist/es/WindowScroller.d.ts b/types/react-virtualized/dist/es/WindowScroller.d.ts index 628d58744d..c3074208d6 100644 --- a/types/react-virtualized/dist/es/WindowScroller.d.ts +++ b/types/react-virtualized/dist/es/WindowScroller.d.ts @@ -11,26 +11,16 @@ export type WindowScrollerChildProps = { width: number; isScrolling: boolean; scrollTop: number; - onChildScroll: () => void; + onChildScroll: (params: { scrollTop: number }) => void; }; export type WindowScrollerProps = { /** * Function responsible for rendering children. * This function should implement the following signature: - * ({ height, isScrolling, scrollLeft, scrollTop, width }) => PropTypes.element + * ({ height, isScrolling, scrollLeft, scrollTop, width, onChildScroll }) => PropTypes.element */ - children: ( - params: { - onChildScroll: (params: { scrollTop: number }) => void; - registerChild: (params?: Element) => void; - height: number; - isScrolling: boolean; - scrollLeft: number; - scrollTop: number; - width: number; - } - ) => React.ReactNode; + children: (params: WindowScrollerChildProps) => React.ReactNode; /** Callback to be invoked on-resize: ({ height, width }) */ onResize?: (params: { height: number; width: number }) => void; diff --git a/types/react-virtualized/index.d.ts b/types/react-virtualized/index.d.ts index b7c557d875..4cbc644bc8 100644 --- a/types/react-virtualized/index.d.ts +++ b/types/react-virtualized/index.d.ts @@ -7,6 +7,7 @@ // Kræn Hansen // Steve Zhang // Maciej Goszczycki +// Brandon Hall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/react-webcam/index.d.ts b/types/react-webcam/index.d.ts index 5bb6337838..5986af5c75 100644 --- a/types/react-webcam/index.d.ts +++ b/types/react-webcam/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mozmorris/react-webcam // Definitions by: Lucas Servén Marín // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-widgets/index.d.ts b/types/react-widgets/index.d.ts index 8115208fa8..df804235e0 100644 --- a/types/react-widgets/index.d.ts +++ b/types/react-widgets/index.d.ts @@ -6,7 +6,7 @@ // Andrew Makarov // Maxime Billemaz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/react-youtube-embed/index.d.ts b/types/react-youtube-embed/index.d.ts index 9fcb2f81cb..3327516ad9 100644 --- a/types/react-youtube-embed/index.d.ts +++ b/types/react-youtube-embed/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/escaladesports/react-youtube-embed#readme // Definitions by: Charles Salmon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; diff --git a/types/react-youtube/index.d.ts b/types/react-youtube/index.d.ts index 65b5858ae6..fe9baf2e42 100644 --- a/types/react-youtube/index.d.ts +++ b/types/react-youtube/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/troybetz/react-youtube // Definitions by: kgtkr // Definitions: https://github.com/borisyankov/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; export default class YouTube extends React.Component<{ diff --git a/types/react/index.d.ts b/types/react/index.d.ts index c130068ca0..2c7110237c 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -19,11 +19,12 @@ // Olivier Pascal // Martin Hochel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// import * as CSS from 'csstype'; +import * as PropTypes from 'prop-types'; type NativeAnimationEvent = AnimationEvent; type NativeClipboardEvent = ClipboardEvent; @@ -2205,30 +2206,28 @@ declare namespace React { // React.PropTypes // ---------------------------------------------------------------------- - type Validator = { bivarianceHack(object: T, key: string, componentName: string, ...rest: any[]): Error | null }["bivarianceHack"]; + type Validator = PropTypes.Validator; - interface Requireable extends Validator { - isRequired: Validator; - } + type Requireable = PropTypes.Requireable; - type ValidationMap = {[K in keyof T]?: Validator }; + type ValidationMap = PropTypes.ValidationMap; interface ReactPropTypes { - any: Requireable; - array: Requireable; - bool: Requireable; - func: Requireable; - number: Requireable; - object: Requireable; - string: Requireable; - node: Requireable; - element: Requireable; - instanceOf(expectedClass: {}): Requireable; - oneOf(types: any[]): Requireable; - oneOfType(types: Array>): Requireable; - arrayOf(type: Validator): Requireable; - objectOf(type: Validator): Requireable; - shape(type: ValidationMap): Requireable; + any: typeof PropTypes.any; + array: typeof PropTypes.array; + bool: typeof PropTypes.bool; + func: typeof PropTypes.func; + number: typeof PropTypes.number; + object: typeof PropTypes.object; + string: typeof PropTypes.string; + node: typeof PropTypes.node; + element: typeof PropTypes.element; + instanceOf: typeof PropTypes.instanceOf; + oneOf: typeof PropTypes.oneOf; + oneOfType: typeof PropTypes.oneOfType; + arrayOf: typeof PropTypes.arrayOf; + objectOf: typeof PropTypes.objectOf; + shape: typeof PropTypes.shape; } // @@ -2282,6 +2281,21 @@ declare namespace React { } } +// Declared props take priority over inferred props +// If declared props have indexed properties, ignore inferred props entirely as keyof gets widened +type MergePropTypes = P & Pick>; + +// Any prop that has a default prop becomes optional, but its type is unchanged +// Undeclared default props are augmented into the resulting allowable attributes +// If declared props have indexed properties, ignore default props entirely as keyof gets widened +// Wrap in an outer-level conditional type to allow distribution over props that are unions +type Defaultize = P extends any + ? string extends keyof P ? P : + & Pick> + & Partial>> + & Partial>> + : never; + declare global { namespace JSX { // tslint:disable-next-line:no-empty-interface @@ -2292,6 +2306,14 @@ declare global { interface ElementAttributesProperty { props: {}; } interface ElementChildrenAttribute { children: {}; } + type LibraryManagedAttributes = C extends { propTypes: infer T; defaultProps: infer D; } + ? Defaultize>, D> + : C extends { propTypes: infer T; } + ? MergePropTypes> + : C extends { defaultProps: infer D; } + ? Defaultize + : P; + // tslint:disable-next-line:no-empty-interface interface IntrinsicAttributes extends React.Attributes { } // tslint:disable-next-line:no-empty-interface diff --git a/types/react/test/index.ts b/types/react/test/index.ts index 227ba5721d..a78a480199 100644 --- a/types/react/test/index.ts +++ b/types/react/test/index.ts @@ -1,6 +1,7 @@ import * as React from "react"; import * as ReactDOM from "react-dom"; import * as ReactDOMServer from "react-dom/server"; +import * as PropTypes from "prop-types"; import createFragment = require("react-addons-create-fragment"); import CSSTransitionGroup = require("react-addons-css-transition-group"); import * as LinkedStateMixin from "react-addons-linked-state-mixin"; @@ -15,12 +16,12 @@ import * as DOM from "react-dom-factories"; interface Props extends React.Attributes { hello: string; - world?: string; + world?: string | null; foo: number; } interface State { - inputValue?: string; + inputValue?: string | null; seconds?: number; } @@ -29,7 +30,7 @@ interface Snapshot { } interface Context { - someValue?: string; + someValue?: string | null; } interface ChildContext { @@ -117,15 +118,18 @@ declare const container: Element; class ModernComponent extends React.Component implements MyComponent, React.ChildContextProvider { static propTypes: React.ValidationMap = { - foo: (() => null) as React.Validator + hello: PropTypes.string.isRequired, + world: PropTypes.string, + foo: PropTypes.number.isRequired, + key: > PropTypes.oneOfType([PropTypes.number, PropTypes.string]) }; static contextTypes: React.ValidationMap = { - someValue: (() => null) as React.Validator + someValue: PropTypes.string }; static childContextTypes: React.ValidationMap = { - someOtherValue: (() => null) as React.Validator + someOtherValue: PropTypes.string.isRequired }; context: Context; @@ -156,7 +160,7 @@ class ModernComponent extends React.Component return DOM.div(null, DOM.input({ ref: input => this._input = input, - value: this.state.inputValue + value: this.state.inputValue ? this.state.inputValue : undefined }), DOM.input({ onChange: event => console.log(event.target) diff --git a/types/react/test/managedAttributes.tsx b/types/react/test/managedAttributes.tsx new file mode 100644 index 0000000000..56466e1cc8 --- /dev/null +++ b/types/react/test/managedAttributes.tsx @@ -0,0 +1,160 @@ +interface LeaveMeAloneDtslint { foo: string; } +// // Re-enable when we move @types/react to TS 3.0 + +// import * as React from 'react'; +// import * as PropTypes from 'prop-types'; + +// interface Props { +// bool?: boolean +// fnc: () => any +// node?: React.ReactNode +// num?: number +// reqNode: NonNullable +// str: string +// } + +// const propTypes = { +// bool: PropTypes.bool, +// fnc: PropTypes.func.isRequired, +// node: PropTypes.node, +// num: PropTypes.number, +// str: PropTypes.string.isRequired, +// extraStr: PropTypes.string.isRequired, +// extraNum: PropTypes.number +// }; + +// const defaultProps = { +// fnc: function() { return 'abc' } as () => any, +// extraBool: false, +// reqNode: 'text_node' as React.ReactNode +// }; + +// class AnnotatedPropTypesAndDefaultProps extends React.Component { +// static propTypes = propTypes; +// static defaultProps = defaultProps; +// } + +// const annotatedPropTypesAndDefaultPropsTests = [ +// // $ExpectError +// , // str and extraStr are required +// , +// // $ExpectError +// , // num type mismatch +// } +// num={0} +// reqNode={} +// str='abc' +// /> +// ]; + +// class UnannotatedPropTypesAndDefaultProps extends React.Component { +// static propTypes = propTypes; +// static defaultProps = defaultProps; +// } + +// const unannotatedPropTypesAndDefaultPropsTests = [ +// // $ExpectError +// , // stra and extraStr are required +// , +// // $ExpectError +// , // extraBool type mismatch +// } +// num={0} +// reqNode={} +// str='abc' +// /> +// ]; + +// class AnnotatedPropTypes extends React.Component { +// static propTypes = propTypes; +// } + +// const annotatedPropTypesTests = [ +// // $ExpectError +// , // str, extraStr, reqNode and fnc are required +// } />, +// // $ExpectError +// } extraBool={false} />, // extraBool doesn't exist +// // $ExpectError +// } num='abc' />, // num type mismatch +// } +// num={0} +// reqNode={} +// str='abc' +// /> +// ]; + +// class UnannotatedPropTypes extends React.Component { +// static propTypes = propTypes; +// } + +// const unannotatedPropTypesTests = [ +// // $ExpectError +// , // str, extraStr and fnc are required +// , +// // $ExpectError +// } />, // reqNode doesn't exist +// // $ExpectError +// } num='abc' />, // num type mismatch +// } +// num={0} +// str='abc' +// /> +// ]; + +// class AnnotatedDefaultProps extends React.Component { +// static defaultProps = defaultProps; +// } + +// const annotatedDefaultPropsTests = [ +// // $ExpectError +// , // str is required +// , +// } />, +// // $ExpectError +// { }} />, // str type mismatch +// +// ]; + +// class UnannotatedDefaultProps extends React.Component { +// static defaultProps = defaultProps; +// } + +// const unannotatedDefaultPropsTests = [ +// , +// } +// /> +// ]; diff --git a/types/react/tsconfig.json b/types/react/tsconfig.json index 2bc92c4894..b666fac305 100644 --- a/types/react/tsconfig.json +++ b/types/react/tsconfig.json @@ -3,7 +3,8 @@ "index.d.ts", "test/index.ts", "test/tsx.tsx", - "test/cssProperties.tsx" + "test/cssProperties.tsx", + "test/managedAttributes.tsx" ], "compilerOptions": { "module": "commonjs", diff --git a/types/react/v15/index.d.ts b/types/react/v15/index.d.ts index 939e26c57a..65f00c258f 100644 --- a/types/react/v15/index.d.ts +++ b/types/react/v15/index.d.ts @@ -13,7 +13,7 @@ // Dovydas Navickas // Stéphane Goetz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /* Known Problems & Workarounds diff --git a/types/react/v15/test/index.ts b/types/react/v15/test/index.ts index 45894cb397..6735e64eeb 100644 --- a/types/react/v15/test/index.ts +++ b/types/react/v15/test/index.ts @@ -256,7 +256,7 @@ const markup: string = ReactDOMServer.renderToStaticMarkup(element); const notValid: boolean = React.isValidElement(props); // false const isValid = React.isValidElement(element); // true let domNode = ReactDOM.findDOMNode(component); -domNode = ReactDOM.findDOMNode(domNode as Element); +domNode = ReactDOM.findDOMNode(domNode); // // React Elements diff --git a/types/react/v15/tsconfig.json b/types/react/v15/tsconfig.json index f9c13ee9f2..d3eb40aae7 100644 --- a/types/react/v15/tsconfig.json +++ b/types/react/v15/tsconfig.json @@ -12,9 +12,8 @@ "dom" ], "paths": { - "react": [ - "react/v15" - ] + "react": ["react/v15"], + "react-dom": ["react-dom/v15"] }, "noImplicitAny": true, "noImplicitThis": false, @@ -29,4 +28,4 @@ "forceConsistentCasingInFileNames": true, "jsx": "preserve" } -} \ No newline at end of file +} diff --git a/types/reactable/index.d.ts b/types/reactable/index.d.ts index 8e3cb8873c..e4315030af 100644 --- a/types/reactable/index.d.ts +++ b/types/reactable/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/glittershark/reactable // Definitions by: Christoph Spielmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/reactcss/index.d.ts b/types/reactcss/index.d.ts index c5fb14bd32..eba4063e2b 100644 --- a/types/reactcss/index.d.ts +++ b/types/reactcss/index.d.ts @@ -2,7 +2,7 @@ // Project: http://reactcss.com/ // Definitions by: Chris Gervang , Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react" diff --git a/types/reactstrap/lib/Alert.d.ts b/types/reactstrap/lib/Alert.d.ts index edfd5303e0..5aa58f862a 100644 --- a/types/reactstrap/lib/Alert.d.ts +++ b/types/reactstrap/lib/Alert.d.ts @@ -1,14 +1,13 @@ import * as React from 'react'; import { CSSModule } from '../index'; +import { FadeProps } from './Fade'; export type UncontrolledProps = React.HTMLAttributes & { className?: string; cssModule?: CSSModule; color?: string; tag?: React.ReactType; - transitionAppearTimeout?: number; - transitionEnterTimeout?: number; - transitionLeaveTimeout?: number; + transition?: FadeProps; } & T; export type UncontrolledAlertProps = UncontrolledProps; diff --git a/types/reactstrap/v4/index.d.ts b/types/reactstrap/v4/index.d.ts index 93eeed908f..0a807b1131 100644 --- a/types/reactstrap/v4/index.d.ts +++ b/types/reactstrap/v4/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/reactstrap/reactstrap#readme // Definitions by: Ali Hammad Baig , Marco Falkenberg , Danilo Barros , Fábio Paiva // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 export interface CSSModule { [className: string]: string; diff --git a/types/reapop/index.d.ts b/types/reapop/index.d.ts index a0f446fa91..c8b1f022fc 100644 --- a/types/reapop/index.d.ts +++ b/types/reapop/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/LouisBarranqueiro/reapop#readme // Definitions by: Barrokgl // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { Dispatch } from 'redux'; diff --git a/types/rebass/index.d.ts b/types/rebass/index.d.ts index 0c55b12240..f209bed8ac 100644 --- a/types/rebass/index.d.ts +++ b/types/rebass/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/jxnblk/rebass // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index a46cbd09b8..dc96bdbe46 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -9,8 +9,9 @@ // Peter Keuter // Jamie Saunders // Paul Melnikow +// Harry Cruse // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { CurveFactory } from 'd3-shape'; @@ -25,7 +26,7 @@ export type TooltipFormatter = (value: string | number | Array, entry: TooltipPayload, index: number) => React.ReactNode; export type ItemSorter = (a: T, b: T) => number; export type ContentRenderer

= (props: P) => React.ReactNode; -export type DataKey = string | number | ((dataObject: any) => number | [number, number]); +export type DataKey = string | number | ((dataObject: any) => number | [number, number] | null); export type IconType = 'plainline' | 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye' | 'plainline'; export type LegendType = IconType | 'none'; @@ -406,6 +407,7 @@ export interface LineProps extends EventAttributes, Partial | ContentRenderer; points?: Point[]; @@ -518,7 +520,7 @@ export interface PolarRadiusAxisProps extends EventAttributes, Partial | ContentRenderer; stroke?: string; tickFormatter: TickFormatterFunction; - domain?: PolarRadiusAxisDomain[]; + domain?: [PolarRadiusAxisDomain, PolarRadiusAxisDomain]; scale?: ScaleType | RechartsFunction; allowDataOverflow?: boolean; } @@ -882,7 +884,7 @@ export interface XAxisProps extends EventAttributes { unit?: string | number; // The unique id of x-axis xAxisId?: string | number; - domain?: AxisDomain[]; + domain?: [AxisDomain, AxisDomain]; // The key of data displayed in the axis dataKey?: DataKey; // The width of axis which is usually calculated internally @@ -914,6 +916,7 @@ export interface XAxisProps extends EventAttributes { reversed?: boolean; // see label section at http://recharts.org/#/en-US/api/XAxis label?: string | number | Label | LabelProps; + allowDuplicatedCategory?: boolean; } export class XAxis extends React.Component { } @@ -933,7 +936,7 @@ export interface YAxisProps extends EventAttributes { unit?: string | number; // The unique id of y-axis yAxisId?: string | number; - domain?: AxisDomain[]; + domain?: [AxisDomain, AxisDomain]; // The key of data displayed in the axis dataKey?: DataKey; // Ticks can be any type when the axis is the type of category diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index 0c893486c3..f0ad8596ab 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -6,7 +6,7 @@ // Rasmus Eneman // Lucas Terra // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// @@ -141,7 +141,7 @@ declare module 'recompose' { stateUpdaterName: TStateUpdaterName, initialState: TState | mapper ): InferableComponentEnhancerWithProps< - TOutter & stateProps, + stateProps, TOutter >; @@ -661,39 +661,24 @@ declare module 'recompose/hoistStatics' { // https://github.com/acdlite/recompose/blob/master/docs/API.md#componentfromstream declare module 'recompose/componentFromStream' { import { componentFromStream } from 'recompose'; + export { componentFromStreamWithConfig } from 'recompose'; export default componentFromStream; } -// https://github.com/acdlite/recompose/blob/master/docs/API.md#componentfromstreamwithconfig -declare module 'recompose/componentFromStreamWithConfig' { - import { componentFromStreamWithConfig } from 'recompose'; - export default componentFromStreamWithConfig; -} - // https://github.com/acdlite/recompose/blob/master/docs/API.md#mappropsstream declare module 'recompose/mapPropsStream' { import { mapPropsStream } from 'recompose'; + export { mapPropsStreamWithConfig } from 'recompose'; export default mapPropsStream; } -// https://github.com/acdlite/recompose/blob/master/docs/API.md#mappropsstreamwithconfig -declare module 'recompose/mapPropsStreamWithConfig' { - import { mapPropsStreamWithConfig } from 'recompose'; - export default mapPropsStreamWithConfig; -} - // https://github.com/acdlite/recompose/blob/master/docs/API.md#createeventhandler declare module 'recompose/createEventHandler' { import { createEventHandler } from 'recompose'; + export { createEventHandlerWithConfig } from 'recompose'; export default createEventHandler; } -// https://github.com/acdlite/recompose/blob/master/docs/API.md#createeventhandlerwithconfig -declare module 'recompose/createEventHandlerWithConfig' { - import { createEventHandlerWithConfig } from 'recompose'; - export default createEventHandlerWithConfig; -} - // https://github.com/acdlite/recompose/blob/master/docs/API.md#setobservableconfig declare module 'recompose/setObservableConfig' { import { setObservableConfig } from 'recompose'; diff --git a/types/recompose/recompose-tests.tsx b/types/recompose/recompose-tests.tsx index c30f5fb8f9..9058a10f4d 100644 --- a/types/recompose/recompose-tests.tsx +++ b/types/recompose/recompose-tests.tsx @@ -62,12 +62,9 @@ import createSinkStandalone from "recompose/createSink"; import componentFromPropStandalone from "recompose/componentFromProp"; import nestStandalone from "recompose/nest"; import hoistStaticsStandalone from "recompose/hoistStatics"; -import componentFromStreamStandalone from "recompose/componentFromStream"; -import componentFromStreamWithConfigStandalone from "recompose/componentFromStreamWithConfig"; -import mapPropsStreamStandalone from "recompose/mapPropsStream"; -import mapPropsStreamWithConfigStandalone from "recompose/mapPropsStreamWithConfig"; -import createEventHandlerStandalone from "recompose/createEventHandler"; -import createEventHandlerWithConfigStandalone from "recompose/createEventHandlerWithConfig"; +import componentFromStreamStandalone, { componentFromStreamWithConfig as componentFromStreamWithConfigStandalone } from "recompose/componentFromStream"; +import mapPropsStreamStandalone, { mapPropsStreamWithConfig as mapPropsStreamWithConfigStandalone } from "recompose/mapPropsStream"; +import createEventHandlerStandalone, { createEventHandlerWithConfig as createEventHandlerWithConfigStandalone } from "recompose/createEventHandler"; import setObservableConfigStandalone from "recompose/setObservableConfig"; function testMapProps() { @@ -135,7 +132,7 @@ function testWithHandlers() { onSubmit: React.MouseEventHandler; onChange: Function; } - const InnerComponent: React.StatelessComponent = ({onChange, onSubmit, foo}) => + const InnerComponent: React.StatelessComponent = ({onChange, onSubmit, foo}) =>

{foo}
; const enhancer = withHandlers({ @@ -260,7 +257,7 @@ function testWithState() { // We can also actually provide the generic necessary const enhancer3 = withState("count", "setCount", 1); const Enhanced3 = enhancer3(props => { - return
{props.title}
; + return
{props.count}
; }); const rendered3 = ( diff --git a/types/redom/index.d.ts b/types/redom/index.d.ts index 24e149258e..fde67bfb12 100644 --- a/types/redom/index.d.ts +++ b/types/redom/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for redom 3.6 +// Type definitions for redom 3.12 // Project: https://github.com/redom/redom/ // Definitions by: Rauli Laine +// Felix Nehrke // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -12,18 +13,40 @@ export type RedomQueryArgument = RedomQueryArgumentValue | RedomQueryArgumentVal export interface RedomComponent { el: HTMLElement; + + update?(item: any, index: number, data: any, context?: any): void; + + onmount?(): void; + + onremount?(): void; + + onunmount?(): void; } export interface RedomComponentConstructor { new (): RedomComponent; } +export class ListPool { + constructor(View: RedomComponentConstructor, key?: string, initData?: any); + + update(data: any[], context?: any): void; +} + export class List implements RedomComponent { el: HTMLElement; constructor(parent: RedomQuery, View: RedomComponentConstructor, key?: string, initData?: any); update(data: any[], context?: any): void; + + onmount?(): void; + + onremount?(): void; + + onunmount?(): void; + + static extend(parent: RedomQuery, View: RedomComponentConstructor, key?: string, initData?: any): RedomComponentConstructor; } export class Place implements RedomComponent { @@ -47,8 +70,10 @@ export interface RouterDictionary { } export function html(query: RedomQuery, ...args: RedomQueryArgument[]): HTMLElement; +export function h(query: RedomQuery, ...args: RedomQueryArgument[]): HTMLElement; export function el(query: RedomQuery, ...args: RedomQueryArgument[]): HTMLElement; +export function listPool(View: RedomComponentConstructor, key?: string, initData?: any): ListPool; export function list(parent: RedomQuery, View: RedomComponentConstructor, key?: string, initData?: any): List; export function mount(parent: RedomElement, child: RedomElement, before?: RedomElement): RedomElement; @@ -65,5 +90,14 @@ export function setStyle(view: RedomElement, arg1: string | object, arg2?: strin export function setChildren(parent: RedomElement, children: RedomElement[]): void; export function svg(query: RedomQuery, ...args: RedomQueryArgument[]): SVGElement; +export function s(query: RedomQuery, ...args: RedomQueryArgument[]): SVGElement; export function text(str: string): Text; + +export namespace list { + function extend(parent: RedomQuery, View: RedomComponentConstructor, key?: string, initData?: any): RedomComponentConstructor; +} + +export namespace svg { + function extend(query: RedomQuery): RedomComponentConstructor; +} diff --git a/types/redom/redom-tests.ts b/types/redom/redom-tests.ts index 0ec18f6a59..b1baff790e 100644 --- a/types/redom/redom-tests.ts +++ b/types/redom/redom-tests.ts @@ -14,3 +14,26 @@ redom.setStyle(el3, { color: 'blue' }); redom.setChildren(el1, [el2, el3]); redom.mount(document.body, redom.text('Hello, World!')); + +class Td implements redom.RedomComponent { + el: HTMLElement; + constructor() { + this.el = redom.h('td'); + } + update(value: any) { + this.el.textContent = value; + } + onmount() { + console.log('mounted td'); + } +} +const Tr = redom.list.extend('tr', Td); +const table = redom.list('table', Tr); +table.onmount = () => console.log('mounted table'); + +table.update([ + [1, 2], + [3, 4], +]); + +redom.mount(document.body, table); diff --git a/types/redux-auth-wrapper/v1/index.d.ts b/types/redux-auth-wrapper/v1/index.d.ts index 366ee7bfdb..cca415812a 100644 --- a/types/redux-auth-wrapper/v1/index.d.ts +++ b/types/redux-auth-wrapper/v1/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mjrussell/redux-auth-wrapper // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { ComponentClass, StatelessComponent, ReactType } from "react"; import { Action } from "redux"; diff --git a/types/redux-auth-wrapper/v1/package.json b/types/redux-auth-wrapper/v1/package.json new file mode 100644 index 0000000000..b5b3eb5dd8 --- /dev/null +++ b/types/redux-auth-wrapper/v1/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "redux": "^3.7.2" + } +} diff --git a/types/redux-devtools-dock-monitor/index.d.ts b/types/redux-devtools-dock-monitor/index.d.ts index 025b24625d..b0cc4a55a8 100644 --- a/types/redux-devtools-dock-monitor/index.d.ts +++ b/types/redux-devtools-dock-monitor/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/gaearon/redux-devtools-dock-monitor // Definitions by: Petryshyn Sergii // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/redux-devtools-log-monitor/index.d.ts b/types/redux-devtools-log-monitor/index.d.ts index 8bbaad7e1f..94d960f51a 100644 --- a/types/redux-devtools-log-monitor/index.d.ts +++ b/types/redux-devtools-log-monitor/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/gaearon/redux-devtools-log-monitor // Definitions by: Petryshyn Sergii // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react' import { ColorScheme } from 'base16' diff --git a/types/redux-first-router-link/index.d.ts b/types/redux-first-router-link/index.d.ts index c99f5b6ac1..8625433b03 100644 --- a/types/redux-first-router-link/index.d.ts +++ b/types/redux-first-router-link/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/faceyspacey/redux-first-router-link#readme // Definitions by: janb87 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; import { Location } from 'redux-first-router'; diff --git a/types/redux-form/lib/Field.d.ts b/types/redux-form/lib/Field.d.ts index d27a10ce47..c303f0d5c3 100644 --- a/types/redux-form/lib/Field.d.ts +++ b/types/redux-form/lib/Field.d.ts @@ -37,7 +37,6 @@ export interface CommonFieldProps extends CommonFieldInputProps { export interface BaseFieldProps

extends Partial { name: string; - label?: string; component?: ComponentType | "input" | "select" | "textarea"; format?: Formatter | null; normalize?: Normalizer; @@ -73,7 +72,6 @@ export class Field

extends Comp export interface WrappedFieldProps { input: WrappedFieldInputProps; meta: WrappedFieldMetaProps; - label?: string; } export interface WrappedFieldInputProps extends CommonFieldInputProps { diff --git a/types/redux-form/lib/FieldArray.d.ts b/types/redux-form/lib/FieldArray.d.ts index b1ddbc6aa6..d800452a3e 100644 --- a/types/redux-form/lib/FieldArray.d.ts +++ b/types/redux-form/lib/FieldArray.d.ts @@ -42,6 +42,7 @@ interface FieldsProps { remove(index: number): void; shift(): FieldValue; swap(indexA: number, indexB: number): void; + move(from: number, to: number): void; unshift(value: FieldValue): void; } diff --git a/types/redux-form/redux-form-tests.tsx b/types/redux-form/redux-form-tests.tsx index 06344b54c5..ea13a9618f 100644 --- a/types/redux-form/redux-form-tests.tsx +++ b/types/redux-form/redux-form-tests.tsx @@ -110,7 +110,6 @@ interface MyFieldCustomProps { type MyFieldProps = MyFieldCustomProps & WrappedFieldProps; const MyField: React.StatelessComponent = ({ children, - label, input, meta, foo diff --git a/types/redux-form/v4/index.d.ts b/types/redux-form/v4/index.d.ts index 4e21aee1fa..d9ac180ccf 100644 --- a/types/redux-form/v4/index.d.ts +++ b/types/redux-form/v4/index.d.ts @@ -464,7 +464,7 @@ export declare const reducer: { [formName: string]: { [fieldName: string]: Normalizer } - }): Reducer; + }): Reducer; /** * Returns a form reducer that will also pass each action through @@ -473,5 +473,5 @@ export declare const reducer: { * passed to each reducer will only be the slice that pertains to that * form. */ - plugin(reducers: { [formName: string]: Reducer }): Reducer; + plugin(reducers: { [formName: string]: Reducer }): Reducer; }; diff --git a/types/redux-infinite-scroll/index.d.ts b/types/redux-infinite-scroll/index.d.ts index 30fa435e2d..70ce20faf4 100644 --- a/types/redux-infinite-scroll/index.d.ts +++ b/types/redux-infinite-scroll/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/RealScout/redux-infinite-scroll // Definitions by: Tony Nikolov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Component, HTMLProps } from "react"; diff --git a/types/redux-router/index.d.ts b/types/redux-router/index.d.ts index bb9764ed61..710aaca0a5 100644 --- a/types/redux-router/index.d.ts +++ b/types/redux-router/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/rackt/redux-router // Definitions by: Stepan Mikhaylyuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import * as ReactRouter from 'react-router'; diff --git a/types/redux-ui/index.d.ts b/types/redux-ui/index.d.ts index 52cfb24b1d..55061e9a28 100644 --- a/types/redux-ui/index.d.ts +++ b/types/redux-ui/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/tonyhb/redux-ui // Definitions by: Andy Shu Xin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// import * as Redux from 'redux'; diff --git a/types/req-cwd/index.d.ts b/types/req-cwd/index.d.ts new file mode 100644 index 0000000000..56ca4f0786 --- /dev/null +++ b/types/req-cwd/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for req-cwd 2.0 +// Project: https://github.com/sindresorhus/req-cwd +// Definitions by: Arturas Molcanovas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/** Like require(), throws when the module can't be found. */ +declare function reqCwd(moduleId: string): any; + +declare namespace reqCwd { + /** Returns null instead of throwing when the module can't be found. */ + function silent(moduleId: string): any; +} + +export = reqCwd; diff --git a/types/req-cwd/req-cwd-tests.ts b/types/req-cwd/req-cwd-tests.ts new file mode 100644 index 0000000000..df95f8161f --- /dev/null +++ b/types/req-cwd/req-cwd-tests.ts @@ -0,0 +1,9 @@ +import * as reqCwd from 'req-cwd'; + +const r1: string = reqCwd('./foo'); +const r2: number = reqCwd('./foo'); +const r3: {foo: string} = reqCwd('./foo'); + +const s1: string | null = reqCwd.silent('./foo'); +const s2: number | null = reqCwd.silent('./foo'); +const s3: {foo: string} | null = reqCwd.silent('./foo'); diff --git a/types/req-cwd/tsconfig.json b/types/req-cwd/tsconfig.json new file mode 100644 index 0000000000..648ca4cf75 --- /dev/null +++ b/types/req-cwd/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", + "req-cwd-tests.ts" + ] +} diff --git a/types/req-cwd/tslint.json b/types/req-cwd/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/req-cwd/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/rheostat/index.d.ts b/types/rheostat/index.d.ts index be173bf31a..9e62865ce9 100644 --- a/types/rheostat/index.d.ts +++ b/types/rheostat/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/airbnb/rheostat // Definitions by: Sasha Bayan , Wil Lee // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/rollup-plugin-json/index.d.ts b/types/rollup-plugin-json/index.d.ts index 150da4f1d3..795f24a005 100644 --- a/types/rollup-plugin-json/index.d.ts +++ b/types/rollup-plugin-json/index.d.ts @@ -1,14 +1,27 @@ -// Type definitions for rollup-plugin-json 2.3 +// Type definitions for rollup-plugin-json 3.0 // Project: https://github.com/rollup/rollup-plugin-json#readme // Definitions by: Andy Mockler +// Martin Hochel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { Plugin } from 'rollup'; export interface Options { + /** + * All JSON files will be parsed by default, but you can also specifically include/exclude files + */ include?: string | string[]; exclude?: string | string[]; + /** + * for tree-shaking, properties will be declared as variables, using either `var` or `const` + * @default false + */ preferConst?: boolean; + /** + * specify indentation for the generated default export — defaults to '\t' + * @default '\t' + */ indent?: string; } diff --git a/types/rollup-plugin-json/package.json b/types/rollup-plugin-json/package.json index 60161a270c..ee69ca3cd2 100644 --- a/types/rollup-plugin-json/package.json +++ b/types/rollup-plugin-json/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "rollup": "^0.54.0" + "rollup": "^0.63.4" } } diff --git a/types/rollup-plugin-json/rollup-plugin-json-tests.ts b/types/rollup-plugin-json/rollup-plugin-json-tests.ts index 50baf7f03f..32e7b26b7a 100644 --- a/types/rollup-plugin-json/rollup-plugin-json-tests.ts +++ b/types/rollup-plugin-json/rollup-plugin-json-tests.ts @@ -1,3 +1,5 @@ import json from 'rollup-plugin-json'; json(); // $ExpectType Plugin + +json({preferConst: true, indent: ' '}); // $ExpectType Plugin diff --git a/types/sane-email-validation/index.d.ts b/types/sane-email-validation/index.d.ts new file mode 100644 index 0000000000..92e285c1ca --- /dev/null +++ b/types/sane-email-validation/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for sane-email-validation 1.1 +// Project: https://github.com/scottgonzalez/sane-email-validation +// Definitions by: Forbes Lindesay +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function isEmail(email: string): boolean; + +declare namespace isEmail { + function isNotEmail(email: string): boolean; +} + +export = isEmail; diff --git a/types/sane-email-validation/sane-email-validation-tests.ts b/types/sane-email-validation/sane-email-validation-tests.ts new file mode 100644 index 0000000000..7b8ad88603 --- /dev/null +++ b/types/sane-email-validation/sane-email-validation-tests.ts @@ -0,0 +1,9 @@ +import isEmail = require('sane-email-validation'); + +const is: boolean = isEmail('foo@bar.com'); +const isNot: boolean = isEmail.isNotEmail('foo@bar.com'); + +// $ExpectError +isEmail(10); +// $ExpectError +isEmail.isNotEmail(10); diff --git a/types/sane-email-validation/tsconfig.json b/types/sane-email-validation/tsconfig.json new file mode 100644 index 0000000000..3b9b568d67 --- /dev/null +++ b/types/sane-email-validation/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", + "sane-email-validation-tests.ts" + ] +} diff --git a/types/sane-email-validation/tslint.json b/types/sane-email-validation/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sane-email-validation/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sanitize-html/index.d.ts b/types/sanitize-html/index.d.ts index bdd70f956a..2e7527e3fc 100644 --- a/types/sanitize-html/index.d.ts +++ b/types/sanitize-html/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for sanitize-html 1.14.1 +// Type definitions for sanitize-html 1.18.2 // Project: https://github.com/punkave/sanitize-html // Definitions by: Rogier Schouten // Afshin Darian // BehindTheMath +// Rinze de Laat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = sanitize; @@ -38,9 +39,12 @@ declare namespace sanitize { interface IOptions { allowedAttributes?: { [index: string]: string[] } | boolean; + allowedStyles?: { [index: string]: { [index: string]: RegExp[] } }; allowedClasses?: { [index: string]: string[] } | boolean; + allowedIframeHostnames?: string[]; allowedSchemes?: string[] | boolean; allowedSchemesByTag?: { [index: string]: string[] } | boolean; + allowedSchemesAppliedToAttributes?: string[]; allowProtocolRelative?: boolean; allowedTags?: string[] | boolean; exclusiveFilter?: (frame: IFrame) => boolean; diff --git a/types/sanitize-html/sanitize-html-tests.ts b/types/sanitize-html/sanitize-html-tests.ts index cc43d64fcb..b02a5a6653 100644 --- a/types/sanitize-html/sanitize-html-tests.ts +++ b/types/sanitize-html/sanitize-html-tests.ts @@ -4,8 +4,17 @@ let options: sanitize.IOptions = { allowedTags: sanitize.defaults.allowedTags.concat('h1', 'h2', 'img'), allowedAttributes: { 'a': sanitize.defaults.allowedAttributes['a'].concat('rel'), - 'img': ['src', 'height', 'width', 'alt'] + 'img': ['src', 'height', 'width', 'alt', 'style'] }, + allowedStyles: { + '*': { + color: [/^red$/], + background: [/^green$/], + 'background-color': [/^#0000FF$/] + } + }, + allowedIframeHostnames: ['www.youtube.com'], + allowedSchemesAppliedToAttributes: [ 'href', 'src', 'cite' ], transformTags: { 'a': sanitize.simpleTransform('a', { 'rel': 'nofollow' }), 'img': (tagName: string, attribs: sanitize.Attributes) => { diff --git a/types/sat/index.d.ts b/types/sat/index.d.ts index 538228049c..901c0814f2 100644 --- a/types/sat/index.d.ts +++ b/types/sat/index.d.ts @@ -59,10 +59,10 @@ declare namespace SAT { setPoints(points: Vector[]): Polygon; setAngle(angle: number): Polygon; setOffset(offset: Vector): Polygon; - recalc(): Polygon; rotate(angle: number): Polygon; translate(x: number, y: number): Polygon; getAABB(): Polygon; + getCentroid(): Vector; } export class Box { diff --git a/types/sdp-transform/index.d.ts b/types/sdp-transform/index.d.ts new file mode 100644 index 0000000000..3219fe9957 --- /dev/null +++ b/types/sdp-transform/index.d.ts @@ -0,0 +1,265 @@ +// Type definitions for sdp-transform 2.4 +// Project: https://github.com/clux/sdp-transform#readme +// Definitions by: @loc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// https://tools.ietf.org/html/rfc4566 +// https://www.iana.org/assignments/sdp-parameters/sdp-parameters.xhtml + +export function write(description: SessionDescription): string; +export function parse(description: string): SessionDescription; +export function parsePayloads(payloads: string): number[]; +export function parseRemoteCandidates(candidates: string): Array<{ + component: number; + ip: string; + port: number; +}>; +export function parseSimulcastStreamList(streams: string): Array<{ + scid: number | string; + paused: boolean; +}>; +export interface ParamMap { + [paramName: string]: number | string; +} +export function parseParams(params: string): ParamMap; +export function parseImageAttributes(params: string): ParamMap[]; + +export interface MediaDescription extends SharedDescriptionFields, MediaAttributes {} + +/** + * Descriptor fields that exist only at the session level (before an m= block). + * + * See the SDP grammar for more details: https://tools.ietf.org/html/rfc4566#section-9 + */ +export interface SessionDescription extends SharedDescriptionFields, SessionAttributes { + version?: number; + // o= + origin?: { + username: string; + sessionId: string | number; + sessionVersion: number; + netType: string; + address: string; + }; + // s= + name?: string; + // u= + uri?: string; + // e= + email?: string; + // p= + phone?: string; + // t=0 0 + timing?: { + start: number; + stop: number; + }; + // z= + timezones?: string; + // r= + repeats?: string; + // m= + media: Array<{ + type: string; + port: number; + protocol: string; + payloads?: string; + } & MediaDescription>; +} + +/** + * These attributes can exist on both the session level and the media level. + * + * https://www.iana.org/assignments/sdp-parameters/sdp-parameters.xhtml#sdp-parameters-8 + */ +export interface SharedAttributes { + // a=sendrecv + // a=recvonly + // a=sendonly + // a=inactive + direction?: 'sendrecv' | 'recvonly' | 'sendonly' | 'inactive'; + // a=control + control?: string; + // a=extmap + ext?: { + value: number; + direction?: string; + uri: string; + config?: string; + }; + // a=setup + setup?: string; + + iceUfrag?: string; + icePwd?: string; + fingerprint?: { + type: string; + hash: string; + }; + // a=source-filter: incl IN IP4 239.5.2.31 10.1.15.5 + sourceFilter?: { + filterMode: 'excl' | 'incl'; + netType: string; + addressTypes: string; + destAddress: string; + srcList: string; + }; + invalid?: Array<{ value: string }>; +} + +/** + * Attributes that only exist at the session level (before an m= block). + * + * https://www.iana.org/assignments/sdp-parameters/sdp-parameters.xhtml#sdp-parameters-7 + */ +export interface SessionAttributes extends SharedAttributes { + icelite?: string; + // a=ice-options:google-ice + iceOptions?: string; + // a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV + msidSemantic?: { + semantic: string; + token: string; + }; + // a=group:BUNDLE audio video + groups?: Array<{ + type: string; + mids: string; + }>; +} + +/** + * Attributes that only exist at the media level (within an m= block). + * + * https://www.iana.org/assignments/sdp-parameters/sdp-parameters.xhtml#sdp-parameters-9 + */ +export interface MediaAttributes extends SharedAttributes { + rtp?: { + payload: number; + codec: string; + rate?: number; + encoding?: number; + }; + rtcp?: { + port: number; + netType?: string; + ipVer?: number; + address?: string; + }; + // a=rtcp-fb:98 nack rpsi + rtcpFb?: { + payload: number; + type: string; + subtype?: string; + }; + // a=rtcp-fb:98 trr-int 100 + rtcpFbTrrInt?: { + payload: number; + value: number; + }; + // a=fmtp + fmtp?: { + payload: number; + config: string; + }; + // a=mid + mid?: string; + // a=msid + msid?: string; + ptime?: number; + // a=maxptime + maxptime?: number; + // a=crypto + crypto?: { + id: number; + suite: string; + config: string; + sessionConfig?: string; + }; + // a=candidate + candidates?: Array<{ + foundation: string; + component: number; + transport: string; + priority: number | string; + ip: string; + port: number; + type: string; + raddr: string; + rport: number; + tcptype: string; + generation: number; + 'network-id'?: number; + 'network-cost'?: number; + }>; + // a=end-of-candidates + endOfCandidates?: string; + // a=remote-candidates + remoteCandidates?: string; + // a=ssrc: + ssrcs?: Array<{ + id: number | string; + attribute: string; + value?: string; + }>; + // a=ssrc-group: + ssrcGroups?: Array<{ + semantics: string; + ssrcs: string; + }>; + // a=rtcp-mux + rtcpMux?: string; + // a=rtcp-rsize + rtcpRsize?: string; + // a=sctpmap + sctpmap?: { + sctpmapNumber: number | string; + app: string; + maxMessageSize: number; + }; + // a=x-google-flag + xGoogleFlag?: string; + // a=rid + rids?: Array<{ + id: number | string; + direction: string; + params?: string; + }>; + // a=imageattr + imageattrs?: Array<{ + pt: number | string; + dir1: string; + attrs1: string; + dir2?: string; + attrs2?: string; + }>; + simulcast?: { + dir1: string; + list1: string; + dir2?: string; + list2?: string; + }; + simulcast_03?: { value: string }; + // a=framerate + framerate?: number | string; +} + +/** + * Descriptor fields that exist at both the session level and media level. + * + * See the SDP grammar for more details: https://tools.ietf.org/html/rfc4566#section-9 + */ +export interface SharedDescriptionFields { + // i= + description?: string; + // c=IN IP4 10.47.197.26 + connection?: { + version: number; + ip: string; + }; + // b=AS:4000 + bandwidth?: { + type: 'TIAS' | 'AS' | 'CT' | 'RR' | 'RS'; + limit: number | string; + }; +} diff --git a/types/sdp-transform/sdp-transform-tests.ts b/types/sdp-transform/sdp-transform-tests.ts new file mode 100644 index 0000000000..4b60e84a5a --- /dev/null +++ b/types/sdp-transform/sdp-transform-tests.ts @@ -0,0 +1,10 @@ +import { + SessionDescription, + parse, + write, +} from 'sdp-transform'; + +const session: SessionDescription = parse(''); +const mediaType: string = session.media[0].type; +session.media[0].type = 'video'; +const sdp: string = write(session); diff --git a/types/sdp-transform/tsconfig.json b/types/sdp-transform/tsconfig.json new file mode 100644 index 0000000000..b4d6bb625b --- /dev/null +++ b/types/sdp-transform/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", + "sdp-transform-tests.ts" + ] +} diff --git a/types/sdp-transform/tslint.json b/types/sdp-transform/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sdp-transform/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/select2/v3/index.d.ts b/types/select2/v3/index.d.ts index 21bb2611c7..771d997384 100644 --- a/types/select2/v3/index.d.ts +++ b/types/select2/v3/index.d.ts @@ -75,6 +75,7 @@ interface Select2Options { dropdownCss?: any; dropdownCssClass?: any; escapeMarkup?: (markup: string) => string; + nextSearchTerm?: (selectedObject: object, currentSearchTerm: string) => string; } interface Select2JQueryEventObject extends JQueryEventObject { diff --git a/types/select2/v3/select2-tests.ts b/types/select2/v3/select2-tests.ts index 3b331cec3b..2d5a400352 100644 --- a/types/select2/v3/select2-tests.ts +++ b/types/select2/v3/select2-tests.ts @@ -210,6 +210,9 @@ $("#e17_2").select2({ }); $("#e18,#e18_2").select2(); alert("Selected value is: " + $("#e8").select2("val")); $("#e8").select2("val", { id: "CA", text: "Califoria" }); +$("#e19").select2({nextSearchTerm: function(selectedObject: object, currentSearchTerm: string) { + return currentSearchTerm; +}}); $("#e8").select2("val"); $("#e8").select2("val", "CA"); diff --git a/types/simple-oauth2/index.d.ts b/types/simple-oauth2/index.d.ts index 21718c0722..19a1ff2698 100644 --- a/types/simple-oauth2/index.d.ts +++ b/types/simple-oauth2/index.d.ts @@ -1,11 +1,10 @@ -// Type definitions for simple-oauth2 1.1 +// Type definitions for simple-oauth2 2.2 // Project: https://github.com/lelylan/simple-oauth2 // Definitions by: Michael Müller , // Troy Lamerton +// Martín Rodriguez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import Bluebird = require("bluebird"); +// TypeScript Version: 2.9 /** Creates a new simple-oauth2 client with the passed configuration */ export function create(options: ModuleOptions): OAuthClient; @@ -33,13 +32,21 @@ export interface ModuleOptions { /** String path to request an authorization code. Default to /oauth/authorize. */ authorizePath?: string }; - /** optional object used to set global options to the internal http library (request-js). */ + /** + * Used to set global options to the internal http library (wreck). + * All options except baseUrl are allowed + * Defaults to header.Accept = "application/json" + */ http?: {}; options?: { - /** Whether or not the client.id/client.secret params are sent in the request body. Defaults to true. */ - useBodyAuth?: boolean, - /** Whether or not the Basic Authorization header should be sent at the token request. */ - useBasicAuthorizationHeader?: boolean + /** Format of data sent in the request body. Defaults to form. */ + bodyFormat?: "json" | "form", + /** + * Indicates the method used to send the client.id/client.secret authorization params at the token request. + * If set to body, the bodyFormat option will be used to format the credentials. + * Defaults to header + */ + authorizationMethod?: "header" | "body" }; } @@ -55,17 +62,19 @@ export interface AccessToken { /** Check if the access token is expired or not */ expired(): boolean; /** Refresh the access token */ - refresh(params: {}, callback: (error: any, result: AccessToken) => void): Bluebird; - refresh(callback?: (error: any, result: AccessToken) => void): Bluebird; + refresh(params?: {}): Promise; /** Revoke access or refresh token */ - revoke(tokenType: TokenType, callback?: (error: any) => void): Bluebird; + revoke(tokenType: TokenType): Promise; + /** Revoke both the existing access and refresh tokens */ + revokeAll(): Promise; } export type AuthorizationCode = string; export interface AuthorizationTokenConfig { + /** Authorization code (from previous step) */ code: AuthorizationCode; + /** A string that represents the callback uri */ redirect_uri: string; - scope?: string | string[]; } export interface PasswordTokenConfig { @@ -88,27 +97,32 @@ export interface OAuthClient { * Redirect the user to the autorization page * @return the absolute authorization url */ - authorizeURL(params?: { - /** A string that represents the registered application URI where the user is redirected after authentication */ - redirect_uri?: string, - /** A string or array of strings that represents the application privileges */ - scope?: string | string[], - /** A string that represents an option opaque value used by the client to main the state between the request and the callback */ - state?: string - }): string, + authorizeURL( + params?: { + /** A key-value pair where key is ModuleOptions#client.idParamName and the value represents the Client-ID */ + [ idParamName: string ]: string | undefined + } & { + /** A string that represents the registered application URI where the user is redirected after authentication */ + redirect_uri?: string, + /** A string or array of strings that represents the application privileges */ + scope?: string | string[], + /** A string that represents an option opaque value used by the client to main the state between the request and the callback */ + state?: string + } + ): string, /** Returns the Access Token object */ - getToken(params: AuthorizationTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + getToken(params: AuthorizationTokenConfig): Promise; }; ownerPassword: { /** Returns the Access Token Object */ - getToken(params: PasswordTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + getToken(params: PasswordTokenConfig): Promise; }; clientCredentials: { /** Returns the Access Token Object */ - getToken(params: ClientCredentialTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + getToken(params: ClientCredentialTokenConfig): Promise; }; accessToken: { diff --git a/types/simple-oauth2/simple-oauth2-tests.ts b/types/simple-oauth2/simple-oauth2-tests.ts index f83a616681..e066ad41c0 100644 --- a/types/simple-oauth2/simple-oauth2-tests.ts +++ b/types/simple-oauth2/simple-oauth2-tests.ts @@ -1,8 +1,11 @@ // off https://github.com/lelylan/simple-oauth2/blob/master/README.md // slightly changed to remove external dependencies +// Initialize the OAuth2 Library +import * as oauth2lib from "simple-oauth2"; + // Set the configuration settings -const credentials = { +const credentials: oauth2lib.ModuleOptions = { client: { id: '', secret: '' @@ -12,13 +15,10 @@ const credentials = { } }; -// Initialize the OAuth2 Library -// const oauth2 = require('simple-oauth2').create(credentials); -import oauth2lib = require("simple-oauth2"); const oauth2 = oauth2lib.create(credentials); // #Authorization Code flow -(() => { +(async () => { // Authorization oauth2 URI const authorizationUri = oauth2.authorizationCode.authorizeURL({ redirect_uri: 'http://localhost:3000/callback', @@ -36,57 +36,47 @@ const oauth2 = oauth2lib.create(credentials); scope: ['', ''] }; - // Callbacks // Save the access token - oauth2.authorizationCode.getToken(tokenConfig, (error, result) => { - if (error) { - console.log('Access Token Error', error.message); - return; - } + try { + const result = await oauth2.authorizationCode.getToken(tokenConfig); + const accessToken = oauth2.accessToken.create(result); + } catch (error) { + console.log('Access Token Error', error.message); + } +})(); - const token = oauth2.accessToken.create(result); - }); +// #Password Credentials Flow +(async () => { + const tokenConfig = { + username: 'username', + password: 'password', + scope: [ '', '' ], + }; - // Promises // Save the access token - oauth2.authorizationCode.getToken(tokenConfig) - .then((result) => { - const token = oauth2.accessToken.create(result); - }) - .catch((error) => { - console.log('Access Token Error', error.message); - }); + try { + const result = await oauth2.ownerPassword.getToken(tokenConfig); + const accessToken = oauth2.accessToken.create(result); + } catch (error) { + console.log('Access Token Error', error.message); + } })(); // #Client Credentials Flow -(() => { +(async () => { const tokenConfig = {}; - // Callbacks // Get the access token object for the client - oauth2.clientCredentials.getToken(tokenConfig, (error, result) => { - if (error) { - console.log('Access Token Error', error.message); - return; - } - - const token = oauth2.accessToken.create(result); - }); - - // Promises - // Get the access token object for the client - oauth2.clientCredentials - .getToken(tokenConfig) - .then((result) => { - const token = oauth2.accessToken.create(result); - }) - .catch((error) => { - console.log('Access Token error', error.message); - }); + try { + const result = await oauth2.clientCredentials.getToken(tokenConfig); + const accessToken = oauth2.accessToken.create(result); + } catch (error) { + console.log('Access Token error', error.message); + } })(); // #Access Token object -(() => { +(async () => { // Sample of a JSON access token (you got it through previous steps) const tokenObject = { access_token: '', @@ -95,62 +85,46 @@ const oauth2 = oauth2lib.create(credentials); }; // Create the access token wrapper - let token = oauth2.accessToken.create(tokenObject); + let accessToken = oauth2.accessToken.create(tokenObject); // Check if the token is expired. If expired it is refreshed. - if (token.expired()) { - // Callbacks - token.refresh((error, result) => { - token = result; - }); - - // Promises - token.refresh() - .then((result) => { - token = result; - }); + if (accessToken.expired()) { + try { + accessToken = await accessToken.refresh(); + } catch (error) { + console.log('Error refreshing access token: ', error.message); + } } - // Callbacks - // Revoke only the access token - token.revoke('access_token', (error) => { + // Revoke both access and refresh tokens + try { + // Revoke only the access token + await accessToken.revoke('access_token'); + // Session ended. But the refresh_token is still valid. + // Revoke the refresh token + await accessToken.revoke('refresh_token'); - // Revoke the refresh_token - token.revoke('refresh_token', (error) => { - console.log('token revoked.'); - }); - }); + console.log('Token revoked'); + } catch (error) { + console.log('Error revoking token: ', error.message); + } - // Promises - // Revoke only the access token - token.revoke('access_token') - .then(() => { - // Revoke the refresh token - return token.revoke('refresh_token'); - }) - .then(() => { - console.log('Token revoked'); - }) - .catch((error) => { - console.log('Error revoking token.', error.message); - }); + // or... + + try { + // Revokes both tokens, refresh token is only revoked if the access_token is properly revoked + await accessToken.revokeAll(); + } catch (error) { + console.log('Error revoking token: ', error.message); + } })(); // #Errors // not applicable, as those errors about missing authentication codes are already found by the typescript compiler // (function () { -// // Callbacks -// oauth2.authorizationCode.getToken({}, (error, token) => { -// if (error) { -// return console.log(error.message); -// } -// }); - -// // Promises -// oauth2.authorizationCode -// .getToken({}) +// oauth2.authorizationCode.getToken({}) // .catch((error) => { // console.log(error.message); // }); diff --git a/types/simple-oauth2/v1/index.d.ts b/types/simple-oauth2/v1/index.d.ts new file mode 100644 index 0000000000..30b1a72d98 --- /dev/null +++ b/types/simple-oauth2/v1/index.d.ts @@ -0,0 +1,133 @@ +// Type definitions for simple-oauth2 1.6 +// Project: https://github.com/lelylan/simple-oauth2 +// Definitions by: Michael Müller , +// Troy Lamerton +// Martín Rodriguez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import Bluebird = require("bluebird"); + +/** Creates a new simple-oauth2 client with the passed configuration */ +export function create(options: ModuleOptions): OAuthClient; + +export interface ModuleOptions { + client: { + /** Service registered client id. Required. */ + id: string, + /** Service registered client secret. Required. */ + secret: string, + /** Parameter name used to send the client secret. Default to client_secret. */ + secretParamName?: string, + /** Parameter name used to send the client id. Default to client_id. */ + idParamName?: string + }; + auth: { + /** String used to set the host to request the tokens to. Required. */ + tokenHost: string, + /** String path to request an access token. Default to /oauth/token. */ + tokenPath?: string, + /** String path to revoke an access token. Default to /oauth/revoke. */ + revokePath?: string, + /** String used to set the host to request an "authorization code". Default to the value set on auth.tokenHost. */ + authorizeHost?: string, + /** String path to request an authorization code. Default to /oauth/authorize. */ + authorizePath?: string + }; + /** + * Used to set global options to the internal http library (wreck). + * All options except baseUrl are allowed + * Defaults to header.Accept = "application/json" + */ + http?: {}; + options?: { + /** Format of data sent in the request body. Defaults to form. */ + bodyFormat?: "json" | "form", + /** + * Indicates the method used to send the client.id/client.secret authorization params at the token request. + * If set to body, the bodyFormat option will be used to format the credentials. + * Defaults to header. + */ + authorizationMethod?: "header" | "body" + }; +} + +export type TokenType = "access_token" | "refresh_token"; + +export interface Token { + [x: string]: any; +} + +export interface AccessToken { + token: Token; + + /** Check if the access token is expired or not */ + expired(): boolean; + /** Refresh the access token */ + refresh(params: {}, callback: (error: any, result: AccessToken) => void): Bluebird; + refresh(callback?: (error: any, result: AccessToken) => void): Bluebird; + /** Revoke access or refresh token */ + revoke(tokenType: TokenType, callback?: (error: any) => void): Bluebird; +} + +export type AuthorizationCode = string; +export interface AuthorizationTokenConfig { + /** Authorization code (from previous step) */ + code: AuthorizationCode; + /** A string that represents the callback uri */ + redirect_uri: string; +} + +export interface PasswordTokenConfig { + /** A string that represents the registered username */ + username: string; + /** A string that represents the registered password. */ + password: string; + /** A string or array of strings that represents the application privileges */ + scope: string | string[]; +} + +export interface ClientCredentialTokenConfig { + /** A string that represents the application privileges */ + scope?: string | string[]; +} + +export interface OAuthClient { + authorizationCode: { + /** + * Redirect the user to the autorization page + * @return the absolute authorization url + */ + authorizeURL( + params?: { + /** A key-value pair where key is ModuleOptions#client.idParamName and the value represents the Client-ID */ + [ idParamName: string ]: string | undefined + } & { + /** A string that represents the registered application URI where the user is redirected after authentication */ + redirect_uri?: string, + /** A string or array of strings that represents the application privileges */ + scope?: string | string[], + /** A string that represents an option opaque value used by the client to main the state between the request and the callback */ + state?: string + } + ): string, + + /** Returns the Access Token object */ + getToken(params: AuthorizationTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + }; + + ownerPassword: { + /** Returns the Access Token Object */ + getToken(params: PasswordTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + }; + + clientCredentials: { + /** Returns the Access Token Object */ + getToken(params: ClientCredentialTokenConfig, callback?: (error: any, result: Token) => void): Bluebird; + }; + + accessToken: { + /** Creates an OAuth2.AccessToken instance */ + create(tokenToUse: Token): AccessToken; + }; +} diff --git a/types/simple-oauth2/v1/simple-oauth2-tests.ts b/types/simple-oauth2/v1/simple-oauth2-tests.ts new file mode 100644 index 0000000000..b3a8b2f952 --- /dev/null +++ b/types/simple-oauth2/v1/simple-oauth2-tests.ts @@ -0,0 +1,188 @@ +// off https://github.com/lelylan/simple-oauth2/blob/master/README.md +// slightly changed to remove external dependencies + +// Initialize the OAuth2 Library +import * as oauth2lib from "simple-oauth2"; + +// Set the configuration settings +const credentials: oauth2lib.ModuleOptions = { + client: { + id: '', + secret: '' + }, + auth: { + tokenHost: 'https://api.oauth.com' + } +}; + +const oauth2 = oauth2lib.create(credentials); + +// #Authorization Code flow +(() => { + // Authorization oauth2 URI + const authorizationUri = oauth2.authorizationCode.authorizeURL({ + redirect_uri: 'http://localhost:3000/callback', + scope: '', + state: '' + }); + + // Redirect example using Express (see http://expressjs.com/api.html#res.redirect) + // res.redirect(authorizationUri); + + // Get the access token object (the authorization code is given from the previous step). + const tokenConfig = { + code: '', + redirect_uri: 'http://localhost:3000/callback', + scope: ['', ''] + }; + + // Callbacks + // Save the access token + oauth2.authorizationCode.getToken(tokenConfig, (error, result) => { + if (error) { + console.log('Access Token Error', error.message); + return; + } + + const token = oauth2.accessToken.create(result); + }); + + // Promises + // Save the access token + oauth2.authorizationCode.getToken(tokenConfig) + .then((result) => { + const token = oauth2.accessToken.create(result); + }) + .catch((error) => { + console.log('Access Token Error', error.message); + }); +})(); + +// #Password Credentials Flow +(() => { + const tokenConfig = { + username: 'username', + password: 'password', + scope: [ '', '' ], + }; + + // Callbacks + // Save the access token + oauth2.ownerPassword.getToken(tokenConfig, (error, result) => { + if (error) { + console.log('Access Token Error', error.message); + return; + } + + const token = oauth2.accessToken.create(result); + }); + + // Promises + // Save the access token + oauth2.ownerPassword.getToken(tokenConfig) + .then((result) => { + const token = oauth2.accessToken.create(result); + }) + .catch((error) => { + console.log('Access Token Error', error.message); + }); +})(); + +// #Client Credentials Flow +(() => { + const tokenConfig = {}; + + // Callbacks + // Get the access token object for the client + oauth2.clientCredentials.getToken(tokenConfig, (error, result) => { + if (error) { + console.log('Access Token Error', error.message); + return; + } + + const token = oauth2.accessToken.create(result); + }); + + // Promises + // Get the access token object for the client + oauth2.clientCredentials.getToken(tokenConfig) + .then((result) => { + const token = oauth2.accessToken.create(result); + }) + .catch((error) => { + console.log('Access Token error', error.message); + }); +})(); + +// #Access Token object +(() => { + // Sample of a JSON access token (you got it through previous steps) + const tokenObject = { + access_token: '', + refresh_token: '', + expires_in: '7200' + }; + + // Create the access token wrapper + let accessToken = oauth2.accessToken.create(tokenObject); + + // Check if the token is expired. If expired it is refreshed. + if (accessToken.expired()) { + // Callbacks + accessToken.refresh((error, result) => { + accessToken = result; + }); + + // Promises + accessToken.refresh() + .then((result) => { + accessToken = result; + }); + } + + // Callbacks + // Revoke only the access token + accessToken.revoke('access_token', (error) => { + // Session ended. But the refresh_token is still valid. + + // Revoke the refresh_token + accessToken.revoke('refresh_token', (error) => { + console.log('token revoked.'); + }); + }); + + // Promises + // Revoke only the access token + accessToken.revoke('access_token') + .then(() => { + // Revoke the refresh token + return accessToken.revoke('refresh_token'); + }) + .then(() => { + console.log('Token revoked'); + }) + .catch((error) => { + console.log('Error revoking token.', error.message); + }); +})(); + +// #Errors +// not applicable, as those errors about missing authentication codes are already found by the typescript compiler + +// (function () { +// // Callbacks +// oauth2.authorizationCode.getToken({}, (error, token) => { +// if (error) { +// return console.log(error.message); +// } +// }); + +// // Promises +// oauth2.authorizationCode +// .getToken({}) +// .catch((error) => { +// console.log(error.message); +// }); + +// // => { "status": "401", "message": "Unauthorized" } +// })(); diff --git a/types/simple-oauth2/v1/tsconfig.json b/types/simple-oauth2/v1/tsconfig.json new file mode 100644 index 0000000000..f19c003707 --- /dev/null +++ b/types/simple-oauth2/v1/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "simple-oauth2": [ + "simple-oauth2/v1" + ], + "simple-oauth2/*": [ + "simple-oauth2/v1/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "simple-oauth2-tests.ts" + ] +} diff --git a/types/simple-oauth2/v1/tslint.json b/types/simple-oauth2/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/simple-oauth2/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/single-spa-react/index.d.ts b/types/single-spa-react/index.d.ts new file mode 100644 index 0000000000..82656bfaf5 --- /dev/null +++ b/types/single-spa-react/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for single-spa-react 2.8 +// Project: https://github.com/CanopyTax/single-spa-react +// Definitions by: Garrett Smith +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; + +export = SingleSpaReact; +declare function SingleSpaReact(opts: SingleSpaReact.Options): SingleSpaReact.Lifecycles; + +declare namespace SingleSpaReact { + interface Options { + React: typeof React; + ReactDOM: typeof ReactDOM; + rootComponent?: React.ComponentClass; + loadRootComponent?: () => Promise; + domElementGetter?: () => Element; + suppressComponentDidCatchWarning?: boolean; + parcelCanUpdate?: boolean; + } + + interface Lifecycles { + bootstrap: (opts: Options, props: any) => Promise; + mount: (opts: Options, props: any) => Promise; + unmount: (opts: Options, props: any) => Promise; + } +} diff --git a/types/single-spa-react/single-spa-react-tests.ts b/types/single-spa-react/single-spa-react-tests.ts new file mode 100644 index 0000000000..7efed91489 --- /dev/null +++ b/types/single-spa-react/single-spa-react-tests.ts @@ -0,0 +1,10 @@ +import singleSpaReact = require('single-spa-react'); +import { Lifecycles } from 'single-spa-react'; +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; + +// $ExpectType Lifecycles +singleSpaReact({ + React, + ReactDOM, +}); diff --git a/types/single-spa-react/tsconfig.json b/types/single-spa-react/tsconfig.json new file mode 100644 index 0000000000..3ccb45cf0c --- /dev/null +++ b/types/single-spa-react/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", + "single-spa-react-tests.ts" + ] +} diff --git a/types/single-spa-react/tslint.json b/types/single-spa-react/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/single-spa-react/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/slack-mock/index.d.ts b/types/slack-mock/index.d.ts new file mode 100644 index 0000000000..2289e554b4 --- /dev/null +++ b/types/slack-mock/index.d.ts @@ -0,0 +1,200 @@ +// Type definitions for slack-mock 1.1 +// Project: https://github.com/Skellington-Closet/slack-mock +// Definitions by: Kris Kalavantavanich +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { IncomingHttpHeaders } from "http"; +import * as nock from "nock"; +import { Url } from "url"; +import * as WebSocket from "ws"; + +export = SlackMock; + +declare function SlackMock(config?: SlackMock.ConfigOptions): SlackMock.Instance; + +declare namespace SlackMock { + let instance: Instance; + + interface Instance { + events: Events; + incomingWebhooks: IncomingWebhooks; + interactiveButtons: InteractiveButtons; + outgoingWebhooks: OutgoingWebhooks; + rtm: Rtm; + slashCommands: SlashCommands; + web: Web; + + reset: () => void; + } + + interface ConfigOptions { + rtmPort?: number; + logLevel?: string; + } + + // Events + + type EventUrl = string | Url; + type EventHttpHeaders = IncomingHttpHeaders; + + interface Events { + send: (targetUrl: EventUrl, body: T) => Promise; + reset: () => void; + calls: Array>; + } + + interface EventCall { + url: EventUrl; + params: T; + headers: EventHttpHeaders; + statusCode: number; + } + + // Incoming Webhooks + + type IncomingWebhookUrl = string; + type IncomingWebhookHttpHeaders = nock.HttpHeaders; + + interface IncomingWebhooks { + addResponse: (opts: IncomingWebhookOptions) => void; + reset: () => void; + calls: Array>; + } + + interface IncomingWebhookOptions { + url?: IncomingWebhookUrl; + statusCode ?: number; + body ?: T; + headers ?: IncomingWebhookHttpHeaders; + } + + interface IncomingWebhookCall { + url: IncomingWebhookUrl; + params: T; + headers: IncomingWebhookHttpHeaders; + } + + // Interactive Buttons + + type InteractiveButtonUrl = string | Url; + type InteractiveButtonHttpHeaders = nock.HttpHeaders; + + interface InteractiveButtons { + send: (targetUrl: InteractiveButtonUrl, body: T) => Promise; + addResponse: (opts: InteractiveButtonOptions) => void; + reset: () => void; + calls: Array>; + } + + interface InteractiveButtonOptions { + url?: InteractiveButtonUrl; + statusCode ?: number; + body ?: T; + headers ?: InteractiveButtonHttpHeaders; + } + + interface InteractiveButtonCall { + url: InteractiveButtonUrl; + params: T; + headers: InteractiveButtonHttpHeaders; + statusCode: number; + type: InteractiveButtonCallType; + } + + enum InteractiveButtonCallType { + response = 'response', + response_url = 'response_url' + } + + // Outgoing Webhooks + + type OutgoingWebhookUrl = string | Url; + type OutgoingWebhookHttpHeaders = IncomingHttpHeaders; + + interface OutgoingWebhooks { + send: (targetUrl: OutgoingWebhookUrl, body: T) => Promise; + reset: () => void; + calls: Array>; + } + + interface OutgoingWebhookCall { + url: OutgoingWebhookUrl; + params: T; + headers: OutgoingWebhookHttpHeaders; + statusCode: number; + } + + // RTM + + interface Rtm { + clients: WebSocket[]; + send: (token: string, message: T) => Promise; + reset: () => void; + calls: Array>; + startServer: (token: string) => void; + stopServer: (token: string) => void; + } + + interface RtmCall { + message: T; + token: string; + rawMessage: WebSocket.Data; + } + + // Slash Commands + + type SlashCommandUrl = string | Url; + type SlashCommandHttpHeaders = IncomingHttpHeaders; + + interface SlashCommands { + send: (targetUrl: SlashCommandUrl, body: T) => Promise; + addResponse: (opts: SlashCommandOptions) => void; + reset: () => void; + calls: Array>; + } + + interface SlashCommandOptions { + url?: SlashCommandUrl; + statusCode ?: number; + body ?: T; + headers ?: SlashCommandHttpHeaders; + } + + interface SlashCommandCall { + url: SlashCommandUrl; + params: T; + headers: SlashCommandHttpHeaders; + statusCode: number; + type: SlashCommandCallType; + } + + enum SlashCommandCallType { + response = 'response', + response_url = 'response_url' + } + + // Web + + type WebUrl = string; + type WebHttpHeaders = nock.HttpHeaders; + + interface Web { + addResponse: (opts: WebOptions) => void; + reset: () => void; + calls: Array>; + } + + interface WebOptions { + url?: WebUrl; + statusCode ?: number; + body ?: T; + headers ?: WebHttpHeaders; + } + + interface WebCall { + url: WebUrl; + params: T; + headers: WebHttpHeaders; + } +} diff --git a/types/slack-mock/slack-mock-tests.ts b/types/slack-mock/slack-mock-tests.ts new file mode 100644 index 0000000000..5b5dabb9c1 --- /dev/null +++ b/types/slack-mock/slack-mock-tests.ts @@ -0,0 +1,103 @@ +import SlackMock = require("slack-mock"); + +// Initialization + +const slackMock = SlackMock.instance; +SlackMock({ + logLevel: "error", + rtmPort: 9090 +}); +SlackMock(); + +// Events +const eventPayload = { }; +slackMock.events.send('http://localhost:9000/event', eventPayload) + .then(() => { + slackMock.events.calls.length; + slackMock.events.calls[0].statusCode; + slackMock.events.calls[0].headers; + slackMock.events.calls[0].params; + slackMock.events.calls[0].url; + }); + +slackMock.events.reset(); + +// Incoming Webhooks +slackMock.incomingWebhooks.calls.length; +slackMock.incomingWebhooks.calls[0].params.text; + +// Interactive Buttons +slackMock.interactiveButtons.addResponse({ + statusCode: 201 +}); + +const interactiveButtonPayload = {text: 'abc'}; +slackMock.interactiveButtons.send('http://localhost:9000/button', interactiveButtonPayload) + .then(() => { + slackMock.interactiveButtons.calls.length; + slackMock.interactiveButtons.calls[0].params.text; + }); + +// Outgoing Webhooks +const outgoingWebhookPayload = {text: 'abc'}; +slackMock.outgoingWebhooks.send('http://localhost:9000/outgoing', outgoingWebhookPayload) + .then(() => { + slackMock.outgoingWebhooks.calls.length; + slackMock.outgoingWebhooks.calls[0].params.text; + }); + +// RTM +slackMock.rtm.send('1234', { + type: 'message', + channel: 'mockChannel', + user: 'usr', + text: 'hello'}) + .then(() => { + slackMock.rtm.calls.length; + slackMock.rtm.calls[0].message.text; + }); +slackMock.rtm.startServer('1234'); +slackMock.rtm.stopServer('1234'); + +// Slash Commands +const slashCommandPayload = { }; +slackMock.slashCommands.send('http://localhost:9000/slash', slashCommandPayload) + .then(() => { + slackMock.slashCommands.calls.length; + slackMock.slashCommands.calls[0].params.text; + slackMock.slashCommands.calls[0].params.response_type; + }); + +// Web (OAuth Example) + +const botToken = 'xoxb-XXXXXXXXXXXX-TTTTTTTTTTTTTT'; +slackMock.web.addResponse({ + url: 'https://slack.com/api/oauth.access', + statusCode: 200, + body: { + access_token: 'xoxp-XXXXXXXX-XXXXXXXX-XXXXX', + scope: 'incoming-webhook,commands,bot', + team_name: 'mockTeam', + team_id: 'Tmock', + bot: { + bot_user_id: 'Bmock', + bot_access_token: botToken + } + } +}); + +slackMock.web.addResponse({ + url: 'https://slack.com/api/rtm.start', + statusCode: 200, + body: { + ok: true, + self: { + name: 'mockSelf', + id: 'Bmock' + }, + team: { + name: 'mockTeam', + id: 'Tmock' + } + } +}); diff --git a/types/slack-mock/tsconfig.json b/types/slack-mock/tsconfig.json new file mode 100644 index 0000000000..e012cc79b1 --- /dev/null +++ b/types/slack-mock/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", + "slack-mock-tests.ts" + ] +} \ No newline at end of file diff --git a/types/slack-mock/tslint.json b/types/slack-mock/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/slack-mock/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/slate-html-serializer/index.d.ts b/types/slate-html-serializer/index.d.ts index cee3041d69..a0bd15f186 100644 --- a/types/slate-html-serializer/index.d.ts +++ b/types/slate-html-serializer/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ianstormtaylor/slate // Definitions by: Brandon Shelton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { BlockProperties, ValueJSON, Value, Node, Mark, Leaf } from 'slate'; diff --git a/types/slate-react/index.d.ts b/types/slate-react/index.d.ts index 3ef179a14b..0bf5c255a9 100644 --- a/types/slate-react/index.d.ts +++ b/types/slate-react/index.d.ts @@ -6,7 +6,7 @@ // Patrick Sachs // Brandon Shelton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { Mark, Node, Block, Change, Schema, Value, Stack } from 'slate'; import * as Immutable from 'immutable'; import * as React from 'react'; diff --git a/types/snapsvg/test/2.ts b/types/snapsvg/test/2.ts index 5afcf36460..708dc6f2bf 100644 --- a/types/snapsvg/test/2.ts +++ b/types/snapsvg/test/2.ts @@ -102,12 +102,12 @@ function tester5() { } Snap.animate(sideLength, sideLength + 100, updater, 1500 /*ms*/); - setTimeout(500, () => { Snap.animate(sideLength + 100, + setTimeout(() => { Snap.animate(sideLength + 100, 0, updater, 100 /*ms*/, easer, - square.remove); }); + square.remove); }, 500); } function tester6() { diff --git a/types/spectacle/index.d.ts b/types/spectacle/index.d.ts index cabd6cf5a1..e00b5dd3c0 100644 --- a/types/spectacle/index.d.ts +++ b/types/spectacle/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/FormidableLabs/victory // Definitions by: Zachary Maybury // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/spectrum/index.d.ts b/types/spectrum/index.d.ts index bc94644a92..86b3077c04 100644 --- a/types/spectrum/index.d.ts +++ b/types/spectrum/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for spectrum 1.5.1 // Project: https://github.com/bgrins/spectrum/ // Definitions by: Mordechai Zuber +// Junyoung Clare Jang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -30,7 +31,7 @@ interface JQuery { /** * Gets the current value from the colorpicker. */ - spectrum(methodName: "get"): tinycolorInstance; + spectrum(methodName: "get"): tinycolor.Instance; /** * Sets the colorpickers value to update the original input. @@ -101,12 +102,12 @@ interface JQuery { /** * Called at the beginning of a drag event on either hue slider, alpha slider, or main color picker areas. */ - on(events: "dragstart.spectrum", handler: (eventObject: JQueryEventObject, color: tinycolorInstance) => any): JQuery; + on(events: "dragstart.spectrum", handler: (eventObject: JQueryEventObject, color: tinycolor.Instance) => any): JQuery; /** * Called at the end of a drag event on either hue slider, alpha slider, or main color picker areas. */ - on(events: "dragstop.spectrum", handler: (eventObject: JQueryEventObject, color: tinycolorInstance) => any): JQuery; + on(events: "dragstop.spectrum", handler: (eventObject: JQueryEventObject, color: tinycolor.Instance) => any): JQuery; } declare namespace Spectrum { @@ -263,18 +264,18 @@ declare namespace Spectrum { /** * Called as the original input changes. Only happens when the input is closed or the 'Choose' button is clicked. */ - change?: (color: tinycolorInstance) => void; + change?: (color: tinycolor.Instance) => void; /** * Called as the user moves around within the colorpicker. */ - move?: (color: tinycolorInstance) => void; + move?: (color: tinycolor.Instance) => void; /** * Called after the colorpicker is opened. This is ignored on a flat colorpicker. * Note, when any colorpicker on the page is shown it will hide any that are already open. */ - show?: (color: tinycolorInstance) => void; + show?: (color: tinycolor.Instance) => void; /** * Called after the colorpicker is hidden. @@ -282,12 +283,12 @@ declare namespace Spectrum { * Note, when any colorpicker on the page is shown it will hide any that are already open. * This event is ignored on a flat colorpicker. */ - hide?: (color: tinycolorInstance) => void; + hide?: (color: tinycolor.Instance) => void; /** * You can prevent the colorpicker from showing up if you return false in the beforeShow event. * This event is ignored on a flat colorpicker. */ - beforeShow?: (color: tinycolorInstance) => void; + beforeShow?: (color: tinycolor.Instance) => void; } } diff --git a/types/ssh2-sftp-client/index.d.ts b/types/ssh2-sftp-client/index.d.ts index a0133961d8..0e1555abaf 100644 --- a/types/ssh2-sftp-client/index.d.ts +++ b/types/ssh2-sftp-client/index.d.ts @@ -1,17 +1,19 @@ -// Type definitions for ssh2-sftp-client 2.0 +// Type definitions for ssh2-sftp-client 2.3 // Project: https://www.npmjs.com/package/ssh2-sftp-client -// Definitions by: igrayson , Ascari Andrea +// Definitions by: igrayson , Ascari Andrea , Kartik Malik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as ssh2 from 'ssh2'; - +import * as ssh2Stream from 'ssh2-streams'; export = sftp; declare class sftp { connect(options: ssh2.ConnectConfig): Promise; list(remoteFilePath: string): Promise; get(remoteFilePath: string, useCompression?: boolean, encoding?: string | null): Promise; + fastGet(remoteFilePath: string, localPath: string, options?: ssh2Stream.TransferOptions): Promise; put(input: string | Buffer | NodeJS.ReadableStream, remoteFilePath: string, useCompression?: boolean, encoding?: string): Promise; + fastPut(localPath: string, emoteFilePath: string, options?: ssh2Stream.TransferOptions): Promise; mkdir(remoteFilePath: string, recursive?: boolean): Promise; rmdir(remoteFilePath: string, recursive?: boolean): Promise; delete(remoteFilePath: string): Promise; diff --git a/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts b/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts index 67d2d35826..0b9c1a940c 100644 --- a/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts +++ b/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts @@ -15,10 +15,14 @@ client.get('/remote/path').then(stream => stream.read(0)); client.get('/remote/path', true, 'utf8').then(stream => stream.read(0)); client.get('/remote/path', true, null).then(stream => stream.read(0)); +client.fastGet('/remote/path', 'local/path').then(() => null); + client.put('/local/path', '/remote/path').then(() => null); client.put(new Buffer('content'), '/remote/path').then(() => null); client.put(fs.createReadStream('Hello World'), '/remote/path').then(() => null); +client.fastPut('/remote/path', 'local/path').then(() => null); + client.mkdir('/remote/path/dir', true).then(() => null); client.rmdir('/remote/path/dir', true).then(() => null); diff --git a/types/stellar-sdk/index.d.ts b/types/stellar-sdk/index.d.ts index d07309eae5..3f963ab18d 100644 --- a/types/stellar-sdk/index.d.ts +++ b/types/stellar-sdk/index.d.ts @@ -825,6 +825,7 @@ export class Transaction { fee: number; source: string; memo: Memo; + signatures: xdr.DecoratedSignature[]; } export class TransactionBuilder { @@ -862,9 +863,11 @@ export class Keypair { publicKey(): string; secret(): string; + rawPublicKey(): Buffer; rawSecretKey(): Buffer; canSign(): boolean; sign(data: Buffer): Buffer; + signatureHint(): xdr.SignatureHint; verify(data: Buffer, signature: Buffer): boolean; } @@ -876,4 +879,9 @@ export namespace xdr { class Asset extends XDRStruct { } class Memo extends XDRStruct { } class TransactionEnvelope extends XDRStruct { } + class DecoratedSignature extends XDRStruct { + constructor(keys: { hint: SignatureHint, signature: Signature }) + } + class SignatureHint { } + class Signature { } } diff --git a/types/storejs/index.d.ts b/types/store/index.d.ts similarity index 79% rename from types/storejs/index.d.ts rename to types/store/index.d.ts index f720d33617..8f46bb9f59 100644 --- a/types/storejs/index.d.ts +++ b/types/store/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for store.js 2.0 -// Project: https://github.com/marcuswestin/store.js/ +// Type definitions for store 2.0 +// Project: https://github.com/marcuswestin/store.js#readme // Definitions by: Vincent Bortone // harry0000 +// Roman Nuritdinov (Ky6uk) // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Cross-browser storage for all use cases, used across the web. @@ -28,6 +29,18 @@ declare const store: StoreJsAPI; declare module 'store' { export = store; } +declare module 'store/dist/store.legacy' { + export = store; +} +declare module 'store/dist/store.legacy.min' { + export = store; +} +declare module 'store/dist/store.modern' { + export = store; +} +declare module 'store/dist/store.modern.min' { + export = store; +} declare const engine: StoreJsEngine; declare module 'store/src/store-engine' { diff --git a/types/storejs/storejs-tests.ts b/types/store/store-tests.ts similarity index 98% rename from types/storejs/storejs-tests.ts rename to types/store/store-tests.ts index 9e631385f5..a992327908 100644 --- a/types/storejs/storejs-tests.ts +++ b/types/store/store-tests.ts @@ -1,4 +1,3 @@ -// Tests for storagejs.d.ts import * as store from 'store'; import * as engine from 'store/src/store-engine'; import * as allPlugin from 'store/plugins/all'; diff --git a/types/storejs/tsconfig.json b/types/store/tsconfig.json similarity index 94% rename from types/storejs/tsconfig.json rename to types/store/tsconfig.json index df8e4268e3..0a81987271 100644 --- a/types/storejs/tsconfig.json +++ b/types/store/tsconfig.json @@ -19,6 +19,6 @@ }, "files": [ "index.d.ts", - "storejs-tests.ts" + "store-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/interact.js/tslint.json b/types/store/tslint.json similarity index 100% rename from types/interact.js/tslint.json rename to types/store/tslint.json diff --git a/types/storejs/v1/index.d.ts b/types/store/v1/index.d.ts similarity index 100% rename from types/storejs/v1/index.d.ts rename to types/store/v1/index.d.ts diff --git a/types/storejs/v1/storejs-tests.ts b/types/store/v1/store-tests.ts similarity index 95% rename from types/storejs/v1/storejs-tests.ts rename to types/store/v1/store-tests.ts index fd0e0f25c3..8446cb011d 100644 --- a/types/storejs/v1/storejs-tests.ts +++ b/types/store/v1/store-tests.ts @@ -1,4 +1,3 @@ -// Tests for storagejs.d.ts import * as store from 'store'; // Store 'marcus' at 'username' diff --git a/types/storejs/v1/tsconfig.json b/types/store/v1/tsconfig.json similarity index 86% rename from types/storejs/v1/tsconfig.json rename to types/store/v1/tsconfig.json index 2d062255ed..6a2ff37411 100644 --- a/types/storejs/v1/tsconfig.json +++ b/types/store/v1/tsconfig.json @@ -15,8 +15,8 @@ ], "types": [], "paths": { - "storejs": [ - "storejs/v1" + "store": [ + "store/v1" ] }, "noEmit": true, @@ -24,6 +24,6 @@ }, "files": [ "index.d.ts", - "storejs-tests.ts" + "store-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/storejs/tslint.json b/types/store/v1/tslint.json similarity index 100% rename from types/storejs/tslint.json rename to types/store/v1/tslint.json diff --git a/types/storejs/v1/tslint.json b/types/storejs/v1/tslint.json deleted file mode 100644 index a41bf5d19a..0000000000 --- a/types/storejs/v1/tslint.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } -} diff --git a/types/storybook-addon-jsx/index.d.ts b/types/storybook-addon-jsx/index.d.ts index f29351ac68..80ec756d3a 100644 --- a/types/storybook-addon-jsx/index.d.ts +++ b/types/storybook-addon-jsx/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/storybooks/storybook // Definitions by: James Newell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import '@storybook/react'; import { ReactNode } from 'react'; diff --git a/types/storybook__addon-a11y/index.d.ts b/types/storybook__addon-a11y/index.d.ts index c29f546b6f..7e7ac3b89e 100644 --- a/types/storybook__addon-a11y/index.d.ts +++ b/types/storybook__addon-a11y/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/storybooks/storybook // Definitions by: HyunSeob // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { StoryDecorator } from '@storybook/react'; diff --git a/types/storybook__addon-actions/index.d.ts b/types/storybook__addon-actions/index.d.ts index 2d5cc73ef8..680777948c 100644 --- a/types/storybook__addon-actions/index.d.ts +++ b/types/storybook__addon-actions/index.d.ts @@ -1,11 +1,17 @@ -// Type definitions for @storybook/addon-actions 3.0 +// Type definitions for @storybook/addon-actions 3.4 // Project: https://github.com/storybooks/storybook -// Definitions by: Joscha Feth +// Definitions by: Joscha Feth , June // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 export type HandlerFunction = (...args: any[]) => undefined; export type DecoratorFunction = (args: any[]) => any[]; +export interface Options { + depth?: number; + clearOnStoryChange?: boolean; + limit?: number; +} -export function decorateAction(decorators: DecoratorFunction[]): (name: string) => HandlerFunction; +export function decorateAction(decorators: DecoratorFunction[]): (name: string, options?: Options) => HandlerFunction; +export function configureActions(options: Options): undefined; export function action(name: string): HandlerFunction; diff --git a/types/storybook__addon-actions/storybook__addon-actions-tests.tsx b/types/storybook__addon-actions/storybook__addon-actions-tests.tsx index b9c9bbba7f..2011694cb7 100644 --- a/types/storybook__addon-actions/storybook__addon-actions-tests.tsx +++ b/types/storybook__addon-actions/storybook__addon-actions-tests.tsx @@ -2,7 +2,11 @@ import * as React from 'react'; import { storiesOf } from '@storybook/react'; -import { action, decorateAction } from '@storybook/addon-actions'; +import { action, decorateAction, configureActions } from '@storybook/addon-actions'; + +configureActions({ + depth: 100 +}); const firstArgAction = decorateAction([ args => args.slice(0, 1) diff --git a/types/storybook__addon-backgrounds/index.d.ts b/types/storybook__addon-backgrounds/index.d.ts index c76a6d160e..68b4a3d18b 100644 --- a/types/storybook__addon-backgrounds/index.d.ts +++ b/types/storybook__addon-backgrounds/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/storybooks/storybook // Definitions by: HyunSeob // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import { StoryDecorator } from '@storybook/react'; diff --git a/types/storybook__addon-centered/index.d.ts b/types/storybook__addon-centered/index.d.ts index 023d01fa97..23c7a06d97 100644 --- a/types/storybook__addon-centered/index.d.ts +++ b/types/storybook__addon-centered/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/storybooks/storybook // Definitions by: kiyopikko // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; import { StoryDecorator } from "@storybook/react"; diff --git a/types/storybook__addon-info/index.d.ts b/types/storybook__addon-info/index.d.ts index c616933b8f..b460823f50 100644 --- a/types/storybook__addon-info/index.d.ts +++ b/types/storybook__addon-info/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for @storybook/addon-info 3.2 +// Type definitions for @storybook/addon-info 3.4 // Project: https://github.com/storybooks/storybook // Definitions by: Mark Kornblum // Mattias Wikstrom // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { RenderFunction } from '@storybook/react'; @@ -29,6 +29,6 @@ export interface Options { maxPropStringLength?: number; } -export function withInfo(textOrOptions: string | Options): (storyFn: RenderFunction) => (context?: object) => React.ReactElement; +export function withInfo(textOrOptions?: string | Options): (storyFn: RenderFunction) => (context?: object) => React.ReactElement; export function setDefaults(newDefaults: Options): Options; diff --git a/types/storybook__addon-info/storybook__addon-info-tests.tsx b/types/storybook__addon-info/storybook__addon-info-tests.tsx index b51a48c4cc..46fd799314 100644 --- a/types/storybook__addon-info/storybook__addon-info-tests.tsx +++ b/types/storybook__addon-info/storybook__addon-info-tests.tsx @@ -12,6 +12,11 @@ setDefaults({ }); storiesOf('Component', module) + .add('no info', + withInfo()(() => + Click the "?" mark at top-right to view the info. + ) + ) .add('simple info', withInfo('doc string about my component')(() => Click the "?" mark at top-right to view the info. diff --git a/types/storybook__addon-jest/index.d.ts b/types/storybook__addon-jest/index.d.ts new file mode 100644 index 0000000000..a84b2588cd --- /dev/null +++ b/types/storybook__addon-jest/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for @storybook/addon-jest 3.4 +// Project: https://github.com/storybooks/storybook +// Definitions by: Matt Oliver +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { StoryDecorator } from '@storybook/react'; + +export type SpecsFunction = (...specs: string[]) => StoryDecorator; + +export interface Options { + results: object; + filesExt?: string; +} + +export function withTests(options: Options): SpecsFunction; diff --git a/types/storybook__addon-jest/storybook__addon-jest-tests.tsx b/types/storybook__addon-jest/storybook__addon-jest-tests.tsx new file mode 100644 index 0000000000..50fe58a12c --- /dev/null +++ b/types/storybook__addon-jest/storybook__addon-jest-tests.tsx @@ -0,0 +1,53 @@ +/// + +import * as React from 'react'; +import { storiesOf } from '@storybook/react'; +import { withTests } from '@storybook/addon-jest'; + +const testDecorator = withTests({ + results: { + numFailedTestSuites: 0, + numFailedTests: 0, + numPassedTestSuites: 1, + numPassedTests: 1, + numPendingTestSuites: 0, + numPendingTests: 0, + numRuntimeErrorTestSuites: 0, + numTotalTestSuites: 1, + numTotalTests: 1, + startTime: 1533301378256, + success: true, + testResults: [ + { + assertionResults: [ + { + ancestorTitles: [ + 'TestComponent', + 'Basic' + ], + failureMessages: [], + fullName: 'TestComponent Basic should render without error', + location: null, + status: 'passed', + title: 'should render without error', + } + ], + endTime: 1533301381197, + message: '', + name: '/path/to/tests', + startTime: 1533301379074, + status: 'passed', + summary: '' + } + ], + wasInterrupted: false, + }, +}); + +storiesOf('Test', module) + .addDecorator(testDecorator('test')) + .add('test', () => ( + + )); diff --git a/types/storybook__addon-jest/tsconfig.json b/types/storybook__addon-jest/tsconfig.json new file mode 100644 index 0000000000..637b2b6bc8 --- /dev/null +++ b/types/storybook__addon-jest/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "paths": { + "@storybook/addon-jest": [ + "storybook__addon-jest" + ], + "@storybook/react": [ + "storybook__react" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "storybook__addon-jest-tests.tsx" + ] +} diff --git a/types/storybook__addon-jest/tslint.json b/types/storybook__addon-jest/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/storybook__addon-jest/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/storybook__addon-knobs/index.d.ts b/types/storybook__addon-knobs/index.d.ts index 3c9bbe0fc4..8c3ddc35f8 100644 --- a/types/storybook__addon-knobs/index.d.ts +++ b/types/storybook__addon-knobs/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for @storybook/addon-knobs 3.3 +// Type definitions for @storybook/addon-knobs 3.4 // Project: https://github.com/storybooks/storybook // Definitions by: Joscha Feth // Martynas Kadisa +// A.MacLeay // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { RenderFunction } from '@storybook/react'; @@ -49,11 +50,14 @@ export function object(name: string, value: T, groupId?: string): T; export type SelectValue = string | number; export function select(name: string, options: { [s: string]: string }, value: T, groupId?: string): T; export function select(name: string, options: { [s: number]: string }, value: T, groupId?: string): T; -export function select(name: string, options: T[], value: T, groupId?: string): T; +export function select(name: string, options: ReadonlyArray, value: T, groupId?: string): T; + +export function selectV2(name: string, options: { [s: string]: T | T[] }, value: T | T[], groupId?: string): T; +export function selectV2(name: string, options: T[], value: T, groupId?: string): T; export function date(name: string, value?: Date, groupId?: string): Date; -export function array(name: string, value: T[], separator?: string, groupId?: string): T[]; +export function array(name: string, value: ReadonlyArray, separator?: string, groupId?: string): T[]; export function button(name: string, handler: () => any, groupId?: string): void; diff --git a/types/storybook__addon-knobs/storybook__addon-knobs-tests.tsx b/types/storybook__addon-knobs/storybook__addon-knobs-tests.tsx index c35268ac6b..85155fc5c7 100644 --- a/types/storybook__addon-knobs/storybook__addon-knobs-tests.tsx +++ b/types/storybook__addon-knobs/storybook__addon-knobs-tests.tsx @@ -14,6 +14,7 @@ import { array, button, knob, + selectV2, } from '@storybook/addon-knobs'; enum SomeEnum { @@ -49,13 +50,16 @@ stories.add('with all knobs', () => { type X = 'a' | 'b'; - const genericSelect: X = select('Some generic select', { a: 'type a', b: 'type b'}, 'b'); + const genericSelect: X = select('Some generic select', { a: 'type a', b: 'type b' }, 'b'); const enumSelectOptions: { [s: number]: string } = {}; enumSelectOptions[SomeEnum.Type1] = "Type 1"; enumSelectOptions[SomeEnum.Type2] = "Type 2"; const genericSelect2: SomeEnum = select('Some generic select', enumSelectOptions, SomeEnum.Type1); + const genericSelectV2: X = selectV2('Some generic select', { 'type a': 'a', 'type b': 'b' }, 'b'); + const genericSelectV2Enum: SomeEnum = selectV2('Some generic select v2', { 'type a': SomeEnum.Type1, 'type b': SomeEnum.Type2 }, SomeEnum.Type2); + const genericArray: string[] = array('Some generic array', ['red', 'green', 'blue']); const genericKnob: X = knob('Some generic knob', { value: 'a', type: 'text' }); @@ -90,6 +94,14 @@ stories.add('dynamic knobs', () => { ); }); +const readonlyOptionsArray: ReadonlyArray = ['hi']; +select('With readonly array', readonlyOptionsArray, readonlyOptionsArray[0]); + +const genericArray = array('With regular array', ['hi', 'there']); + +const userInputArray = array('With readonly array', readonlyOptionsArray); +userInputArray.push('Make sure that the output is still mutable although the input need not be!'); + // groups const groupId = 'GROUP-ID1'; diff --git a/types/storybook__addon-links/index.d.ts b/types/storybook__addon-links/index.d.ts index 99a9edc492..4d25a7150e 100644 --- a/types/storybook__addon-links/index.d.ts +++ b/types/storybook__addon-links/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Joscha Feth , // Jesse Pinho // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; diff --git a/types/storybook__addon-notes/index.d.ts b/types/storybook__addon-notes/index.d.ts index 1332cfcf7e..f212cbce63 100644 --- a/types/storybook__addon-notes/index.d.ts +++ b/types/storybook__addon-notes/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Joscha Feth // A.MacLeay // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from 'react'; import { RenderFunction } from '@storybook/react'; diff --git a/types/storybook__react-native/index.d.ts b/types/storybook__react-native/index.d.ts index 4bcd20ec30..1a0d0bee48 100644 --- a/types/storybook__react-native/index.d.ts +++ b/types/storybook__react-native/index.d.ts @@ -4,7 +4,7 @@ // Anton Izmailov // Alec Hill // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as Storybook from '@storybook/react'; diff --git a/types/storybook__react/index.d.ts b/types/storybook__react/index.d.ts index 853295de25..3aa3445f61 100644 --- a/types/storybook__react/index.d.ts +++ b/types/storybook__react/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Joscha Feth // Anton Izmailov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/stream-chain/stream-chain-tests.ts b/types/stream-chain/stream-chain-tests.ts index 282b88c7da..43d4f3d68b 100644 --- a/types/stream-chain/stream-chain-tests.ts +++ b/types/stream-chain/stream-chain-tests.ts @@ -142,7 +142,7 @@ const streamToArray = (array: number[]): Writable => // include Writable const out1: number[] = []; - const chain = new Chain([(x: number) => 2 * x], streamToArray(out1)); + const chain = new Chain([(x: number) => 2 * x, streamToArray(out1)]); const out2: number[] = []; streamFromArray([1, 2, 3]).pipe(chain); @@ -153,7 +153,7 @@ const streamToArray = (array: number[]): Writable => // include Readable and Writable const out1: number[] = []; - const chain = new Chain([streamFromArray([1, 2, 3]), (x: number) => 2 * x], streamToArray(out1)); + const chain = new Chain([streamFromArray([1, 2, 3]), (x: number) => 2 * x, streamToArray(out1)]); const out2: number[] = []; chain.on('data', value => out2.push(+value)); diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index bf359012d1..cc944284e0 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -189,7 +189,7 @@ declare namespace Stripe { * account holder to setup a username and password, and handle all account * management directly with them. Possible values are custom and standard. */ - type: 'custom' | 'standard'; + type: "custom" | "standard"; } interface IAccountShared { @@ -1470,7 +1470,7 @@ declare namespace Stripe { source?: sources.ISourceCreationOptionsExtended; } - interface ICustomerListOptions extends IListOptionsCreated { + interface ICustomerListOptions extends IListOptionsCreated { /** * A filter on the list based on the customer’s email field. The value must be a string. */ @@ -4347,7 +4347,7 @@ declare namespace Stripe { /** * Value is 'card' */ - object: 'card'; + object: "card"; /** * The card number @@ -4679,6 +4679,12 @@ declare namespace Stripe { */ trial_period_days?: number; + /** + * Indicates if a plan’s trial_period_days should be applied to the subscription. Setting trial_end per subscription is preferred, + * and this defaults to false. Setting this flag to true together with trial_end is not allowed. + */ + trial_from_plan?: boolean; + /** * List of subscription items, each with an attached plan. */ @@ -5033,6 +5039,11 @@ declare namespace Stripe { * For other types of refunds, it can be pending, succeeded, failed, or canceled. */ status: "pending" | "succeeded" | "failed" | "canceled"; + + /** + * If the refund failed, the reason for refund failure if known. + */ + failure_reason?: "lost_or_stolen_card" | "expired_or_canceled_card" | "unknown"; } interface IRefundCreationOptions extends IDataOptionsWithMetadata { diff --git a/types/stripe/stripe-tests.ts b/types/stripe/stripe-tests.ts index ef30b621b2..4e538abddb 100644 --- a/types/stripe/stripe-tests.ts +++ b/types/stripe/stripe-tests.ts @@ -59,6 +59,7 @@ stripe.charges.create({ // asynchronously called charge.refunds.create().then(function (refund) { + const reason = refund.failure_reason; // asynchronously called }); charge.refunds.create({ amount: 100 }).then(function (refund) { diff --git a/types/styled-jsx/index.d.ts b/types/styled-jsx/index.d.ts index 5e15388837..35f0112b6f 100644 --- a/types/styled-jsx/index.d.ts +++ b/types/styled-jsx/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/zeit/styled-jsx // Definitions by: R1ZZU // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import "react"; diff --git a/types/styled-system/dist/mixed.d.ts b/types/styled-system/dist/mixed.d.ts new file mode 100644 index 0000000000..25f115aa55 --- /dev/null +++ b/types/styled-system/dist/mixed.d.ts @@ -0,0 +1,7 @@ +export interface MixedProps { + key?: any; + // Defaults to "variant" + prop?: string; +} + +export function mixed(...args: any[]): any; diff --git a/types/styled-system/dist/space.d.ts b/types/styled-system/dist/space.d.ts new file mode 100644 index 0000000000..b3996a559c --- /dev/null +++ b/types/styled-system/dist/space.d.ts @@ -0,0 +1,23 @@ +export type ResponsiveValue = T | Array; + +export type SpaceValue = number | string; +export type ResponsiveSpaceValue = ResponsiveValue; + +export interface SpaceProps { + m?: ResponsiveSpaceValue; + mt?: ResponsiveSpaceValue; + mr?: ResponsiveSpaceValue; + mb?: ResponsiveSpaceValue; + ml?: ResponsiveSpaceValue; + mx?: ResponsiveSpaceValue; + my?: ResponsiveSpaceValue; + p?: ResponsiveSpaceValue; + pt?: ResponsiveSpaceValue; + pr?: ResponsiveSpaceValue; + pb?: ResponsiveSpaceValue; + pl?: ResponsiveSpaceValue; + px?: ResponsiveSpaceValue; + py?: ResponsiveSpaceValue; +} + +export function space(...args: any[]): any; diff --git a/types/styled-system/dist/styles.d.ts b/types/styled-system/dist/styles.d.ts new file mode 100644 index 0000000000..57f470e96a --- /dev/null +++ b/types/styled-system/dist/styles.d.ts @@ -0,0 +1,687 @@ +import { ResponsiveValue, ResponsiveSpaceValue, SpaceValue } from './space'; + +export * from './space'; + +export type GlobalStyleValues = "inherit" | "initial" | "unset"; + +export interface BaseTheme { + breakpoints?: number[]; + space?: number[]; + fontSizes?: number[]; + colors?: { + [name: string]: string; + }; +} + +/** + * Font Size + */ + +export type FontSizeValue = number | string; +export type ResponsiveFontSizeValue = ResponsiveValue; + +export interface FontSizeProps { + fontSize?: ResponsiveFontSizeValue; +} + +export function fontSize(...args: any[]): any; + +/** + * Color + */ +export type ColorValue = string; +export type ResponsiveColorValue = ResponsiveValue; + +export interface TextColorProps { + color?: ResponsiveColorValue; +} + +export function textColor(...args: any[]): any; + +export interface BgColorProps { + bg?: ResponsiveColorValue; +} + +export function bgColor(...args: any[]): any; + +export interface ColorProps extends TextColorProps, BgColorProps {} + +export function color(...args: any[]): any; + +/** + * Typography + */ +export type TypographyValue = string; +export type ResponsiveTypographyValue = ResponsiveValue; + +export interface FontFamilyProps { + fontFamily?: ResponsiveTypographyValue; +} +export function fontFamily(...args: any[]): any; + +export type TextAlignValue = + | "left" + | "right" + | "center" + | "justify" + | "justify-all" + | "start" + | "end" + | "match-parent"; +export type ResponsiveTextAlignValue = ResponsiveValue; + +export interface TextAlignProps { + textAlign?: ResponsiveTextAlignValue; +} + +export function textAlign(...args: any[]): any; + +export type LineHeightValue = number | string; +export type ResponsiveLineHeightValue = ResponsiveValue; +export interface LineHeightProps { + lineHeight?: ResponsiveLineHeightValue; +} +export function lineHeight(...args: any[]): any; + +export type FontWeightValue = + | GlobalStyleValues + | "normal" + | "bold" + | "lighter" + | "bolder" + | number; +export type ResponsiveFontWeightValue = ResponsiveValue; + +export interface FontWeightProps { + fontWeight?: ResponsiveFontWeightValue; +} + +export function fontWeight(...args: any[]): any; + +export type LetterSpacingValue = number | string; +export type ResponsiveLetterSpacingValue = ResponsiveValue; +export interface LetterSpacingProps { + letterSpacing?: ResponsiveLetterSpacingValue; +} +export function letterSpacing(...args: any[]): any; + +/** + * Layout + */ + +export type DisplayValue = + | "inline" + | "block" + | "contents" + | "flex" + | "grid" + | "inline-block"; +export type ResponsiveDisplayValue = ResponsiveValue; +export interface DisplayProps { + display?: ResponsiveDisplayValue; +} + +export function display(...args: any[]): any; + +export interface MaxWidthProps { + maxWidth?: ResponsiveSpaceValue; +} + +export function maxWidth(...args: any[]): any; + +export interface MinWidthProps { + minWidth?: ResponsiveSpaceValue; +} + +export function minWidth(...args: any[]): any; + +export interface WidthProps { + width?: ResponsiveSpaceValue; +} + +export function width(...args: any[]): any; + +export interface MaxHeightProps { + maxHeight?: ResponsiveSpaceValue; +} + +export function maxHeight(...args: any[]): any; + +export interface MinHeightProps { + minHeight?: ResponsiveSpaceValue; +} + +export function minHeight(...args: any[]): any; + +export interface HeightProps { + height?: ResponsiveSpaceValue; +} + +export function height(...args: any[]): any; + +export interface SizeWidthProps { + size?: ResponsiveSpaceValue; +} + +export function sizeWidth(...args: any[]): any; + +export interface SizeHeightProps { + size?: ResponsiveSpaceValue; +} + +export function sizeHeight(...args: any[]): any; + +export interface SizeProps extends SizeHeightProps, SizeWidthProps {} + +export function size(...args: any[]): any; + +export type RatioValue = SpaceValue; +export type ResponsiveRatioValue = ResponsiveValue; + +export interface RatioProps { + ratio?: ResponsiveRatioValue; +} + +export function ratio(...args: any[]): any; + +export type VerticleAlignValue = + | "baseline" + | "sub" + | "super" + | "text-top" + | "text-bottom" + | "middle" + | "top" + | "bottom" + | string + | number; +export type ResponsiveVerticleAlignValue = ResponsiveValue; + +export interface VerticleAlignProps { + verticalAlign?: ResponsiveVerticleAlignValue; +} + +export function verticleAlign(...args: any[]): any; + +/** + * Flexbox + */ + +export type AlignItemsValue = + | "normal" + | "stretch" + | "center" + | "start" + | "end" + | "flex-start" + | "flex-end" + | "self-start" + | "self-end" + | "left" + | "right" + | "baseline" + | "first baseline" + | "last baseline" + | "safe center" + | "unsafe center"; +export type ResponsiveAlignItemsValue = ResponsiveValue; + +export interface AlignItemsProps { + alignItems?: ResponsiveAlignItemsValue; +} + +export function alignItems(...args: any[]): any; + +export type AlignContentValue = + | GlobalStyleValues + | "center" + | "start" + | "end" + | "flex-start" + | "flex-end" + | "normal" + | "baseline" + | "first baseline" + | "last baseline" + | "space-between" + | "space-around" + | "space-evenly" + | "stretch" + | "safe center" + | "unsafe center"; +export type ResponsiveAlignContentValue = ResponsiveValue; + +export interface AlignContentProps { + alignContent?: ResponsiveAlignContentValue; +} + +export function alignContent(...args: any[]): any; + +export type JustifyContentValue = + | "center" + | "start" + | "end" + | "flex-start" + | "flex-end" + | "left" + | "right" + | "baseline" + | "first baseline" + | "last baseline" + | "space-between" + | "space-around" + | "space-evenly" + | "stretch" + | "safe center" + | "unsafe center"; +export type ResponsiveJustifyContentValue = ResponsiveValue< + JustifyContentValue +>; + +export interface JustifyContentProps { + justifyContent?: ResponsiveJustifyContentValue; +} + +export function justifyContent(...args: any[]): any; + +export type FlexWrapValue = true | "nowrap" | "wrap" | "wrap-reverse"; +export type ResponsiveFlexWrapValue = ResponsiveValue; + +export interface FlexWrapProps { + flexWrap?: ResponsiveFlexWrapValue; +} + +export function flexWrap(...args: any[]): any; + +export type FlexBasisValue = + | GlobalStyleValues + | "auto" + | "fill" + | "max-content" + | "min-content" + | "fit-content" + | "content"; +export type ResponsiveFlexBasisValue = ResponsiveValue; + +export interface FlexBasisProps { + // TODO: The FlexBasisValue currently really only exists for documentation + // purposes, because flex-basis also accepts `Nem` and `Npx` strings. + // Not sure there’s a way to still have the union values show up as + // auto-completion results. + flexBasis?: ResponsiveFlexBasisValue | string; +} + +export function flexBasis(...args: any[]): any; + +export type FlexDirectionValue = + | GlobalStyleValues + | "row" + | "row-reverse" + | "column" + | "column-reverse"; + +export type ResponsiveFlexDirectionValue = ResponsiveValue; + +export interface FlexDirectionProps { + flexDirection?: ResponsiveFlexDirectionValue; +} + +export function flexDirection(...args: any[]): any; + +export type FlexValue = number | string; +export type ResponsiveFlexValue = ResponsiveValue; + +export interface FlexProps { + flex?: ResponsiveFlexValue; +} + +export function flex(...args: any[]): any; + +export type JustifySelfValue = + | GlobalStyleValues + | "auto" + | "normal" + | "stretch" + | "center" + | "start" + | "end" + | "flex-start" + | "flex-end" + | "self-start" + | "self-end" + | "left" + | "right" + | "baseline" + | "first baseline" + | "last baseline" + | "safe center" + | "unsafe center"; + +export type ResponsiveJustifySelfValue = ResponsiveValue; + +export interface JustifySelfProps { + justifySelf?: ResponsiveJustifySelfValue; +} + +export function justifySelf(...args: any[]): any; + +export type AlignSelfValue = + | "auto" + | "normal" + | "center" + | "start" + | "end" + | "self-start" + | "self-end" + | "flex-start" + | "flex-end" + | "left" + | "right" + | "baseline" + | "first baseline" + | "last baseline" + | "stretch" + | "safe center" + | "unsafe center"; +export type ResponsiveAlignSelfValue = ResponsiveValue; + +export interface AlignSelfProps { + alignSelf?: ResponsiveAlignSelfValue; +} + +export function alignSelf(...args: any[]): any; + +export type OrderValue = GlobalStyleValues | number; +export type ResponsiveOrderValue = ResponsiveValue; + +export interface OrderProps { + order?: ResponsiveOrderValue; +} + +export function order(...args: any[]): any; + +/** + * Grid Layout + */ + +export type GridGapValue = number | string; +export type ResponsiveGridGapValue = ResponsiveValue; + +export interface GridGapProps { + gridGap?: ResponsiveGridGapValue; +} + +export function gridGap(...args: any[]): any; + +export interface GridColumnGapProps { + gridColumnGap?: ResponsiveGridGapValue; +} + +export function gridColumnGap(...args: any[]): any; + +export interface GridRowGapProps { + gridRowGap?: ResponsiveGridGapValue; +} + +export function gridRowGap(...args: any[]): any; + +export type GridCellValue = string; +export type ResponsiveGridCellValue = ResponsiveValue; + +export interface GridColumnProps { + gridColumn?: ResponsiveGridCellValue; +} + +export function gridColumn(...args: any[]): any; + +export interface GridRowProps { + gridRow?: ResponsiveGridCellValue; +} + +export function gridRow(...args: any[]): any; + +export type GridAutoValue = string; +export type ResponsiveGridAutoValue = ResponsiveValue; + +export interface GridAutoFlowProps { + gridAutoFlow?: ResponsiveGridAutoValue; +} + +export function gridAutoFlow(...args: any[]): any; + +export interface GridAutoColumnsProps { + gridAutoColumns?: ResponsiveGridAutoValue; +} + +export function gridAutoColumns(...args: any[]): any; + +export interface GridAutoRowsProps { + gridAutoRows?: ResponsiveGridAutoValue; +} + +export function gridAutoRows(...args: any[]): any; + +export type GridTemplateValue = string; +export type ResponsiveGridTemplateValue = ResponsiveValue; + +export interface GridTemplatesColumnsProps { + gridTemplateColumns?: ResponsiveGridTemplateValue; +} + +export function gridTemplateColumns(...args: any[]): any; + +export interface GridTemplatesRowsProps { + gridTemplateRows?: ResponsiveGridTemplateValue; +} + +export function gridTemplateRows(...args: any[]): any; + +/** + * Borders + */ + +export type BorderValue = string | number; +export type ResponsiveBorderValue = ResponsiveValue; + +export interface BorderProps { + border?: ResponsiveBorderValue; +} + +export function border(...args: any[]): any; + +export interface BorderTopProps { + borderTop?: ResponsiveBorderValue; +} + +export function borderTop(...args: any[]): any; + +export interface BorderRightProps { + borderRight?: ResponsiveBorderValue; +} + +export function borderRight(...args: any[]): any; + +export interface BorderBottomProps { + borderBottom?: ResponsiveBorderValue; +} + +export function borderBottom(...args: any[]): any; + +export interface BorderLeftProps { + borderLeft?: ResponsiveBorderValue; +} + +export function borderLeft(...args: any[]): any; + +export interface BordersProps extends BorderTopProps, BorderRightProps, BorderBottomProps, BorderLeftProps {} + +export function borders(...args: any[]): any; + +export type BorderColorValue = string; +export type ResponsiveBorderColorValue = ResponsiveValue; + +export interface BorderColorProps { + borderColor?: ResponsiveBorderColorValue; +} + +export function borderColor(...args: any[]): any; + +export type BorderRadiusValue = string | number; +export type ResponsiveBorderRadiusValue = ResponsiveValue; + +export interface BorderRadiusProps { + borderRadius?: ResponsiveBorderRadiusValue; +} + +export function borderRadius(...args: any[]): any; + +export type BoxShadowValue = string | number; +export type ResponsiveBoxShadowValue = ResponsiveValue; + +export interface BoxShadowProps { + boxShadow?: ResponsiveBoxShadowValue; +} + +export function boxShadow(...arg: any[]): any; + +export type OpacityValue = string | number; +export type ResponsiveOpacityValue = ResponsiveValue; + +export interface OpacityProps { + opacity?: ResponsiveOpacityValue; +} + +export function opacity(...arg: any[]): any; + +/** + * Background + */ + +export type BackgroundValue = string; +export type ResponsiveBackgroundValue = ResponsiveValue; + +export interface BackgroundProps { + background?: ResponsiveBackgroundValue; +} + +export function background(...args: any[]): any; + +export type BackgroundImageValue = string; +export type ResponsiveBackgroundImageValue = ResponsiveValue; + +export interface BackgroundImageProps { + backgroundImage?: ResponsiveBackgroundImageValue; +} + +export function backgroundImage(...args: any[]): any; + +export type BackgroundSizeValue = string; +export type ResponsiveBackgroundSizeValue = ResponsiveValue; + +export interface BackgroundSizeProps { + backgroundSize?: ResponsiveBackgroundSizeValue; +} + +export function backgroundSize(...args: any[]): any; + +export type BackgroundPositionValue = string; +export type ResponsiveBackgroundPositionValue = ResponsiveValue; + +export interface BackgroundPositionProps { + backgroundPosition?: ResponsiveBackgroundPositionValue; +} + +export function backgroundPosition(...args: any[]): any; + +export type BackgroundRepeatValue = string; +export type ResponsiveBackgroundRepeatValue = ResponsiveValue; + +export interface BackgroundRepeatProps { + backgroundRepeat?: ResponsiveBackgroundRepeatValue; +} + +export function backgroundRepeat(...args: any[]): any; + +/** + * Position + */ + +export type PositionValue = + | "static" + | "relative" + | "absolute" + | "sticky" + | "fixed"; +export type ResponsivePositionValue = ResponsiveValue; + +export interface PositionProps { + position?: ResponsivePositionValue; +} + +export function position(...args: any[]): any; + +export type ZIndexValue = GlobalStyleValues | "auto" | number; +export type ResponsiveZIndexValue = ResponsiveValue; + +export interface ZIndexProps { + zIndex?: ZIndexValue; +} + +export function zIndex(...args: any[]): any; + +export type TopValue = string | number; +export type ResponsiveTopValue = ResponsiveValue; + +export interface TopProps { + top?: ResponsiveTopValue; +} + +export function top(...args: any[]): any; + +export type RightValue = string | number; +export type ResponsiveRightValue = ResponsiveValue; + +export interface RightProps { + right?: ResponsiveRightValue; +} + +export function right(...args: any[]): any; + +export type BottomValue = string | number; +export type ResponsiveBottomValue = ResponsiveValue; + +export interface BottomProps { + bottom?: ResponsiveBottomValue; +} + +export function bottom(...args: any[]): any; + +export type LeftValue = string | number; +export type ResponsiveLeftValue = ResponsiveValue; + +export interface LeftProps { + left?: ResponsiveLeftValue; +} + +export function left(...args: any[]): any; + +export type Variant = string; +export type ResponsiveVariant = ResponsiveValue; + +export interface TextStyleProps { + textStyle?: ResponsiveVariant; +} + +export function textStyle(...args: any[]): any; + +export interface ColorStyleProps { + colors?: ResponsiveVariant; +} + +export function colorStyle(...args: any[]): any; + +export interface ButtonStyleProps { + variant?: ResponsiveVariant; +} + +export function buttonStyle(...args: any[]): any; diff --git a/types/styled-system/dist/util.d.ts b/types/styled-system/dist/util.d.ts new file mode 100644 index 0000000000..f91b2b6620 --- /dev/null +++ b/types/styled-system/dist/util.d.ts @@ -0,0 +1,26 @@ +export const defaultBreakpoints: string[]; +export function is(n: any): boolean; +export function num(n: any): boolean; +export function px(n: any): string; + +export function get(obj: any, ...paths: Array): any; + +export function themeGet(keys: string, fallback?: string): any; +export function cloneFunc(fn: (...args: any[]) => any): (...args: any[]) => any; + +export function merge(a: any, b: any): any; + +export function compose(...funcs: ((...args: any[]) => any)[]): (...args: any[]) => any; + +export function createMediaQuery(n: string): string; + +export interface LowLevelStylefunctionArguments { + prop: string; + cssProperty?: string; + key?: string; + getter?: () => any; + transformValue?: () => any; + scale?: Array; +} + +export function style(args: LowLevelStylefunctionArguments): any; diff --git a/types/styled-system/dist/variant.d.ts b/types/styled-system/dist/variant.d.ts new file mode 100644 index 0000000000..8a3f8b15ec --- /dev/null +++ b/types/styled-system/dist/variant.d.ts @@ -0,0 +1,7 @@ +export interface VariantArgs { + key?: string; + // Defaults to "variant" + prop?: string; +} + +export function variant(props: VariantArgs): (...args: any[]) => any; diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index d99382e5fd..d9c386242c 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for styled-system 2.3 +// Type definitions for styled-system 3.0 // Project: https://github.com/jxnblk/styled-system#readme // Definitions by: Marshall Bowers // Ben McCormick @@ -6,674 +6,20 @@ // Christopher Pappas // Eloy Durán // Matthieu Vachon +// Adam Lavin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 -/** - * Core - */ +import * as util from './dist/util'; -export type GlobalStyleValues = "inherit" | "initial" | "unset"; +export { util }; +export { + style, + themeGet, + merge, + compose, +} from './dist/util'; -export interface BaseTheme { - breakpoints?: number[]; - space?: number[]; - fontSizes?: number[]; - colors?: { - [name: string]: string; - }; -} - -/** - * Space - */ - -export type ResponsiveValue = T | Array; - -export type SpaceValue = number | string; -export type ResponsiveSpaceValue = ResponsiveValue; - -export interface SpaceProps { - m?: ResponsiveSpaceValue; - mt?: ResponsiveSpaceValue; - mr?: ResponsiveSpaceValue; - mb?: ResponsiveSpaceValue; - ml?: ResponsiveSpaceValue; - mx?: ResponsiveSpaceValue; - my?: ResponsiveSpaceValue; - p?: ResponsiveSpaceValue; - pt?: ResponsiveSpaceValue; - pr?: ResponsiveSpaceValue; - pb?: ResponsiveSpaceValue; - pl?: ResponsiveSpaceValue; - px?: ResponsiveSpaceValue; - py?: ResponsiveSpaceValue; -} - -export function space(...args: any[]): any; - -/** - * Width - */ - -export type WidthValue = number | string; -export type ResponsiveWidthValue = ResponsiveValue; - -export interface WidthProps { - width?: ResponsiveWidthValue; -} - -export interface MinWidthProps { - minWidth?: ResponsiveWidthValue; -} - -export interface MaxWidthProps { - maxWidth?: ResponsiveWidthValue; -} - -export function width(...args: any[]): any; -export function minWidth(...args: any[]): any; -export function maxWidth(...args: any[]): any; - -/** - * Height - */ - -export type HeightValue = number | string; -export type ResponsiveHeightValue = ResponsiveValue; - -export interface HeightProps { - height?: ResponsiveHeightValue; -} - -export interface MinHeightProps { - minHeight?: ResponsiveHeightValue; -} - -export interface MaxHeightProps { - maxHeight?: ResponsiveHeightValue; -} - -export function height(...args: any[]): any; -export function minHeight(...args: any[]): any; -export function maxHeight(...args: any[]): any; - -/** - * Font Size - */ - -export type FontSizeValue = number | string; -export type ResponsiveFontSizeValue = ResponsiveValue; - -export interface FontSizeProps { - fontSize?: ResponsiveFontSizeValue; -} - -export function fontSize(...args: any[]): any; - -/** - * Color - */ -export type ColorValue = string; -export type ResponsiveColorValue = ResponsiveValue; - -export interface ColorProps { - color?: ResponsiveColorValue; -} - -export function color(...args: any[]): any; - -/** - * Typography - */ -export interface FontFamilyProps { - fontFamily?: string; -} -export function fontFamily(...args: any[]): any; - -export type TextAlignValue = - | "left" - | "right" - | "center" - | "justify" - | "justify-all" - | "start" - | "end" - | "match-parent"; -export type ResponsiveTextAlignValue = ResponsiveValue; - -export interface TextAlignProps { - textAlign?: ResponsiveTextAlignValue; -} - -export function textAlign(...args: any[]): any; - -export type LineHeightValue = number | string; -export type ResponsiveLineHeightValue = ResponsiveValue; -export interface LineHeightProps { - lineHeight?: ResponsiveLineHeightValue; -} -export function lineHeight(...args: any[]): any; - -export type FontWeightValue = - | GlobalStyleValues - | "normal" - | "bold" - | "lighter" - | "bolder" - | number; - -export interface FontWeightProps { - fontWeight?: FontWeightValue; -} - -export function fontWeight(...args: any[]): any; - -export type LetterSpacingValue = number | string; -export type ResponsiveLetterSpacingValue = ResponsiveValue; -export interface LetterSpacingProps { - letterSpacing?: ResponsiveLetterSpacingValue; -} -export function letterSpacing(...args: any[]): any; - -/** - * Layout - */ - -export type DisplayValue = - | "inline" - | "block" - | "contents" - | "flex" - | "grid" - | "inline-block"; -export type ResponsiveDisplayValue = ResponsiveValue; -export interface DisplayProps { - display?: ResponsiveDisplayValue; -} - -export function display(...args: any[]): any; - -export interface SizeProps { - size?: ResponsiveWidthValue | ResponsiveHeightValue; -} - -export function size(...args: any[]): any; - -export type RatioValue = SpaceValue; - -export interface RatioProps { - ratio?: RatioValue; -} - -export function ratio(...args: any[]): any; - -/** - * Flexbox - */ - -export type AlignItemsValue = - | "normal" - | "stretch" - | "center" - | "start" - | "end" - | "flex-start" - | "flex-end" - | "self-start" - | "self-end" - | "left" - | "right" - | "baseline" - | "first baseline" - | "last baseline" - | "safe center" - | "unsafe center"; -export type ResponsiveAlignItemsValue = ResponsiveValue; - -export interface AlignItemsProps { - align?: ResponsiveAlignItemsValue; - alignItems?: ResponsiveAlignItemsValue; -} - -export function alignItems(...args: any[]): any; - -export type JustifyContentValue = - | "center" - | "start" - | "end" - | "flex-start" - | "flex-end" - | "left" - | "right" - | "baseline" - | "first baseline" - | "last baseline" - | "space-between" - | "space-around" - | "space-evenly" - | "stretch" - | "safe center" - | "unsafe center"; -export type ResponsiveJustifyContentValue = ResponsiveValue< - JustifyContentValue ->; - -export interface JustifyContentProps { - justify?: ResponsiveJustifyContentValue; - justifyContent?: ResponsiveJustifyContentValue; -} - -export function justifyContent(...args: any[]): any; - -export type FlexWrapValue = true | "nowrap" | "wrap" | "wrap-reverse"; - -export interface FlexWrapProps { - wrap?: FlexWrapValue; - flexWrap?: FlexWrapValue; -} - -export function flexWrap(...args: any[]): any; - -export type FlexDirectionValue = - | GlobalStyleValues - | "row" - | "row-reverse" - | "column" - | "column-reverse"; - -export type ResponsiveFlexDirectionValue = ResponsiveValue; - -export interface FlexDirectionProps { - flexDirection?: ResponsiveFlexDirectionValue; -} - -export function flexDirection(...args: any[]): any; - -export type FlexValue = number | string; -export type ResponsiveFlexValue = ResponsiveValue; - -export interface FlexProps { - flex?: ResponsiveFlexValue; -} - -export function flex(...args: any[]): any; - -export type AlignContentValue = - | GlobalStyleValues - | "center" - | "start" - | "end" - | "flex-start" - | "flex-end" - | "normal" - | "baseline" - | "first baseline" - | "last baseline" - | "space-between" - | "space-around" - | "space-evenly" - | "stretch" - | "safe center" - | "unsafe center"; -export type ResponsiveAlignContentValue = ResponsiveValue; - -export interface AlignContentProps { - alignContent?: ResponsiveAlignItemsValue; -} - -export function alignContent(...args: any[]): any; - -export type JustifySelfValue = - | GlobalStyleValues - | "auto" - | "normal" - | "stretch" - | "center" - | "start" - | "end" - | "flex-start" - | "flex-end" - | "self-start" - | "self-end" - | "left" - | "right" - | "baseline" - | "first baseline" - | "last baseline" - | "safe center" - | "unsafe center"; - -export type ResponsiveJustifySelfValue = ResponsiveValue; - -export interface JustifySelfProps { - justifySelf?: ResponsiveJustifySelfValue; -} - -export function justifySelf(...args: any[]): any; - -export type AlignSelfValue = - | "auto" - | "normal" - | "center" - | "start" - | "end" - | "self-start" - | "self-end" - | "flex-start" - | "flex-end" - | "left" - | "right" - | "baseline" - | "first baseline" - | "last baseline" - | "stretch" - | "safe center" - | "unsafe center"; -export type ResponsiveAlignSelfValue = ResponsiveValue; - -export interface AlignSelfProps { - alignSelf?: ResponsiveAlignSelfValue; -} - -export function alignSelf(...args: any[]): any; - -export type OrderValue = GlobalStyleValues | number; -export type ResponsiveOrderValue = ResponsiveValue; - -export interface OrderProps { - order?: ResponsiveOrderValue; -} - -export function order(...args: any[]): any; - -export type FlexBasisValue = - | GlobalStyleValues - | "auto" - | "fill" - | "max-content" - | "min-content" - | "fit-content" - | "content"; - -export interface FlexBasisProps { - // TODO: The FlexBasisValue currently really only exists for documentation - // purposes, because flex-basis also accepts `Nem` and `Npx` strings. - // Not sure there’s a way to still have the union values show up as - // auto-completion results. - flexBasis?: FlexBasisValue | string; -} - -export function flexBasis(...args: any[]): any; - -/** - * Grid Layout - */ - -export type GridGapValue = number | string; -export type ResponsiveGridGapValue = ResponsiveValue; - -export interface GridGapProps { - gridGap?: ResponsiveGridGapValue; -} - -export function gridGap(...args: any[]): any; - -export interface GridRowGapProps { - gridRowGap?: ResponsiveGridGapValue; -} - -export function gridRowGap(...args: any[]): any; - -export interface GridColumnGapProps { - gridColumnGap?: ResponsiveGridGapValue; -} - -export function gridColumnGap(...args: any[]): any; - -export type GridCellValue = string; -export type ResponsiveGridCellValue = ResponsiveValue; - -export interface GridColumnProps { - gridColumn?: ResponsiveGridCellValue; -} - -export function gridColumn(...args: any[]): any; - -export interface GridRowProps { - gridRow?: ResponsiveGridCellValue; -} - -export function gridRow(...args: any[]): any; - -export type GridAutoValue = string; - -export interface GridAutoFlowProps { - gridAutoFlow?: GridAutoValue; -} - -export function gridAutoFlow(...args: any[]): any; - -export interface GridAutoRowsProps { - gridAutoRows?: GridAutoValue; -} - -export function gridAutoRows(...args: any[]): any; - -export interface GridAutoColumnsProps { - gridAutoColumns?: GridAutoValue; -} - -export function gridAutoColumns(...args: any[]): any; - -export type GridTemplateValue = string; -export type ResponsiveGridTemplateValue = ResponsiveValue; - -export interface GridTemplatesRowsProps { - gridTemplateRows?: ResponsiveGridTemplateValue; -} - -export function gridTemplateRows(...args: any[]): any; - -export interface GridTemplatesColumnsProps { - gridTemplateColumns?: ResponsiveGridTemplateValue; -} - -export function gridTemplateColumns(...args: any[]): any; - -/** - * Background - */ - -export type BackgroundValue = string; -export interface BackgroundProps { - background?: BackgroundValue; - bg?: BackgroundValue; -} - -export function background(...args: any[]): any; - -export type BackgroundImageValue = string; -export interface BackgroundImageProps { - /** - * Value will be wrapped in url() - */ - backgroundImage?: BackgroundImageValue; -} - -export function backgroundImage(...args: any[]): any; - -export type BackgroundSizeValue = string; -export interface BackgroundSizeProps { - backgroundSize?: BackgroundSizeValue; -} - -export function backgroundSize(...args: any[]): any; - -export type BackgroundPositionValue = string; -export interface BackgroundPositionProps { - backgroundPosition?: BackgroundPositionValue; -} - -export function backgroundPosition(...args: any[]): any; - -export type BackgroundRepeatValue = string; -export interface BackgroundRepeatProps { - backgroundRepeat?: BackgroundRepeatValue; -} - -export function backgroundRepeat(...args: any[]): any; - -/** - * Misc - */ - -export type BorderRadiusValue = string | number; -export interface BorderRadiusProps { - borderRadius?: BorderRadiusValue; -} -export function borderRadius(...args: any[]): any; - -export type BorderColorValue = string; -export interface BorderColorProps { - borderColor?: BorderColorValue; -} -export function borderColor(...args: any[]): any; - -export type BorderValue = string | number; -export type ResponsiveBorderValue = ResponsiveValue; - -export interface BorderProps { - border?: ResponsiveBorderValue; -} -export function border(...args: any[]): any; -export interface BordersProps { - border?: ResponsiveBorderValue; - borderTop?: ResponsiveBorderValue; - borderRight?: ResponsiveBorderValue; - borderBottom?: ResponsiveBorderValue; - borderLeft?: ResponsiveBorderValue; -} -export function borders(...args: any[]): any; - -export type BoxShadowValue = string | number; -export interface BoxShadowProps { - boxShadow?: BoxShadowValue; -} -export function boxShadow(...arg: any[]): any; - -/** - * Position - */ - -export type PositionValue = - | "static" - | "relative" - | "absolute" - | "sticky" - | "fixed"; -export type ResponsivePositionValue = ResponsiveValue; -export interface PositionProps { - position?: ResponsivePositionValue; -} -export function position(...args: any[]): any; - -export type ZIndexValue = GlobalStyleValues | "auto" | number; - -export interface ZIndexProps { - zIndex?: ZIndexValue; -} -export function zIndex(...args: any[]): any; - -export type TopValue = string | number; -export type ResponsiveTopValue = ResponsiveValue; -export interface TopProps { - top?: ResponsiveTopValue; -} -export function top(...args: any[]): any; - -export type RightValue = string | number; -export type ResponsiveRightValue = ResponsiveValue; -export interface RightProps { - right?: ResponsiveRightValue; -} -export function right(...args: any[]): any; - -export type BottomValue = string | number; -export type ResponsiveBottomValue = ResponsiveValue; -export interface BottomProps { - bottom?: ResponsiveBottomValue; -} -export function bottom(...args: any[]): any; - -export type LeftValue = string | number; -export type ResponsiveLeftValue = ResponsiveValue; -export interface LeftProps { - left?: ResponsiveLeftValue; -} -export function left(...args: any[]): any; - -/** - * Pseudo-classes - */ - -export interface PseudoStyleValue { - color?: ColorValue; - backgroundColor?: ColorValue; - borderColor?: BorderColorValue; - boxShadow?: BoxShadowValue; - textDecoration?: string; -} -export type HoverValue = PseudoStyleValue; -export interface HoverProps { - hover?: HoverValue; -} -export function hover(...args: any[]): any; - -export type FocusValue = PseudoStyleValue; -export interface FocusProps { - focus?: FocusValue; -} -export function focus(...args: any[]): any; - -export type ActiveValue = PseudoStyleValue; -export interface ActiveProps { - active?: ActiveValue; -} -export function active(...args: any[]): any; - -export type DisabledValue = PseudoStyleValue; -export interface DisabledProps { - disabledStyle?: DisabledValue; -} -export function disabled(...args: any[]): any; - -/** - * Utilities - */ - -export function theme(keys: string): any; -export function themeGet(keys: string, fallback?: string): any; - -export function cleanElement(component: any): any; - -export function removeProps(props: any): any; - -/** - * Low-level style export functions - */ - -export interface LowLevelStylefunctionArguments { - prop: string; - cssProperty?: string; - key?: string; - numberToPx?: boolean; - alias?: string; - getter?: () => any; -} - -export function style(args: LowLevelStylefunctionArguments): any; - -export function responsiveStyle(args: LowLevelStylefunctionArguments): any; - -export function pseudoStyle(args: LowLevelStylefunctionArguments): any; +export * from './dist/styles'; +export * from './dist/variant'; +export * from './dist/mixed'; diff --git a/types/styled-system/styled-system-tests.tsx b/types/styled-system/styled-system-tests.tsx index fa472f892a..6062948a50 100644 --- a/types/styled-system/styled-system-tests.tsx +++ b/types/styled-system/styled-system-tests.tsx @@ -85,14 +85,6 @@ import { BackgroundPositionProps, BackgroundRepeatProps, BackgroundSizeProps, - hover, - HoverProps, - focus, - FocusProps, - active, - ActiveProps, - disabled, - DisabledProps, GridGapProps, GridRowGapProps, GridColumnGapProps, @@ -112,9 +104,32 @@ import { gridAutoRows, gridAutoColumns, gridTemplateColumns, - gridTemplateRows + gridTemplateRows, + bgColor, + BgColorProps, + border, + borderBottom, + borderLeft, + borderRight, + borderTop, + BorderProps, + textStyle, + colorStyle, + buttonStyle, + variant, + mixed, + ColorStyleProps, + TextStyleProps, + VariantArgs, + ButtonStyleProps, + MixedProps, } from "styled-system"; +const boxStyle = variant({ + prop: 'boxStyle', + key: 'box', +}); + interface BoxProps extends SpaceProps, WidthProps, @@ -122,6 +137,7 @@ interface BoxProps ColorProps, DisplayProps, BackgroundProps, + BgColorProps, MaxWidthProps, MinWidthProps, HeightProps, @@ -133,6 +149,7 @@ interface BoxProps FlexProps, JustifySelfProps, AlignSelfProps, + BorderProps, BordersProps, BorderRadiusProps, PositionProps, @@ -146,10 +163,11 @@ interface BoxProps BackgroundPositionProps, BackgroundRepeatProps, BackgroundSizeProps, - HoverProps, - FocusProps, - ActiveProps, - DisabledProps {} + ColorStyleProps, + TextStyleProps, + MixedProps { + boxStyle?: string; + } const Box = styled.div.attrs({})` border-radius: ${themeGet("radii.small", "4px")}; @@ -170,7 +188,12 @@ border-radius: ${themeGet("radii.small", "4px")}; ${flex} ${justifySelf} ${alignSelf} + ${border} ${borders} + ${borderTop} + ${borderRight} + ${borderBottom} + ${borderLeft} ${borderRadius} ${position} ${zIndex} @@ -183,12 +206,19 @@ border-radius: ${themeGet("radii.small", "4px")}; ${backgroundPosition} ${backgroundRepeat} ${backgroundSize} - ${hover} - ${focus} - ${active} - ${disabled} + ${alignContent} + ${alignItems} + ${bgColor} + ${backgroundImage} + ${textStyle} + ${colorStyle} + ${mixed} `; +Box.defaultProps = { + boxStyle: 'normal', +}; + interface TextProps extends FontSizeProps, FontFamilyProps, @@ -245,6 +275,15 @@ const Grid = styled.div.attrs({})` ${gridTemplateColumns}; `; +interface ButtonProps + extends SpaceProps, + ButtonStyleProps {} + +const TestButton = styled.button.attrs({})` + ${buttonStyle} + ${space} +`; + const test = () => (

// width: 50% @@ -348,7 +387,6 @@ const test = () => ( // flexWrap (responsive) - // flexBasis (responsive) // flexDirection (responsive) @@ -411,14 +449,7 @@ const test = () => ( backgroundPosition="center" backgroundRepeat="repeat-x" /> - - - - + +
); diff --git a/types/stylelint/index.d.ts b/types/stylelint/index.d.ts index 67316843a9..2068aff709 100644 --- a/types/stylelint/index.d.ts +++ b/types/stylelint/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for stylelint 7.11 +// Type definitions for stylelint 9.4 // Project: https://github.com/stylelint/stylelint // Definitions by: Alan Agius // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export type FormatterType = "json" | "string" | "verbose"; +export type FormatterType = "json" | "string" | "verbose" | "compact"; export type SyntaxType = "scss" | "sass" | "less" | "sugarss"; @@ -45,6 +45,7 @@ export interface LintResult { export namespace formatters { function json(results: LintResult[]): string; function string(results: LintResult[]): string; + function compact(results: LintResult[]): string; function verbose(results: LintResult[]): string; } diff --git a/types/stylelint/tslint.json b/types/stylelint/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/stylelint/tslint.json +++ b/types/stylelint/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/stylelint/v7/index.d.ts b/types/stylelint/v7/index.d.ts new file mode 100644 index 0000000000..67316843a9 --- /dev/null +++ b/types/stylelint/v7/index.d.ts @@ -0,0 +1,51 @@ +// Type definitions for stylelint 7.11 +// Project: https://github.com/stylelint/stylelint +// Definitions by: Alan Agius +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type FormatterType = "json" | "string" | "verbose"; + +export type SyntaxType = "scss" | "sass" | "less" | "sugarss"; + +export interface LinterOptions { + code?: string; + codeFilename?: string; + config?: JSON; + configBasedir?: string; + configFile?: string; + configOverrides?: JSON; + cache?: boolean; + cacheLocation?: string; + files?: string | string[]; + fix?: boolean; + formatter?: FormatterType; + ignoreDisables?: boolean; + reportNeedlessDisables?: boolean; + ignorePath?: boolean; + syntax?: SyntaxType; + customSyntax?: string; +} + +export interface LinterResult { + errored: boolean; + output: string; + postcssResults: any[]; + results: LintResult[]; +} + +export interface LintResult { + source: string; + errored: boolean | undefined; + ignored: boolean | undefined; + warnings: string[]; + deprecations: string[]; + invalidOptionWarnings: any[]; +} + +export namespace formatters { + function json(results: LintResult[]): string; + function string(results: LintResult[]): string; + function verbose(results: LintResult[]): string; +} + +export function lint(options?: LinterOptions): Promise; diff --git a/types/stylelint/v7/stylelint-tests.ts b/types/stylelint/v7/stylelint-tests.ts new file mode 100644 index 0000000000..785eb2e425 --- /dev/null +++ b/types/stylelint/v7/stylelint-tests.ts @@ -0,0 +1,24 @@ +import { LinterOptions, FormatterType, SyntaxType, lint, LintResult, LinterResult } from "stylelint"; + +const options: LinterOptions = { + code: "div { color: red }", + files: ["**/**.scss"], + formatter: "json", + cache: true, + cacheLocation: "./stylelint.cache.json", + ignoreDisables: true, + reportNeedlessDisables: true, + ignorePath: true, + syntax: "scss" +}; + +lint(options).then((x: LinterResult) => { + const err: boolean = x.errored; + const output: string = x.output; + const postcssResults: any[] = x.postcssResults; + const results: LintResult[] = x.results; +}); + +const formatter: FormatterType = "json"; + +const syntax: SyntaxType = "scss"; diff --git a/types/stylelint/v7/tsconfig.json b/types/stylelint/v7/tsconfig.json new file mode 100644 index 0000000000..b6f6796252 --- /dev/null +++ b/types/stylelint/v7/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "stylelint": [ + "stylelint/v7" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "stylelint-tests.ts" + ] +} diff --git a/types/stylelint/v7/tslint.json b/types/stylelint/v7/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/stylelint/v7/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/svg-path-parser/index.d.ts b/types/svg-path-parser/index.d.ts new file mode 100644 index 0000000000..d90ad4f66f --- /dev/null +++ b/types/svg-path-parser/index.d.ts @@ -0,0 +1,102 @@ +// Type definitions for svg-path-parser 1.1 +// Project: https://github.com/hughsk/svg-path-parser#readme +// Definitions by: tyru +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function parseSVG(input: string): Command[]; +export function makeAbsolute(commands: Command[]): Command[]; + +export interface Command { + code: 'm' | 'M' | 'l' | 'L' | 'h' | 'H' | 'v' | 'V' | 'c' | 'C' | 's' | 'S' | 'q' | 'Q' | 't' | 'T' | 'a' | 'A' | 'z' | 'Z'; + command: 'moveto' | 'lineto' | 'horizontal lineto' | 'vertical lineto' | 'curveto' | 'smooth curveto' | 'quadratic curveto' | 'smooth quadratic curveto' | 'elliptical arc' | 'closepath'; + relative?: boolean; +} + +export interface MoveToCommand { + code: 'm' | 'M'; + command: 'moveto'; + relative?: boolean; + x: number; + y: number; +} + +export interface LineToCommand { + code: 'l' | 'L'; + command: 'lineto'; + relative?: boolean; + x: number; + y: number; +} + +export interface HorizontalLineToCommand { + code: 'h' | 'H'; + command: 'horizontal lineto'; + relative?: boolean; + x: number; +} + +export interface VerticalLineToCommand { + code: 'v' | 'V'; + command: 'vertical lineto'; + relative?: boolean; + y: number; +} + +export interface ClosePathCommand { + code: 'z' | 'Z'; + command: 'closepath'; + relative?: boolean; +} + +export interface CurveToCommand { + code: 'c' | 'C'; + command: 'curveto'; + relative?: boolean; + x1: number; + y1: number; + x2: number; + y2: number; + x: number; + y: number; +} + +export interface SmoothCurveToCommand { + code: 's' | 'S'; + command: 'smooth curveto'; + relative?: boolean; + x2: number; + y2: number; + x: number; + y: number; +} + +export interface QuadraticCurveToCommand { + code: 'q' | 'Q'; + command: 'quadratic curveto'; + relative?: boolean; + x1: number; + y1: number; + x: number; + y: number; +} + +export interface SmoothQuadraticCurveToCommand { + code: 't' | 'T'; + command: 'smooth quadratic curveto'; + relative?: boolean; + x: number; + y: number; +} + +export interface EllipticalArcCommand { + code: 'a' | 'A'; + command: 'elliptical arc'; + relative?: boolean; + rx: number; + ry: number; + xAxisRotation: number; + largeArc: boolean; + sweep: boolean; + x: number; + y: number; +} diff --git a/types/svg-path-parser/svg-path-parser-tests.ts b/types/svg-path-parser/svg-path-parser-tests.ts new file mode 100644 index 0000000000..4966054a79 --- /dev/null +++ b/types/svg-path-parser/svg-path-parser-tests.ts @@ -0,0 +1,79 @@ +/// + +import * as svgParser from 'svg-path-parser'; + +function isMoveToCommand(cmd: svgParser.Command): cmd is svgParser.MoveToCommand { + return cmd.command === 'moveto'; +} + +function isLineToCommand(cmd: svgParser.Command): cmd is svgParser.LineToCommand { + return cmd.command === 'lineto'; +} + +function isHorizontalLineToCommand(cmd: svgParser.Command): cmd is svgParser.HorizontalLineToCommand { + return cmd.command === 'horizontal lineto'; +} + +function isVerticalLineToCommand(cmd: svgParser.Command): cmd is svgParser.VerticalLineToCommand { + return cmd.command === 'vertical lineto'; +} + +function isClosePathCommand(cmd: svgParser.Command): cmd is svgParser.ClosePathCommand { + return cmd.command === 'closepath'; +} + +function isCurveToCommand(cmd: svgParser.Command): cmd is svgParser.CurveToCommand { + return cmd.command === 'curveto'; +} + +function isSmoothCurveToCommand(cmd: svgParser.Command): cmd is svgParser.SmoothCurveToCommand { + return cmd.command === 'smooth curveto'; +} + +function isQuadraticCurveToCommand(cmd: svgParser.Command): cmd is svgParser.QuadraticCurveToCommand { + return cmd.command === 'quadratic curveto'; +} + +function isSmoothQuadraticCurveToCommand(cmd: svgParser.Command): cmd is svgParser.SmoothQuadraticCurveToCommand { + return cmd.command === 'smooth quadratic curveto'; +} + +function isEllipticalArcCommand(cmd: svgParser.Command): cmd is svgParser.EllipticalArcCommand { + return cmd.command === 'elliptical arc'; +} + +function stringify(cmd: svgParser.Command) { + if (isMoveToCommand(cmd)) { + return `${cmd.code} ${cmd.x} ${cmd.y}`; + } else if (isLineToCommand(cmd)) { + return `${cmd.code} ${cmd.x} ${cmd.y}`; + } else if (isLineToCommand(cmd)) { + return `${cmd.code} ${cmd.x} ${cmd.y}`; + } else if (isHorizontalLineToCommand(cmd)) { + return `${cmd.code} ${cmd.x}`; + } else if (isVerticalLineToCommand(cmd)) { + return `${cmd.code} ${cmd.y}`; + } else if (isClosePathCommand(cmd)) { + return `${cmd.code}`; + } else if (isCurveToCommand(cmd)) { + return `${cmd.code} ${cmd.x1} ${cmd.y1} ${cmd.x2} ${cmd.y2} ${cmd.x} ${cmd.y}`; + } else if (isSmoothCurveToCommand(cmd)) { + return `${cmd.code} ${cmd.x2} ${cmd.y2} ${cmd.x} ${cmd.y}`; + } else if (isQuadraticCurveToCommand(cmd)) { + return `${cmd.code} ${cmd.x1} ${cmd.y1} ${cmd.x} ${cmd.y}`; + } else if (isSmoothQuadraticCurveToCommand(cmd)) { + return `${cmd.code} ${cmd.x} ${cmd.y}`; + } else if (isEllipticalArcCommand(cmd)) { + return `${cmd.code} ${cmd.rx} ${cmd.ry} ${cmd.xAxisRotation} ${cmd.largeArc} ${cmd.sweep} ${cmd.x} ${cmd.y}`; + } else { + throw new Error(`${cmd.code} command is unknown command: cmd = ${JSON.stringify(cmd)}`); + } +} + +let cmds = svgParser.parseSVG('M 0 0 L 50 50'); +// makeAbsolute() changes cmds inplacely +cmds = svgParser.makeAbsolute(cmds); + +cmds.filter((cmd: svgParser.Command) => !cmd.relative) // relative commands must not exist + .map(stringify) + .forEach(console.log); diff --git a/types/svg-path-parser/tsconfig.json b/types/svg-path-parser/tsconfig.json new file mode 100644 index 0000000000..024c3cc91f --- /dev/null +++ b/types/svg-path-parser/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", + "svg-path-parser-tests.ts" + ] +} diff --git a/types/svg-path-parser/tslint.json b/types/svg-path-parser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/svg-path-parser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/thepiratebay/index.d.ts b/types/thepiratebay/index.d.ts new file mode 100644 index 0000000000..20a1cc8945 --- /dev/null +++ b/types/thepiratebay/index.d.ts @@ -0,0 +1,69 @@ +// Type definitions for thepiratebay 1.4 +// Project: http://github.com/t3chnoboy/thepiratebay +// Definitions by: Jack Sorrell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function search(query?: string, options?: SearchOptions): Promise; +export function getTorrent(id: string | number | { link: string; [propName: string]: any; }): Promise; +export function getComments(id: string | number): Promise; +export function topTorrents(category?: number): Promise; +export function recentTorrents(): Promise; +export function userTorrents(user: string, options?: SearchOptions): Promise; +export function getTvShow(id: string | number): Promise; +export function getCategories(): Promise; + +export interface SearchOptions { + category?: string | number; + filter?: { verified?: boolean }; + page?: number; + orderBy?: string; + sortBy?: string; +} + +export interface Category { + id: string; + name: string; +} + +export interface CategoryGroup extends Category { + subcategories: Category[]; +} + +export interface Torrent { + id: string; + name: string; + size: string; + link: string; + seeders: string; + leechers: string; + uploadDate: string; + magnetLink: string; + uploader: string; + uploaderLink: string; +} + +export interface TorrentDetails extends Torrent { + description: string; +} + +export interface TorrentSearchResult extends Torrent { + category: Category; + subcategory: Category; + verified: boolean; +} + +export interface Comment { + user: string; + comment: string; +} + +export interface TVTorrent { + id: string; + title: string; + link: string; +} + +export interface TVSeason { + title: string; + torrents: TVTorrent[]; +} diff --git a/types/thepiratebay/thepiratebay-tests.ts b/types/thepiratebay/thepiratebay-tests.ts new file mode 100644 index 0000000000..76c56eb269 --- /dev/null +++ b/types/thepiratebay/thepiratebay-tests.ts @@ -0,0 +1,104 @@ +import * as PirateBay from 'thepiratebay'; + +// $ExpectType Promise +const searchResultPromise = PirateBay.search('Game of Thrones', { + category: 'all', + filter: { + verified: false + }, + page: 0, + orderBy: 'leeches', + sortBy: 'desc' +}); +searchResultPromise.then((res: PirateBay.TorrentSearchResult[]) => { + res[0].id; // $ExpectType string + res[0].name; // $ExpectType string + res[0].size; // $ExpectType string + res[0].link; // $ExpectType string + res[0].seeders; // $ExpectType string + res[0].leechers; // $ExpectType string + res[0].uploadDate; // $ExpectType string + res[0].magnetLink; // $ExpectType string + res[0].uploader; // $ExpectType string + res[0].uploaderLink; // $ExpectType string + + const category = res[0].category; // $ExpectType Category + category.id; // $ExpectType string + category.name; // $ExpectType string + + res[0].subcategory; // $ExpectType Category + res[0].verified; // $ExpectType boolean +}); +// $ExpectError +PirateBay.search(15); + +// $ExpectType Promise +const torrentPromise = PirateBay.getTorrent('15496322'); +torrentPromise.then((torrent: PirateBay.TorrentDetails) => { + torrent.id; // $ExpectType string + torrent.name; // $ExpectType string + torrent.size; // $ExpectType string + torrent.link; // $ExpectType string + torrent.seeders; // $ExpectType string + torrent.leechers; // $ExpectType string + torrent.uploadDate; // $ExpectType string + torrent.magnetLink; // $ExpectType string + torrent.uploader; // $ExpectType string + torrent.uploaderLink; // $ExpectType string + torrent.description; // $ExpectType string +}); +// $ExpectType Promise +PirateBay.getTorrent(15496322); +// $ExpectError +PirateBay.getTorrent(false); +// $ExpectType Promise +PirateBay.getTorrent('https://thepiratebay.org/torrent/15496322/Ubuntu_16.04.1_LTS_Desktop_64-bit'); +// $ExpectType Promise +PirateBay.getTorrent({ name: "ubuntu", link: 'https://thepiratebay.org/torrent/15496322/Ubuntu_16.04.1_LTS_Desktop_64-bit' }); + +// $ExpectType Promise +PirateBay.topTorrents(); +// $ExpectError +PirateBay.topTorrents(true); +// $ExpectType Promise +PirateBay.topTorrents(400); + +// $ExpectType Promise +PirateBay.recentTorrents(); +// $ExpectError +PirateBay.recentTorrents(10); + +// $ExpectError +PirateBay.userTorrents(); +// $ExpectType Promise +PirateBay.userTorrents('alice', { + page: 3, + orderBy: 'name', + sortBy: 'asc' +}); +// $ExpectType Promise +PirateBay.userTorrents('bob'); + +// $ExpectType Promise +const categoryGroup = PirateBay.getCategories(); +categoryGroup.then((groups: PirateBay.CategoryGroup[]) => { + groups[0].id; // $ExpectType string + groups[0].name; // $ExpectType string + groups[0].subcategories; // $ExpectType Category[] +}); +// $ExpectError +PirateBay.getCategories(154); + +// $ExpectError +PirateBay.getTvShow(); +// $ExpectType Promise +const tvShow = PirateBay.getTvShow(15); +tvShow.then((seasons: PirateBay.TVSeason[]) => { + seasons[0].title; // $ExpectType string + const torrents = seasons[0].torrents; // $ExpectType TVTorrent[] + torrents[0].id; // $ExpectType string + torrents[0].title; // $ExpectType string + torrents[0].link; // $ExpectType string +}); +// $ExpectType Promise +PirateBay.getTvShow('15'); diff --git a/types/thepiratebay/tsconfig.json b/types/thepiratebay/tsconfig.json new file mode 100644 index 0000000000..1d491e4d75 --- /dev/null +++ b/types/thepiratebay/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", + "thepiratebay-tests.ts" + ] +} diff --git a/types/thepiratebay/tslint.json b/types/thepiratebay/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/thepiratebay/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts old mode 100644 new mode 100755 index b4daf0bd93..520db93b96 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -2302,8 +2302,21 @@ export class LoadingManager { */ onError: (url: string) => void; + /** + * If provided, the callback will be passed each resource URL before a request is sent. + * The callback may return the original URL, or a new URL to override loading behavior. + * This behavior can be used to load assets from .ZIP files, drag-and-drop APIs, and Data URIs. + * @param callback URL modifier callback. Called with url argument, and must return resolvedURL. + */ setURLModifier(callback?: (url: string) => string): void; + /** + * Given a URL, uses the URL modifier callback (if any) and returns a resolved URL. + * If no URL modifier is set, returns the original URL. + * @param url the url to load + */ + resolveURL(url: string): string; + itemStart(url: string): void; itemEnd(url: string): void; itemError(url: string): void; @@ -5568,12 +5581,12 @@ export class WebGLRenderer implements Renderer { getPixelRatio(): number; setPixelRatio(value: number): void; - + getDrawingBufferSize(): { width: number; height: number; }; setDrawingBufferSize(width: number, height: number, pixelRatio: number): void; getSize(): { width: number; height: number; }; - + /** * Resizes the output canvas to (width, height), and also sets the viewport to fit that size, starting in (0, 0). */ @@ -5645,6 +5658,11 @@ export class WebGLRenderer implements Renderer { * A build in function that can be used instead of requestAnimationFrame. For WebVR projects this function must be used. * @param callback The function will be called every available frame. If `null` is passed it will stop any already ongoing animation. */ + setAnimationLoop(callback: Function): void; + + /** + * @deprecated Use {@link WebGLRenderer#setAnimationLoop .setAnimationLoop()} instead. + */ animate(callback: Function): void; /** diff --git a/types/timezone-js/index.d.ts b/types/timezone-js/index.d.ts index 5a648ab41e..ee39a7ee7b 100644 --- a/types/timezone-js/index.d.ts +++ b/types/timezone-js/index.d.ts @@ -19,7 +19,7 @@ export declare class Date { setTimezone: (timezone: string) => void; // regular Date members - toString(): string; + toString(format?:string): string; toDateString(): string; toTimeString(): string; toLocaleString(): string; diff --git a/types/tinajs__tina-redux/index.d.ts b/types/tinajs__tina-redux/index.d.ts new file mode 100644 index 0000000000..e48665e696 --- /dev/null +++ b/types/tinajs__tina-redux/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for @tinajs/tina-redux 1.4 +// Project: https://github.com/tinajs/tina-redux +// Definitions by: Jiayu Liu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tinajs__tina-redux +// TypeScript Version: 2.3 + +import { Store, Dispatch } from "redux"; + +type MapStateToProps = (state: any) => any; +type mapDispatchToProps = (dispatch: Dispatch) => any; + +interface HOC { + onLoad: () => void; + onUnload: () => void; + methods: object; +} + +declare class TinaRedux { + constructor(reduxStore: Store); + connect(mapState?: MapStateToProps, mapDispatch?: mapDispatchToProps): HOC; +} + +export = TinaRedux; diff --git a/types/tinajs__tina-redux/package.json b/types/tinajs__tina-redux/package.json new file mode 100644 index 0000000000..7f5b19d45b --- /dev/null +++ b/types/tinajs__tina-redux/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "redux": "^4.0.0" + } +} diff --git a/types/tinajs__tina-redux/tinajs__tina-redux-tests.ts b/types/tinajs__tina-redux/tinajs__tina-redux-tests.ts new file mode 100644 index 0000000000..d4a7c2225f --- /dev/null +++ b/types/tinajs__tina-redux/tinajs__tina-redux-tests.ts @@ -0,0 +1,51 @@ +import { createStore, combineReducers, Action } from "redux"; +import TinaRedux from "@tinajs/tina-redux"; + +interface Todo { + id: number; + text: string; + completed: boolean; +} + +interface TodoAction extends Action, Todo {} + +const intialState: Todo[] = [ + { id: 1, text: "Star Tina.js", completed: false }, + { id: 2, text: "Star Tina-Redux", completed: true }, + { id: 3, text: "Build a mini-program with Tina.js", completed: false }, + { id: 4, text: "Add to Showcase of Tina.js", completed: false } +]; + +const todos = (state = intialState, action: TodoAction) => { + switch (action.type) { + case "ADD_TODO": + return [ + ...state, + { + id: action.id, + text: action.text, + completed: false + } + ]; + case "TOGGLE_TODO": + return state.map( + todo => + todo.id === action.id + ? { ...todo, completed: !todo.completed } + : todo + ); + case "CLEAR_COMPLETED_TODOS": + return state.filter(todo => !todo.completed); + default: + return state; + } +}; + +const todoApp = combineReducers({ + todos +}); + +const reduxStore = createStore(todoApp); +const store = new TinaRedux(reduxStore); + +export default store; diff --git a/types/tinajs__tina-redux/tsconfig.json b/types/tinajs__tina-redux/tsconfig.json new file mode 100644 index 0000000000..c3b4905b15 --- /dev/null +++ b/types/tinajs__tina-redux/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "allowSyntheticDefaultImports": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@tinajs/tina": ["tinajs__tina"], + "@tinajs/tina-redux": ["tinajs__tina-redux"] + } + }, + "files": ["index.d.ts", "tinajs__tina-redux-tests.ts"] +} diff --git a/types/tinajs__tina-redux/tslint.json b/types/tinajs__tina-redux/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/tinajs__tina-redux/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/tiny-slider-react/index.d.ts b/types/tiny-slider-react/index.d.ts index 9cf22beab7..81c8a38377 100644 --- a/types/tiny-slider-react/index.d.ts +++ b/types/tiny-slider-react/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/jechav/tiny-slider-react#readme // Definitions by: Christian Rackerseder // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 import * as React from "react"; export interface CommonOptions { diff --git a/types/tinycolor2/index.d.ts b/types/tinycolor2/index.d.ts index 921d8a4f08..4d28d623ac 100644 --- a/types/tinycolor2/index.d.ts +++ b/types/tinycolor2/index.d.ts @@ -1,393 +1,673 @@ -// Type definitions for tinycolor v1.4.1 +// Type definitions for tinycolor 1.4 // Project: https://github.com/bgrins/TinyColor -// Definitions by: Mordechai Zuber , Geert Jansen , Niels van Hoorn +// Definitions by: Mordechai Zuber , +// Geert Jansen , +// Niels van Hoorn , +// Junyoung Clare Jang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 -declare var tinycolor: tinycolor; +declare namespace tinycolor { + type ColorInputWithoutInstance = + | string + | ColorFormats.PRGB + | ColorFormats.PRGBA + | ColorFormats.RGB + | ColorFormats.RGBA + | ColorFormats.HSL + | ColorFormats.HSLA + | ColorFormats.HSV + | ColorFormats.HSVA + ; + type ColorInput = ColorInputWithoutInstance | Instance; -interface tinycolor { + namespace ColorFormats { + interface Alpha { + a: number; + } - /** - * Create a tinycolor instance of the color named. - * - * @param color - the color as a string to create an instance for. - */ - (color: string): tinycolorInstance; + interface PRGB { + r: string; + g: string; + b: string; + } - /** - * Create a tinycolor instance with the given RGB values. - * - * @param color - the rgb values to apply to the new instance. - */ - (color: ColorFormats.RGB): tinycolorInstance; + interface PRGBA extends PRGB, Alpha {} - /** - * Create a tinycolor instance with the given RGBA values. - * - * @param color - the rgba values to apply to the new instance. - */ - (color: ColorFormats.RGBA): tinycolorInstance; + interface RGB { + r: number; + g: number; + b: number; + } - /** - * Create a tinycolor instance with the given HSL values. - * - * @param color - the hsl values to apply to the new instance. - */ - (color: ColorFormats.HSL): tinycolorInstance; + interface RGBA extends RGB, Alpha {} - /** - * Create a tinycolor instance with the given HSLA values. - * - * @param color - the hsla values to apply to the new instance. - */ - (color: ColorFormats.HSLA): tinycolorInstance; + interface HSL { + h: number; + s: number; + l: number; + } - /** - * Create a tinycolor instance with the given HSV values. - * - * @param color - the hsv values to apply to the new instance. - */ - (color: ColorFormats.HSV): tinycolorInstance; + interface HSLA extends HSL, Alpha {} - /** - * Create a tinycolor instance with the given HSVA values. - * - * @param color - the hsva values to apply to the new instance. - */ - (color: ColorFormats.HSVA): tinycolorInstance; + interface HSV { + h: number; + s: number; + v: number; + } - /** - * Create a tinycolor instance based off the relative values. - * Works with any color formats - * - * @param ratio - the relative color/hue values to apply to the new instance. - */ - fromRatio(ratio: any): tinycolorInstance; // any of the interfaces defined in the ColorFormats module. + interface HSVA extends HSV { + a: number; + } + } - /** - * Compares the two colors and returns the difference between their brightness and color/hue - * - * @param firstColor - the first color to be used in the comparison. - * @param secondColor - the second color to be used in the comparison. - */ - readability(firstColor: ColorInput, secondColor: ColorInput): Readable.Readable; + interface ConstructorOptions { + format?: string; + gradientType?: boolean; + } - /** - * Ensure that foreground and background color combinations meet WCAG2 guidelines. - * - * @param foreColor - the fore color wanted. - * @param backColor - the back color wanted. - * @param wcag2 - The 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA'; the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'. If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}. - */ - isReadable(foreColor: ColorInput, backColor: ColorInput, wcag2?: {level?: string, size?: string}): boolean; + interface WCAG2Options { + level?: "AA" | "AAA"; + size?: "large" | "small"; + } - /** - * Given a base color and a list of possible foreground or background colors for that base, - * returns the most readable color. Optionally returns Black or White if the most readable color is unreadable. - * - * @param color - the base color. - * @param colorsToCompare - array of colors to pick the most readable one from. - * @param args - and object with extra arguments - */ - mostReadable(color: ColorInput, colorsToCompare: ColorInput[], args?: {includeFallbackColors?: boolean, level?: string, size?: string}): tinycolorInstance; + interface MostReadableArgs extends WCAG2Options { + includeFallbackColors?: boolean; + } - /**/ - mix(color1: ColorInput, color2: ColorInput, amount?: number): tinycolorInstance; + interface Constructor { + /** + * Create a tinycolor instance of the color named. + * + * @param color - the color as one of the valid color input format. + */ + new (color?: ColorInput, opts?: ConstructorOptions): Instance; + (color?: ColorInput, opts?: ConstructorOptions): Instance; - /** - * Can be called with any tinycolor input - */ - equals(color1: ColorInput, color2: ColorInput): boolean; + /** + * Create a tinycolor instance based off the relative values. + * Works with any color formats + * + * @param ratio - the relative color/hue values to apply to the new instance. + */ + fromRatio(ratio?: ColorInputWithoutInstance): Instance; - /** - * Returns a random color - */ - random(): tinycolorInstance; + /** + * Compares two colors. Each colors can be any color inputs. + */ + equals(color1?: ColorInput, color2?: ColorInput): boolean; - /** - * key: hex value - * value: string name ex. hexnames["f00"] --> "red" - */ - hexNames: { [key: string]: string }; + /** + * Returns a random color + */ + random(): Instance; - /** - * key: 'real' color name - * value: hex value ex. names["red"] --> "f00" - */ - names: { [key: string]: string }; -} + mix(color1: ColorInput, color2: ColorInput, amount?: number): Instance; -interface tinycolorInstance { + /** + * Compares the two colors and returns the constrast between two colors as a number. + * + * @param color1 - the first color to be used in the comparison. + * @param color2 - the second color to be used in the comparison. + */ + readability(color1: ColorInput, color2: ColorInput): number; - /** - * Return an indication whether the color was successfully parsed. - */ - isValid(): boolean; + /** + * Ensure that foreground and background color combinations meet WCAG2 guidelines. + * + * @param color1 - the fore color wanted. + * @param color2 - the back color wanted. + * @param wcag2 - WCAG option. If the entire object is absent, function use the default of {level:"AA",size:"small"}. + * @param wcag2.level - The 'level' property states 'AA' or 'AAA' + * if missing or invalid, it defaults to 'AA' + * @param wcag2.size - The 'size' property states 'large' or 'small' + * if missing or invalid, it defaults to 'small'. + */ + isReadable(color1: ColorInput, color2: ColorInput, wcag2?: WCAG2Options): boolean; - /** - * Return an indication whether the color's perceived brightness is light. - */ - isLight(): boolean; + /** + * Given a base color and a list of possible foreground or background colors for that base, + * returns the most readable color. Optionally returns Black or White if the most readable color is unreadable. + * + * @param color - the base color. + * @param colorsToCompare - array of colors to pick the most readable one from. + * @param args - and object with extra arguments + */ + mostReadable(baseColor: ColorInput, colorList: ColorInput[], args?: MostReadableArgs): Instance; - /** - * Return an indication whether the color's perceived brightness is dark. - */ - isDark(): boolean; + /** + * key: 'real' color name + * value: hex value ex. names["red"] --> "f00" + */ + names: { + aliceblue: "f0f8ff"; + antiquewhite: "faebd7"; + aqua: "0ff"; + aquamarine: "7fffd4"; + azure: "f0ffff"; + beige: "f5f5dc"; + bisque: "ffe4c4"; + black: "000"; + blanchedalmond: "ffebcd"; + blue: "00f"; + blueviolet: "8a2be2"; + brown: "a52a2a"; + burlywood: "deb887"; + burntsienna: "ea7e5d"; + cadetblue: "5f9ea0"; + chartreuse: "7fff00"; + chocolate: "d2691e"; + coral: "ff7f50"; + cornflowerblue: "6495ed"; + cornsilk: "fff8dc"; + crimson: "dc143c"; + cyan: "0ff"; + darkblue: "00008b"; + darkcyan: "008b8b"; + darkgoldenrod: "b8860b"; + darkgray: "a9a9a9"; + darkgreen: "006400"; + darkgrey: "a9a9a9"; + darkkhaki: "bdb76b"; + darkmagenta: "8b008b"; + darkolivegreen: "556b2f"; + darkorange: "ff8c00"; + darkorchid: "9932cc"; + darkred: "8b0000"; + darksalmon: "e9967a"; + darkseagreen: "8fbc8f"; + darkslateblue: "483d8b"; + darkslategray: "2f4f4f"; + darkslategrey: "2f4f4f"; + darkturquoise: "00ced1"; + darkviolet: "9400d3"; + deeppink: "ff1493"; + deepskyblue: "00bfff"; + dimgray: "696969"; + dimgrey: "696969"; + dodgerblue: "1e90ff"; + firebrick: "b22222"; + floralwhite: "fffaf0"; + forestgreen: "228b22"; + fuchsia: "f0f"; + gainsboro: "dcdcdc"; + ghostwhite: "f8f8ff"; + gold: "ffd700"; + goldenrod: "daa520"; + gray: "808080"; + green: "008000"; + greenyellow: "adff2f"; + grey: "808080"; + honeydew: "f0fff0"; + hotpink: "ff69b4"; + indianred: "cd5c5c"; + indigo: "4b0082"; + ivory: "fffff0"; + khaki: "f0e68c"; + lavender: "e6e6fa"; + lavenderblush: "fff0f5"; + lawngreen: "7cfc00"; + lemonchiffon: "fffacd"; + lightblue: "add8e6"; + lightcoral: "f08080"; + lightcyan: "e0ffff"; + lightgoldenrodyellow: "fafad2"; + lightgray: "d3d3d3"; + lightgreen: "90ee90"; + lightgrey: "d3d3d3"; + lightpink: "ffb6c1"; + lightsalmon: "ffa07a"; + lightseagreen: "20b2aa"; + lightskyblue: "87cefa"; + lightslategray: "789"; + lightslategrey: "789"; + lightsteelblue: "b0c4de"; + lightyellow: "ffffe0"; + lime: "0f0"; + limegreen: "32cd32"; + linen: "faf0e6"; + magenta: "f0f"; + maroon: "800000"; + mediumaquamarine: "66cdaa"; + mediumblue: "0000cd"; + mediumorchid: "ba55d3"; + mediumpurple: "9370db"; + mediumseagreen: "3cb371"; + mediumslateblue: "7b68ee"; + mediumspringgreen: "00fa9a"; + mediumturquoise: "48d1cc"; + mediumvioletred: "c71585"; + midnightblue: "191970"; + mintcream: "f5fffa"; + mistyrose: "ffe4e1"; + moccasin: "ffe4b5"; + navajowhite: "ffdead"; + navy: "000080"; + oldlace: "fdf5e6"; + olive: "808000"; + olivedrab: "6b8e23"; + orange: "ffa500"; + orangered: "ff4500"; + orchid: "da70d6"; + palegoldenrod: "eee8aa"; + palegreen: "98fb98"; + paleturquoise: "afeeee"; + palevioletred: "db7093"; + papayawhip: "ffefd5"; + peachpuff: "ffdab9"; + peru: "cd853f"; + pink: "ffc0cb"; + plum: "dda0dd"; + powderblue: "b0e0e6"; + purple: "800080"; + rebeccapurple: "663399"; + red: "f00"; + rosybrown: "bc8f8f"; + royalblue: "4169e1"; + saddlebrown: "8b4513"; + salmon: "fa8072"; + sandybrown: "f4a460"; + seagreen: "2e8b57"; + seashell: "fff5ee"; + sienna: "a0522d"; + silver: "c0c0c0"; + skyblue: "87ceeb"; + slateblue: "6a5acd"; + slategray: "708090"; + slategrey: "708090"; + snow: "fffafa"; + springgreen: "00ff7f"; + steelblue: "4682b4"; + tan: "d2b48c"; + teal: "008080"; + thistle: "d8bfd8"; + tomato: "ff6347"; + turquoise: "40e0d0"; + violet: "ee82ee"; + wheat: "f5deb3"; + white: "fff"; + whitesmoke: "f5f5f5"; + yellow: "ff0"; + yellowgreen: "9acd32"; + }; - /** - * Returns the format used to create the tinycolor instance. - */ - getFormat(): string; + /** + * key: hex value + * value: string name ex. hexnames["f00"] --> "red" + */ + hexNames: { + "f0f8ff": "aliceblue"; + "faebd7": "antiquewhite"; + "0ff": "aqua" | "cyan"; + "7fffd4": "aquamarine"; + "f0ffff": "azure"; + "f5f5dc": "beige"; + "ffe4c4": "bisque"; + "000": "black"; + "ffebcd": "blanchedalmond"; + "00f": "blue"; + "8a2be2": "blueviolet"; + "a52a2a": "brown"; + "deb887": "burlywood"; + "ea7e5d": "burntsienna"; + "5f9ea0": "cadetblue"; + "7fff00": "chartreuse"; + "d2691e": "chocolate"; + "ff7f50": "coral"; + "6495ed": "cornflowerblue"; + "fff8dc": "cornsilk"; + "dc143c": "crimson"; + "00008b": "darkblue"; + "008b8b": "darkcyan"; + "b8860b": "darkgoldenrod"; + "a9a9a9": "darkgray" | "darkgrey"; + "006400": "darkgreen"; + "bdb76b": "darkkhaki"; + "8b008b": "darkmagenta"; + "556b2f": "darkolivegreen"; + "ff8c00": "darkorange"; + "9932cc": "darkorchid"; + "8b0000": "darkred"; + "e9967a": "darksalmon"; + "8fbc8f": "darkseagreen"; + "483d8b": "darkslateblue"; + "2f4f4f": "darkslategray" | "darkslategrey"; + "00ced1": "darkturquoise"; + "9400d3": "darkviolet"; + "ff1493": "deeppink"; + "00bfff": "deepskyblue"; + "696969": "dimgray" | "dimgrey"; + "1e90ff": "dodgerblue"; + "b22222": "firebrick"; + "fffaf0": "floralwhite"; + "228b22": "forestgreen"; + "f0f": "fuchsia" | "magenta"; + "dcdcdc": "gainsboro"; + "f8f8ff": "ghostwhite"; + "ffd700": "gold"; + "daa520": "goldenrod"; + "808080": "gray" | "grey"; + "008000": "green"; + "adff2f": "greenyellow"; + "f0fff0": "honeydew"; + "ff69b4": "hotpink"; + "cd5c5c": "indianred"; + "4b0082": "indigo"; + "fffff0": "ivory"; + "f0e68c": "khaki"; + "e6e6fa": "lavender"; + "fff0f5": "lavenderblush"; + "7cfc00": "lawngreen"; + "fffacd": "lemonchiffon"; + "add8e6": "lightblue"; + "f08080": "lightcoral"; + "e0ffff": "lightcyan"; + "fafad2": "lightgoldenrodyellow"; + "d3d3d3": "lightgray" | "lightgrey"; + "90ee90": "lightgreen"; + "ffb6c1": "lightpink"; + "ffa07a": "lightsalmon"; + "20b2aa": "lightseagreen"; + "87cefa": "lightskyblue"; + "789": "lightslategray" | "lightslategrey"; + "b0c4de": "lightsteelblue"; + "ffffe0": "lightyellow"; + "0f0": "lime"; + "32cd32": "limegreen"; + "faf0e6": "linen"; + "800000": "maroon"; + "66cdaa": "mediumaquamarine"; + "0000cd": "mediumblue"; + "ba55d3": "mediumorchid"; + "9370db": "mediumpurple"; + "3cb371": "mediumseagreen"; + "7b68ee": "mediumslateblue"; + "00fa9a": "mediumspringgreen"; + "48d1cc": "mediumturquoise"; + "c71585": "mediumvioletred"; + "191970": "midnightblue"; + "f5fffa": "mintcream"; + "ffe4e1": "mistyrose"; + "ffe4b5": "moccasin"; + "ffdead": "navajowhite"; + "000080": "navy"; + "fdf5e6": "oldlace"; + "808000": "olive"; + "6b8e23": "olivedrab"; + "ffa500": "orange"; + "ff4500": "orangered"; + "da70d6": "orchid"; + "eee8aa": "palegoldenrod"; + "98fb98": "palegreen"; + "afeeee": "paleturquoise"; + "db7093": "palevioletred"; + "ffefd5": "papayawhip"; + "ffdab9": "peachpuff"; + "cd853f": "peru"; + "ffc0cb": "pink"; + "dda0dd": "plum"; + "b0e0e6": "powderblue"; + "800080": "purple"; + "663399": "rebeccapurple"; + "f00": "red"; + "bc8f8f": "rosybrown"; + "4169e1": "royalblue"; + "8b4513": "saddlebrown"; + "fa8072": "salmon"; + "f4a460": "sandybrown"; + "2e8b57": "seagreen"; + "fff5ee": "seashell"; + "a0522d": "sienna"; + "c0c0c0": "silver"; + "87ceeb": "skyblue"; + "6a5acd": "slateblue"; + "708090": "slategray" | "slategrey"; + "fffafa": "snow"; + "00ff7f": "springgreen"; + "4682b4": "steelblue"; + "d2b48c": "tan"; + "008080": "teal"; + "d8bfd8": "thistle"; + "ff6347": "tomato"; + "40e0d0": "turquoise"; + "ee82ee": "violet"; + "f5deb3": "wheat"; + "fff": "white"; + "f5f5f5": "whitesmoke"; + "ff0": "yellow"; + "9acd32": "yellowgreen"; + }; + } - /** - * Returns the input passed into the constructer used to create the tinycolor instance. - */ - getOriginalInput(): any; // any of the interfaces in ColorFormats or a string + interface Instance { + /** + * Return an indication whether the color's perceived brightness is dark. + */ + isDark(): boolean; - /** - * Returns the alpha value of the color - */ - getAlpha(): number; + /** + * Return an indication whether the color's perceived brightness is light. + */ + isLight(): boolean; - /** - * Returns the perceived brightness of the color, from 0-255. - */ - getBrightness(): number; + /** + * Return an indication whether the color was successfully parsed. + */ + isValid(): boolean; - /** - * Returns the perceived luminance of a color, from 0-1. - */ - getLuminance(): number; + /** + * Returns the input passed into the constructer used to create the tinycolor instance. + */ + getOriginalInput(): ColorInput; - /** - * Sets the alpha value on the current color. - * - * @param alpha - The new alpha value. The accepted range is 0-1. - */ - setAlpha(alpha: number): tinycolorInstance; + /** + * Returns the format used to create the tinycolor instance. + */ + getFormat(): string; - /** - * Returns the object as a HSVA object. - */ - toHsv(): ColorFormats.HSVA; + /** + * Returns the alpha value of the color + */ + getAlpha(): number; - /** - * Returns the hsva values interpolated into a string with the following format: - * "hsva(xxx, xxx, xxx, xx)". - */ - toHsvString(): string; + /** + * Returns the perceived brightness of the color, from 0-255. + */ + getBrightness(): number; - /** - * Returns the object as a HSLA object. - */ - toHsl(): ColorFormats.HSLA; + /** + * Returns the perceived luminance of a color, from 0-1. + */ + getLuminance(): number; - /** - * Returns the hsla values interpolated into a string with the following format: - * "hsla(xxx, xxx, xxx, xx)". - */ - toHslString(): string; + /** + * Sets the alpha value on the current color. + * + * @param alpha - The new alpha value. The accepted range is 0-1. + */ + setAlpha(alpha: number): Instance; - /** - * Returns the hex value of the color. - */ - toHex(): string; + /** + * Returns the object as a HSVA object. + */ + toHsv(): ColorFormats.HSVA; - /** - * Returns the hex value of the color -with a # appened. - */ - toHexString(): string; + /** + * Returns the hsva values interpolated into a string with the following format: + * "hsva(xxx, xxx, xxx, xx)". + */ + toHsvString(): string; - /** - * Returns the hex 8 value of the color. - */ - toHex8(): string; + /** + * Returns the object as a HSLA object. + */ + toHsl(): ColorFormats.HSLA; - /** - * Returns the hex 8 value of the color -with a # appened. - */ - toHex8String(): string; + /** + * Returns the hsla values interpolated into a string with the following format: + * "hsla(xxx, xxx, xxx, xx)". + */ + toHslString(): string; - /** - * Returns the object as a RGBA object. - */ - toRgb(): ColorFormats.RGBA; + /** + * Returns the hex value of the color. + */ + toHex(): string; - /** - * Returns the RGBA values interpolated into a string with the following format: - * "RGBA(xxx, xxx, xxx, xx)". - */ - toRgbString(): string; + /** + * Returns the hex value of the color -with a # appened. + */ + toHexString(): string; - /** - * Returns the object as a RGBA object. - */ - toPercentageRgb(): ColorFormats.RGBA; + /** + * Returns the hex 8 value of the color. + */ + toHex8(): string; - /** - * Returns the RGBA relative values interpolated into a string with the following format: - * "RGBA(xxx, xxx, xxx, xx)". - */ - toPercentageRgbString(): string; + /** + * Returns the hex 8 value of the color -with a # appened. + */ + toHex8String(): string; - /** - * The 'real' name of the color -if there is one. - */ - toName(): string; + /** + * Returns the object as a RGBA object. + */ + toRgb(): ColorFormats.RGBA; - /** - * Returns the color represented as a Microsoft filter for use in old versions of IE. - */ - toFilter(): string; + /** + * Returns the RGBA values interpolated into a string with the following format: + * "RGBA(xxx, xxx, xxx, xx)". + */ + toRgbString(): string; - /** - * String representation of the color. - * - * @param format - The format to be used when displaying the string representation. - * The accepted values are: "rgb", "prgb", "hex6", "hex3", "hex8", "name", "hsl", "hsv". - */ - toString(format?: string): string; + /** + * Returns the object as a RGBA object. + */ + toPercentageRgb(): ColorFormats.PRGBA; - /** - * Lighten the color a given amount. Providing 100 will always return white. - * - * @param amount - The amount to lighten by. The valid range is 0 to 100. - * Default value: 10. - */ - lighten(amount?: number): tinycolorInstance; + /** + * Returns the RGBA relative values interpolated into a string with the following format: + * "RGBA(xxx, xxx, xxx, xx)". + */ + toPercentageRgbString(): string; - /** - * Brighten the color a given amount. - * - * @param amount - The amount to brighten by. The valid range is 0 to 100. - * Default value: 10. - */ - brighten(amount?: number): tinycolorInstance; + /** + * The 'real' name of the color -if there is one. + */ + toName(): string | false; - /** - * Darken the color a given amount. - * Providing 100 will always return black. - * - * @param amount - The amount to darken by. The valid range is 0 to 100. - * Default value: 10. - */ - darken(amount?: number): tinycolorInstance; - /** - * Desaturate the color a given amount. - * Providing 100 will is the same as calling greyscale. - * - * @param amount - The amount to desaturate by. The valid range is 0 to 100. - * Default value: 10. - */ - desaturate(amount?: number): tinycolorInstance; + /** + * Returns the color represented as a Microsoft filter for use in old versions of IE. + */ + toFilter(): string; - /** - * Saturate the color a given amount. - * - * @param amount - The amount to saturate by. The valid range is 0 to 100. - * Default value: 10. - */ - saturate(amount?: number): tinycolorInstance; + /** + * String representation of the color. + * + * @param format - The format to be used when displaying the string representation. + * The accepted values are: "rgb", "prgb", "hex6", "hex3", "hex8", "name", "hsl", "hsv". + */ + toString(format?: "rgb" | "prgb" | "hex" | "hex6" | "hex3" | "hex4" | "hex8" | "name" | "hsl" | "hsv"): string; - /** - * Completely desaturates a color into greyscale. - * Same as calling desaturate(100). - */ - greyscale(): tinycolorInstance; + /** + * Gets a new instance with the current color + */ + clone(): Instance; - /** - * Spin the hue a given amount. Calling with 0, 360, or -360 will do nothing. - * - * @param amount - The amount to spin by. The valid range is -360 to 360. - * Default value: 0. - */ - spin(amount?: number): tinycolorInstance; + /** + * Lighten the color a given amount. Providing 100 will always return white. + * + * @param amount - The amount to lighten by. The valid range is 0 to 100. + * Default value: 10. + */ + lighten(amount?: number): Instance; - /** - * Gets an analogous color scheme based off of the current color. - * - * @param results - The amount of results to return. - * Default value: 6. - * @param slices - The amount to slice the input color by. - * Default value: 30. - */ - analogous(results?: number, slices?: number): tinycolorInstance[]; + /** + * Brighten the color a given amount. + * + * @param amount - The amount to brighten by. The valid range is 0 to 100. + * Default value: 10. + */ + brighten(amount?: number): Instance; - /** - * Gets a monochromatic color scheme based off of the current color. - * - * @param results - The amount of results to return. - * Default value: 6. - */ - monochromatic(results?: number): tinycolorInstance[]; + /** + * Darken the color a given amount. + * Providing 100 will always return black. + * + * @param amount - The amount to darken by. The valid range is 0 to 100. + * Default value: 10. + */ + darken(amount?: number): Instance; + /** + * Desaturate the color a given amount. + * Providing 100 will is the same as calling greyscale. + * + * @param amount - The amount to desaturate by. The valid range is 0 to 100. + * Default value: 10. + */ + desaturate(amount?: number): Instance; - /** - * Gets a split complement color scheme based off of the current color. - */ - splitcomplement(): tinycolorInstance[]; + /** + * Saturate the color a given amount. + * + * @param amount - The amount to saturate by. The valid range is 0 to 100. + * Default value: 10. + */ + saturate(amount?: number): Instance; - /** - * Gets a triad based off of the current color. - */ - triad(): tinycolorInstance[]; + /** + * Completely desaturates a color into greyscale. + * Same as calling desaturate(100). + */ + greyscale(): Instance; - /** - * Gets a tetrad based off of the current color. - */ - tetrad(): tinycolorInstance[]; + /** + * Spin the hue a given amount. Calling with 0, 360, or -360 will do nothing. + * + * @param amount - The amount to spin by. The valid range is -360 to 360. + */ + spin(amount: number): Instance; - /** - * Gets the complement of the current color - */ - complement(): tinycolorInstance; + /** + * Gets an analogous color scheme based off of the current color. + * + * @param results - The amount of results to return. + * Default value: 6. + * @param slices - The amount to slice the input color by. + * Default value: 30. + */ + analogous(results?: number, slices?: number): Instance[]; - /** - * Gets a new instance with the current color - */ - clone(): tinycolorInstance; -} + /** + * Gets the complement of the current color + */ + complement(): Instance; -declare namespace Readable { - interface Readable { - brightness: number; - color: number; + /** + * Gets a monochromatic color scheme based off of the current color. + * + * @param results - The amount of results to return. + * Default value: 6. + */ + monochromatic(results?: number): Instance[]; + + /** + * Gets a split complement color scheme based off of the current color. + */ + splitcomplement(): [Instance, Instance, Instance]; + + /** + * Gets a triad based off of the current color. + */ + triad(): [Instance, Instance, Instance]; + + /** + * Gets a tetrad based off of the current color. + */ + tetrad(): [Instance, Instance, Instance, Instance]; } } -declare namespace ColorFormats { - interface RGB { - r: number; - g: number; - b: number; - } - - interface RGBA extends RGB { - a: number - } - - interface HSL { - h: number; - s: number; - l: number; - } - - interface HSLA extends HSL { - a: number; - } - - interface HSV { - h: number; - s: number; - v: number; - } - - interface HSVA extends HSV { - a: number; - } -} - -type ColorInput = string | ColorFormats.RGB | ColorFormats.RGBA | ColorFormats.HSL | ColorFormats.HSLA | ColorFormats.HSV | ColorFormats.HSVA | tinycolorInstance - -declare module 'tinycolor2' { - export = tinycolor; -} \ No newline at end of file +declare const tinycolor: tinycolor.Constructor; +export = tinycolor; +export as namespace tinycolor; diff --git a/types/tinycolor2/tinycolor2-tests.ts b/types/tinycolor2/tinycolor2-tests.ts index f6a6634f5f..96eb31ed23 100644 --- a/types/tinycolor2/tinycolor2-tests.ts +++ b/types/tinycolor2/tinycolor2-tests.ts @@ -1,126 +1,200 @@ - - /* * Not all possible formats for construction are displayed. * To see a complete list please view: https://github.com/bgrins/TinyColor */ -var tester: tinycolorInstance = tinycolor("red"); +const testColor: tinycolor.Instance = tinycolor("red"); /* Constructor Tests*/ // string -tester = tinycolor("#ffffff"); +// $ExpectType Instance +tinycolor("#ffffff"); -//rgb && rgba -tester = tinycolor({ r: 40, g: 30, b: 20 }); -tester = tinycolor({ r: 255, g: 20, b: 10, a: 0 }); -tester = tinycolor.fromRatio({ r: 0.5, g: 0.2, b: 1, a: 0 }); -tester = tinycolor.fromRatio({ r: 1, g: 0, b: 0.7, a: 0 }); +// rgb && rgba +// $ExpectType Instance +tinycolor({ r: 40, g: 30, b: 20 }); +// $ExpectType Instance +tinycolor({ r: 255, g: 20, b: 10, a: 0 }); +// $ExpectType Instance +tinycolor.fromRatio({ r: 0.5, g: 0.2, b: 1, a: 0 }); +// $ExpectType Instance +tinycolor.fromRatio({ r: 1, g: 0, b: 0.7, a: 0 }); -//hsl && hsla -tester = tinycolor({ h: 0, s: 0, l: 0 }); -tester = tinycolor({ h: 0, s: 0, l: 0, a: 0 }); -tester = tinycolor.fromRatio({ h: 0.5, s: 0.2, l: 1, a: 0 }); +// hsl && hsla +// $ExpectType Instance +tinycolor({ h: 0, s: 0, l: 0 }); +// $ExpectType Instance +tinycolor({ h: 0, s: 0, l: 0, a: 0 }); +// $ExpectType Instance +tinycolor.fromRatio({ h: 0.5, s: 0.2, l: 1, a: 0 }); -//hsv && hsva -tester = tinycolor({ h: 0, s: 0, v: 0 }); -tester = tinycolor({ h: 0, s: 0, v: 0, a: 0 }); +// hsv && hsva +// $ExpectType Instance +tinycolor({ h: 0, s: 0, v: 0 }); +// $ExpectType Instance +tinycolor({ h: 0, s: 0, v: 0, a: 0 }); -//tinycolor static methods -tester = tinycolor.mix(tester, tester); -tester = tinycolor.mix("#ff0000", "#00ff00"); -tester = tinycolor.mix(tester, tester, 50); -tester = tinycolor.random(); -var isEqual = tinycolor.equals(tester, tester); +// tinycolor static methods +// $ExpectType Instance +tinycolor.mix(testColor, testColor); +// $ExpectType Instance +tinycolor.mix("#ff0000", "#00ff00"); +// $ExpectType Instance +tinycolor.mix(testColor, testColor, 50); +// $ExpectType Instance +tinycolor.random(); -/*Tinycolor object properties*/ +// $ExpectType boolean +tinycolor.equals(testColor, testColor); -var readable: Readable.Readable = tinycolor.readability(tester, tester); -var isReadable: boolean = tinycolor.isReadable(tester, tester); -var isReadable: boolean = tinycolor.isReadable(tester, tester, {size: "small"}); -tester = tinycolor.mostReadable(tester, [tester, tester, tester]); -tester = tinycolor.mostReadable(tester, [tester, tester, tester], {size: "large", level:"AA"}); +// $ExpectType number +tinycolor.readability(testColor, testColor); +// $ExpectType boolean +tinycolor.isReadable(testColor, testColor); +// $ExpectType boolean +tinycolor.isReadable(testColor, testColor, {size: "small"}); +// $ExpectType Instance +tinycolor.mostReadable(testColor, [testColor, testColor, testColor]); +// $ExpectType Instance +tinycolor.mostReadable(testColor, [testColor, testColor, testColor], {size: "large", level: "AA"}); -var hexNames: { [key: string]: string } = tinycolor.hexNames; -var names: { [key: string]: string } = tinycolor.names; +const hexNames: { [key: string]: string } = tinycolor.hexNames; +const names: { [key: string]: string } = tinycolor.names; +// $ExpectType "linen" +tinycolor.hexNames["faf0e6"]; +// $ExpectType "yellow" +tinycolor.hexNames["ff0"]; +// $ExpectType "f0f8ff" +tinycolor.names["aliceblue"]; +// $ExpectType "808080" +tinycolor.names["gray"]; -/*Instance Methods*/ +/* Instance Methods */ -//check properties -var isValid: boolean = tester.isValid(); -var isLight: boolean = tester.isLight(); -var isDark: boolean = tester.isDark(); +// check properties +// $ExpectType boolean +testColor.isValid(); +// $ExpectType boolean +testColor.isLight(); +// $ExpectType boolean +testColor.isDark(); -//get properties -var alpha: number = tester.getAlpha(); -var brightness: number = tester.getBrightness(); -var format: string = tester.getFormat(); -var originalInput: any = tester.getOriginalInput(); +// get properties +const alpha: number = testColor.getAlpha(); +// $ExpectType number +testColor.getBrightness(); +// $ExpectType string +testColor.getFormat(); +// $ExpectType ColorInput +testColor.getOriginalInput(); -//set properties -tester = tester.setAlpha(alpha); +// set properties +// $ExpectType Instance +testColor.setAlpha(alpha); -//representations -var hsva: ColorFormats.HSVA = tester.toHsv(); -var hsvString: string = tester.toHsvString(); +// representations +// $ExpectType HSVA +testColor.toHsv(); +// $ExpectType string +testColor.toHsvString(); -var hsl: ColorFormats.HSLA = tester.toHsl(); -var hslString: string = tester.toHslString(); +// $ExpectType HSLA +testColor.toHsl(); +// $ExpectType string +testColor.toHslString(); -var hex: string = tester.toHex(); -var hexString: string = tester.toHexString(); +// $ExpectType string +testColor.toHex(); +// $ExpectType string +testColor.toHexString(); -var hex8: string = tester.toHex8(); -var hex8String: string = tester.toHex8String(); +// $ExpectType string +testColor.toHex8(); +// $ExpectType string +testColor.toHex8String(); -var rgba: ColorFormats.RGBA = tester.toRgb(); -var rgbString: string = tester.toString(); +// $ExpectType RGBA +testColor.toRgb(); +// $ExpectType string +testColor.toString(); -var percentageRGBA: ColorFormats.RGBA = tester.toPercentageRgb(); -var percentageRGBString: string = tester.toPercentageRgbString(); +// $ExpectType PRGBA +testColor.toPercentageRgb(); +// $ExpectType string +testColor.toPercentageRgbString(); -var name_: string = tester.toName(); -var filter: string = tester.toFilter(); -var sString: string = tester.toString(); -sString = tester.toString("rgb"); -sString = tester.toString("prgb"); -sString = tester.toString("hex6"); -sString = tester.toString("hex3"); -sString = tester.toString("hex8"); -sString = tester.toString("name"); -sString = tester.toString("hsl"); -sString = tester.toString("hsv"); +// $ExpectType string | false +testColor.toName(); +// $ExpectType string +testColor.toFilter(); +// $ExpectType string +testColor.toString(); +// $ExpectType string +testColor.toString("rgb"); +// $ExpectType string +testColor.toString("prgb"); +// $ExpectType string +testColor.toString("hex6"); +// $ExpectType string +testColor.toString("hex3"); +// $ExpectType string +testColor.toString("hex8"); +// $ExpectType string +testColor.toString("name"); +// $ExpectType string +testColor.toString("hsl"); +// $ExpectType string +testColor.toString("hsv"); -//color modifications -tester = tester.lighten(); -tester = tester.lighten(20); +// color modifications +// $ExpectType Instance +testColor.lighten(); +// $ExpectType Instance +testColor.lighten(20); -tester = tester.brighten(); -tester = tester.brighten(20); +// $ExpectType Instance +testColor.brighten(); +// $ExpectType Instance +testColor.brighten(20); -tester = tester.darken(); -tester = tester.darken(20); +// $ExpectType Instance +testColor.darken(); +// $ExpectType Instance +testColor.darken(20); -tester = tester.desaturate(); -tester = tester.desaturate(20); +// $ExpectType Instance +testColor.desaturate(); +// $ExpectType Instance +testColor.desaturate(20); -tester = tester.saturate(); -tester = tester.saturate(20); +// $ExpectType Instance +testColor.saturate(); +// $ExpectType Instance +testColor.saturate(20); -tester = tester.spin(); -tester = tester.spin(20); +// $ExpectType Instance +testColor.spin(20); -tester = tester.greyscale(); +// $ExpectType Instance +testColor.greyscale(); -//color combinations -var colors: tinycolorInstance[] = tester.analogous(); -colors = tester.analogous(6, 30); +// color combinations +// $ExpectType Instance[] +testColor.analogous(); +// $ExpectType Instance[] +testColor.analogous(6, 30); -colors = tester.monochromatic(); -colors = tester.monochromatic(10); +// $ExpectType Instance[] +testColor.monochromatic(); +// $ExpectType Instance[] +testColor.monochromatic(10); -colors = tester.splitcomplement(); -colors = tester.triad(); -colors = tester.tetrad(); +// $ExpectType [Instance, Instance, Instance] +testColor.splitcomplement(); +// $ExpectType [Instance, Instance, Instance] +testColor.triad(); +// $ExpectType [Instance, Instance, Instance, Instance] +testColor.tetrad(); -tester = tester.complement(); \ No newline at end of file +// $ExpectType Instance +testColor.complement(); diff --git a/types/tinycolor2/tslint.json b/types/tinycolor2/tslint.json index a41bf5d19a..64aace11d6 100644 --- a/types/tinycolor2/tslint.json +++ b/types/tinycolor2/tslint.json @@ -1,79 +1,6 @@ { "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 + "max-line-length": false } } diff --git a/types/twit/index.d.ts b/types/twit/index.d.ts index c0367da976..ce8484bbe1 100644 --- a/types/twit/index.d.ts +++ b/types/twit/index.d.ts @@ -4,6 +4,7 @@ // sapphiredev // abraham // siwalik +// plhery // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -262,7 +263,7 @@ declare module 'twit' { user_id?: number | string, lat?: number, long?: number, - follow?: boolean, + follow?: boolean | string, include_email?: boolean, cursor?: number | string, tweet_mode?: string, @@ -271,6 +272,8 @@ declare module 'twit' { include_rts?: boolean, skip_status?: boolean, url?: string, + include_user_entities?: boolean, + stringify_ids?: boolean, } export interface PromiseResponse { data: Response, diff --git a/types/umzug/index.d.ts b/types/umzug/index.d.ts index f74c5933be..a163ea01d9 100644 --- a/types/umzug/index.d.ts +++ b/types/umzug/index.d.ts @@ -1,13 +1,15 @@ -// Type definitions for Umzug v2.1.0 +// Type definitions for Umzug v2.2.0 // Project: https://github.com/sequelize/umzug // Definitions by: Ivan Drinchev // Margus Lamp // Troy McKinnon +// Emmanuel Gautier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { EventEmitter } from 'events'; import Sequelize = require("sequelize"); +import MongoDB = require("mongodb"); declare namespace umzug { @@ -116,6 +118,27 @@ declare namespace umzug { } + interface MongoDBStorageOptions extends Storage { + + /** + * The MongoDB database connection instance. + */ + connection?: MongoDB.Db; + + /** + * The to be used Mongo collection cursor. + * Defaults to collection created from collectionName attribute. + */ + collection?: MongoDB.Collection; + + /** + * The name of the collection used by the connection. + * Defaults to 'migrations' + */ + collectionName?: string; + + } + interface ExecuteOptions { migrations?: Array; method?: string; @@ -125,12 +148,12 @@ declare namespace umzug { /** * The storage. */ - storage?: "json" | "sequelize" | Storage; + storage?: "json" | "sequelize" | "mongodb" | Storage; /** * The options for the storage. */ - storageOptions?: JSONStorageOptions | SequelizeStorageOptions | Object; + storageOptions?: JSONStorageOptions | SequelizeStorageOptions | MongoDBStorageOptions | Object; /** * The logging function. diff --git a/types/umzug/umzug-tests.ts b/types/umzug/umzug-tests.ts index 95ccf15665..730f350315 100644 --- a/types/umzug/umzug-tests.ts +++ b/types/umzug/umzug-tests.ts @@ -1,5 +1,6 @@ import Umzug = require('umzug'); import Sequelize = require('sequelize'); +import MongoDB = require('mongodb'); let someVar: Umzug.Umzug; const umzug = new Umzug({}); @@ -44,7 +45,7 @@ umzug.on('reverted', (name: string, migration: Umzug.Migration) => null); new Umzug({ // The storage. - // Possible values: 'json', 'sequelize', an object + // Possible values: 'json', 'sequelize', 'mongodb' an object storage: 'json', // The options for the storage. @@ -80,7 +81,7 @@ new Umzug({ new Umzug({ // The storage. - // Possible values: 'json', 'sequelize', an object + // Possible values: 'json', 'sequelize', 'mongodb' an object storage: 'json', storageOptions: { path: '/db/sequelize-meta.json', @@ -121,3 +122,30 @@ new Umzug({ }, }); + +const mongodb = new MongoDB.Db('database', new MongoDB.Server('host', 21017)); + +new Umzug({ + // The storage. + // Possible values: 'json', 'sequelize', 'mongodb' an object + storage: 'mongodb', + storageOptions: { + /** + * The MongoDB database connection instance. + */ + connection: mongodb, + + /** + * The to be used Mongo collection cursor. + * Defaults to collection created from collectionName attribute. + */ + collection: mongodb.collection, + + /** + * The name of the collection used by the connection. + * Defaults to 'migrations' + */ + collectionName: 'migrations' + }, + +}); diff --git a/types/uri-templates/index.d.ts b/types/uri-templates/index.d.ts index ad8cead946..d378de8a4f 100644 --- a/types/uri-templates/index.d.ts +++ b/types/uri-templates/index.d.ts @@ -1,16 +1,19 @@ -// Type definitions for uri-templates 0.1.2 +// Type definitions for uri-templates 0.1.9 // Project: https://github.com/geraintluff/uri-templates // Definitions by: Bart van der Schoor +// Bartek Szczepański // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - declare function utpl(template: string): utpl.URITemplate; declare namespace utpl { export interface URITemplate { - fillFromObject(vars: Object): string; + fillFromObject(vars: { [key: string]: string }): string; fill(callback: (varName: string) => string): string; - fromUri(uri: string): Object; + fill(vars: { [key: string]: string }): string; + fromUri(uri: string): { [key: string]: string }; + varNames: string[]; + template: string; } } diff --git a/types/uri-templates/uri-templates-tests.ts b/types/uri-templates/uri-templates-tests.ts index 0aeb5e0bfe..d29b801de1 100644 --- a/types/uri-templates/uri-templates-tests.ts +++ b/types/uri-templates/uri-templates-tests.ts @@ -1,15 +1,23 @@ - import utmpl = require('uri-templates'); import URITemplate = utmpl.URITemplate; -var str: string; -var u: URITemplate; -var obj: Object; +let str: string; +let u: URITemplate; +const obj = { test: 'test1' }; u = utmpl(str); str = u.fillFromObject(obj); -str = u.fill((key) => { - return str; +str = u.fill(key => { + return str; }); -obj = u.fromUri(str); +str = u.fill(obj); +const newObj = u.fromUri(str); + +let varNames: string[]; + +varNames = u.varNames; + +let template: string; + +template = u.template; diff --git a/types/url-regex/index.d.ts b/types/url-regex/index.d.ts index ed51c6e34d..58f3793baa 100644 --- a/types/url-regex/index.d.ts +++ b/types/url-regex/index.d.ts @@ -1,12 +1,15 @@ -// Type definitions for url-regex 4.0 +// Type definitions for url-regex 4.1 // Project: https://github.com/kevva/url-regex // Definitions by: Daniel Perez Alvarez +// sosukesuzuki // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** Regular expression for matching URLs. */ declare function urlRegex(options?: { /** Only match an exact string. Useful with RegExp#test to check if a string is a URL. */ exact?: boolean; + /** Force URLs to start with a valid protocol or www. If set to false it'll match the TLD against a list of valid TLDs(https://github.com/stephenmathieson/node-tlds). */ + strict?: boolean; }): RegExp; export = urlRegex; diff --git a/types/url-regex/url-regex-tests.ts b/types/url-regex/url-regex-tests.ts index 2a2db45a28..de62d9a796 100644 --- a/types/url-regex/url-regex-tests.ts +++ b/types/url-regex/url-regex-tests.ts @@ -8,4 +8,6 @@ urlRegex({exact: true}).test('https://github.com foo bar'); urlRegex({exact: true}).test('https://github.com'); +urlRegex({exact: true, strict: false}).test('github.com'); + 'foo https://github.com bar //google.com'.match(urlRegex()); diff --git a/types/valiant/index.d.ts b/types/valiant/index.d.ts new file mode 100644 index 0000000000..d63aff72c5 --- /dev/null +++ b/types/valiant/index.d.ts @@ -0,0 +1,51 @@ +// Type definitions for valiant 2.0 +// Project: https://github.com/tweetdeck/valiant#readme +// Definitions by: whatasoda +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export as namespace Valiant; + +export function createInterval(compareValues?: IntervalConstructor['compareValues']): IntervalConstructor; + +export interface IntervalConstructor { + new (from: Endpoint, to: Endpoint): Interval; + prototype: Interval; + empty: Interval; + whole: Interval; + negInf: Endpoint; + posInf: Endpoint; + negativeInfinity: Endpoint; + positiveInfinity: Endpoint; + adjacentEndpoint(endpoint: Endpoint): Endpoint; + compareEndpoints(a: Endpoint, b: Endpoint): number; + compareValues(a: T, b: T): number; + excEnd(value: T): Endpoint; + exclusiveEndpoint(value: T): Endpoint; + incEnd(value: T): Endpoint; + inclusiveEndpoint(value: T): Endpoint; + singleton(value: T): Interval; +} + +export interface Interval { + constructor: IntervalConstructor; + empty: boolean; + from: Endpoint; + to: Endpoint; + hull(interval: Interval): Interval; + unify(interval: Interval): Interval; + isEmpty(): boolean; + equalTo(interval: Interval): boolean; + contains(value: T): boolean; + isSubsetOf(interval: Interval): boolean; + intersection(interval: Interval): boolean; + contiguousWith(interval: Interval): boolean; + fromComparator(a: Endpoint, b: Endpoint): number; + toComparator(a: Endpoint, b: Endpoint): number; +} + +export interface Endpoint { + finite: boolean; + inclusive: boolean; + value: T; +} diff --git a/types/valiant/tsconfig.json b/types/valiant/tsconfig.json new file mode 100644 index 0000000000..8cac2a107b --- /dev/null +++ b/types/valiant/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", + "valiant-tests.ts" + ] +} diff --git a/types/valiant/tslint.json b/types/valiant/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/valiant/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/valiant/valiant-tests.ts b/types/valiant/valiant-tests.ts new file mode 100644 index 0000000000..ff0383cb09 --- /dev/null +++ b/types/valiant/valiant-tests.ts @@ -0,0 +1,53 @@ +import { createInterval } from "valiant"; + +// To make an Interval, you need to create a constructor: +const Interval = createInterval(); + +// By default it will manage integers: +// (0,100] — the numbers 0 to 100, excluding 0 +new Interval( + Interval.exclusiveEndpoint(0), + Interval.inclusiveEndpoint(100) +); + +// You can provide a custom sort function to support a different data type: +const DateInterval = createInterval(function sortDates(a, b) { + return a.getTime() - b.getTime(); +}); + +// [12 hours ago,now] — 12 hours ago until now +new DateInterval( + DateInterval.incEnd( + new Date(Date.now() - (1000 * 60 * 60 * 12)) + ), + DateInterval.incEnd( + new Date(Date.now()) + ) +); + +// You can do calculations with two intervals: +const i = new Interval(Interval.incEnd(1), Interval.incEnd(3)); +const j = new Interval(Interval.incEnd(2), Interval.incEnd(4)); +const k = new Interval(Interval.incEnd(5), Interval.incEnd(6)); + +i.intersection(j); // 2, 3 +i.hull(j); // 1, 4 +i.contiguousWith(j); // true +i.unify(j); // 1, 4 + +i.intersection(k); // Interval.empty +i.hull(k); // 1, 6 +i.contiguousWith(k); // false +i.unify(k); // Interval.empty + +i.equalTo(j); // false +i.contains(2); // true +i.isSubsetOf(j); // false + +// If there is no possible unification, the empty set (Interval.empty) results. +// There are two special intervals: +Interval.empty; // {} +Interval.whole; // -Infinity, Infinity + +// You can also create an interval of value: +Interval.singleton(5); // [5,5] diff --git a/types/velocity-animate/index.d.ts b/types/velocity-animate/index.d.ts index f6b696870f..24dc53b4be 100644 --- a/types/velocity-animate/index.d.ts +++ b/types/velocity-animate/index.d.ts @@ -87,8 +87,8 @@ declare namespace jquery.velocity { interface VelocityStatic { Sequences: any; mock: any; - animate(options: {elements: NodeListOf; properties: Properties; options: Options}): any; - animate(elements: HTMLElement|NodeListOf, properties: Properties, options: Options): any; + animate(options: {elements: HTMLCollection | NodeListOf; properties: Properties; options: Options}): any; + animate(elements: HTMLElement | HTMLCollection | NodeListOf, properties: Properties, options: Options): any; RegisterEffect(name: string, options: RegisterEffectOptions): VelocityStatic; RunSequence(sequence: SequenceCall[]): VelocityStatic; diff --git a/types/vexflow/index.d.ts b/types/vexflow/index.d.ts index 714cfe5c0a..c25ac00958 100644 --- a/types/vexflow/index.d.ts +++ b/types/vexflow/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for VexFlow v1.2.84 +// Type definitions for VexFlow v1.2.85 // Project: http://vexflow.com // Definitions by: Roman Quiring // Sebastian Haas // Basti Hoffmann +// Simon Schmid // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped //inconsistent namespace: this is a helper funtion from tables.js and should not pollute the global namespace! @@ -553,6 +554,7 @@ declare namespace Vex { setYShift(y : number) : Modifier; setXShift(x : number) : void; //inconsistent type: void -> Modifier draw() : void; + alignSubNotesWithNote(subNotes : Note[], note : Note) : void; } namespace Modifier { @@ -690,6 +692,11 @@ declare namespace Vex { draw() : void; } + class NoteSubGroup extends Modifier { + constructor(subnotes : Note[]); + preFormat() : void; + } + class Ornament extends Modifier { constructor(type : string); static DEBUG : boolean; @@ -1295,6 +1302,10 @@ declare namespace Vex { getWidth() : number; getX() : number; setX(x : number) : TickContext; + getXBase() : number; + setXBase(xBase : number) : void; + getXOffset() : number; + setXOffset(xOffset : number) : void; getPixelsUsed() : number; setPixelsUsed(pixelsUsed : number) : TickContext; setPadding(padding : number) : TickContext; diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index 6f152a9fcb..5b245440bd 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -5,7 +5,7 @@ // Krzysztof Cebula // Vitaliy Polyanskiy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.8 /// diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index f18ff8890e..8ac320d190 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Video.js 6.2 +// Type definitions for Video.js 7.2 // Project: https://github.com/videojs/video.js // Definitions by: Vincent Bortone // Simon Clériot @@ -15,285 +15,6629 @@ // Javascript, whether the browser is playing the video through HTML5 // video, Flash, or any other supported playback technologies. -declare function videojs( - id: any, - options?: videojs.PlayerOptions, - ready?: () => void -): videojs.Player; -export default videojs; +/** + * Doubles as the main function for users to create a inplayer instance and also + * the main library object. + * The `videojs` function can be used to initialize or retrieve a player. + * + * @param id + * Video element or video element ID + * + * @param [options] + * Optional options object for config/settings + * + * @param [ready] + * Optional ready callback + * + * @return A player instance + */ +declare function videojs(id: any, options?: videojs.PlayerOptions, ready?: () => void): videojs.Player; +export = videojs; export as namespace videojs; declare namespace videojs { - const getComponent: typeof Component.getComponent; - const registerComponent: typeof Component.registerComponent; - const getPlugin: typeof Plugin.getPlugin; - function registerPlugin( - pluginName: string, - pluginFn: (this: Player, ...parameters: any[]) => void - ): void; - function addLanguage(lang: string, data: { [key: string]: string }): void; - function mergeOptions( - option: A, - option2?: B, - option3?: C, - option4?: D, - option5?: E, - option6?: F - ): A & B & C & D & E & F; + /** + * Adding languages so that they're available to all players. + * Example: `addLanguage('es', { 'Hello': 'Hola' });` + * + * @param code + * The language code or dictionary property + * + * @param data + * The data values to be translated + * + * @return The resulting language dictionary object + */ + function addLanguage(code: string, data: LanguageTranslations): LanguageTranslations; - interface PlayerOptions { - aspectRatio?: string; - autoplay?: boolean; - autoSetup?: boolean; - children?: string[]; - controlBar?: { - volumePanel?: { - inline?: boolean; - vertical?: boolean; - }; - }; - controls?: boolean; - defaultVolume?: number; - fluid?: boolean; - height?: number; - html5?: any; - inactivityTimeout?: number; - language?: string; - languages?: { [key: string]: string }; - loop?: boolean; - muted?: boolean; - nativeControlsForTouch?: boolean; - notSupportedMessage?: string; - playbackRates?: number[]; - plugins?: any; - poster?: string; - preload?: string; - sourceOrder?: boolean; - sources?: Source[]; - src?: string; - techCanOverridePoster?: boolean; - techOrder?: string[]; - width?: number; - } + /** + * Bind (a.k.a proxy or Context). A simple method for changing the context of a function + * It also stores a unique id on the function so it can be easily removed from events. + * + * @param context + * The object to bind as scope. + * + * @param fn + * The function to be bound to a scope. + * + * @param [uid] + * An optional unique ID for the function to be set + * + * @return The new function that will be bound into the context given + */ + function bind any)>(context: any, fn: F, uid?: number): F; - interface Source { - type: string; - src: string; - } + /** + * Should create a fake `TimeRange` object which mimics an HTML5 time range instance. + * + * @param start + * The start of a single range or an array of ranges + * + * @param end + * The end of a single range. + */ + function createTimeRanges(start?: number | TimeRange[], end?: number): TimeRange; - interface Dimensions { - width: number; - height: number; - } + /** + * A suite of browser and device tests from {@link browser}. + * + */ + const browser: Browser; - class EventTarget { - addEventListener( - type: string | string[], - callback: (eventObject: Event) => void - ): void; - dispatchEvent(event: string | Event | { [key: string]: any }): void; - off( - type?: string | string[], - callback?: (eventObject: Event) => void - ): void; - on( - type: string | string[], - callback: (eventObject: Event) => void - ): void; - one( - type: string | string[], - callback: (eventObject: Event) => void - ): void; - removeEventListener( - type?: string | string[], - callback?: (eventObject: Event) => void - ): void; - trigger(event: string | Event | { [key: string]: any }): void; - } + const dom: Dom; - class Component extends EventTarget { - constructor(player: Player, options: any); + /** + * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in seconds) + * will force a number of leading zeros to cover the length of the guide. + * + * @param seconds + * Number of seconds to be turned into a string + * + * @param guide + * Number (in seconds) to model the string after + * + * @return Time formatted as H:MM:SS or M:SS + */ + function formatTime(seconds: number, guide: number): string; - static getComponent(name: "Player" | "player"): typeof Player; - static getComponent(name: "Button" | "button"): typeof Button; - static getComponent( - name: "ClickableComponent" | "clickablecomponent" - ): typeof ClickableComponent; - static getComponent( - name: "ModalDialog" | "modaldialog" - ): typeof ModalDialog; - static getComponent( - name: "ControlBar" | "controlbar" - ): typeof ControlBar; - static getComponent( - name: "Component" | "component" | string - ): typeof Component; - static registerComponent( - name: string, - ComponentToRegister: typeof Component - ): typeof Component; + /** + * Returns an array of all current players. + * + * @return An array of all players. The array will be in the order that + * `Object.keys` provides, which could potentially vary between + * JavaScript engines. + * + */ + function getAllPlayers(): Player[]; - $(selector: string, context?: string | Element): Element; - $$(selector: string, context?: string | Element): NodeList; - addChild( - component: string, - optionsopt?: any, - indexopt?: number - ): Component; - addChild( - component: Element, - optionsopt?: any, - indexopt?: number - ): Element; - addChild( - component: T, - optionsopt?: any, - indexopt?: number - ): T; - addClass(classToAdd: string): void; - blur(): void; - buildCSSClass(): string; - cancelAnimationFrame(id: number): number; - children(): Component[]; - controlText(key: string): string; - clearInterval(intervalId: number): number; - clearTimeout(timeoutId: number): number; - contentEl(): Element; - createEl( - tagNameopt?: string, - properties?: any, - attributes?: any - ): Element; - currentDimension(widthOrHeight: "width" | "height"): number; - currentDimensions(): Dimensions; - currentHeight(): number; - currentWidth(): number; - dimension(widthOrHeight: "width" | "height"): number; - dimension( - widthOrHeight: "width" | "height", - num: string | number, - skipListenersopt?: boolean - ): void; - dimensions(width: string | number, height: string | number): void; - dispose(): void; - el(): Element; - enableTouchActivity(): void; - focus(): void; - getAttribute(attribute: string): string | null; - getChild(name: string): Component | undefined; - getChildById(id: string): Component | undefined; - hasClass(classToCheck: string): boolean; - height(): number | string; - height(num: number | string, skipListeners?: boolean): void; - hide(): void; - id(): string; - initChildren(): void; - localize(key: string, tokens?: string[], defaultValue?: string): string; - name(): string; - options(obj: any): any; - played(): TimeRanges; - player(): Player; - ready(callback: (this: this) => void): this; - removeAttribute(attribute: string): void; - removeChild(component: Component): void; - removeClass(classToRemove: string): void; - requestAnimationFrame(fn: () => void): number; - setAttribute(attribute: string, value: string): void; - setInterval(fn: () => void, interval: number): number; - setTimeout(fn: () => void, timeout: number): number; - show(): void; - toggleClass( - classToToggle: string, - predicate?: - | boolean - | ((element: Element, classToToggle: string) => boolean) - ): void; - trigger(eventName: string, ...parameters: any[]): void; - triggerReady(): void; - width(): string | number; - width(num: number, skipListeners?: number): void; - } + /** + * Get a component class object by name + * + * @borrows Component.getComponent as getComponent + */ + const getComponent: typeof Component.getComponent; - class ControlBar extends Component {} + /** + * Get a single player based on an ID or DOM element. + * + * This is useful if you want to check if an element or ID has an associated + * Video.js player, but not create one if it doesn't. + * + * @param id + * An HTML element - `