Merge pull request #4 from DefinitelyTyped/master

Sync
This commit is contained in:
Dominik Palo
2019-01-31 13:49:49 +01:00
committed by GitHub
2995 changed files with 225719 additions and 46424 deletions

View File

@@ -5,5 +5,5 @@ indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
[{*.json,*.yml,*.ts}]
[{*.json,*.yml,*.ts,*.tsx,*.md}]
indent_style = space

1108
.github/CODEOWNERS vendored

File diff suppressed because it is too large Load Diff

105
README.md
View File

@@ -1,12 +1,23 @@
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
[![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
# DefinitelyTyped
> The repository for *high quality* TypeScript type definitions.
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) and [Korean!](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md)*
*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md), [Korean](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md), and [Russian](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md)!*
## Current status
This section tracks the health of the repository and publishing process.
It may be helpful for contributors experiencing any issues with their PRs and packages.
* All packages are type-checking/linting cleanly: [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
* All packages are being published to npm in under 10,000 seconds: [![Publish Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13)
* [typescript-bot](https://github.com/typescript-bot) has been active on DefinitelyTyped [![Activity Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14)
If anything here seems wrong, or any of the above are failing, please raise an issue in [the DefinitelyTyped Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped).
[![Join the chat at https://gitter.im/DefinitelyTyped/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/DefinitelyTyped/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
## What are declaration files?
@@ -169,8 +180,14 @@ If a package was never on DefinitelyTyped, it does not need to be added to `notN
#### Lint
To lint a package, just add a `tslint.json` to that package containing `{ "extends": "dtslint/dt.json" }`. All new packages must be linted.
If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. For example:
All new packages must be linted. To lint a package, add a `tslint.json` to that package containing
```js
{
"extends": "dtslint/dt.json"
}
```
This should be the only content in a finished project's `tslint.json` file. If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. For example:
```js
{
@@ -238,17 +255,71 @@ Here are the [currently requested definitions](https://github.com/DefinitelyType
If types are part of a web standard, they should be contributed to [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) so that they can become part of the default `lib.dom.d.ts`.
#### Should I add an empty namespace to a package that doesn't export a module to use ES6 style imports?
Some packages, like [chai-http](https://github.com/chaijs/chai-http), export a function.
Importing this module with an ES6 style import in the form `import * as foo from "foo";` leads to the error:
> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct
This error can be suppressed by merging the function declaration with an empty namespace of the same name, but this practice is discouraged.
This is a commonly cited [Stack Overflow answer](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) regarding this matter.
It is more appropriate to import the module using the `import foo = require("foo");` syntax.
Nevertheless, if you want to use a default import like `import foo from "foo";` you have two options:
- you can use the [`--allowSyntheticDefaultImports` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs) if your module runtime supports an interop scheme for non-ECMAScript modules, i.e. if default imports work in your environment (e.g. Webpack, SystemJS, esm).
- you can use the [`--esModuleInterop` compiler option](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop) if you want TypeScript to take care of non-ECMAScript interop (since Typescript 2.7).
#### A package uses `export =`, but I prefer to use default imports. Can I change `export =` to `export default`?
If you are using TypeScript 2.7 or later, use `--esModuleInterop` in your project.
Otherwise, if default imports work in your environment (e.g. Webpack, SystemJS, esm), consider turning on the [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) compiler option.
Like in the previous question, refer to using either the [`--allowSyntheticDefaultImports`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-8.html#support-for-default-import-interop-with-systemjs)
or [`--esModuleInterop`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop)
compiler options.
Do not change the type definition if it is accurate.
For an NPM package, `export =` is accurate if `node -p 'require("foo")'` is the export, and `export default` is accurate if `node -p 'require("foo").default'` is the export.
For an NPM package, `export =` is accurate if `node -p 'require("foo")'` works to import a module, and `export default` is accurate if `node -p 'require("foo").default'` works to import a module.
#### I want to use features from TypeScript 2.1 or above.
Then you will have to add a comment to the last line of your definition header (after `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`.
#### I want to use features from TypeScript 3.1 or above.
You can use the same `// TypeScript Version: 3.1` comment as above.
However, if your project needs to maintain types that are compatible with 3.1 and above *at the same time as* types that are compatible with 3.0 or below, you will need to use the `typesVersions` feature, which is available in TypeScript 3.1 and above.
You can find a detailed explanation of this feature in the [official TypeScript documentation](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-1.html#version-selection-with-typesversions).
Here's a short explanation to get you started:
1. You'll have to add a `package.json` file to your package definition, with the following contents:
```json
{
"private": true,
"types": "index",
"typesVersions": {
">=3.1.0-0": { "*": ["ts3.1/*"] }
}
}
```
2. Create the sub-directory mentioned in the `typesVersions` field inside your types directory (`ts3.1/` in this example)
and add the types and tests specific for the new TypeScript version. You don't need the typical definition header
in any of the files from the `ts3.1/` directory.
3. Set the `baseUrl` and `typeRoots` options in `ts3.1/tsconfig.json` to the correct paths, they should look something like this:
```json
{
"compilerOptions": {
"baseUrl": "../../",
"typeRoots": ["../../"]
}
}
```
You can look [here](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/debounce-promise) and [here](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/create-html-element) for examples.
#### I want to add a DOM API not present in TypeScript by default.
This may belong in [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). See the guidelines there.
@@ -316,19 +387,6 @@ When `dts-gen` is used to scaffold a scoped package, the `paths` property has to
GitHub doesn't [support](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) file history for renamed files. Use [`git log --follow`](https://www.git-scm.com/docs/git-log) instead.
#### Should I add an empty namespace to a package that doesn't export a module to use ES6 style imports?
Some packages, like [chai-http](https://github.com/chaijs/chai-http), export a function.
Importing this module with an ES6 style import in the form `import * as foo from "foo";` leads to the error:
> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct
This error can be suppressed by merging the function declaration with an empty namespace of the same name, but this practice is discouraged.
This is a commonly cited [Stack Overflow answer](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) regarding this matter.
It is more appropriate to import the module using the `import foo = require("foo");` syntax, or to use a default import like `import foo from "foo";` if using the `--allowSyntheticDefaultImports` flag if your module runtime supports an interop scheme for non-ECMAScript modules as such.
## License
This project is licensed under the MIT license.
@@ -336,6 +394,3 @@ This project is licensed under the MIT license.
Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file.
[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon)
[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) Are packages being published to npm in less than 10,000 seconds on average?
[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Has typescript-bot been active on DefinitelyTyped in the last two hours?

353
README.ru.md Normal file
View File

@@ -0,0 +1,353 @@
<!-- markdownlint-disable MD001 MD012 MD026 -->
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
[![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
> Репозиторий для *высококачественных* определений типов TypeScript.
Также посетите веб-сайт [definitelytyped.org](http://definitelytyped.org), хотя информация в этом README более свежая.
*Вы также можете прочитать этот README на [английском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md), [испанском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) и [корейском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md).*
## Что такое файлы декларации (файлы описания/объявления типов)?
Смотрите [руководство по TypeScript](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).
## Как их получить?
### npm
Это предпочтительный метод. Это доступно только для пользователей TypeScript 2.0+. Например:
```sh
npm install --save-dev @types/node
```
Затем типы должны автоматически включаться компилятором.
Подробнее смотрите в [справочнике](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html).
Для пакета NPM "foo", описания будут находиться в "@types/foo".
Если вы не можете найти свой пакет, ищите его в [TypeSearch](https://microsoft.github.io/TypeSearch/).
Если вы все еще не можете найти его, проверьте [включает](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) ли пакет собственную типизацию.
Обычно это отражается в поле `"types"` или `"typings"` файла `package.json`, или просто ищите любые файлы ".d.ts" в пакете и вручную включайте их в `/// <reference path="" />`.
### Другие методы
Эти методы могут быть использованы TypeScript 1.0.
* [Typings](https://github.com/typings/typings)
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (используйте предпочтительные альтернативы, публикация типа nuget DT отключена)
* Вручную загрузите из ветки `master` этого репозитория
Возможно, вам придется добавить ручные [ссылки](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
## Как я могу внести свой вклад?
DefinitelyTyped работает только благодаря вкладу таких пользователей, как вы!
### Тестирование
Прежде чем поделиться своим улучшением с миром, используйте его сами.
#### Тестирование редактирования существующего пакета
Для добавления новых функций вы можете использовать [разрешение модулей](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"],
```
(Вы также можете использовать `src/types`.)
Создайте `types/foo/index.d.ts` содержащие объявления для модуля "foo".
Теперь вы сможете импортировать из `"foo"` в свой код, и он будет направлен к новому определению типа.
Затем запустите сборку (build) *и* запустите код, чтобы убедиться, что ваше определение типа действительно соответствует тому, что происходит во время выполнения.
После того как вы проверили свои определения с реальным кодом, создайте [Запрос на принятие изменений (PR)](#make-a-pull-request)
и следуйте инструкциям [чтобы отредактировать существующий](#edit-an-existing-package) или
[создать новый пакет](#create-a-new-package).
### Запрос на принятие изменений (PR)
После того, как вы проверили ваш пакет, вы можете поделиться им с DefinitelyTyped.
Во-первых, [разветвите](https://guides.github.com/activities/forking/) этот репозиторий, установите [node](https://nodejs.org/), и запустите `npm install`.
#### Изменение существующего пакета
* `cd types/my-package-to-edit`
* Внесите изменения. Не забудьте отредактировать тесты.
Если вы вносите критические изменения, не забудьте [обновить основную версию](#i-want-to-update-a-package-to-a-new-major-version).
* Вы также можете добавить себя в раздел "Definitions by" заголовка пакета.
* Это приведет к тому, что вы будете уведомлены (через ваше имя пользователя GitHub) о том, что кто-то делает запрос на принятие изменений (PR) или проблему с пакетом.
* Сделайте это, добавив свое имя в конец строки, например `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
* Или, если есть больше людей, это может быть многострочным
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* Если есть `tslint.json`, запустите `npm run lint package-name`. В противном случае запустите `tsc` в директории пакета.
Когда вы создаете PR для редактирования существующего пакета, `dt-bot` должен @-уведомить
предыдущих авторов. Если этого не произойдет, вы можете сделать это самостоятельно в комментарии, связанном с PR.
#### Созданое нового пакета
Если вы являетесь автором библиотеки и ваш пакет написан на TypeScript, [свяжите автоматически сгенерированные файлы объявлений](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) в вашем пакете, а не публикуйте в DefinitelyTyped.
Если вы добавляете типизацию для пакета NPM, создайте директорию с тем же именем.
Если пакет, для которого вы добавляете типизацию, отсутствует в NPM, убедитесь, что выбранное вами имя не конфликтует с именем пакета в NPM.
(Вы можете использовать `npm info foo` чтобы проверить наличие пакета `foo`.)
Ваш пакет должен иметь такую ​​структуру:
| Файл | Назначение |
| ------------- | ---------------------------------------------------------------------------------------------------- |
| index.d.ts | Содержит типизацию для пакета. |
| foo-tests.ts | Содержит пример кода, который проверяет типизацию. Этот код *не* запускается, но он проверен на тип. |
| tsconfig.json | Позволяет вам запускать `tsc` внутри пакета. |
| tslint.json | Включает linting. |
Создайте их, запустив `npx dts-gen --dt --name my-package-name --template module` если у вас npm ≥ 5.2.0, `npm install -g dts-gen` и `dts-gen --dt --name my-package-name --template module` в противном случае.
Посмотреть все варианты на [dts-gen](https://github.com/Microsoft/dts-gen).
Вы можете отредактировать `tsconfig.json` чтобы добавить новые файлы, добавить `"target": "es6"` (необходимо для асинхронных функций), добавить в `"lib"`, или добавить опцию компилятора `"jsx"`.
Члены группы DefinitelyTyped регулярно следят за новыми PR, но имейте в виду, что количество других PR может замедлить ход событий.
Хороший пример пакета смотрите [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).
* Форматирование: либо используйте все табы, либо всегда используйте 4 пробела.
* `function sum(nums: number[]): number`: используйте `ReadonlyArray` если функция не записывает свои параметры.
* `interface Foo { new(): Foo; }`:
Это определяет тип объектов, с методом `new`. Вы, вероятно, хотите объявить `declare class Foo { constructor(); }`.
* `const Class: { new(): IClass; }`:
Предпочитайте использовать объявление класса `class Class { constructor(); }` вместо `new`.
* `getMeAT<T>(): T`:
Если параметр типа не отображается в типах каких-либо параметров, у вас нет универсальной функции, а просто замаскированное утверждение типа.
Предпочитайте использовать утверждение реального типа, например, `getMeAT() as number`.
Пример, где допустим параметр типа: `function id<T>(value: T): T;`.
Пример, где это недопустимо: `function parseJson<T>(json: string): T;`.
Исключение: `new Map<string, number>()` все ОК.
* Использование типов `Function` and `Object` почти никогда не является хорошей идеей. В 99% случаев можно указать более конкретный тип. Примеры: `(x: number) => number` для [функций](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) and `{ x: number, y: number }` для объектов. Если нет никакой уверенности в типе, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) является правильным выбором, а не `Object`. Если единственным известным фактом о типе является то, что это какой-то объект, используйте тип [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), а не `Object` или `{ [key: string]: any }`.
* `var foo: string | any`:
когда `any` используется в типе объединения, результирующий тип все еще `any`. Таким образом, хотя `string` часть аннотации этого типа может _выглядеть_ полезной, на самом деле она не предлагает никакой дополнительной проверки типов по сравнению с простым использованием `any`.
В зависимости от намерения, приемлемыми альтернативами могут быть `any`, `string`, или `string | object`.
#### Удаление пакета
Когда пакет [объединяет](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) свои собственные типы, типы должны быть удалены из DefinitelyTyped чтобы избежать путаницы.
Вы можете удалить его, запустив `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`.
* `typingsPackageName`: название директории, который нужно удалить.
* `asOfVersion`: заглушка будет опубликована в `@types/foo` с этой версией. Должна быть выше, чем любая опубликованная на данный момент версия
* `sourceRepoURL`: Это должно указывать на репозиторий, который содержит типизации.
* `libraryName`: описательное имя библиотеки, например, "Angular 2" вместо "angular2". (Если опущено, будет идентично "typingsPackageName".)
Любые другие пакеты в DefinitelyTyped которые ссылаются на удаленный пакет, должны быть обновлены для ссылки на связанные типы. Для этого добавьте в `package.json` ссыклу `"dependencies": { "foo": "x.y.z" }`.
Если пакет никогда не был в DefinitelyTyped, его не нужно добавлять в `notNeededPackages.json`.
#### Lint
Все новые пакеты должны быть проанализированы lint. Для этого добавьте `tslint.json` в этот пакет, содержащий
```js
{
"extends": "dtslint/dt.json"
}
```
Это должно быть единственным содержимым в файле `tslint.json` готового проекта. Если `tslint.json` отключает правила, это потому, что это еще не исправлено. Например:
```js
{
"extends": "dtslint/dt.json",
"rules": {
// This package uses the Function type, and it will take effort to fix.
"ban-types": false
}
}
```
(Чтобы указать, что правило lint действительно не применяется, используйте `// tslint:disable rule-name` или лучше, `//tslint:disable-next-line rule-name`.)
Чтобы проверить, что выражение имеет заданный тип, используйте `$ExpectType`. Чтобы проверить, что выражение вызывает ошибку компиляции, используйте `$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` в NPM?
Ветвь `master` автоматически публикуется в область `@types` на NPM благодаря [types-publisher](https://github.com/Microsoft/types-publisher).
#### Я отправил PR. Когда он сольется?
Это зависит, но большинство запросов на получение данных будут объединены в течение недели. PR, утвержденные автором, указанным в заголовке определения, обычно объединяются быстрее; PR для новых определений займет больше времени, так как они требуют большего количества проверок от сопровождающих. Каждый PR проверяется членом команды TypeScript или DefinitelyTyped перед объединением, поэтому будьте терпеливы, так как человеческий фактор может вызвать задержки. Посмотрите на [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) чтобы увидеть, как сопровождающие работают через открытые PR.
#### Мой PR слит; когда будет обновлен пакет `@types` NPM?
Пакеты NPM должны обновиться в течение нескольких часов. Если прошло более 24 часов, пингуйте @RyanCavanaugh и @andy-ms в PR, чтобы расследовать.
#### Я пишу определение, которое зависит от другого определения. Должен ли я использовать `<reference types="" />` или import?
Если модуль, на который вы ссылаетесь, является внешним модулем (использует `export`), используйте import.
Если модуль, на который вы ссылаетесь, является окружающим модулем (использует `declare module`, или просто объявляет глобальные переменные), используйте `<reference types="" />`.
#### Я заметил, что у некоторых пакетов есть `package.json`.
Обычно вам это не нужно. При публикации пакета мы обычно автоматически создаем `package.json`.
`package.json` может быть включен для определения зависимостей. Вот [пример](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json).
Мы не разрешаем определять другие поля, такие как "description", вручную.
Кроме того, если вам нужно сослаться на более старую версию типизаций, вы должны сделать это, добавив в `package.json` строки `"dependencies": { "@types/foo": "x.y.z" }`.
#### В некоторых пакетах отсутствует `tslint.json`, а в некоторых `tsconfig.json` отсутствует `"noImplicitAny": true`, `"noImplicitThis": true`, или `"strictNullChecks": true`.
Тогда они не правы. Вы можете помочь, отправив PR, чтобы исправить их.
#### Могу ли я запросить определение?
Вот [текущие запрошенные определения](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest).
#### Как насчет определений типов для DOM?
Если типы являются частью веб-стандарта, они должны быть добавлены в [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) чтобы они могли стать частью `lib.dom.d.ts` по умолчанию.
#### Пакет использует export `export =`, но я предпочитаю использовать импорт по умолчанию. Могу ли я изменить `export =` на `export default`?
Если вы используете TypeScript 2.7 или более позднюю версию, используйте `--esModuleInterop` в вашем проекте.
В противном случае, если импорт по умолчанию работает в вашей среде (например, Webpack, SystemJS, esm), рассмотрите возможность включения опции компилятора [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html).
Не меняйте определение типа, если оно точное.
Для пакета NPM, `export =` является точным, если `node -p 'require("foo")'` является экспортом, а `export default` является точным, если `node -p 'require("foo").default'` является экспортом.
#### Я хочу использовать функции из TypeScript 2.1 или выше.
В таком случае вам нужно будет добавить комментарий к последней строке заголовка вашего определения (после `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`.
#### Я хочу добавить DOM API, отсутствующий в TypeScript по умолчанию.
Это может принадлежать [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). Смотрите инструкции там.
Если стандарт все еще является черновиком, добавляйте сюда.
Используйте имя, начинающееся с `dom-` и включите ссылку на стандарт в качестве ссылки "Project" в заголовке.
Когда он завершает черновой режим, мы можем удалить его из DefinitelyTyped и объявить устаревшим связанный пакет `@types`.
#### Я хочу обновить пакет новой старшей версии
Если вы намерены продолжить обновление старой версии пакета, вы можете создать новую подпапку с текущей версией, например, `v2` и скопируйте в него существующие файлы. Если это так, вам необходимо:
1. Обновите относительные пути в `tsconfig.json` а также в `tslint.json`.
2. Добавьте правила сопоставления путей, чтобы убедиться, что тесты выполняются для предполагаемой версии.
Например [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like:
```json
{
"compilerOptions": {
"baseUrl": "../../",
"typeRoots": ["../../"],
"paths": {
"history": [ "history/v2" ]
}
},
"files": [
"index.d.ts",
"history-tests.ts"
]
}
```
Если в DefinitelyTyped есть другие пакеты, несовместимые с новой версией, вам нужно будет добавить сопоставления путей к старой версии. Вам также нужно будет сделать это для пакетов в зависимости от пакетов в зависимости от старой версии.
Например, `react-router` зависит от `history@2`, поэтому [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) есть сопоставление пути с `"history": [ "history/v2" ]`;
транзитивно `react-router-bootstrap` (который зависит от `react-router`) также добавляет отображение пути в свой [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
Также, `/// <reference types=".." />` не будет работать с отображением пути, поэтому зависимости должны использовать `import`.
#### Как мне написать определения для пакетов, которые могут использоваться и глобально и в качестве модуля?
Руководство TypeScript содержит отличную [общую информацию о написании определений](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, а также указаны объекты, доступные для глобальной области. Этот метод демонстрируется практически в определении для [definition for big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), библиотекой, которую можно загружать глобально с помощью тега скрипта на веб-странице или импортировать с помощью импорта по требованию или в стиле ES6.
Чтобы проверить, как ваше определение может использоваться как при глобальных ссылках, так и в качестве импортированного модуля, создайте тестовую папку `test`, и поместите туда два тестовых файла. Назовите один `YourLibraryName-global.test.ts` а другой `YourLibraryName-module.test.ts`. *Глобальный* тестовый файл должен использовать определение в соответствии с тем, как он будет использоваться в скрипте, загруженном на веб-страницу, где библиотека доступна в глобальной области видимости - в этом сценарии не следует указывать оператор импорта. Тестовый файл *модуля* должен использовать определение в соответствии с тем, как оно будет использоваться при импорте (включая оператор(ы) `import`). Если вы указали свойство `files` в файле `tsconfig.json`, обязательно включите оба тестовых файла. [Практический пример этого](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) также доступен в определении big.js.
Обратите внимание, что не требуется полностью использовать определение в каждом тестовом файле - достаточно протестировать только глобально доступные элементы в глобальном тестовом файле и полностью выполнить определение в тестовом файле модуля, или наоборот.
#### А как насчет областных пакетов?
Типы для пакета с областью `@foo/bar` должны указываться в `types/foo__bar`. Обратите внимание на двойное подчеркивание.
Когда `dts-gen` используется для компоновки пакета с областью действия, свойство `paths` должно быть вручную адаптировано в сгенерированном файле
`tsconfig.json` для правильной ссылки на пакет с областью действия:
```json
{
"paths":{
"@foo/bar": ["foo__bar"]
}
}
```
#### История файлов в GitHub выглядит неполной.
GitHub не [поддерживает](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).
#### Должен ли я добавить пустой namespace в пакет, который не экспортирует модуль для использования импорта в стиле ES6?
Некоторые пакеты, такие как [chai-http](https://github.com/chaijs/chai-http), экспортируют функцию.
Импорт этого модуля с импортом в стиле ES6 в форме `import * as foo from "foo";` приводит к ошибке:
> 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 foo from "foo";` при использовании флага `--allowSyntheticDefaultImports`, если среда выполнения вашего модуля поддерживает схему взаимодействия для модулей не-ECMAScript как таковых.
## Лицензия
Этот проект лицензирован по лицензии MIT.
Авторские права на файлы определений принадлежат каждому участнику, указанному в начале каждого файла определения.
[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon)
[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) В среднем пакеты публикуются на npm менее чем за 10000 секунд?
[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Был ли typescript-bot активным на DefinitelyTyped в последние два часа?

View File

@@ -684,6 +684,12 @@
"sourceRepoURL": "https://handsontable.com/",
"asOfVersion": "0.35.0"
},
{
"libraryName": "hibp",
"typingsPackageName": "hibp",
"sourceRepoURL": "https://github.com/wKovacs64/hibp",
"asOfVersion": "7.3.0"
},
{
"libraryName": "homeworks",
"typingsPackageName": "homeworks",
@@ -1062,6 +1068,12 @@
"sourceRepoURL": "https://github.com/paularmstrong/normalizr",
"asOfVersion": "2.0.18"
},
{
"libraryName": "Nuka Carousel",
"typingsPackageName": "nuka-carousel",
"sourceRepoURL": "https://github.com/FormidableLabs/nuka-carousel/",
"asOfVersion": "4.4.6"
},
{
"libraryName": "Numbro",
"typingsPackageName": "numbro",
@@ -1482,6 +1494,12 @@
"sourceRepoURL": "https://github.com/zeh/simplesignal",
"asOfVersion": "1.0.0"
},
{
"libraryName": "sip.js",
"typingsPackageName": "sip.js",
"sourceRepoURL": "https://github.com/onsip/SIP.js",
"asOfVersion": "0.12.0"
},
{
"libraryName": "smooth-scrollbar",
"typingsPackageName": "smooth-scrollbar",
@@ -1512,6 +1530,12 @@
"sourceRepoURL": "https://github.com/mozilla/source-map",
"asOfVersion": "0.5.7"
},
{
"libraryName": "Spectacle",
"typingsPackageName": "spectacle",
"sourceRepoURL": "http://github.com/FormidableLabs/spectacle/",
"asOfVersion": "5.2.3"
},
{
"libraryName": "Spin.js",
"typingsPackageName": "spin.js",
@@ -1638,6 +1662,12 @@
"sourceRepoURL": "https://github.com/dpa99c/phonegap-launch-navigator",
"asOfVersion": "4.0.0"
},
{
"libraryName": "Universal Router",
"typingsPackageName": "universal-router",
"sourceRepoURL": "https://github.com/kriasoft/universal-router",
"asOfVersion": "8.0.0"
},
{
"libraryName": "upper-case",
"typingsPackageName": "upper-case",
@@ -1698,6 +1728,12 @@
"sourceRepoURL": "https://github.com/tgdwyer/WebCola",
"asOfVersion": "3.2.0"
},
{
"libraryName": "WebdriverIO",
"typingsPackageName": "webdriverio",
"sourceRepoURL": "git@github.com:webdriverio/webdriverio.git",
"asOfVersion": "5.0.0"
},
{
"libraryName": "webgme",
"typingsPackageName": "webgme",

View File

@@ -23,5 +23,6 @@
"devDependencies": {
"dtslint": "github:Microsoft/dtslint#production",
"types-publisher": "github:Microsoft/types-publisher#production"
}
},
"dependencies": {}
}

View File

@@ -20,11 +20,17 @@ const l3: AcceptLanguageParser.Language = {
quality: 0.9
};
type Lang = "en-US" | "ko-KR";
const enUs: Lang = "en-US";
const koKr: Lang = "ko-KR";
const parsed1: AcceptLanguageParser.Language[] = AcceptLanguageParser.parse('');
const pick1: string | null = AcceptLanguageParser.pick([''], '');
const pick2: string | null = AcceptLanguageParser.pick([''], [l1, l2, l3]);
const pick3: string | null = AcceptLanguageParser.pick([''], '', {});
const pick4: string | null = AcceptLanguageParser.pick([''], '', { loose: true });
const pick5: Lang | null = AcceptLanguageParser.pick<Lang>([enUs, koKr], [l1, l2, l3]);
const pick6: Lang | null = AcceptLanguageParser.pick([enUs, koKr], [l1, l2, l3]);
const pickOptions: AcceptLanguageParser.PickOptions = {
loose: true

View File

@@ -1,17 +1,18 @@
// Type definitions for accept-language-parser 1.5
// Project: https://github.com/opentable/accept-language-parser
// Definitions by: Niklas Wulf <https://github.com/kampfgnom>
// Wooram Jun <https://github.com/chatoo2412>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
// https://github.com/opentable/accept-language-parser/blob/v1.4.1/index.js
// https://github.com/opentable/accept-language-parser/blob/v1.5.0/index.js
export function parse(acceptLanguage: string): Language[];
export function pick(
supportedLanguages: string[],
export function pick<T extends string>(
supportedLanguages: T[],
acceptLanguage: string | Language[],
options?: PickOptions
): string | null;
): T | null;
export interface Language {
code: string;

View File

@@ -14,6 +14,8 @@ accept.language("en;q=0.7, en-GB;q=0.8", ["en-gb"]); // language === "en-GB"
const languages = accept.languages("da, en;q=0.7, en-GB;q=0.8"); // languages === ["da", "en-GB", "en"]
languages.lastIndexOf('');
accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1");
accept.mediaType("text/plain, application/json;q=0.5, text/html, */*;q=0.1", ["application/json", "text/html"]);
const mediaTypes = accept.mediaTypes("text/plain, application/json;q=0.5, text/html, */*;q=0.1");
// mediaTypes === ["text/plain", "text/html", "application/json", "*/*"]
mediaTypes.lastIndexOf('');

View File

@@ -10,6 +10,7 @@ export function encoding(encodingHeader?: string, preferences?: string[]): strin
export function encodings(encodingHeader?: string): string[];
export function language(languageHeader?: string, preferences?: string[]): string;
export function languages(languageHeader?: string): string[];
export function mediaType(mediaTypeHeader?: string, preferences?: string[]): string;
export function mediaTypes(mediaTypeHeader?: string): string[];
export function parseAll(
headers: Record<string, string | string[] | undefined>

12
types/ace/index.d.ts vendored
View File

@@ -549,6 +549,16 @@ declare namespace AceAjax {
getFoldsInRange(range: Range): any;
highlight(text: string): void;
/**
* Highlight lines from `startRow` to `EndRow`.
* @param startRow Define the start line of the highlight
* @param endRow Define the end line of the highlight
* @param clazz Set the CSS class for the marker
* @param inFront Set to `true` to establish a front marker
**/
highlightLines(startRow:number, endRow: number, clazz: string, inFront: boolean): Range;
/**
* Sets the `EditSession` to point to a new `Document`. If a `BackgroundTokenizer` exists, it also points to `doc`.
@@ -1223,7 +1233,7 @@ declare namespace AceAjax {
/**
* Returns `true` if the current `textInput` is in focus.
**/
isFocused(): void;
isFocused(): boolean;
/**
* Blurs the current `textInput`.

View File

@@ -246,9 +246,7 @@ declare namespace acorn {
let LooseParser: ILooseParserClass | undefined;
let pluginsLoose: PluginsObject | undefined;
interface ILooseParserClass {
new (input: string, options?: Options): ILooseParser;
}
type ILooseParserClass = new (input: string, options?: Options) => ILooseParser;
interface ILooseParser {}

View File

@@ -0,0 +1,17 @@
import activeWin = require('active-win');
// $ExpectType Promise<Result>
activeWin();
// $ExpectType Result
activeWin.sync();
let win = {
title: 'Unicorns - Google Search',
id: 5762,
owner: {
name: 'Google Chrome',
processId: 310,
},
};
win = activeWin.sync();

30
types/active-win/index.d.ts vendored Normal file
View File

@@ -0,0 +1,30 @@
// Type definitions for active-win 4.0
// Project: https://github.com/sindresorhus/active-win#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = activeWin;
declare function activeWin(): Promise<activeWin.Result>;
declare namespace activeWin {
function sync(): Result;
interface Result {
title: string;
id: number;
bounds?: {
x: number;
y: number;
width: number;
height: number;
};
owner: {
name: string;
processId: number;
bundleId?: number;
path?: string;
};
memoryUsage?: number;
}
}

View File

@@ -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",
"active-win-tests.ts"
]
}

View File

@@ -0,0 +1,28 @@
import * as ActiveStorage from 'activestorage';
ActiveStorage.start();
const delegate: ActiveStorage.DirectUploadDelegate = {
directUploadWillCreateBlobWithXHR(xhr) {
console.log(xhr.status);
},
directUploadWillStoreFileWithXHR(xhr) {
console.log(xhr.status);
},
};
const d = new ActiveStorage.DirectUpload(
new File([], 'blank.txt'),
'/rails/active_storage/direct_uploads',
delegate
);
d.create((error, blob) => {
if (error) {
console.log(error.message);
} else {
const { byte_size, checksum, content_type, filename, signed_id } = blob;
console.log({ byte_size, checksum, content_type, filename, signed_id });
}
});

33
types/activestorage/index.d.ts vendored Normal file
View File

@@ -0,0 +1,33 @@
// Type definitions for ActiveStorage 5.2
// Project: https://github.com/rails/rails/tree/master/activestorage/app/javascipt
// Definitions by: Cameron Bothner <https://github.com/cbothner>
// Definitions: https://github.com/cbothner/DefinitelyTyped
// TypeScript Version: 2.1
export as namespace ActiveStorage
export function start(): void;
export class DirectUpload {
id: number;
file: File;
url: string;
constructor(file: File, url: string, delegate: DirectUploadDelegate)
create(callback: (error: Error, blob: Blob) => void): void;
}
export interface DirectUploadDelegate {
directUploadWillCreateBlobWithXHR?: (xhr: XMLHttpRequest) => void;
directUploadWillStoreFileWithXHR?: (xhr: XMLHttpRequest) => void;
}
export interface Blob {
byte_size: number;
checksum: string;
content_type: string;
filename: string;
signed_id: string;
}

View File

@@ -0,0 +1,16 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": ["index.d.ts", "activestorage-tests.ts"]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -0,0 +1,40 @@
/*
| Copyright 2018 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
import * as adlib from "adlib";
const transform1: adlib.TransformFunction =
(key: string, value: any, settings: any, param?: any): any => {
return null;
};
const transformsList: adlib.TransformsList = {
firstXform: transform1
};
const template = {
value: '{{ instance.color }}'
};
const settings = {
instance: {
color: 'red'
}
};
const interpolated = adlib.adlib(template, settings, transformsList);
const list: string[] = adlib.listDependencies(template);

75
types/adlib/index.d.ts vendored Normal file
View File

@@ -0,0 +1,75 @@
// Type definitions for adlib 3.0
// Project: https://github.com/Esri/adlib
// Definitions by: Esri <https://github.com/Esri>
// Mike Tschudi <https://github.com/MikeTschudi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
/*
| Copyright 2018 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
/**
* Transform function to apply to interpolated value.
*
* @param key Path within a handlebar-style expression to attempt to replace; e.g., `s.animal.type` in
* https://github.com/Esri/adlib#transforms
* @param value Value to replace expression with
* @param settings Hash providing values to insert into template; see https://github.com/Esri/adlib#general-pattern
* @param param Parameter for transform function; e.g., the `optional` transform accepts a count of levels
* to delete if the value is not found (default is 0--just the current level);
* see https://github.com/Esri/adlib#optional-transform
*/
export interface TransformFunction {
(
key: string,
value: any,
settings: any,
param?: any
): any;
}
/**
* Set of transformation functions keyed by the transform function's name.
*/
export interface TransformsList {
[ transformFnName: string ]: TransformFunction;
}
/**
* A JavaScript library for interpolating property values in JSON Objects.
*
* @param template A template that possibly containing handlebar-style property values to replace;
* see https://github.com/Esri/adlib#general-pattern
* @param settings Hash providing values to insert into template; see https://github.com/Esri/adlib#general-pattern
* @param transforms Set of transformation functions
* @return Copy of template with replacements performed
*/
export function adlib(
template: any,
settings: any,
transforms?: TransformsList
): any;
/**
* Reads a template and spits out unique handlebar-style property values.
*
* @param template A template that possibly containing handlebar-style property values to replace;
* see https://github.com/Esri/adlib#general-pattern
* @return List of unique property values in template
*/
export function listDependencies(
template: any
): string [];

23
types/adlib/tsconfig.json Normal file
View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"adlib-tests.ts"
]
}

1
types/adlib/tslint.json Normal file
View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -0,0 +1,10 @@
import * as aesjs from 'aes-js';
const key = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const data: Uint8Array = aesjs.utils.utf8.toBytes('hello world');
const ecb = new aesjs.ModeOfOperation.ecb(key);
ecb.decrypt(ecb.encrypt(data));
const hex: string = aesjs.utils.hex.fromBytes(data);

134
types/aes-js/index.d.ts vendored Normal file
View File

@@ -0,0 +1,134 @@
// Type definitions for aes-js 3.1
// Project: https://github.com/ricmoo/aes-js
// Definitions by: Federico Bond <https://github.com/federicobond>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export type ByteSource = ArrayBuffer | Uint8Array | number[];
export class AES {
/**
* Create a new AES block cipher.
* @param key The cipher key.
*/
constructor(key: ByteSource)
encrypt(v: ByteSource): ByteSource;
}
/**
* Create a new Counter state for CTR cipher mode.
* @param initialValue The Counter initial value.
*/
export class Counter {
constructor(initialValue: number)
setValue(value: number): void;
setBytes(bytes: ByteSource): void;
increment(): void;
}
export namespace ModeOfOperation {
class ModeOfOperationECB {
/**
* Create a new ECB stream cipher.
* @param key The cipher key.
*/
constructor(key: ByteSource)
encrypt(v: ByteSource): Uint8Array;
decrypt(v: ByteSource): Uint8Array;
}
class ModeOfOperationCBC {
/**
* Create a new CBC stream cipher.
* @param key The cipher key.
* @param iv The cipher initialization vector.
*/
constructor(key: ByteSource, iv: ByteSource);
encrypt(v: ByteSource): Uint8Array;
decrypt(v: ByteSource): Uint8Array;
}
class ModeOfOperationCFB {
/**
* Create a new CFB stream cipher.
* @param key The cipher key.
* @param iv The cipher initialization vector.
* @param segmentSize The cipher segment size.
*/
constructor(key: ByteSource, iv: ByteSource, segmentSize: number);
encrypt(v: ByteSource): Uint8Array;
decrypt(v: ByteSource): Uint8Array;
}
class ModeOfOperationOFB {
/**
* Create a new OFB stream cipher.
* @param key The cipher key.
* @param iv The cipher initialization vector.
*/
constructor(key: ByteSource, iv: ByteSource);
encrypt(v: ByteSource): Uint8Array;
decrypt(v: ByteSource): Uint8Array;
}
class ModeOfOperationCTR {
/**
* Create a new CTR stream cipher.
* @param key The cipher key.
* @param counter The cipher counter state.
*/
constructor(key: ByteSource, counter?: Counter)
encrypt(v: ByteSource): Uint8Array;
decrypt(v: ByteSource): Uint8Array;
}
const ecb: typeof ModeOfOperationECB;
const cbc: typeof ModeOfOperationCBC;
const cfb: typeof ModeOfOperationCFB;
const ofb: typeof ModeOfOperationOFB;
const ctr: typeof ModeOfOperationCTR;
}
export namespace utils {
namespace utf8 {
/**
* Convert a UTF8 encoded string to a Uint8Array.
* @param data The input string.
*/
function toBytes(data: string): Uint8Array;
/**
* Convert an array-like object containing UTF8 data to a string.
* @param data The input data.
*/
function fromBytes(data: ByteSource): string;
}
namespace hex {
/**
* Convert a hexadecimal string to a Uint8Array.
* @param data The input string.
*/
function toBytes(data: string): Uint8Array;
/**
* Convert an array-like object to a hexadecimal string.
* @param data The input data.
*/
function fromBytes(data: ByteSource): string;
}
}
export namespace padding {
namespace pkcs7 {
/**
* Add standard PKCS7 padding to an array.
* @param data The input data.
*/
function pad(data: ByteSource): Uint8Array;
/**
* Remove standard PKCS7 padding from an array.
* @param data The input data.
*/
function strip(data: ByteSource): Uint8Array;
}
}

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"aes-js-tests.ts"
]
}

1
types/aes-js/tslint.json Normal file
View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -319,6 +319,22 @@ export interface Utils {
delimiter?: string
): void;
};
device: {
isWebXRAvailable: boolean;
getVRDisplay(): VRDisplay[];
checkHeadsetConnected(): boolean;
checkHasPositionalTracking(): boolean;
isMobile(): boolean;
isTablet(): boolean;
isIOS(): boolean;
isGearVR(): boolean;
isOculusGo(): boolean;
isR7(): boolean;
isLandscape(): boolean;
isBrowserEnvironment(): boolean;
isNodeEnvironment(): boolean;
PolyfillControls(object3D: THREE.Object3D): void;
};
styleParser: {
parse(value: string): object;
stringify(data: object): string;
@@ -342,7 +358,7 @@ export interface Utils {
// Definitions
// used as mixins to register functions to create classes (newable functions) in A-Frame
export type ComponentDefinition<T extends object = object> = T & Partial<Component>;
export type ComponentDefinition<T extends object = object> = T & Partial<Component> & ThisType<T & Component>;
export type GeometryDefinition<T extends object = object, U = any> = T & Partial<Geometry<U>>;
export type NodeDefinition<T extends object = object> = T & Partial<ANode>;
export interface PrimitiveDefinition {

View File

@@ -30,7 +30,7 @@ AFRAME.registerComponent('set-image', {
init: function() {
var data = this.data;
var el = this.el!;
var el = this.el;
this.setupFadeAnimation();
@@ -133,14 +133,14 @@ AFRAME.registerComponent('arrow-key-rotation', {
if (!this.data.enabled) {
return;
}
var rotation = this.el!.getAttribute('rotation');
var rotation = this.el.getAttribute('rotation');
if (!rotation) {
return;
}
if (this.directionX || this.directionY) {
rotation.x += this.data.dx * this.directionY;
rotation.y += this.data.dy * this.directionX;
this.el!.setAttribute('rotation', rotation);
this.el.setAttribute('rotation', rotation);
}
}
});
@@ -164,10 +164,10 @@ AFRAME.registerComponent('hide-once-playing', {
}
},
onPlaying: function() {
this.el!.setAttribute('visible', false);
this.el.setAttribute('visible', false);
},
onPause: function() {
this.el!.setAttribute('visible', true);
this.el.setAttribute('visible', true);
}
});
@@ -178,10 +178,10 @@ AFRAME.registerComponent('play-on-vrdisplayactivate-or-enter-vr', {
},
play: function() {
window.addEventListener('vrdisplayactivate', this.playVideo);
this.el!.sceneEl!.addEventListener('enter-vr', this.playVideoNextTick);
this.el.sceneEl!.addEventListener('enter-vr', this.playVideoNextTick);
},
pause: function() {
this.el!.sceneEl!.removeEventListener('enter-vr', this.playVideoNextTick);
this.el.sceneEl!.removeEventListener('enter-vr', this.playVideoNextTick);
window.removeEventListener('vrdisplayactivate', this.playVideo);
},
playVideoNextTick: function() {
@@ -189,7 +189,7 @@ AFRAME.registerComponent('play-on-vrdisplayactivate-or-enter-vr', {
},
playVideo: function() {
// TODO improve type
var video = (this.el! as Entity<any>).components.material.material.map.image;
var video = (this.el as Entity<any>).components.material.material.map.image;
if (!video) {
return;
}
@@ -208,7 +208,7 @@ AFRAME.registerComponent('play-on-window-click', {
window.removeEventListener('click', this.onClick);
},
onClick: function() {
var video = (this.el! as Entity<any>).components.material.material.map.image;
var video = (this.el as Entity<any>).components.material.material.map.image;
if (!video) {
return;
}
@@ -227,7 +227,7 @@ AFRAME.registerComponent('toggle-play-on-window-click', {
window.removeEventListener('click', this.onClick);
},
onClick: function() {
var video = (this.el! as Entity<any>).components.material.material.map.image;
var video = (this.el as Entity<any>).components.material.material.map.image;
if (!video) {
return;
}
@@ -359,7 +359,7 @@ AFRAME.registerComponent('audioanalyser-levels-scale', {
return;
}
children = this.el!.children;
children = this.el.children;
for (var i = 0; i < children.length; i++) {
(children[i] as ANode).setAttribute('scale', {
x: 1,
@@ -382,7 +382,7 @@ AFRAME.registerComponent('audioanalyser-volume-bind', {
tick: function() {
var analyserComponent;
var data = this.data;
var el = this.el!;
var el = this.el;
var value;
analyserComponent = data.analyserEl.components.audioanalyser;
@@ -404,7 +404,7 @@ AFRAME.registerComponent('audioanalyser-volume-scale', {
tick: function() {
var analyserEl = this.data.analyserEl || this.el;
var analyserComponent;
var el = this.el!;
var el = this.el;
var volume;
analyserComponent = analyserEl.components.audioanalyser;
@@ -542,7 +542,7 @@ AFRAME.registerComponent('audioanalyser-waveform', {
},
remove: function() {
this.el!.removeObject3D('waveformContainer');
this.el.removeObject3D('waveformContainer');
}
});
@@ -874,7 +874,7 @@ AFRAME.registerComponent('color-on-beat', {
init: function() {
var analyserEl = this.data.analyserEl || this.el;
var el = this.el!;
var el = this.el;
analyserEl.addEventListener('audioanalyser-beat', function() {
el.setAttribute(
@@ -909,12 +909,12 @@ AFRAME.registerComponent('remove-on-event', {
removeEventListener: function() {
var data = this.data;
var el = this.el!;
var el = this.el;
el.removeEventListener(data.event, this._removeEntity);
},
_removeEntity: function() {
var el = this.el!;
var el = this.el;
if ((el as any).parentEl) {
(el as any).parentEl.removeChild(el);
}
@@ -1016,7 +1016,7 @@ function rgbToHex(r: number, g: number, b: number) {
AFRAME.registerComponent('random-material', {
init: function() {
this.el!.setAttribute('material', {
this.el.setAttribute('material', {
color: this.getRandomColor(),
metalness: Math.random(),
roughness: Math.random()
@@ -1034,7 +1034,7 @@ AFRAME.registerComponent('random-material', {
AFRAME.registerComponent('random-torus-knot', {
init: function() {
this.el!.setAttribute('geometry', {
this.el.setAttribute('geometry', {
primitive: 'torusKnot',
radius: Math.random() * 10,
radiusTubular: Math.random() * 0.75,

View File

@@ -75,6 +75,7 @@ const Component = registerComponent('test-component', {
},
init() {
this.data.num = 0;
this.el.setAttribute('custom-attribute', 'custom-value');
},
update() {},
tick() {},

View File

@@ -0,0 +1,206 @@
import * as React from 'react';
import * as PropTypes from 'prop-types';
import * as AirbnbPropTypes from 'airbnb-prop-types';
class ClassComp extends React.Component {
render() {
return null;
}
}
function FuncComp() {
return null;
}
// $ExpectType Requireable<number | null>
AirbnbPropTypes.and([PropTypes.number]);
// $ExpectType Requireable<number | null>
AirbnbPropTypes.and([PropTypes.number, AirbnbPropTypes.nonNegativeInteger]);
// $ExpectType Validator<number>
AirbnbPropTypes.and([PropTypes.number, AirbnbPropTypes.integer()], 'foo').isRequired;
// $ExpectType Requireable<number>
AirbnbPropTypes.between({ lt: 1 });
// $ExpectType Requireable<number>
AirbnbPropTypes.between({ lte: 2 });
// $ExpectType Requireable<number>
AirbnbPropTypes.between({ gt: 3 });
// $ExpectType Requireable<number>
AirbnbPropTypes.between({ gte: 4 });
// $ExpectType Requireable<number>
AirbnbPropTypes.between({ lt: 1, gt: 0 });
// $ExpectType Requireable<boolean>
AirbnbPropTypes.booleanSome('foo', 'bar', 'baz');
// $ExpectType Requireable<ReactNodeLike>
AirbnbPropTypes.childrenHavePropXorChildren('foo');
// $ExpectType Requireable<ReactNodeLike>
AirbnbPropTypes.childrenOf(PropTypes.string);
// $ExpectType Requireable<ReactNodeLike>
AirbnbPropTypes.childrenOfType(ClassComp);
// $ExpectType Requireable<ReactNodeLike>
AirbnbPropTypes.childrenOfType(FuncComp);
// $ExpectType Requireable<ReactNodeLike>
AirbnbPropTypes.childrenOfType('div');
// $ExpectType Requireable<ReactNodeLike>
AirbnbPropTypes.childrenOfType(ClassComp, FuncComp, 'div');
// $ExpectType Requireable<ReactNodeLike>
AirbnbPropTypes.childrenSequenceOf({ validator: PropTypes.number });
// $ExpectType Requireable<ReactNodeLike>
AirbnbPropTypes.childrenSequenceOf({ validator: PropTypes.string, max: 100 });
// $ExpectType Requireable<ReactNodeLike>
AirbnbPropTypes.childrenSequenceOf({ validator: PropTypes.bool, min: 0 });
// $ExpectType Requireable<ReactNodeLike>
AirbnbPropTypes.componentWithName('Foo');
// $ExpectType Requireable<ReactNodeLike>
AirbnbPropTypes.componentWithName(/Foo/);
// $ExpectType Requireable<ReactNodeLike>
AirbnbPropTypes.componentWithName('Foo', { stripHOCs: ['connect'] });
// $ExpectType Requireable<number>
AirbnbPropTypes.disallowedIf(PropTypes.number, 'foo', PropTypes.string);
// $ExpectType Requireable<ReactElementLike>
AirbnbPropTypes.elementType(ClassComp);
// $ExpectType Requireable<ReactElementLike>
AirbnbPropTypes.elementType(FuncComp);
// $ExpectType Requireable<ReactElementLike>
AirbnbPropTypes.elementType('div');
// $ExpectType Requireable<ReactElementLike>
AirbnbPropTypes.elementType('*');
// $ExpectError
AirbnbPropTypes.elementType(ClassComp, FuncComp, 'div');
// $ExpectType Requireable<null | undefined>
AirbnbPropTypes.explicitNull();
// $ExpectType Validator<never>
AirbnbPropTypes.explicitNull().isRequired;
interface ForbidShape {
foo: string;
bar: number;
baz?: boolean | null;
}
// $ExpectType ValidationMap<{ foo: string | null; bar: number; baz: boolean | null; }>
AirbnbPropTypes.forbidExtraProps({
foo: PropTypes.string,
bar: PropTypes.number.isRequired,
baz: PropTypes.bool,
});
// $ExpectType ValidationMap<ForbidShape>
AirbnbPropTypes.forbidExtraProps<ForbidShape>({
foo: PropTypes.string.isRequired,
bar: PropTypes.number.isRequired,
baz: PropTypes.bool,
});
// $ExpectType Requireable<number>
AirbnbPropTypes.integer();
// $ExpectType Requireable<{}>
AirbnbPropTypes.keysOf(PropTypes.number);
// $ExpectType Requireable<{}>
AirbnbPropTypes.keysOf(PropTypes.number, 'foo');
// $ExpectType Requireable<{}>
AirbnbPropTypes.keysOf(PropTypes.oneOf(['foo', 'bar']));
// $ExpectType Requireable<number>
AirbnbPropTypes.mutuallyExclusiveProps(PropTypes.number);
// $ExpectType Requireable<number>
AirbnbPropTypes.mutuallyExclusiveProps(PropTypes.number, 'foo');
// $ExpectType Requireable<string>
AirbnbPropTypes.mutuallyExclusiveProps(PropTypes.string, 'foo', 'bar');
// $ExpectType Requireable<boolean>
AirbnbPropTypes.mutuallyExclusiveTrueProps('foo');
// $ExpectType Requireable<boolean>
AirbnbPropTypes.mutuallyExclusiveTrueProps('foo', 'bar');
// $ExpectType Requireable<ReactNodeLike>
AirbnbPropTypes.nChildren(1, PropTypes.number);
// $ExpectType Requireable<ReactNodeLike>
AirbnbPropTypes.nChildren(1, AirbnbPropTypes.childrenOfType('span'));
// $ExpectType Requireable<number>
AirbnbPropTypes.nonNegativeInteger;
// $ExpectType Requireable<number>
AirbnbPropTypes.nonNegativeNumber();
// $ExpectType Requireable<string>
AirbnbPropTypes.numericString();
// $ExpectType Requireable<{}>
AirbnbPropTypes.object();
// $ExpectType Requireable<{ foo: string; }>
AirbnbPropTypes.object<{ foo: string }>();
AirbnbPropTypes.or([PropTypes.bool.isRequired, AirbnbPropTypes.explicitNull().isRequired]);
AirbnbPropTypes.or([PropTypes.bool, PropTypes.number, PropTypes.arrayOf(PropTypes.string)]);
AirbnbPropTypes.or([PropTypes.number, PropTypes.string, PropTypes.bool], 'foo');
// $ExpectType Requireable<number>
AirbnbPropTypes.range(0, 10);
// $ExpectType Requireable<5>
AirbnbPropTypes.range<5>(0, 10);
// $ExpectType Requireable<string | null>
AirbnbPropTypes.requiredBy('foo', PropTypes.string);
// $ExpectType Validator<number>
AirbnbPropTypes.requiredBy('bar', PropTypes.number, 42).isRequired;
// $ExpectType Requireable<{}>
AirbnbPropTypes.restrictedProp();
// $ExpectType Requireable<{}>
AirbnbPropTypes.restrictedProp(() => 'Error');
// $ExpectType Requireable<{}>
AirbnbPropTypes.restrictedProp(() => new Error('Error'));
// $ExpectType Requireable<{}>
AirbnbPropTypes.sequenceOf({ validator: PropTypes.number });
// $ExpectType Requireable<{}>
AirbnbPropTypes.sequenceOf({ validator: PropTypes.number }, { validator: PropTypes.string });
// $ExpectType Requireable<{}>
AirbnbPropTypes.sequenceOf(
{ validator: PropTypes.number, min: 0, max: 10 },
{ validator: PropTypes.string },
{ validator: PropTypes.bool },
);
interface ShapeShape {
foo: string;
bar?: number | null;
}
// $ExpectType Requireable<{ foo: string | null; }>
AirbnbPropTypes.shape({
foo: PropTypes.string,
});
// $ExpectType Requireable<{ foo: string | null; bar: number | null; }>
AirbnbPropTypes.shape({
foo: PropTypes.string,
bar: PropTypes.number,
});
// $ExpectType Requireable<ShapeShape>
AirbnbPropTypes.shape<ShapeShape>({
foo: PropTypes.string.isRequired,
bar: PropTypes.number,
});
// $ExpectType Requireable<string>
AirbnbPropTypes.stringStartsWith('foo');
// $ExpectType Requireable<any[]>
AirbnbPropTypes.uniqueArray();
// $ExpectType Requireable<string[]>
AirbnbPropTypes.uniqueArray<string>();
// $ExpectType Requireable<{ [key: string]: number | null; }>
AirbnbPropTypes.valuesOf(PropTypes.number);

198
types/airbnb-prop-types/index.d.ts vendored Normal file
View File

@@ -0,0 +1,198 @@
// Type definitions for airbnb-prop-types 2.11
// Project: https://github.com/airbnb/prop-types
// Definitions by: Miles Johnson <https://github.com/milesj>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.0
import * as PropTypes from 'prop-types';
export interface ReactComponentLike {
setState(...args: any[]): any;
forceUpdate(...args: any[]): any;
render(): PropTypes.ReactNodeLike;
props: any;
state: any;
context: any;
refs: any;
}
export interface ReactClassComponentLike {
new (...args: any[]): ReactComponentLike;
}
export type ReactFunctionComponentLike = (...args: any[]) => PropTypes.ReactNodeLike;
export type ReactTypeLike = string | ReactClassComponentLike | ReactFunctionComponentLike;
export interface Specifier<T = any> {
max?: number;
min?: number;
validator: PropTypes.Validator<T>;
}
export function and<A>(
propTypes: [PropTypes.Validator<A>],
name?: string,
): PropTypes.Requireable<A>;
export function and<A, B>(
propTypes: [PropTypes.Validator<A>, PropTypes.Validator<B>],
name?: string,
): PropTypes.Requireable<A & B>;
export function and<A, B, C>(
propTypes: [PropTypes.Validator<A>, PropTypes.Validator<B>, PropTypes.Validator<C>],
name?: string,
): PropTypes.Requireable<A & B & C>;
export function and<T>(
propTypes: Array<PropTypes.Validator<any>>,
name?: string,
): PropTypes.Requireable<T>;
export function between(options: {
lt?: number;
lte?: number;
gt?: number;
gte?: number;
}): PropTypes.Requireable<number>;
export function booleanSome(...props: string[]): PropTypes.Requireable<boolean>;
export function childrenHavePropXorChildren<T = PropTypes.ReactNodeLike>(
prop: string | symbol,
): PropTypes.Requireable<T>;
export function childrenOf<T = PropTypes.ReactNodeLike, P = any>(
propType: PropTypes.Validator<P>,
): PropTypes.Requireable<T>;
export function childrenOfType<T = PropTypes.ReactNodeLike>(
...types: ReactTypeLike[]
): PropTypes.Requireable<T>;
export function childrenSequenceOf<T = PropTypes.ReactNodeLike>(
...specifiers: Specifier[]
): PropTypes.Requireable<T>;
export function componentWithName<T = PropTypes.ReactNodeLike>(
name: string | RegExp,
options?: { stripHOCs: ReadonlyArray<string> },
): PropTypes.Requireable<T>;
export function disallowedIf<T>(
propType: PropTypes.Requireable<T>,
otherPropName: string,
otherPropType: PropTypes.Validator<any>,
): PropTypes.Requireable<T>;
export function elementType<T = PropTypes.ReactElementLike>(
type: ReactTypeLike,
): PropTypes.Requireable<T>;
export function explicitNull(): PropTypes.Requireable<null | undefined>;
export function forbidExtraProps<T extends object>(
propTypes: PropTypes.ValidationMap<T>,
): PropTypes.ValidationMap<T>;
export function integer(): PropTypes.Requireable<number>;
export function keysOf<T, P>(
propType: PropTypes.Validator<P>,
name?: string,
): PropTypes.Requireable<T>;
export function mutuallyExclusiveProps<T>(
propType: PropTypes.Requireable<T>,
...propNames: string[]
): PropTypes.Requireable<T>;
export function mutuallyExclusiveProps<T>(
// tslint:disable-next-line:unified-signatures
propType: PropTypes.Validator<T>,
...propNames: string[]
): PropTypes.Requireable<T>;
export function mutuallyExclusiveTrueProps(...propNames: string[]): PropTypes.Requireable<boolean>;
export function nChildren<T = PropTypes.ReactNodeLike, P = any>(
n: number,
propType?: PropTypes.Validator<P>,
): PropTypes.Requireable<T>;
export const nonNegativeInteger: PropTypes.Requireable<number>;
export function nonNegativeNumber(): PropTypes.Requireable<number>;
export function numericString(): PropTypes.Requireable<string>;
export function object<T extends object>(): PropTypes.Requireable<T>;
export function or<A>(propTypes: [PropTypes.Validator<A>], name?: string): PropTypes.Requireable<A>;
export function or<A, B>(
propTypes: [PropTypes.Validator<A>, PropTypes.Validator<B>],
name?: string,
): PropTypes.Requireable<A | B>;
export function or<A, B, C>(
propTypes: [PropTypes.Validator<A>, PropTypes.Validator<B>, PropTypes.Validator<C>],
name?: string,
): PropTypes.Requireable<A | B | C>;
export function or<T>(
propTypes: Array<PropTypes.Validator<T>>,
name?: string,
): PropTypes.Requireable<T>;
export function or<T = any>(
// tslint:disable-next-line:unified-signatures
propTypes: Array<PropTypes.Validator<any>>,
name?: string,
): PropTypes.Requireable<T>;
export function range<T extends number>(min?: number, max?: number): PropTypes.Requireable<T>;
export function range(min?: number, max?: number): PropTypes.Requireable<number>;
export function requiredBy<P>(
requiredByPropName: string,
propType: PropTypes.Validator<P>,
defaultValue?: any,
): PropTypes.Requireable<P>;
export function restrictedProp<T>(
messageFunction?: (
props: object,
propName: string,
componentName: string,
location: string,
propFullName: string,
) => string | Error | undefined,
): PropTypes.Requireable<T>;
export function sequenceOf<T>(...specifiers: Specifier[]): PropTypes.Requireable<T>;
export function shape<T extends object>(
propTypes: PropTypes.ValidationMap<T>,
): PropTypes.Requireable<T>;
export function stringStartsWith(string: string): PropTypes.Requireable<string>;
export function uniqueArray<T = any>(): PropTypes.Requireable<T[]>;
export function uniqueArrayOf<T, P>(
propType: PropTypes.Validator<P>,
mapperOrName: ((value: any) => any) | string,
name?: string,
): PropTypes.Requireable<T[]>;
export function valuesOf<T>(
propType: PropTypes.Validator<T>,
): PropTypes.Requireable<{ [key: string]: T }>;
export function withShape<T extends object, P, S>(
propType: PropTypes.Validator<P>,
propTypes: PropTypes.ValidationMap<S>,
): PropTypes.Requireable<T>;

View File

@@ -0,0 +1,16 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": ["index.d.ts", "airbnb-prop-types-tests.ts"]
}

View File

@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"no-unnecessary-generics": false
}
}

View File

@@ -18,6 +18,7 @@ declare namespace OSS {
internal?: boolean; // access OSS with aliyun internal network or not, default is false. If your servers are running on aliyun too, you can set true to save lot of money.
secure?: boolean; // instruct OSS client to use HTTPS (secure: true) or HTTP (secure: false) protocol.
timeout?: string | number; // instance level timeout for all operations, default is 60s
cname?: boolean; // use custom domain name
}
interface Bucket {
@@ -29,7 +30,7 @@ declare namespace OSS {
type StorageType = "Standard" | "IA" | "Archive";
type ACLType = "public-read-write" | "public-read" | "and private";
type ACLType = "public-read-write" | "public-read" | "private";
type HTTPMethods = "GET" | "POST" | "DELETE" | "PUT";
@@ -174,6 +175,7 @@ declare namespace OSS {
mime?: string; // custom mime, will send with Content-Type entity header
meta?: UserMeta; // user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 }
callback: ObjectCallback;
headers?: object;
}
interface PutObjectResult {
@@ -188,6 +190,7 @@ declare namespace OSS {
mime: string; // custom mime, will send with Content-Type entity header
meta: UserMeta;
callback: ObjectCallback;
headers?: object;
}
interface AppendObjectOptions {

View File

@@ -0,0 +1,5 @@
import allKeys = require('all-keys');
allKeys(Symbol.prototype); // $ExpectType Set<string>
allKeys(Symbol.prototype, { includeObjectPrototype: false }); // $ExpectType Set<string>
allKeys(Symbol.prototype, { includeSymbols: false }); // $ExpectType Set<string>

29
types/all-keys/index.d.ts vendored Normal file
View File

@@ -0,0 +1,29 @@
// Type definitions for all-keys 2.0
// Project: https://github.com/sindresorhus/all-keys#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
export = allKeys;
/**
* Get all property keys of an object including non-enumerable and inherited ones.
* Like [Reflect.ownKeys()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/ownKeys)
* but traverses up the prototype-chain.
*/
declare function allKeys(obj: object, options?: allKeys.Options): Set<string>;
declare namespace allKeys {
interface Options {
/**
* Include `Object.prototype` properties like `isPrototypeOf`.
* @default true
*/
includeObjectPrototype?: boolean;
/**
* Include [Symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) keys.
* @default true
*/
includeSymbols?: boolean;
}
}

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"all-keys-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -0,0 +1,4 @@
import allPropertyNames = require('all-property-names');
// $ExpectType Set<string>
allPropertyNames(Symbol.prototype);

9
types/all-property-names/index.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
// Type definitions for all-property-names 1.0
// Project: https://github.com/sindresorhus/all-property-names#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
export = allPropertyNames;
declare function allPropertyNames(input: object): Set<string>;

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"all-property-names-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -54,12 +54,12 @@ declare namespace AltJS {
export type Source = {[name:string]: () => SourceModel<any>};
export interface SourceModel<S> {
local(state:any, ...args: any[]):any;
local?(state:any, ...args: any[]):any;
remote(state:any, ...args: any[]):Promise<S>;
shouldFetch?(fetchFn:(...args:Array<any>) => boolean):void;
loading?:(args:any) => void;
success?:(state:S) => void;
error?:(args:any) => void;
success:(state:S) => void;
error:(args:any) => void;
interceptResponse?(response:any, action:Action<any>, ...args:Array<any>):any;
}

View File

@@ -0,0 +1,22 @@
const aMap = new AMap.Map('id', {
resizeEnable: true,
animateEnable: true
});
aMap.setCenter(new AMap.LngLat(0, 0));
AMap.plugin(['someplugin'], () => {
console.log('plugin loaded');
});
AMap.convertFrom([116.3, 39.9], 'gps', (status, result) => {
if (result.info === 'ok') {
const _ = result.locations;
}
});
new AMap.Marker({
map: aMap,
title: '',
position: new AMap.LngLat(0, 0),
});

1392
types/amap-js-sdk/index.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"amap-js-sdk-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -1,5 +1,7 @@
// Tests for Amplitude SDK TypeScript definitions
import amplitude = require('amplitude-js');
module Amplitude.Tests {
function all() {

View File

@@ -4,143 +4,142 @@
// Dan Manastireanu <https://github.com/danmana>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module amplitude {
export as namespace amplitude;
type Callback = (responseCode: number, responseBody: string, details?: { reason: string; }) => void;
type LogReturn = number | void;
type Callback = (responseCode: number, responseBody: string, details?: { reason: string; }) => void;
type LogReturn = number | void;
interface Config {
apiEndpoint?: string;
batchEvents?: boolean;
cookieExpiration?: number;
cookieName?: string;
userId?: string;
deviceId?: string;
deviceIdFromUrlParam?: boolean;
domain?: string;
eventUploadPeriodMillis?: number;
eventUploadThreshold?: number;
forceHttps?: boolean;
includeGclid?: boolean;
includeReferrer?: boolean;
includeUtm?: boolean;
language?: string;
logLevel?: 'DISABLE' | 'ERROR' | 'WARN' | 'INFO';
optOut?: boolean;
platform?: string;
saveEvents?: boolean;
savedMaxCount?: number;
saveParamsReferrerOncePerSession?: boolean;
sessionTimeout?: number;
trackingOptions?: {
city?: boolean;
country?: boolean;
device_model?: boolean;
dma?: boolean;
ip_address?: boolean;
language?: boolean;
os_name?: boolean;
os_version?: boolean;
platform?: boolean;
region?: boolean;
version_name?: boolean;
},
unsentKey?: string;
unsentIdentifyKey?: string;
uploadBatchSize?: number;
}
export class Identify {
set(key: string, value: any): Identify;
setOnce(key: string, value: any): Identify;
add(key: string, value: number | string): Identify;
append(key: string, value: any): Identify;
prepend(key: string, value: any): Identify;
unset(key: string): Identify;
}
export class Revenue {
setProductId(productId: string): Revenue;
setQuantity(quantity: number): Revenue;
setPrice(price: number): Revenue;
setRevenueType(revenueType: string): Revenue;
setEventProperties(eventProperties: any): Revenue;
}
export class AmplitudeClient {
constructor(instanceName?: string);
options: Config;
init(apiKey: string, userId?: string, config?: Config, callback?: (client: AmplitudeClient) => void): void;
setVersionName(versionName: string): void;
isNewSession(): boolean;
setSessionId(sessionId: number): void;
getSessionId(): number;
setDomain(domain: string): void;
setUserId(userId: string): void;
setDeviceId(id: string): void;
regenerateDeviceId(): void;
identify(identify_obj: Identify, opt_callback?: Callback): void;
setUserProperties(properties: any): void;
setGlobalUserProperties(properties: any): void;
clearUserProperties(): void;
setOptOut(enable: boolean): void;
setGroup(groupType: string, groupName: string | string[]): void;
logEvent(event: string, data?: any, callback?: Callback): LogReturn;
logEventWithGroups(event: string, data?: any, groups?: any, callback?: Callback): LogReturn;
logRevenueV2(revenue_obj: Revenue): LogReturn;
logRevenue(pric: number, quantity: number, product: string): LogReturn;
logEventWithTimestamp(event: string, data?: any, timestamp?: number, callback?: Callback): LogReturn;
}
// Proxy methods that get executed on the default AmplitudeClient instance (not all client methods are proxied)
export function init(apiKey: string, userId?: string, options?: Config, callback?: (client: AmplitudeClient) => void): void;
export function setVersionName(version: string): void;
export function isNewSession(): boolean;
export function getSessionId(): number;
export function setDomain(domain: string): void;
export function setUserId(userId: string): void;
export function setDeviceId(id: string): void;
export function regenerateDeviceId(): void;
export function identify(identify: Identify, callback?: Callback): void;
export function setUserProperties(properties: any): void;
export function setGlobalUserProperties(properties: any): void;
export function clearUserProperties(): void;
export function setOptOut(optOut: boolean): void;
export function setGroup(groupType: string, groupName: string | string[]): void;
export function logEvent(event: string, data?: any, callback?: Callback): LogReturn;
export function logEventWithGroups(event: string, data?: any, groups?: any, callback?: Callback): LogReturn;
export function logRevenueV2(revenue_obj: Revenue): LogReturn;
export function logRevenue(pric: number, quantity: number, product: string): LogReturn;
export function logEventWithTimestamp(event: string, data?: any, timestamp?: number, callback?: Callback): LogReturn;
export function getInstance(instanceName?: string): AmplitudeClient;
export const __VERSION__: string;
export var options: Config;
interface Config {
apiEndpoint?: string;
batchEvents?: boolean;
cookieExpiration?: number;
cookieName?: string;
userId?: string;
deviceId?: string;
deviceIdFromUrlParam?: boolean;
domain?: string;
eventUploadPeriodMillis?: number;
eventUploadThreshold?: number;
forceHttps?: boolean;
includeGclid?: boolean;
includeReferrer?: boolean;
includeUtm?: boolean;
language?: string;
logLevel?: 'DISABLE' | 'ERROR' | 'WARN' | 'INFO';
optOut?: boolean;
platform?: string;
saveEvents?: boolean;
savedMaxCount?: number;
saveParamsReferrerOncePerSession?: boolean;
sessionTimeout?: number;
trackingOptions?: {
city?: boolean;
country?: boolean;
device_model?: boolean;
dma?: boolean;
ip_address?: boolean;
language?: boolean;
os_name?: boolean;
os_version?: boolean;
platform?: boolean;
region?: boolean;
version_name?: boolean;
},
unsentKey?: string;
unsentIdentifyKey?: string;
uploadBatchSize?: number;
}
export class Identify {
set(key: string, value: any): Identify;
setOnce(key: string, value: any): Identify;
add(key: string, value: number | string): Identify;
append(key: string, value: any): Identify;
prepend(key: string, value: any): Identify;
unset(key: string): Identify;
}
export class Revenue {
setProductId(productId: string): Revenue;
setQuantity(quantity: number): Revenue;
setPrice(price: number): Revenue;
setRevenueType(revenueType: string): Revenue;
setEventProperties(eventProperties: any): Revenue;
}
export class AmplitudeClient {
constructor(instanceName?: string);
options: Config;
init(apiKey: string, userId?: string, config?: Config, callback?: (client: AmplitudeClient) => void): void;
setVersionName(versionName: string): void;
isNewSession(): boolean;
setSessionId(sessionId: number): void;
getSessionId(): number;
setDomain(domain: string): void;
setUserId(userId: string): void;
setDeviceId(id: string): void;
regenerateDeviceId(): void;
identify(identify_obj: Identify, opt_callback?: Callback): void;
setUserProperties(properties: any): void;
setGlobalUserProperties(properties: any): void;
clearUserProperties(): void;
setOptOut(enable: boolean): void;
setGroup(groupType: string, groupName: string | string[]): void;
logEvent(event: string, data?: any, callback?: Callback): LogReturn;
logEventWithGroups(event: string, data?: any, groups?: any, callback?: Callback): LogReturn;
logRevenueV2(revenue_obj: Revenue): LogReturn;
logRevenue(pric: number, quantity: number, product: string): LogReturn;
logEventWithTimestamp(event: string, data?: any, timestamp?: number, callback?: Callback): LogReturn;
}
// Proxy methods that get executed on the default AmplitudeClient instance (not all client methods are proxied)
export function init(apiKey: string, userId?: string, options?: Config, callback?: (client: AmplitudeClient) => void): void;
export function setVersionName(version: string): void;
export function isNewSession(): boolean;
export function getSessionId(): number;
export function setDomain(domain: string): void;
export function setUserId(userId: string): void;
export function setDeviceId(id: string): void;
export function regenerateDeviceId(): void;
export function identify(identify: Identify, callback?: Callback): void;
export function setUserProperties(properties: any): void;
export function setGlobalUserProperties(properties: any): void;
export function clearUserProperties(): void;
export function setOptOut(optOut: boolean): void;
export function setGroup(groupType: string, groupName: string | string[]): void;
export function logEvent(event: string, data?: any, callback?: Callback): LogReturn;
export function logEventWithGroups(event: string, data?: any, groups?: any, callback?: Callback): LogReturn;
export function logRevenueV2(revenue_obj: Revenue): LogReturn;
export function logRevenue(pric: number, quantity: number, product: string): LogReturn;
export function logEventWithTimestamp(event: string, data?: any, timestamp?: number, callback?: Callback): LogReturn;
export function getInstance(instanceName?: string): AmplitudeClient;
export const __VERSION__: string;
export var options: Config;

View File

@@ -1,10 +1,10 @@
import Analytics = require("analytics-node");
var analytics: Analytics;
let analytics: Analytics;
function testConfig(): void {
analytics = new Analytics('YOUR_WRITE_KEY', {
flushAt: 20,
flushAfter: 10000,
flushInterval: 10000,
host: "http://example.com",
enable: true
});
@@ -33,7 +33,7 @@ function testIdentify(): void {
if (err) {
console.error(err);
} else {
data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`))
data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`));
}
});
}
@@ -59,7 +59,7 @@ function testTrack(): void {
if (err) {
console.error(err);
} else {
data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`))
data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`));
}
});
}
@@ -91,20 +91,20 @@ function testPage(): void {
if (err) {
console.error(err);
} else {
data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`))
data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`));
}
});
}
function testAlias(): void {
// the anonymous user does actions ...
analytics.track({ userId: 'anonymous_user', event: 'Anonymous Event' })
analytics.track({ userId: 'anonymous_user', event: 'Anonymous Event' });
// the anonymous user signs up and is aliased
analytics.alias({ previousId: 'anonymous_user', userId: 'identified@gmail.com' })
analytics.alias({ previousId: 'anonymous_user', userId: 'identified@gmail.com' });
// the identified user is identified
analytics.identify({ userId: 'identified@gmail.com', traits: { plan: 'Free' } })
analytics.identify({ userId: 'identified@gmail.com', traits: { plan: 'Free' } });
// the identified user does actions ...
analytics.track({ userId: 'identified@gmail.com', event: 'Identified Action' })
analytics.track({ userId: 'identified@gmail.com', event: 'Identified Action' });
}
function testGroup(): void {
@@ -128,35 +128,41 @@ function testGroup(): void {
if (err) {
console.error(err);
} else {
data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`))
data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`));
}
});
}
function testIntegrations(): void {
analytics.track({
event: 'Upgraded Membershipt',
event: 'Upgraded Membership',
userId: '97234974',
integrations: {
'All': false,
'Vero': true,
'Google Analytics': false
All: false,
Vero: true,
'Google Analytics': false,
AppsFlyer: {
appsflyer_id: 'example-id'
}
}
});
analytics.track({
event: 'Upgraded Membershipt',
event: 'Upgraded Membership',
userId: '97234974',
integrations: {
'All': false,
'Vero': true,
'Google Analytics': false
All: false,
Vero: true,
'Google Analytics': false,
AppsFlyer: {
appsflyer_id: 'example-id'
}
}
}, (err, data) => {
if (err) {
console.error(err);
} else {
data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`))
data.batch.forEach((message) => console.log(`${data.sentAt} : ${message}`));
}
});
}
@@ -164,8 +170,10 @@ function testIntegrations(): void {
function testFlush(): void {
analytics.flush();
analytics.flush((err, batch) => {
if (err) { alert("Oh nos!"); }
else { console.log(batch.batch[0].type); }
if (err) {
alert("Oh nos!");
} else {
console.log(batch.batch[0].type);
}
});
}

View File

@@ -1,4 +1,4 @@
// Type definitions for Segment's analytics.js for Node.js
// Type definitions for analytics-node 3.1
// Project: https://segment.com/docs/libraries/node/
// Definitions by: Andrew Fong <https://github.com/fongandrew>
// Thomas Thiebaud <https://github.com/thomasthiebaud>
@@ -19,7 +19,7 @@ declare namespace AnalyticsNode {
_metadata: {
nodeVersion: string;
[key: string]: any;
},
};
timestamp?: Date;
messageId?: string;
anonymousId?: string | number;
@@ -27,19 +27,21 @@ declare namespace AnalyticsNode {
}
interface Data {
batch: Message[],
batch: Message[];
timestamp: Date;
sentAt: Date;
}
interface Integrations {
[index: string]: boolean;
[integration_name: string]: IntegrationValue;
}
export class Analytics {
type IntegrationValue = boolean | { [integration_key: string]: any };
class Analytics {
constructor(writeKey: string, opts?: {
flushAt?: number,
flushAfter?: number,
flushInterval?: number,
host?: string,
enable?: boolean
});
@@ -49,9 +51,9 @@ declare namespace AnalyticsNode {
identify(message: {
userId?: string | number;
anonymousId?: string | number;
traits?: Object;
traits?: any;
timestamp?: Date;
context?: Object;
context?: any;
integrations?: Integrations;
}, callback?: (err: Error, data: Data) => void): Analytics;
@@ -60,9 +62,9 @@ declare namespace AnalyticsNode {
userId?: string | number;
anonymousId?: string | number;
event: string;
properties?: Object;
properties?: any;
timestamp?: Date;
context?: Object;
context?: any;
integrations?: Integrations;
}, callback?: (err: Error, data: Data) => void): Analytics;
@@ -73,9 +75,9 @@ declare namespace AnalyticsNode {
anonymousId?: string | number;
category?: string;
name?: string;
properties?: Object;
properties?: any;
timestamp?: Date;
context?: Object;
context?: any;
integrations?: Integrations;
}, callback?: (err: Error, data: Data) => void): Analytics;
@@ -93,8 +95,8 @@ declare namespace AnalyticsNode {
userId?: string | number;
anonymousId?: string | number;
groupId: string | number;
traits?: Object;
context?: Object;
traits?: any;
context?: any;
timestamp?: Date;
integrations?: Integrations;
}, callback?: (err: Error, data: Data) => void): Analytics;

View File

@@ -1,79 +1 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}
{ "extends": "dtslint/dt.json" }

View File

@@ -153,6 +153,10 @@ declare module 'angular' {
defaultFontSet(name: string): IIconProvider;
}
interface IInkRippleProvider {
disableInkRipple(): void;
}
type IMedia = (media: string) => boolean;
interface ISidenavObject {
@@ -340,6 +344,7 @@ declare module 'angular' {
}
interface IMenuService {
close(): void;
hide(response?: any, options?: any): IPromise<any>;
open(event?: MouseEvent): void;
}

View File

@@ -90,6 +90,7 @@ angular.injector(['ng']).invoke(function ($cacheFactory: angular.ICacheFactorySe
responseError() {}
};
actionDescriptor.cancellable = true;
actionDescriptor.hasBody = true;
});
///////////////////////////////////////

View File

@@ -88,6 +88,7 @@ declare module 'angular' {
withCredentials?: boolean;
responseType?: string;
interceptor?: IResourceInterceptor;
hasBody?: boolean;
}
// Allow specify more resource methods

View File

@@ -1502,16 +1502,28 @@ interface MyScope extends ng.IScope {
foo: string;
}
const directiveCompileFnWithGeneric: ng.IDirectiveCompileFn<MyScope> = (
templateElement: JQLite,
templateAttributes: ng.IAttributes,
transclude: ng.ITranscludeFunction
): ng.IDirectiveLinkFn<MyScope> => {
return (
scope: MyScope,
instanceElement: JQLite,
instanceAttributes: ng.IAttributes
) => {
return null;
};
};
interface MyElement extends JQLite {
foo: string;
}
interface MyAttributes extends ng.IAttributes {
foo: string;
}
interface MyController extends ng.INgModelController {
foo: string;
}
angular.module('WithGenerics', [])
.directive('directiveUsingGenerics', () => {
return {
restrict: 'E',
link(scope: MyScope, element: MyElement, templateAttributes: MyAttributes, controller: MyController) {
scope['name'] = 'Jeff';
}
};
})
.directive('linkFunctionUsingGenerics', () => {
return (scope: MyScope, element: MyElement, templateAttributes: MyAttributes, controller: MyController) => {
scope['name'] = 'Jeff';
};
});

View File

@@ -240,8 +240,9 @@ declare namespace angular {
* @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind)
* @param directiveFactory An injectable directive factory function.
*/
directive<TScope extends IScope = IScope>(name: string, directiveFactory: Injectable<IDirectiveFactory<TScope>>): IModule;
directive<TScope extends IScope = IScope>(object: {[directiveName: string]: Injectable<IDirectiveFactory<TScope>>}): IModule;
directive<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController>(name: string, directiveFactory: Injectable<IDirectiveFactory<TScope, TElement, TAttributes, TController>>): IModule;
directive<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController>(object: {[directiveName: string]: Injectable<IDirectiveFactory<TScope, TElement, TAttributes, TController>>}): IModule;
/**
* Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.
*
@@ -1346,8 +1347,8 @@ declare namespace angular {
}
interface ICompileProvider extends IServiceProvider {
directive<TScope extends IScope = IScope>(name: string, directiveFactory: Injectable<IDirectiveFactory<TScope>>): ICompileProvider;
directive<TScope extends IScope = IScope>(object: {[directiveName: string]: Injectable<IDirectiveFactory<TScope>>}): ICompileProvider;
directive<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController>(name: string, directiveFactory: Injectable<IDirectiveFactory<TScope, TElement, TAttributes, TController>>): ICompileProvider;
directive<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController>(object: {[directiveName: string]: Injectable<IDirectiveFactory<TScope, TElement, TAttributes, TController>>}): ICompileProvider;
component(name: string, options: IComponentOptions): ICompileProvider;
component(object: {[componentName: string]: IComponentOptions}): ICompileProvider;
@@ -2066,29 +2067,31 @@ declare namespace angular {
// and http://docs.angularjs.org/guide/directive
///////////////////////////////////////////////////////////////////////////
interface IDirectiveFactory<TScope extends IScope = IScope> {
(...args: any[]): IDirective<TScope> | IDirectiveLinkFn<TScope>;
type IDirectiveController = IController | IController[] | {[key: string]: IController};
interface IDirectiveFactory<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController> {
(...args: any[]): IDirective<TScope, TElement, TAttributes, TController> | IDirectiveLinkFn<TScope, TElement, TAttributes, TController>;
}
interface IDirectiveLinkFn<TScope extends IScope = IScope> {
interface IDirectiveLinkFn<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController> {
(
scope: TScope,
instanceElement: JQLite,
instanceAttributes: IAttributes,
controller?: IController | IController[] | {[key: string]: IController},
instanceElement: TElement,
instanceAttributes: TAttributes,
controller?: TController,
transclude?: ITranscludeFunction
): void;
}
interface IDirectivePrePost<TScope extends IScope = IScope> {
pre?: IDirectiveLinkFn<TScope>;
post?: IDirectiveLinkFn<TScope>;
interface IDirectivePrePost<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController> {
pre?: IDirectiveLinkFn<TScope, TElement, TAttributes, TController>;
post?: IDirectiveLinkFn<TScope, TElement, TAttributes, TController>;
}
interface IDirectiveCompileFn<TScope extends IScope = IScope> {
interface IDirectiveCompileFn<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController> {
(
templateElement: JQLite,
templateAttributes: IAttributes,
templateElement: TElement,
templateAttributes: TAttributes,
/**
* @deprecated
* Note: The transclude function that is passed to the compile function is deprecated,
@@ -2096,11 +2099,11 @@ declare namespace angular {
* that is passed to the link function instead.
*/
transclude: ITranscludeFunction
): void | IDirectiveLinkFn<TScope> | IDirectivePrePost<TScope>;
): void | IDirectiveLinkFn<TScope, TElement, TAttributes, TController> | IDirectivePrePost<TScope, TElement, TAttributes, TController>;
}
interface IDirective<TScope extends IScope = IScope> {
compile?: IDirectiveCompileFn<TScope>;
interface IDirective<TScope extends IScope = IScope, TElement extends JQLite = JQLite, TAttributes extends IAttributes = IAttributes, TController extends IDirectiveController = IController> {
compile?: IDirectiveCompileFn<TScope, TElement, TAttributes, TController>;
controller?: string | Injectable<IControllerConstructor>;
controllerAs?: string;
/**
@@ -2109,7 +2112,7 @@ declare namespace angular {
* relies upon bindings inside a $onInit method on the controller, instead.
*/
bindToController?: boolean | {[boundProperty: string]: string};
link?: IDirectiveLinkFn<TScope> | IDirectivePrePost<TScope>;
link?: IDirectiveLinkFn<TScope, TElement, TAttributes, TController> | IDirectivePrePost<TScope, TElement, TAttributes, TController>;
multiElement?: boolean;
priority?: number;
/**
@@ -2119,9 +2122,9 @@ declare namespace angular {
require?: string | string[] | {[controller: string]: string};
restrict?: string;
scope?: boolean | {[boundProperty: string]: string};
template?: string | ((tElement: JQLite, tAttrs: IAttributes) => string);
template?: string | ((tElement: TElement, tAttrs: TAttributes) => string);
templateNamespace?: string;
templateUrl?: string | ((tElement: JQLite, tAttrs: IAttributes) => string);
templateUrl?: string | ((tElement: TElement, tAttrs: TAttributes) => string);
terminal?: boolean;
transclude?: boolean | 'element' | {[slot: string]: string};
}

View File

@@ -774,6 +774,7 @@ interface BaseJQueryEventObject extends Event {
pageY: number;
/**
* For key or mouse events, this property indicates the specific key or button that was pressed.
* @deprecated Use `key` for KeyEvents or `button` for MouseEvents instead.
* @see {@link https://api.jquery.com/event.which/}
*/
which: number;
@@ -804,9 +805,12 @@ interface JQueryMouseEventObject extends JQueryInputEventObject {
}
interface JQueryKeyEventObject extends JQueryInputEventObject {
char: any;
/** @deprecated */
char: string;
/** @deprecated */
charCode: number;
key: any;
key: string;
/** @deprecated */
keyCode: number;
}

View File

@@ -1,30 +1,35 @@
import * as colors from 'ansi-colors';
import colors = require('ansi-colors');
let s: string;
colors.red('This is a red string!'); // $ExpectType string
colors.green('This is a red string!'); // $ExpectType string
colors.cyan('This is a cyan string!'); // $ExpectType string
colors.yellow('This is a yellow string!'); // $ExpectType string
s = colors.bgblack("hello");
s = colors.bgblue("hello");
s = colors.bgcyan("hello");
s = colors.bggreen("hello");
s = colors.bgmagenta("hello");
s = colors.bgred("hello");
s = colors.bgwhite("hello");
s = colors.bgyellow("hello");
s = colors.black("hello");
s = colors.blue("hello");
s = colors.bold("hello");
s = colors.cyan("hello");
s = colors.dim("hello");
s = colors.gray("hello");
s = colors.green("hello");
s = colors.grey("hello");
s = colors.hidden("hello");
s = colors.inverse("hello");
s = colors.italic("hello");
s = colors.magenta("hello");
s = colors.red("hello");
s = colors.reset("hello");
s = colors.strikethrough("hello");
s = colors.underline("hello");
s = colors.white("hello");
s = colors.yellow("hello");
colors.bold.red('this is a bold red message'); // $ExpectType string
colors.bold.yellow.italic('this is a bold yellow italicized message'); // $ExpectType string
colors.green.bold.underline('this is a bold green underlined message'); // $ExpectType string
colors.yellow(`foo ${colors.red.bold('red')} bar ${colors.cyan('cyan')} baz`); // $ExpectType string
colors.bold(`foo ${colors.red.dim('bar')} baz`); // $ExpectType string
colors.enabled = false;
colors.visible = false;
colors.hasAnsi(colors.blue('foo')); // $ExpectType boolean
colors.hasColor(colors.blue('foo')); // $ExpectType boolean
colors.unstyle(colors.blue.bold('foo bar baz')); // $ExpectType string
colors.stripColor(colors.blue.bold('foo bar baz')); // $ExpectType string
colors.none('foo'); // $ExpectType string
colors.clear('foo'); // $ExpectType string
colors.noop('foo'); // $ExpectType string
colors.define('reset', [0, 0], 'modifier');
colors.symbols.ballotCross; // $ExpectType string | undefined
colors.symbols.windows.ballotCross; // $ExpectError
colors.symbols.other.ballotCross; // $ExpectType string
colors.symbols.cross; // $ExpectType string
colors.symbols.windows.cross; // $ExpectType string
colors.symbols.other.cross; // $ExpectType string

View File

@@ -1,31 +1,111 @@
// Type definitions for ansi-colors 1.0
// Type definitions for ansi-colors 3.2
// Project: https://github.com/doowb/ansi-colors
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
export function bgblack(s: string): string;
export function bgblue(s: string): string;
export function bgcyan(s: string): string;
export function bggreen(s: string): string;
export function bgmagenta(s: string): string;
export function bgred(s: string): string;
export function bgwhite(s: string): string;
export function bgyellow(s: string): string;
export function black(s: string): string;
export function blue(s: string): string;
export function bold(s: string): string;
export function cyan(s: string): string;
export function dim(s: string): string;
export function gray(s: string): string;
export function green(s: string): string;
export function grey(s: string): string;
export function hidden(s: string): string;
export function inverse(s: string): string;
export function italic(s: string): string;
export function magenta(s: string): string;
export function red(s: string): string;
export function reset(s: string): string;
export function strikethrough(s: string): string;
export function underline(s: string): string;
export function white(s: string): string;
export function yellow(s: string): string;
export = colors;
declare const colors: colors.Colors;
declare namespace colors {
type ColorFn = ((text: string) => string) & Colors;
interface Colors {
enabled: boolean;
visible: boolean;
reset: ColorFn;
bold: ColorFn;
dim: ColorFn;
italic: ColorFn;
underline: ColorFn;
inverse: ColorFn;
hidden: ColorFn;
strikethrough: ColorFn;
black: ColorFn;
red: ColorFn;
green: ColorFn;
yellow: ColorFn;
blue: ColorFn;
magenta: ColorFn;
cyan: ColorFn;
white: ColorFn;
gray: ColorFn;
grey: ColorFn;
bgBlack: ColorFn;
bgRed: ColorFn;
bgGreen: ColorFn;
bgYellow: ColorFn;
bgBlue: ColorFn;
bgMagenta: ColorFn;
bgCyan: ColorFn;
bgWhite: ColorFn;
blackBright: ColorFn;
redBright: ColorFn;
greenBright: ColorFn;
yellowBright: ColorFn;
blueBright: ColorFn;
magentaBright: ColorFn;
cyanBright: ColorFn;
whiteBright: ColorFn;
bgBlackBright: ColorFn;
bgRedBright: ColorFn;
bgGreenBright: ColorFn;
bgYellowBright: ColorFn;
bgBlueBright: ColorFn;
bgMagentaBright: ColorFn;
bgCyanBright: ColorFn;
bgWhiteBright: ColorFn;
hasColor(text: string): boolean;
hasAnsi(text: string): boolean;
unstyle(text: string): string;
stripColor(text: string): string;
none(text: string): string;
clear(text: string): string;
noop(text: string): string;
symbols: Symbols & {
windows: WindowsSymbols;
other: OtherPlatformsSymbols;
};
define(
name: string,
codes: [number, number],
type: 'modifier' | 'color' | 'bg' | 'bright' | 'bgBright'
): void;
}
interface WindowsSymbols {
bullet: string;
check: string;
cross: string;
ellipsis: string;
heart: string;
info: string;
line: string;
middot: string;
minus: string;
plus: string;
question: string;
questionSmall: string;
pointer: string;
pointerSmall: string;
warning: string;
}
interface ExtendedSymbols {
ballotCross: string;
questionFull: string;
}
type Symbols = WindowsSymbols & Partial<ExtendedSymbols>;
type OtherPlatformsSymbols = WindowsSymbols & ExtendedSymbols;
}

View File

@@ -20,4 +20,4 @@
"index.d.ts",
"ansi-colors-tests.ts"
]
}
}

View File

@@ -0,0 +1,30 @@
import * as colors from 'ansi-colors';
let s: string;
s = colors.bgblack("hello");
s = colors.bgblue("hello");
s = colors.bgcyan("hello");
s = colors.bggreen("hello");
s = colors.bgmagenta("hello");
s = colors.bgred("hello");
s = colors.bgwhite("hello");
s = colors.bgyellow("hello");
s = colors.black("hello");
s = colors.blue("hello");
s = colors.bold("hello");
s = colors.cyan("hello");
s = colors.dim("hello");
s = colors.gray("hello");
s = colors.green("hello");
s = colors.grey("hello");
s = colors.hidden("hello");
s = colors.inverse("hello");
s = colors.italic("hello");
s = colors.magenta("hello");
s = colors.red("hello");
s = colors.reset("hello");
s = colors.strikethrough("hello");
s = colors.underline("hello");
s = colors.white("hello");
s = colors.yellow("hello");

31
types/ansi-colors/v1/index.d.ts vendored Normal file
View File

@@ -0,0 +1,31 @@
// Type definitions for ansi-colors 1.0
// Project: https://github.com/doowb/ansi-colors
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export function bgblack(s: string): string;
export function bgblue(s: string): string;
export function bgcyan(s: string): string;
export function bggreen(s: string): string;
export function bgmagenta(s: string): string;
export function bgred(s: string): string;
export function bgwhite(s: string): string;
export function bgyellow(s: string): string;
export function black(s: string): string;
export function blue(s: string): string;
export function bold(s: string): string;
export function cyan(s: string): string;
export function dim(s: string): string;
export function gray(s: string): string;
export function green(s: string): string;
export function grey(s: string): string;
export function hidden(s: string): string;
export function inverse(s: string): string;
export function italic(s: string): string;
export function magenta(s: string): string;
export function red(s: string): string;
export function reset(s: string): string;
export function strikethrough(s: string): string;
export function underline(s: string): string;
export function white(s: string): string;
export function yellow(s: string): string;

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"paths": {
"ansi-colors": [
"ansi-colors/v1"
]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"ansi-colors-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -9,5 +9,8 @@ ansiRegex().test('\u001B[4mcake\u001B[0m'); // $ExpectType boolean
ansiRegex().test('cake'); // $ExpectType boolean
// => false
ansiRegex({onlyFirst: true}).test('cake'); // $ExpectType boolean
// => false
'\u001B[4mcake\u001B[0m'.match(ansiRegex()); // $ExpectType RegExpMatchArray | null
// => ['\u001B[4m', '\u001B[0m']

View File

@@ -1,7 +1,16 @@
// Type definitions for ansi-regex 3.0
// Type definitions for ansi-regex 4.0
// Project: https://github.com/chalk/ansi-regex#readme
// Definitions by: Manish Vachharajani <https://github.com/mvachhar>
// Florian Keller <https://github.com/ffflorian>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function r(): RegExp;
export = r;
declare namespace ansiRegex {
interface Options {
/** Match only the first ANSI escape. */
onlyFirst?: boolean;
}
}
declare function ansiRegex(options?: ansiRegex.Options): RegExp;
export = ansiRegex;

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,4 @@
// Type definitions for ArcGIS API for JavaScript 3.26
// Type definitions for ArcGIS API for JavaScript 3.27
// Project: https://developers.arcgis.com/javascript/3/
// Definitions by: Esri <https://github.com/Esri>
// Bjorn Svensson <https://github.com/bsvensson>
@@ -560,7 +560,7 @@ declare module "esri" {
/** An array of driving time break values. */
breakValues?: number[];
/** The point feature layer around which drive-time areas will be drawn. */
inputLayer: FeatureLayer;
inputLayers: FeatureLayer[];
/** The geometry type of the input layer. */
inputType?: string;
/** Reference to the map object. */
@@ -1351,6 +1351,8 @@ declare module "esri" {
clip?: number;
/** If the widget is enabled and layers can be swiped. */
enabled?: boolean;
/** Indicates whether layer placement should be inverted (switched). */
invertPlacement?: boolean;
/** The layers to be swiped. */
layers: Layer[];
/** The number of pixels to place the tool from the left of the map. */
@@ -2532,7 +2534,7 @@ declare module "esri/Credential" {
class Credential {
/** Token expiration time specified as number of milliseconds since 1 January 1970 00:00:00 UTC. */
expires: number;
/** Indicates whether this credential belongs to a user with admin privileges. */
/** Indicates that this credential was created to access the ArcGIS REST Admin service */
isAdmin: boolean;
/** The Identity Manager's setOAuthRedirectionHandler returns an object that contains a "state" parameter. */
oAuthState: any;
@@ -2600,6 +2602,12 @@ declare module "esri/IdentityManagerBase" {
tokenValidity: number;
/** If your application is on the same domain as *.arcgis.com or ArcGIS Enterprise Server, the IdentityManager will redirect the user to its sign-in page. */
useSignInPage: boolean;
/**
* Returns a Credential object if the user has already signed in to access the given resource and is allowed to do so when using the given application id.
* @param resUrl The resource URL.
* @param appId The registered OAuth application id.
*/
checkAppAccess(resUrl: string, appId: string): any;
/**
* Returns the credential (via Deferred) if the user has already signed in to access the given resource.
* @param resUrl The resource URL.
@@ -2891,7 +2899,7 @@ declare module "esri/SnappingManager" {
}
declare module "esri/SpatialReference" {
/** The spatial reference of a map, layer, or inputs to and outputs from a task. */
/** Defines the spatial reference of a map, layer, or task parameters. */
class SpatialReference {
/** The well-known ID of a spatial reference. */
wkid: number;
@@ -2953,6 +2961,54 @@ declare module "esri/TimeExtent" {
export = TimeExtent;
}
declare module "esri/arcadeProfiles/fieldCalculateProfile" {
/** Module that implements the Arcade field calculate profile in web apps that calculate field values using Arcade expressions. */
var fieldCalculateProfile: {
/**
* Initializes the field calculate profile for the given Arcade expressions.
* @param expressions An array of Arcade expressions intended for use in the calculate profile.
*/
initialize(expressions: string[]): any;
};
export = fieldCalculateProfile;
}
declare module "esri/arcadeProfiles/labelingProfile" {
/** Module that implements the Arcade labeling profile in web apps that label features using Arcade expressions. */
var labelingProfile: {
/**
* Initializes the labeling profile for the given Arcade expressions.
* @param expressions An array of Arcade expressions intended for use in a label class.
*/
initialize(expressions: string[]): any;
};
export = labelingProfile;
}
declare module "esri/arcadeProfiles/popupProfile" {
/** Module that implements the Arcade popup profile for web apps that contain popups that reference Arcade expressions. */
var popupProfile: {
/**
* Initializes the popup profile for the given Arcade expressions.
* @param expressions An array of Arcade expressions intended for use in a popup template.
*/
initialize(expressions: string[]): any;
};
export = popupProfile;
}
declare module "esri/arcadeProfiles/visualizationProfile" {
/** Module that implements the Arcade visualization profile in web apps that render features using Arcade expressions. */
var visualizationProfile: {
/**
* Initializes the visualization profile for the given Arcade expressions.
* @param expressions An array of Arcade expressions intended for use in a renderer.
*/
initialize(expressions: string[]): any;
};
export = visualizationProfile;
}
declare module "esri/arcgis/OAuthInfo" {
import esri = require("esri");
@@ -4827,6 +4883,8 @@ declare module "esri/dijit/LayerSwipe" {
clip: number;
/** If the widget is enabled and layers can be swiped. */
enabled: boolean;
/** Indicates whether layer placement should be inverted (switched). */
invertPlacement: boolean;
/** The layers to be swiped. */
layers: Layer[];
/** The number of pixels to place the tool from the left of the map. */
@@ -6285,7 +6343,7 @@ declare module "esri/dijit/analysis/CreateDriveTimeAreas" {
/** An array of driving time break values. */
breakValues: number[];
/** The point feature layer around which drive-time areas will be drawn. */
inputLayer: FeatureLayer;
inputLayers: FeatureLayer[];
/** The geometry type of the input layer. */
inputType: string;
/** Reference to the map object. */
@@ -9073,6 +9131,8 @@ declare module "esri/graphic" {
getNode(): any;
/** Returns one or more DOM nodes used to draw the graphic. */
getNodes(): any;
/** Applicable to label graphics. */
getParentGraphic(): Graphic;
/** Returns the dojox/gfx/shape.Shape of the Esri graphic. */
getShape(): any;
/** Returns one or more dojox/gfx/shape.Shape used to draw the graphic. */
@@ -10314,6 +10374,8 @@ declare module "esri/layers/FeatureLayer" {
on(type: "query-limit-exceeded", listener: (event: { target: FeatureLayer }) => void): esri.Handle;
/** Fires when queryRelatedFeatures() is complete. */
on(type: "query-related-features-complete", listener: (event: { relatedFeatures: any; target: FeatureLayer }) => void): esri.Handle;
/** Fires right before the actual refresh kicks in for the layer, and only fires when the refresh is triggered by the refreshInterval. */
on(type: "refresh-tick", listener: (event: { target: FeatureLayer }) => void): esri.Handle;
/** Fires when a layer resumes drawing. */
on(type: "resume", listener: (event: { target: FeatureLayer }) => void): esri.Handle;
/** Fires when a layer's minScale and/or maxScale is changed. */
@@ -12419,7 +12481,7 @@ declare module "esri/map" {
getMinScale(): number;
/** Returns the minimum zoom level of the map. */
getMinZoom(): number;
/** Returns the current map scale. */
/** Returns the map scale at the center of the view. */
getScale(): number;
/** Returns the current zoom level of the map. */
getZoom(): number;

View File

@@ -0,0 +1,8 @@
import diff = require('arr-diff');
const a = ['a', 'b', 'c', 'd'];
const b = [1, 2];
diff(['a']); // $ExpectType string[]
diff(['a'], [1]); // $ExpectType string[]
diff([1], ['a']); // $ExpectType number[]

8
types/arr-diff/index.d.ts vendored Normal file
View File

@@ -0,0 +1,8 @@
// Type definitions for arr-diff 4.0
// Project: https://github.com/jonschlinkert/arr-diff
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = arrDiff;
declare function arrDiff<T>(first: T[], ...args: any[][]): T[];

View File

@@ -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",
"arr-diff-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@@ -0,0 +1,8 @@
import arrayMove = require('array-move');
const input = ['a', 'b', 'c'];
const input2 = [1, 2, 3];
arrayMove(input, 1, 2); // $ExpectType string[]
arrayMove(input2, 1, 2); // $ExpectType number[]
arrayMove.mut(input, 1, 2); // $ExpectType void

27
types/array-move/index.d.ts vendored Normal file
View File

@@ -0,0 +1,27 @@
// Type definitions for array-move 1.0
// Project: https://github.com/sindresorhus/array-move
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = arrayMove;
/**
* Move an array item to a different position.
*
* @param from Index of item to move. If negative, it will begin that many elements from the end.
* @param to Index of where to move the item. If negative, it will begin that many elements from the end.
* @returns A new array with the item moved to the new position.
*/
declare function arrayMove<T extends any[]>(input: T, from: number, to: number): T;
declare namespace arrayMove {
/**
* Moves the item to the new position in the input array.
*
* Useful for huge arrays where absolute performance is needed.
*
* @param from Index of item to move. If negative, it will begin that many elements from the end.
* @param to Index of where to move the item. If negative, it will begin that many elements from the end.
*/
function mut(input: any[], from: number, to: number): void;
}

View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"array-move-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

88
types/asn1/asn1-tests.ts Normal file
View File

@@ -0,0 +1,88 @@
import { Ber, BerReader, BerWriter } from 'asn1';
let buf: Buffer = Buffer.alloc(0);
let bool = false;
let str = '';
let num = 0;
let numOrNull: number | null = 0;
const roStrArray: ReadonlyArray<string> = [str];
const reader = new BerReader(buf);
numOrNull = reader.peek();
bool = reader.readBoolean();
numOrNull = reader.readByte(bool);
num = reader.readEnumeration();
num = reader.readInt();
num = reader.readLength();
num = reader.readLength(num);
str = reader.readOID();
str = reader.readOID(num);
numOrNull = reader.readSequence();
numOrNull = reader.readSequence(num);
str = reader.readString();
str = reader.readString(num);
buf = reader.readString(num, bool);
num = reader._readTag();
num = reader._readTag(num);
let writer = new BerWriter();
writer = new BerWriter({
size: num,
growthFactor: num,
});
buf = writer.buffer;
buf = writer._buf;
num = writer._size;
num = writer._offset;
writer.endSequence();
writer.startSequence();
writer.startSequence(num);
writer.writeBoolean(bool);
writer.writeBoolean(bool, num);
writer.writeBuffer(buf, num);
writer.writeByte(num);
writer.writeEnumeration(num);
writer.writeEnumeration(num, num);
writer.writeInt(num);
writer.writeInt(num, num);
writer.writeLength(num);
writer.writeNull();
writer.writeOID(str, num);
writer.writeString(str);
writer.writeString(str, num);
writer.writeStringArray(roStrArray);
writer._ensure(num);
num = Ber.BMPString;
num = Ber.BitString;
num = Ber.Boolean;
num = Ber.CharacterString;
num = Ber.Constructor;
num = Ber.Context;
num = Ber.EOC;
num = Ber.Enumeration;
num = Ber.External;
num = Ber.GeneralString;
num = Ber.GeneralizedTime;
num = Ber.GraphicString;
num = Ber.IA5String;
num = Ber.Integer;
num = Ber.Null;
num = Ber.NumericString;
num = Ber.OID;
num = Ber.ObjectDescriptor;
num = Ber.OctetString;
num = Ber.PDV;
num = Ber.PrintableString;
num = Ber.Real;
num = Ber.RelativeOID;
num = Ber.Sequence;
num = Ber.Set;
num = Ber.T61String;
num = Ber.UTCTime;
num = Ber.UniversalString;
num = Ber.Utf8String;
num = Ber.VideotexString;
num = Ber.VisibleString;

126
types/asn1/index.d.ts vendored Normal file
View File

@@ -0,0 +1,126 @@
// Type definitions for asn1 0.2
// Project: https://github.com/joyent/node-asn1
// Definitions by: Jim Geurts <https://github.com/jgeurts>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="node" />
export class BerReader {
readonly buffer: Buffer;
readonly offset: number;
readonly length: number;
readonly remain: number;
readonly _buf: Buffer;
_size: number;
_offset: number;
constructor(data: Buffer);
peek(): number | null;
readBoolean(): boolean;
readByte(peek: boolean): number | null;
readEnumeration(): number;
readInt(): number;
readLength(offset?: number): number;
readOID(tag?: number): string;
readSequence(tag?: number): number | null;
readString(tag?: number): string;
readString(tag: number, retbuf: boolean): Buffer;
_readTag(tag?: number): number;
}
export class BerWriter {
readonly buffer: Buffer;
readonly _buf: Buffer;
readonly _size: number;
_offset: number;
constructor(options?: {
size: number;
growthFactor: number;
});
endSequence(): void;
startSequence(tag?: number): void;
writeBoolean(b: boolean, tag?: number): void;
writeBuffer(buf: Buffer, tag: number): void;
writeByte(b: number): void;
writeEnumeration(i: number, tag?: number): void;
writeInt(i: number, tag?: number): void;
writeLength(len: number): void;
writeNull(): void;
writeOID(s: string, tag: number): void;
writeString(s: string, tag?: number): void;
writeStringArray(strings: ReadonlyArray<string>): void;
_ensure(length: number): void;
}
export namespace Ber {
const BMPString: number;
const BitString: number;
const Boolean: number;
const CharacterString: number;
const Constructor: number;
const Context: number;
const EOC: number;
const Enumeration: number;
const External: number;
const GeneralString: number;
const GeneralizedTime: number;
const GraphicString: number;
const IA5String: number;
const Integer: number;
const Null: number;
const NumericString: number;
const OID: number;
const ObjectDescriptor: number;
const OctetString: number;
const PDV: number;
const PrintableString: number;
const Real: number;
const RelativeOID: number;
const Sequence: number;
const Set: number;
const T61String: number;
const UTCTime: number;
const UniversalString: number;
const Utf8String: number;
const VideotexString: number;
const VisibleString: number;
}
/*
declare enum BerType {
EOC = 0,
Boolean = 1,
Integer = 2,
BitString = 3,
OctetString = 4,
Null = 5,
OID = 6,
ObjectDescriptor = 7,
External = 8,
Real = 9, // float
Enumeration = 10,
PDV = 11,
Utf8String = 12,
RelativeOID = 13,
Sequence = 16,
Set = 17,
NumericString = 18,
PrintableString = 19,
T61String = 20,
VideotexString = 21,
IA5String = 22,
UTCTime = 23,
GeneralizedTime = 24,
GraphicString = 25,
VisibleString = 26,
GeneralString = 28,
UniversalString = 29,
CharacterString = 30,
BMPString = 31,
Constructor = 32,
Context = 128,
}
*/

25
types/asn1/tsconfig.json Normal file
View File

@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noUnusedParameters": true,
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"asn1-tests.ts"
]
}

3
types/asn1/tslint.json Normal file
View File

@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}

View File

@@ -0,0 +1,16 @@
import Koa = require('koa');
import asyncBusboy = require('async-busboy');
async function middleware(ctx: Koa.Context, next: () => Promise<any>) {
const {files, fields} = await asyncBusboy(ctx.req);
}
async function middleware2(ctx: Koa.Context, next: () => Promise<any>) {
const {fields} = await asyncBusboy(ctx.req, {
limits: {
fileSize: 2 * 1024 * 1024,
},
onFile: (fieldname: string, file: NodeJS.ReadableStream, filename: string, encoding: string, mimetype: string) => {
}
});
}

28
types/async-busboy/index.d.ts vendored Normal file
View File

@@ -0,0 +1,28 @@
// Type definitions for async-busboy 0.7
// Project: https://github.com/m4nuC/async-busboy#readme
// Definitions by: Hiroshi Ioka <https://github.com/hirochachacha>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import * as fs from 'fs';
import * as http from 'http';
import busboy = require('busboy');
interface Options extends busboy.BusboyConfig {
onFile: (
fieldname: string,
file: NodeJS.ReadableStream,
filename: string,
encoding: string,
mimetype: string) => void;
}
type AsyncBusboy = (
req: http.IncomingMessage,
options?: Options
) => Promise<{fields: {[key: string]: any}; files?: fs.ReadStream[]}>;
declare const asyncBusboy: AsyncBusboy;
export = asyncBusboy;

View File

@@ -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",
"async-busboy-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

103
types/async/index.d.ts vendored
View File

@@ -1,13 +1,18 @@
// Type definitions for Async 2.0.1
// Type definitions for Async 2.4
// Project: https://github.com/caolan/async
// Definitions by: Boris Yankov <https://github.com/borisyankov>, Arseniy Maximov <https://github.com/kern0>, Joe Herman <https://github.com/Penryn>, Angus Fenying <https://github.com/fenying>, Pascal Martin <https://github.com/pascalmartin>
// Definitions by: Boris Yankov <https://github.com/borisyankov>
// Arseniy Maximov <https://github.com/kern0>
// Joe Herman <https://github.com/Penryn>
// Angus Fenying <https://github.com/fenying>
// Pascal Martin <https://github.com/pascalmartin>
// Dmitri Trofimov <https://github.com/Dmitri1337>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
export as namespace async;
export interface Dictionary<T> { [key: string]: T; }
export type IterableCollection<T> = T[] | IterableIterator<T> | Dictionary<T>
export type IterableCollection<T> = T[] | IterableIterator<T> | Dictionary<T>;
export interface ErrorCallback<E = Error> { (err?: E | null): void; }
export interface AsyncBooleanResultCallback<E = Error> { (err?: E | null, truthValue?: boolean): void; }
@@ -26,30 +31,40 @@ export interface AsyncBooleanIterator<T, E = Error> { (item: T, callback: AsyncB
export interface AsyncWorker<T, E = Error> { (task: T, callback: ErrorCallback<E>): void; }
export interface AsyncVoidFunction<E = Error> { (callback: ErrorCallback<E>): void; }
export type AsyncAutoTasks<R extends Dictionary<any>, E> = { [K in keyof R]: AsyncAutoTask<R[K], R, E> }
export type AsyncAutoTask<R1, R extends Dictionary<any>, E> = AsyncAutoTaskFunctionWithoutDependencies<R1, E> | (keyof R | AsyncAutoTaskFunction<R1, R, E>)[];
export type AsyncAutoTasks<R extends Dictionary<any>, E> = { [K in keyof R]: AsyncAutoTask<R[K], R, E> };
export type AsyncAutoTask<R1, R extends Dictionary<any>, E> = AsyncAutoTaskFunctionWithoutDependencies<R1, E> | Array<keyof R | AsyncAutoTaskFunction<R1, R, E>>;
export interface AsyncAutoTaskFunctionWithoutDependencies<R1, E = Error> { (cb: AsyncResultCallback<R1, E> | ErrorCallback<E>): void; }
export interface AsyncAutoTaskFunction<R1, R extends Dictionary<any>, E = Error> { (results: R, cb: AsyncResultCallback<R1, E> | ErrorCallback<E>): void; }
export interface DataContainer<T> {
data: T;
}
export interface CallbackContainer {
callback: Function;
}
export interface PriorityContainer {
priority: number;
}
export interface AsyncQueue<T> {
length(): number;
started: boolean;
running(): number;
idle(): boolean;
concurrency: number;
push<R,E = Error>(task: T | T[], callback?: AsyncResultCallback<R, E>): void;
push<R, E = Error>(task: T | T[], callback?: AsyncResultCallback<R, E>): void;
unshift<E = Error>(task: T | T[], callback?: ErrorCallback<E>): void;
remove(filter: (node: DataContainer<T>) => boolean): void;
saturated: () => any;
empty: () => any;
drain: () => any;
paused: boolean;
pause(): void
pause(): void;
resume(): void;
kill(): void;
workersList(): {
data: T,
callback: Function
}[];
workersList<TWorker extends DataContainer<T>, CallbackContainer>(): TWorker[];
error(error: Error, data: any): void;
unsaturated(): void;
buffer: number;
@@ -60,7 +75,7 @@ export interface AsyncPriorityQueue<T> {
concurrency: number;
started: boolean;
paused: boolean;
push<R,E = Error>(task: T | T[], priority: number, callback?: AsyncResultArrayCallback<R, E>): void;
push<R, E = Error>(task: T | T[], priority: number, callback?: AsyncResultArrayCallback<R, E>): void;
saturated: () => any;
empty: () => any;
drain: () => any;
@@ -69,11 +84,7 @@ export interface AsyncPriorityQueue<T> {
pause(): void;
resume(): void;
kill(): void;
workersList(): {
data: T,
priority: number,
callback: Function
}[];
workersList<TWorker extends DataContainer<T>, CallbackContainer, PriorityContainer>(): TWorker[];
error(error: Error, data: any): void;
unsaturated(): void;
buffer: number;
@@ -82,7 +93,7 @@ export interface AsyncPriorityQueue<T> {
export interface AsyncCargo {
length(): number;
payload?: number;
push(task: any, callback? : Function): void;
push(task: any, callback?: Function): void;
saturated(): void;
empty(): void;
drain(): void;
@@ -105,11 +116,17 @@ export function forEachOfLimit<T, E = Error>(obj: IterableCollection<T>, limit:
export const eachOf: typeof forEachOf;
export const eachOfSeries: typeof forEachOf;
export const eachOfLimit: typeof forEachOfLimit;
export function map<T, R, E = Error>(arr: T[] | IterableIterator<T>, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function map<T, R, E = Error>(arr: Dictionary<T>, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function map<T, R, E = Error>(arr: T[] | IterableIterator<T> | Dictionary<T>, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export const mapSeries: typeof map;
export function mapLimit<T, R, E = Error>(arr: IterableCollection<T>, limit: number, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function mapValuesLimit<T, R, E = Error>(obj: Dictionary<T>, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback<R, E>) => void, callback: AsyncResultObjectCallback<R, E>): void;
export function mapValuesLimit<T, R, E = Error>(
obj: Dictionary<T>,
limit: number,
iteratee: (value: T, key: string, callback: AsyncResultCallback<R, E>) => void,
callback: AsyncResultObjectCallback<R, E>
): void;
export function mapValues<T, R, E = Error>(obj: Dictionary<T>, iteratee: (value: T, key: string, callback: AsyncResultCallback<R, E>) => void, callback: AsyncResultObjectCallback<R, E>): void;
export const mapValuesSeries: typeof mapValues;
export function filter<T, E = Error>(arr: IterableCollection<T>, iterator: AsyncBooleanIterator<T, E>, callback?: AsyncResultArrayCallback<T, E>): void;
@@ -151,7 +168,7 @@ export function concatLimit<T, R, E = Error>(arr: IterableCollection<T>, limit:
export const concatSeries: typeof concat;
// Control Flow
export function series<T, E = Error>(tasks: AsyncFunction<T, E>[], callback?: AsyncResultArrayCallback<T, E>): void;
export function series<T, E = Error>(tasks: Array<AsyncFunction<T, E>>, callback?: AsyncResultArrayCallback<T, E>): void;
export function series<T, E = Error>(tasks: Dictionary<AsyncFunction<T, E>>, callback?: AsyncResultObjectCallback<T, E>): void;
export function parallel<T, E = Error>(tasks: Array<AsyncFunction<T, E>>, callback?: AsyncResultArrayCallback<T, E>): void;
export function parallel<T, E = Error>(tasks: Dictionary<AsyncFunction<T, E>>, callback?: AsyncResultObjectCallback<T, E>): void;
@@ -161,9 +178,9 @@ export function whilst<E = Error>(test: () => boolean, fn: AsyncVoidFunction<E>,
export function doWhilst<T, E = Error>(fn: AsyncFunctionEx<T, E>, test: (...results: T[]) => boolean, callback: ErrorCallback<E>): void;
export function until<E = Error>(test: () => boolean, fn: AsyncVoidFunction<E>, callback: ErrorCallback<E>): void;
export function doUntil<T, E = Error>(fn: AsyncFunctionEx<T, E>, test: (...results: T[]) => boolean, callback: ErrorCallback<E>): void;
export function during<E = Error>(test: (testCallback : AsyncBooleanResultCallback<E>) => void, fn: AsyncVoidFunction<E>, callback: ErrorCallback<E>): void;
export function during<E = Error>(test: (testCallback: AsyncBooleanResultCallback<E>) => void, fn: AsyncVoidFunction<E>, callback: ErrorCallback<E>): void;
export function doDuring<E = Error>(fn: AsyncVoidFunction<E>, test: (testCallback: AsyncBooleanResultCallback<E>) => void, callback: ErrorCallback<E>): void;
export function forever<E = Error>(next: (next : ErrorCallback<E>) => void, errBack: ErrorCallback<E>) : void;
export function forever<E = Error>(next: (next: ErrorCallback<E>) => void, errBack: ErrorCallback<E>): void;
export function waterfall<T, E = Error>(tasks: Function[], callback?: AsyncResultCallback<T, E>): void;
export function compose(...fns: Function[]): Function;
export function seq(...fns: Function[]): Function;
@@ -172,34 +189,52 @@ export function applyEachSeries(fns: Function[], ...argsAndCallback: any[]): voi
export function queue<T, E = Error>(worker: AsyncWorker<T, E>, concurrency?: number): AsyncQueue<T>;
export function queue<T, R, E = Error>(worker: AsyncResultIterator<T, R, E>, concurrency?: number): AsyncQueue<T>;
export function priorityQueue<T, E = Error>(worker: AsyncWorker<T, E>, concurrency: number): AsyncPriorityQueue<T>;
export function cargo<E = Error>(worker : (tasks: any[], callback : ErrorCallback<E>) => void, payload? : number) : AsyncCargo;
export function cargo<E = Error>(worker: (tasks: any[], callback: ErrorCallback<E>) => void, payload?: number): AsyncCargo;
export function auto<R extends Dictionary<any>, E = Error>(tasks: AsyncAutoTasks<R, E>, concurrency?: number, callback?: AsyncResultCallback<R, E>): void;
export function auto<R extends Dictionary<any>, E = Error>(tasks: AsyncAutoTasks<R, E>, callback?: AsyncResultCallback<R, E>): void;
export function autoInject<E = Error>(tasks: any, callback?: AsyncResultCallback<any, E>): void;
export function retry<T, E = Error>(opts: number, task: (callback : AsyncResultCallback<T, E>, results: any) => void, callback: AsyncResultCallback<any, E>): void;
export function retry<T, E = Error>(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback<T, E>, results : any) => void, callback: AsyncResultCallback<any, E>): void;
export function retry<T, E = Error>(
opts: number | {
times: number,
interval: number | ((retryCount: number) => number)
},
task: (callback: AsyncResultCallback<T, E>, results: any) => void,
callback: AsyncResultCallback<any, E>
): void;
export function retryable<T, E = Error>(opts: number | {times: number, interval: number}, task: AsyncFunction<T, E>): AsyncFunction<T, E>;
export function apply<E = Error>(fn: Function, ...args: any[]): AsyncFunction<any,E>;
export function apply<E = Error>(fn: Function, ...args: any[]): AsyncFunction<any, E>;
export function nextTick(callback: Function, ...args: any[]): void;
export const setImmediate: typeof nextTick;
export function reflect<T, E = Error>(fn: AsyncFunction<T, E>) : (callback: (err: null, result: {error?: E, value?: T}) => void) => void;
export function reflectAll<T, E = Error>(tasks: AsyncFunction<T, E>[]): ((callback: (err: null, result: {error?: E, value?: T}) => void) => void)[];
export function reflect<T, E = Error>(fn: AsyncFunction<T, E>): (callback: (err: null, result: {error?: E, value?: T}) => void) => void;
export function reflectAll<T, E = Error>(tasks: Array<AsyncFunction<T, E>>): Array<(callback: (err: null, result: {error?: E, value?: T}) => void) => void>;
export function timeout<T, E = Error>(fn: AsyncFunction<T, E>, milliseconds: number, info?: any): AsyncFunction<T, E>;
export function timeout<T, R, E = Error>(fn: AsyncResultIterator<T, R, E>, milliseconds: number, info?: any): AsyncResultIterator<T, R, E>;
export function times<T, E> (n: number, iterator: AsyncResultIterator<number, T, E>, callback: AsyncResultArrayCallback<T, E>): void;
export function times<T, E>(n: number, iterator: AsyncResultIterator<number, T, E>, callback: AsyncResultArrayCallback<T, E>): void;
export function timesSeries<T, E = Error>(n: number, iterator: AsyncResultIterator<number, T, E>, callback: AsyncResultArrayCallback<T, E>): void;
export function timesLimit<T, E = Error>(n: number, limit: number, iterator: AsyncResultIterator<number, T, E>, callback: AsyncResultArrayCallback<T, E>): void;
export function transform<T, R, E = Error>(arr: T[], iteratee: (acc: R[], item: T, key: number, callback: (error?: E) => void) => void, callback?: AsyncResultArrayCallback<T, E>): void;
export function transform<T, R, E = Error>(arr: T[], acc: R[], iteratee: (acc: R[], item: T, key: number, callback: (error?: E) => void) => void, callback?: AsyncResultArrayCallback<T, E>): void;
export function transform<T, R, E = Error>(arr: {[key: string] : T}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void, callback?: AsyncResultObjectCallback<T, E>): void;
export function transform<T, R, E = Error>(arr: {[key: string] : T}, acc: {[key: string] : R}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void, callback?: AsyncResultObjectCallback<T, E>): void;
export function transform<T, R, E = Error>(
arr: {[key: string]: T},
iteratee: (acc: {[key: string]: R}, item: T, key: string, callback: (error?: E) => void) => void,
callback?: AsyncResultObjectCallback<T, E>
): void;
export function race<T, E = Error>(tasks: (AsyncFunction<T, E>)[], callback: AsyncResultCallback<T, E>) : void;
export function transform<T, R, E = Error>(
arr: {[key: string]: T},
acc: {[key: string]: R},
iteratee: (acc: {[key: string]: R}, item: T, key: string, callback: (error?: E) => void) => void,
callback?: AsyncResultObjectCallback<T, E>
): void;
export function race<T, E = Error>(tasks: Array<AsyncFunction<T, E>>, callback: AsyncResultCallback<T, E>): void;
// Utils
export function memoize(fn: Function, hasher?: Function): Function;

View File

@@ -10,45 +10,45 @@ function eachOfIterator<T, K, E>(item: T, key: K, callback: (err: Error) => void
function concatIterator<T, R, E>(item: T, callback: (err: E, res: R[]) => void) { }
async.map(collectionGenerator(), funcMapIterator, funcMapComplete)
async.mapSeries(collectionGenerator(), funcMapIterator, funcMapComplete)
async.mapLimit(collectionGenerator(), 2, funcMapIterator, funcMapComplete)
async.map(collectionGenerator(), funcMapIterator, funcMapComplete);
async.mapSeries(collectionGenerator(), funcMapIterator, funcMapComplete);
async.mapLimit(collectionGenerator(), 2, funcMapIterator, funcMapComplete);
async.filter(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { })
async.filterSeries(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { })
async.filterLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, results: any[]) { })
async.select(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { })
async.selectSeries(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { })
async.selectLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, results: any[]) { })
async.filter(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { });
async.filterSeries(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { });
async.filterLimit(collectionGenerator(), 2, booleanIterator, (err: Error, results: any[]) => { });
async.select(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { });
async.selectSeries(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { });
async.selectLimit(collectionGenerator(), 2, booleanIterator, (err: Error, results: any[]) => { });
async.reject(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { })
async.rejectSeries(collectionGenerator(), booleanIterator, function (err: Error, results: any[]) { })
async.rejectLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, results: any[]) { })
async.reject(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { });
async.rejectSeries(collectionGenerator(), booleanIterator, (err: Error, results: any[]) => { });
async.rejectLimit(collectionGenerator(), 2, booleanIterator, (err: Error, results: any[]) => { });
async.each(collectionGenerator(), eachIterator, function (err: Error) { })
async.eachLimit(collectionGenerator(), 2, eachIterator, function (err: Error) { })
async.eachSeries(collectionGenerator(), eachIterator, function (err: Error) { })
async.eachOf(collectionGenerator(), eachOfIterator, function (err: Error) { })
async.eachOfLimit(collectionGenerator(), 2, eachOfIterator, function (err: Error) { })
async.eachOfSeries(collectionGenerator(), eachOfIterator, function (err: Error) { })
async.forEach(collectionGenerator(), eachIterator, function (err: Error) { })
async.forEachLimit(collectionGenerator(), 2, eachIterator, function (err: Error) { })
async.forEachSeries(collectionGenerator(), eachIterator, function (err: Error) { })
async.forEachOf(collectionGenerator(), eachOfIterator, function (err: Error) { })
async.forEachOfLimit(collectionGenerator(), 2, eachOfIterator, function (err: Error) { })
async.forEachOfSeries(collectionGenerator(), eachOfIterator, function (err: Error) { })
async.each(collectionGenerator(), eachIterator, (err: Error) => { });
async.eachLimit(collectionGenerator(), 2, eachIterator, (err: Error) => { });
async.eachSeries(collectionGenerator(), eachIterator, (err: Error) => { });
async.eachOf(collectionGenerator(), eachOfIterator, (err: Error) => { });
async.eachOfLimit(collectionGenerator(), 2, eachOfIterator, (err: Error) => { });
async.eachOfSeries(collectionGenerator(), eachOfIterator, (err: Error) => { });
async.forEach(collectionGenerator(), eachIterator, (err: Error) => { });
async.forEachLimit(collectionGenerator(), 2, eachIterator, (err: Error) => { });
async.forEachSeries(collectionGenerator(), eachIterator, (err: Error) => { });
async.forEachOf(collectionGenerator(), eachOfIterator, (err: Error) => { });
async.forEachOfLimit(collectionGenerator(), 2, eachOfIterator, (err: Error) => { });
async.forEachOfSeries(collectionGenerator(), eachOfIterator, (err: Error) => { });
async.every(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { })
async.everyLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, res: boolean) { })
async.everySeries(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { })
async.every(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { });
async.everyLimit(collectionGenerator(), 2, booleanIterator, (err: Error, res: boolean) => { });
async.everySeries(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { });
async.some(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { })
async.someLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, res: boolean) { })
async.someSeries(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { })
async.some(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { });
async.someLimit(collectionGenerator(), 2, booleanIterator, (err: Error, res: boolean) => { });
async.someSeries(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { });
async.detect(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { })
async.detectLimit(collectionGenerator(), 2, booleanIterator, function (err: Error, res: boolean) { })
async.detectSeries(collectionGenerator(), booleanIterator, function (err: Error, res: boolean) { })
async.detect(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { });
async.detectLimit(collectionGenerator(), 2, booleanIterator, (err: Error, res: boolean) => { });
async.detectSeries(collectionGenerator(), booleanIterator, (err: Error, res: boolean) => { });
async.concat(collectionGenerator(), concatIterator, (err: Error, res: any[]) => { })
async.concatSeries(collectionGenerator(), concatIterator, (err: Error, res: any[]) => { })
async.concat(collectionGenerator(), concatIterator, (err: Error, res: any[]) => { });
async.concatSeries(collectionGenerator(), concatIterator, (err: Error, res: any[]) => { });

View File

@@ -1,74 +1,58 @@
interface StringCallback { (err?: Error, result?: string): void; }
interface AsyncStringGetter { (callback: StringCallback): void; }
var taskArray: AsyncStringGetter[] = [
function (callback) {
setTimeout(function () {
callback(undefined, 'one');
}, 200);
},
function (callback) {
setTimeout(function () {
callback(undefined, 'two');
}, 100);
},
const taskArray: AsyncStringGetter[] = [
callback => { setTimeout(() => { callback(undefined, 'one'); }, 200); },
callback => { setTimeout(() => { callback(undefined, 'two'); }, 100); }
];
async.series(taskArray, function (err, results) {
async.series(taskArray, (err, results) => {
if (results) {
let first = results[0];
const first = results[0];
if (first) {
console.log(first.match(/o/))
}
}
});
async.parallel(taskArray, function (err, results) {
if (results) {
let first = results[0];
if (first) {
console.log(first.match(/o/))
}
}
});
async.parallelLimit(taskArray, 3, function (err, results) {
if (results) {
let first = results[0];
if (first) {
console.log(first.match(/o/))
console.log(first.match(/o/));
}
}
});
async.parallel(taskArray, (err, results) => {
if (results) {
const first = results[0];
if (first) {
console.log(first.match(/o/));
}
}
});
async.parallelLimit(taskArray, 3, (err, results) => {
if (results) {
const first = results[0];
if (first) {
console.log(first.match(/o/));
}
}
});
interface Lookup<T> { [key: string]: T; }
interface NumberCallback { (err?: Error, result?: number): void; }
interface AsyncNumberGetter { (callback: NumberCallback): void; }
var taskDict: Lookup<AsyncNumberGetter> = {
one: function(callback) {
setTimeout(function() {
callback(undefined, 1);
}, 200);
},
two: function(callback) {
setTimeout(function() {
callback(undefined, 2);
}, 100);
}
}
const taskDict: Lookup<AsyncNumberGetter> = {
one: callback => { setTimeout(() => { callback(undefined, 1); }, 200); },
two: callback => { setTimeout(() => { callback(undefined, 2); }, 100); }
};
async.series(taskDict, function(err, results) {
let one = results['one'];
console.log(one && one.toFixed(1))
});
async.parallel(taskDict, function(err, results) {
let one = results['one'];
console.log(one && one.toFixed(1))
});
async.parallelLimit(taskDict, 3, function(err, results) {
let one = results['one'];
console.log(one && one.toFixed(1))
async.series(taskDict, (err, results) => {
const one = results['one'];
console.log(one && one.toFixed(1));
});
async.parallel(taskDict, (err, results) => {
const one = results['one'];
console.log(one && one.toFixed(1));
});
async.parallelLimit(taskDict, 3, (err, results) => {
const one = results['one'];
console.log(one && one.toFixed(1));
});

File diff suppressed because it is too large Load Diff

View File

@@ -1,34 +1,8 @@
{
"extends": "dtslint/dt.json",
"rules": {
// TODOs
"arrow-return-shorthand": false,
"array-type": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"max-line-length": false,
"no-consecutive-blank-lines": false,
"no-padding": false,
"no-unnecessary-generics": false,
"no-var-keyword": false,
"no-void-expression": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-const": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"trim-file": false,
"typedef-whitespace": false,
"unified-signatures": false,
"whitespace": false
"ban-types": true, // PRODUCES ERRORS WHEN REMOVED
"callable-types": false, // HAS ISSUES
"no-unnecessary-generics": false // HAS ISSUES
}
}

View File

@@ -136,6 +136,12 @@ webAuth.passwordlessStart({
send: 'code'
}, (err, data) => {});
webAuth.passwordlessLogin({
connection: 'the_connection',
phoneNumber: '123',
verificationCode: '456'
}, (err, data) => {});
webAuth.signupAndAuthorize({
connection: 'the_connection',
email: 'me@example.com',

View File

@@ -270,6 +270,13 @@ export class WebAuth {
*/
passwordlessVerify(options: PasswordlessVerifyOptions, callback: Auth0Callback<any>): void;
/**
* Logs in a user with the verification code sent to the user
* @param options
* @param callback
*/
passwordlessLogin(options: PasswordlessLoginOptions, callback: Auth0Callback<any>): void;
/**
* Renews an existing session on Auth0's servers using `response_mode=web_message` (i.e. Auth0's hosted login page)
*
@@ -615,6 +622,13 @@ export interface PasswordlessVerifyOptions {
send?: string;
}
export interface PasswordlessLoginOptions {
connection: string;
verificationCode: string;
phoneNumber?: string;
email?: string;
}
export interface Auth0UserProfile {
name: string;
nickname: string;
@@ -798,6 +812,8 @@ export interface AuthorizeOptions {
login_hint?: string;
prompt?: string;
mode?: "login" | "signUp";
accessType?: string;
approvalPrompt?: string;
}
export interface CheckSessionOptions extends AuthorizeOptions {

View File

@@ -130,7 +130,8 @@ const otherOptions : Auth0LockConstructorOptions = {
hashCleanup: false,
leeway: 30,
_enableImpersonation: true,
_enableIdPInitiatedLogin: false
_enableIdPInitiatedLogin: false,
defaultADUsernameFromEmailPrefix: false
};
new Auth0Lock(CLIENT_ID, DOMAIN, otherOptions);

View File

@@ -130,7 +130,7 @@ interface Auth0LockConstructorOptions {
closable?: boolean;
configurationBaseUrl?: string;
container?: string;
defaultADUsernameFromEmailPrefix?: string;
defaultADUsernameFromEmailPrefix?: boolean;
defaultDatabaseConnection?: string;
defaultEnterpriseConnection?: string;
flashMessage?: Auth0LockFlashMessageOptions;

View File

@@ -147,11 +147,21 @@ management
management
.updateUser({id: "user_id"}, {"email": "hi@me.co"}, (err: Error, users: auth0.User) => {});
// Update user metadata
management
.updateUserMetadata({id: "user_id"}, {"key": "value"});
// Update user metadata with JSON object
management
.updateUserMetadata({id: "user_id"}, {
key: "value",
numKey: 123,
objKey: {
foo: "bar",
another: "value"
}
});
// Update user metadata using callback
management
.updateUserMetadata({id: "user_id"}, {"key": "value"}, (err: Error, users: auth0.User) => {});

View File

@@ -1,6 +1,8 @@
// Type definitions for auth0 2.9.2
// Type definitions for auth0 2.9.3
// Project: https://github.com/auth0/node-auth0
// Definitions by: Seth Westphal <https://github.com/westy92>
// Ian Howe <https://github.com/ianhowe76>
// Alex Bjørlig <https://github.com/dauledk>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
@@ -32,7 +34,7 @@ export interface RetryOptions {
}
export interface UserMetadata {
[propName: string]: string
[propName: string]: any
}
export interface AppMetadata {
@@ -46,7 +48,10 @@ export interface UserData {
verify_email?: boolean;
password?: string;
phone_number?: string;
phone_verified?: boolean,
phone_verified?: boolean;
given_name?: string;
family_name?: string;
name?: string;
user_metadata?: UserMetadata;
app_metadata?: AppMetadata;
}

View File

@@ -43,5 +43,7 @@ function test_client() {
});
};
connection.open();
if (!connection.isOpen && !connection.isRetrying && connection.session == null) {
connection.open();
}
}

View File

@@ -1,6 +1,6 @@
// Type definitions for AutobahnJS v0.9.7
// Type definitions for AutobahnJS 0.9
// Project: http://autobahn.ws/js/
// Definitions by: Elad Zelingher <https://github.com/darkl>, Andy Hawkins <https://github.com/a904guy/,http://a904guy.com/,http://www.bmbsqd.com>, Wladimir Totino <https://github.com/valepu>, Mathias Teier <https://github.com/glenroy37/,http://kagent.at>
// Definitions by: Elad Zelingher <https://github.com/darkl>, Andy Hawkins <https://github.com/a904guy>, Wladimir Totino <https://github.com/valepu>, Mathias Teier <https://github.com/glenroy37>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="when" />
@@ -191,7 +191,9 @@ declare namespace autobahn {
constructor(options?: IConnectionOptions);
isOpen: boolean;
isRetrying: boolean;
session?: Session;
open(): void;
close(reason?: string, message?: string): void;

Some files were not shown because too many files have changed in this diff Show More