mirror of
https://github.com/gosticks/DefinitelyTyped.git
synced 2026-06-28 22:30:01 +00:00
@@ -5,5 +5,5 @@ indent_size = 4
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
|
||||
[{*.json,*.yml}]
|
||||
[{*.json,*.yml,*.ts}]
|
||||
indent_style = space
|
||||
|
||||
9648
.github/CODEOWNERS
vendored
9648
.github/CODEOWNERS
vendored
File diff suppressed because it is too large
Load Diff
1
.gitignore
vendored
1
.gitignore
vendored
@@ -46,6 +46,7 @@ npm-debug.log
|
||||
.settings/launch.json
|
||||
.vs
|
||||
.vscode
|
||||
.history
|
||||
|
||||
# yarn
|
||||
yarn.lock
|
||||
|
||||
38
README.es.md
38
README.es.md
@@ -22,15 +22,15 @@ Este es el método preferido. Solo está disponible para usuarios TypeScript 2.0
|
||||
npm install --save-dev @types/node
|
||||
```
|
||||
|
||||
Los types deberían ser incluidos automaticamente por el compilador.
|
||||
Los types deberían ser incluidos automáticamente por el compilador.
|
||||
Vea más en el [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html).
|
||||
|
||||
Para un paquete NPM "foo", Estos `typings` estarán en "@types/foo".
|
||||
Para un paquete NPM "foo", estos `typings` estarán en "@types/foo".
|
||||
Si no puedes encontrar tu paquete, búscalo en [TypeSearch](https://microsoft.github.io/TypeSearch/).
|
||||
|
||||
Si aún no puedes encontrarlo, comprueba si el paquete ya [incluye](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) los typings.
|
||||
Esto es provisto usualmente en el campo `"types"` o `"typings"` en el `package.json`,
|
||||
o solo busca por cualquier archivo ".d.ts" en el paquete e incluyelo manualmente con un `/// <reference path="" />`.
|
||||
o solo busca por cualquier archivo ".d.ts" en el paquete e inclúyelo manualmente con un `/// <reference path="" />`.
|
||||
|
||||
|
||||
### Otros métodos
|
||||
@@ -39,7 +39,7 @@ Estos pueden ser utilizados por TypeScript 1.0.
|
||||
|
||||
* [Typings](https://github.com/typings/typings)
|
||||
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use las alternativas preferidas, la publicación DT type de nuget ha sido desactivada)
|
||||
* Descarguelo manualmente desde la `master` branch de este repositorio
|
||||
* Descárguelo manualmente desde la `master` branch de este repositorio
|
||||
|
||||
Tal vez debas añadir manualmente las [referencias](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
|
||||
|
||||
@@ -88,7 +88,7 @@ Primero, haz un [fork](https://guides.github.com/activities/forking/) en este re
|
||||
* `cd types/my-package-to-edit`
|
||||
* Haz cambios. Recuerda editar las pruebas.
|
||||
Si realiza cambios importantes, no olvide [actualizar una versión principal](#quiero-actualizar-un-paquete-a-una-nueva-versión-principal).
|
||||
* También puede que quieras añadirte la sección "Definitions by" en el encabezado del paquete.
|
||||
* También puede que quieras añadirle la sección "Definitions by" en el encabezado del paquete.
|
||||
- Esto hará que seas notificado (a través de tu nombre de usuario en GitHub) cada vez que alguien haga un pull request o issue sobre el paquete.
|
||||
- Haz esto añadiendo tu nombre al final de la línea, así como en `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
|
||||
- O si hay más personas, puede ser multiline
|
||||
@@ -109,7 +109,7 @@ Si no lo hace, puedes hacerlo en el comentario asociado con el PR.
|
||||
Si eres el autor de la librería, o puedes hacer un pull request a la biblioteca, [bundle types](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) en vez de publicarlo en DefinitelyTyped.
|
||||
|
||||
Si estás agregando typings para un paquete NPM, crea un directorio con el mismo nombre.
|
||||
Si el paquete al que le estás agregando typings no es para NPM, asegurate de que el nombre que escojas no genere problemas con el nombre del paquete en NPM.
|
||||
Si el paquete al que le estás agregando typings no es para NPM, asegúrate de que el nombre que escojas no genere problemas con el nombre del paquete en NPM.
|
||||
(Puedes usar `npm info foo` para verificar la existencia del paquete `foo`.)
|
||||
|
||||
Tu paquete debería tener esta estructura:
|
||||
@@ -126,7 +126,7 @@ Ve todas las opciones en [dts-gen](https://github.com/Microsoft/dts-gen).
|
||||
|
||||
También puedes configurar el `tsconfig.json` para añadir nuevos archivos, para agregar un `"target": "es6"` (necesitado por las funciones asíncronas), para agregar a la `"lib"`, o para agregar la opción de compilación `"jsx"`.
|
||||
|
||||
Los miembros de DefinitelyTyped frecuentemente monitorean nuevos PRs, pero ten en mente que la cantidad de PRs podrian ralentizar el proceso.
|
||||
Los miembros de DefinitelyTyped frecuentemente monitorean nuevos PRs, pero ten en mente que la cantidad de PRs podrían ralentizar el proceso.
|
||||
|
||||
Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js).
|
||||
|
||||
@@ -135,7 +135,7 @@ Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTy
|
||||
|
||||
* Primero, sigue el consejo del [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
|
||||
* Formatear: Ya sea utilizar todo en tabs, o siempre utiliza 4 espacios.
|
||||
* `function sum(nums: number[]): number`: Utiliza `ReadonlyArray` si una funcion no escribe a sus parámetros.
|
||||
* `function sum(nums: number[]): number`: Utiliza `ReadonlyArray` si una función no escribe a sus parámetros.
|
||||
* `interface Foo { new(): Foo; }`:
|
||||
Este define el tipo de objeto que esten nuevos. Probablemente quieras `declare class Foo { constructor(); }`.
|
||||
* `const Class: { new(): IClass; }`:
|
||||
@@ -146,7 +146,7 @@ Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTy
|
||||
Un ejemplo donde un tipo de parámetro es aceptable: `function id<T>(value: T): T;`.
|
||||
Un ejemplo donde no es aceptable: `function parseJson<T>(json: string): T;`.
|
||||
Una excepción: `new Map<string, number>()` está bien.
|
||||
* Utilizando los tipos `Function` y `Object` casi nunca es una buena idea. En 99% de los casos es posible especificar un tipo más especifico. Los ejemplos son `(x: number) => number` para [funciones](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) y `{ x: number, y: number }` para objetos. Si no hay certeza en lo absoluto del tipo, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) es la opción correcta, no `Object`. Si el único hecho conocido sobre el tipo es que es un objecto, usa el tipo [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), no `Object` o `{ [key: string]: any }`.
|
||||
* Utilizando los tipos `Function` y `Object` casi nunca es una buena idea. En 99% de los casos es posible especificar un tipo más específico. Los ejemplos son `(x: number) => number` para [funciones](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) y `{ x: number, y: number }` para objetos. Si no hay certeza en lo absoluto del tipo, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) es la opción correcta, no `Object`. Si el único hecho conocido sobre el tipo es que es un objecto, usa el tipo [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), no `Object` o `{ [key: string]: any }`.
|
||||
* `var foo: string | any`:
|
||||
Cuando es usado `any` en un tipo de unión, el tipo resultante todavía es `any`. Así que mientras la porción `string` de este tipo de anotación puede _verse_ útil, de hecho, no ofrece ningún typechecking adicional más que un simple `any`.
|
||||
Dependiendo de la intención, una alternativa aceptable puede ser `any`, `string`, o `string | object`.
|
||||
@@ -204,11 +204,11 @@ Este script utiliza [dtslint](https://github.com/Microsoft/dtslint).
|
||||
|
||||
#### ¿Cuál es exactamente la relación entre este repositorio y los paquetes de `@types` en NPM?
|
||||
|
||||
La `master` branch es automaticamente publicada en el alcance de los `@types` en NPM gracias a los [types-publisher](https://github.com/Microsoft/types-publisher).
|
||||
La `master` branch es automáticamente publicada en el alcance de los `@types` en NPM gracias a los [types-publisher](https://github.com/Microsoft/types-publisher).
|
||||
|
||||
#### He enviado un pull request. ¿Cuánto tardará en ser merged?
|
||||
|
||||
Esto depende, pero la mayoría de los pull requests serán merged en alrededor de una semana. PRs que hayan sido aprovados por un autor listado en el encabezado de las definiciones usualmente son merged más rápidamente; PRs para nuevas definiciones tomarán más tiempo ya que requieren más revisiones de los mantenedores. Cada PR es revisado por un miembro de TypeScript o DefinitelyTyped antes de ser merged, por favor se paciente debido a que factores humanos pueden causar retrasos. Revisa el [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) para ver el progreso mientras los mantenedores trabajan on los PRs abiertos.
|
||||
Esto depende, pero la mayoría de los pull requests serán merged en alrededor de una semana. PRs que hayan sido aprobados por un autor listado en el encabezado de las definiciones usualmente son merged más rápidamente; PRs para nuevas definiciones tomarán más tiempo ya que requieren más revisiones de los mantenedores. Cada PR es revisado por un miembro de TypeScript o DefinitelyTyped antes de ser merged, por favor sé paciente debido a que factores humanos pueden causar retrasos. Revisa el [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) para ver el progreso mientras los mantenedores trabajan en los PRs abiertos.
|
||||
|
||||
#### Mi PR ha sido merged; ¿cuándo será actualizado el paquete de `@types` NPM?
|
||||
|
||||
@@ -216,12 +216,12 @@ Los paquetes NPM deberán ser actualizados en unas cuantas horas. Si ha pasado m
|
||||
|
||||
#### Estoy escribiendo una definición que depende de otra definición. Debería utilizar `<reference types="" />` o una import?
|
||||
|
||||
Si el modulo al cual te estás refiriendo es un módulo externo (utiliza `export`), utilice una import.
|
||||
Si el módulo al cual te estás refiriendo es un módulo externo (utiliza `export`), utilice una import.
|
||||
Si el módulo al cual te refieres es un módulo ambiente (utiliza `declare module`, o simplemente declara las globales), utilice `<reference types="" />`.
|
||||
|
||||
#### He notado que algunos paquetes aquí tienen `package.json`.
|
||||
|
||||
Normalmente no lo necesitaras. Cuando publicas un paquete normalmente nosotros automáticamente crearemos un `package.json` para eso.
|
||||
Normalmente no lo necesitarás. Cuando publicas un paquete normalmente nosotros automáticamente crearemos un `package.json` para eso.
|
||||
Un `package.json` puede ser incluido por el bien de especificar dependencias. Aquí tienen un [ejemplo](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json).
|
||||
No aceptamos otros campos, tales como `"description"`, para que sean definidos manualmente.
|
||||
Además, si necesitas referencia a una versión anterior de typings, debes hacerlo añadiendo `"dependencies": { "@types/foo": "x.y.z" }` al package.json.
|
||||
@@ -260,7 +260,7 @@ Cuando ya no sea un borrador, lo podremos eliminar desde DefinitelyType y hacer
|
||||
Si planeas continuar actualizando la versión anterior del paquete, puedes crear una subcarpeta con la versión actual p.ej. `v2`, y copia los archivos existentes. Si es así, necesitarás:
|
||||
|
||||
1. Actualiza las rutas relativas en `tsconfig.json` al igual que `tslint.json`.
|
||||
2. Añadir reglas de mapeo de rutas para asegurart de que la prueba se está ejecutando contra la versión prevista.
|
||||
2. Añadir reglas de mapeo de rutas para asegurarte de que la prueba se está ejecutando contra la versión prevista.
|
||||
|
||||
Por ejemplo [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) se ve así:
|
||||
|
||||
@@ -280,24 +280,24 @@ Por ejemplo [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi
|
||||
}
|
||||
```
|
||||
|
||||
Si hay otros paquetes en DefinitelyTyped que son incompatibles con la nueva versión, necesitaras mapear las rutas a la versión anterior. También deberá hacer esto para los paquetes que dependen de paquetes que dependen de una version anterior.
|
||||
Si hay otros paquetes en DefinitelyTyped que son incompatibles con la nueva versión, necesitarás mapear las rutas a la versión anterior. También deberá hacer esto para los paquetes que dependen de paquetes que dependen de una version anterior.
|
||||
|
||||
Por ejemplo, `react-router` depende de `history@2`, así que [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) tiene una ruta mapeada a "history": `[ "history/v2" ]`;
|
||||
transitivo así mismo, `react-router-bootstrap` (que depende de `react-router`) también añade una ruta mapeada en su [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
|
||||
|
||||
Además, `/// <reference types=".." />` no trabajara con rutas mapeadas, así que las dependencias deberán utilizar `import`.
|
||||
Además, `/// <reference types=".." />` no trabajará con rutas mapeadas, así que las dependencias deberán utilizar `import`.
|
||||
|
||||
#### ¿Cómo escribo definitions para paquetes que pueden ser usados globalmente y como un módulo?
|
||||
|
||||
El manual de TypeScript contiene excelente [información general para escribir definiciones](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), ademas [este archivo de definiciones de ejemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) el cual muestra como crear una definición utilizando la sintaxis de módulo en ES6, asi como también especificando objetos que son disponibles en el alcance global. Esta técnica es demostrada practicamente en la [definición para big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), el cual es una librería que puede ser cargada globalmente a travéz de una etiqueta script en una página web, o importada via require o imports estilo ES6.
|
||||
El manual de TypeScript contiene excelente [información general para escribir definiciones](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), además [este archivo de definiciones de ejemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) el cual muestra como crear una definición utilizando la sintaxis de módulo en ES6, asi como también especificando objetos que son disponibles en el alcance global. Esta técnica es demostrada prácticamente en la [definición para big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), el cual es una librería que puede ser cargada globalmente a través de una etiqueta script en una página web, o importada vía require o imports estilo ES6.
|
||||
|
||||
Para probar como puede ser usada tu definición cuando se refieren globalmente o como un módulo importado, crea una carpeta `test`, y coloca dos archivos de prueba en él. nombra uno `YourLibraryName-global.test.ts` y el otro `YourLibraryName-module.test.ts`. El archivo de prueba _global_ debe ejercer la definición de acuerdo como va a ser usado en un script cargado en una página web donde la librería estará disponible en el alcance global - en este escenario no debes de especificar la sentencia de import. El archivo _módulo_ de prueba debe de ejercer la definición de acuerdo a como va a ser utilizado cuando sea importado (incluyendo las sentencias `import`). Si especificas un propiedad `files` en tu archivo tsconfig.json, asegurate de incluir ambos archivos de prueba. Un [ejemplo práctico de esto](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) es también disponible en la definición de big.js.
|
||||
Para probar como puede ser usada tu definición cuando se refieren globalmente o como un módulo importado, crea una carpeta `test`, y coloca dos archivos de prueba en él. nombra uno `YourLibraryName-global.test.ts` y el otro `YourLibraryName-module.test.ts`. El archivo de prueba _global_ debe ejercer la definición de acuerdo como va a ser usado en un script cargado en una página web donde la librería estará disponible en el alcance global - en este escenario no debes de especificar la sentencia de import. El archivo _módulo_ de prueba debe de ejercer la definición de acuerdo a como va a ser utilizado cuando sea importado (incluyendo las sentencias `import`). Si especificas una propiedad `files` en tu archivo tsconfig.json, asegurate de incluir ambos archivos de prueba. Un [ejemplo práctico de esto](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) es también disponible en la definición de big.js.
|
||||
|
||||
Por favor tenga en cuenta que no es necesario para ejercer plenamente la definición en cada archivo de prueba - Es suficiente con probar solo los elementos globalmente accesibles en la prueba de archivos globales y ejercer la definición en el módulo del archivo de prueba, o viceversa.
|
||||
|
||||
#### ¿Qué pasa con paquetes scoped?
|
||||
|
||||
Types para un paquete scoped `@foo/bar` deberán ir en `types/foo__bar`. tenga en cuenta el doble guion bajo.
|
||||
Types para un paquete scoped `@foo/bar` deberán ir en `types/foo__bar`. tenga en cuenta el doble guión bajo.
|
||||
|
||||
Cuando `dts-gen` es utilizado como scaffold en un paquete scoped, las propiedades `paths` deberán ser adaptadas manualmente en el paquete generado
|
||||
`tsconfig.json` para referenciar correctamente el paquete scoped:
|
||||
|
||||
338
README.ko.md
Normal file
338
README.ko.md
Normal file
@@ -0,0 +1,338 @@
|
||||
# DefinitelyTyped [](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
|
||||
|
||||
[](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
> 이 저장소는 고품질의 타입스크립트(TypeScript) 자료형 정의(Type definition)를 위한 저장소입니다.
|
||||
|
||||
이 문서가 가장 최신 내용을 담고있긴 하지만, [공식 사이트(definitelytyped.org)](http://definitelytyped.org)도 확인해보시면 좋습니다.
|
||||
|
||||
## 선언 파일(Declaration file)이 뭔가요?
|
||||
|
||||
[타입스크립트 안내서(TypeScript handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)를 읽어보세요.
|
||||
|
||||
## 선언 파일(Declaration file)을 어떻게 받을 수 있나요??
|
||||
|
||||
### npm 사용하기
|
||||
|
||||
아래 방법은 타입스크립트(TypeScript) 2.0+ 이상의 버전을 사용하는 사람들만 사용할 수 있는 방법이기는 합니다만, 이 방법을 사용하기를 장려합니다.
|
||||
|
||||
```sh
|
||||
npm install --save-dev @types/node
|
||||
```
|
||||
|
||||
`node` 를 위한 자료형(Typing)이 컴파일 과정에 자동으로 포함될 겁니다.
|
||||
더 자세한 내용은 [안내서(Handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html)에서 확인해보실 수 있습니다.
|
||||
|
||||
NPM 의 "foo" 패키지에 대응되는 자료형 패키지는 "@types/foo" 입니다.
|
||||
원하시는 패키지를 찾을 수 없는 경우, [타입서치(TypeSearch)](https://microsoft.github.io/TypeSearch/) 사이트에서 한 번 찾아보세요.
|
||||
|
||||
타입서치(TypeSearch)에서도 찾을 수 없는 경우, 찾고 있는 패키지가 자료형(Typing)을
|
||||
[함께 제공](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)하고 있지는 않은지 확인해보세요.
|
||||
패키지에 포함된 자료형(Typing)은 주로 `package.json` 파일의 `"types"` 나 `"typings"` 필드(Field)를 통해 제공되지만,
|
||||
`/// <reference path="" />` 같은 주석을 사용하여 패키지 안의 ".d.ts" 파일들을 직접 가져와야 할 수도 있습니다.
|
||||
|
||||
|
||||
### 그 외의 방법들
|
||||
|
||||
타입스크립트(TypeScript) 1.0 버전에서 사용할 수 있는 방법은 다음과 같습니다.
|
||||
|
||||
* [Typings](https://github.com/typings/typings) 을 사용하기
|
||||
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped) 을 사용하기~~ (다른 방법을 사용해주세요. NuGet 은 더 이상 DT 자료형(Typing)을 제공하지 않습니다.)
|
||||
* 이 저장소의 `master` 브랜치를 직접 내려받기
|
||||
|
||||
위 방법을 사용할 경우 수동으로 [참조(Reference)](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html)를 추가해주어야 할 수 있습니다.
|
||||
|
||||
|
||||
## 어떻게 이곳에 기여할 수 있나요?
|
||||
|
||||
여러분과 같은 많은 기여자들의 도움 덕분에 이 저장소가 돌아가고 있습니다. 감사합니다.
|
||||
|
||||
### 테스트
|
||||
|
||||
여러분이 만든 자료형 선언(Type declation)을 세상에 공유하기에 앞서, 여러분이 스스로 여러분의 자료형 선언(Type declation)을 사용하고 확인해주세요.
|
||||
|
||||
#### 이미 존재하는 자료형 패키지를 임시로 수정하기
|
||||
|
||||
이미 존재하는 패키지의 자료형 선언(Type declaration)에 새로운 기능을 추가하려면 [모듈 증강(module augmentation)](http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)를 사용할 수 있습니다.
|
||||
물론 `node_modules/@types/foo/index.d.ts` 를 직접 수정하실 수도 있으며, 이 파일을 복사한 다음 아래의 과정을 따라하실 수도 있습니다.
|
||||
|
||||
|
||||
#### 새 자료형 패키지를 임시로 추가하기
|
||||
|
||||
사용하고 계신 `tsconfig.json` 에 다음 내용을 추가해주세요.
|
||||
|
||||
```json
|
||||
"baseUrl": "types",
|
||||
"typeRoots": ["types"],
|
||||
```
|
||||
|
||||
(`types` 대신 `src/types` 을 사용하실 수도 있습니다.)
|
||||
그리고 "foo" 모듈(Module)에 대한 선언(Declaration)을 포함하는 `types/foo/index.d.ts` 파일을 만들어주세요.
|
||||
이제 코드 안에서 여러분의 새 자료형 선언(Type declaration)을 사용하는 `"foo"` 모듈(Module)을 임포트(Import)하실 수 있을 겁니다.
|
||||
코드를 컴파일하고 실행시켜서 여러분의 자료형(Typing)이 실행 중에 실제로 벌어지는 일과 잘 맞아떨어지는지 확인해주세요.
|
||||
실제 코드를 통한 확인이 끝나면, [풀 리퀘스트(Pull request)](#풀-리퀘스트pull-request-만들기)를 만들어주세요.
|
||||
[이미 존재하는 패키지를 수정](#이미-존재하는-패키지를-수정하기)하거나 [새 패키지를 만들기](#새-패키지-만들기)위한 과정들을 따라하시면 됩니다.
|
||||
|
||||
|
||||
### 풀 리퀘스트(Pull request) 만들기
|
||||
|
||||
여러분의 자료형 선언이 잘 작동하는지 확인하셨다면, DefinitelyTyped 에 공유해주세요.
|
||||
|
||||
우선, 이 저장소를 [포크(fork)](https://guides.github.com/activities/forking/)해 주시고, [node](https://nodejs.org/) 를 설치하신 뒤, `npm install` 명령을 실행해주세요.
|
||||
|
||||
|
||||
#### 이미 존재하는 패키지를 수정하기
|
||||
|
||||
* `cd types/my-package-to-edit` 명령을 실행합니다.
|
||||
* 자료형(Typing) 파일들을 수정합니다. 테스트를 추가하는 것도 잊지마세요!
|
||||
만약 브레이킹 체인지(Breaking change)를 만드셨다면, [메이저 버전(major version)](#i-want-to-update-a-package-to-a-new-major-version)을 꼭 올려주세요.
|
||||
* 패키지 머릿주석의 "Definitions by" 부분에 여러분의 이름을 추가하실 수도 있습니다.
|
||||
- 이름을 추가하시면 다른 사람들이 그 패키지에 대한 풀 리퀘스트(Pull request)나 이슈(Issue)를 만들 때 여러분에게 알람이 갑니다.
|
||||
- `// Definitions by: Alice <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` 명령을 실행시키고 결과를 확인해주세요.
|
||||
|
||||
이미 존재하는 패키지에 대한 풀 리퀘스트(Pull request)를 만들었을 경우에는, `dt-bot` 이 이전 저자들을 자동으로 호출하는지 확인해주세요.
|
||||
그렇지 않은 경우에는, 여러분이 직접 풀 리퀘스트(Pull request)와 관계있는 사람들을 호출할 수도 있습니다.
|
||||
|
||||
|
||||
#### 새 패키지를 만들기
|
||||
|
||||
만약 라이브러리를 만드는 중이고 라이브러리가 타입스크립트(TypeScript)로 쓰여있다면, DefinitelyTyped 에 선언(Declaration)을 올리는 대신 패키지에 [자동생성된 선언(Declaration) 파일을 포함](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)시킬 수 있습니다.
|
||||
|
||||
NPM 패키지를 위한 자료형(Typing) 패키지를 만드시려면, 패키지의 이름과 같은 이름의 디렉토리를 만들어주세요.
|
||||
NPM 에 올라가 있지 않은 패키지를 위한 자료형(Typing) 패키지를 만드시려면, 그 패키지가 NPM 에 올라와 있는 패키지와 이름이 겹치지 않는지 확인해주세요.
|
||||
(`npm info foo` 명령어를 사용하여 `foo` 패키지가 NPM 에 있는지 확인할 수 있습니다.)
|
||||
|
||||
새 자료형 패키지는 다음과 같은 구조로 구성되어있어야만 합니다.
|
||||
|
||||
| 파일 이름 | 용도 |
|
||||
| --- | --- |
|
||||
| index.d.ts | 패키지를 위한 자료형(Typing)을 포함하는 파일입니다. |
|
||||
| foo-tests.ts | 자료형(Typing)의 테스트를 위한 파일입니다. 이 파일의 코드는 실행되지는 않지만, 자료형 검사(Type checking)를 통과해야 합니다. |
|
||||
| tsconfig.json | `tsc` 명령을 돌릴 수 있게 해주는 파일입니다. |
|
||||
| tslint.json | 린터(Linter)를 사용할 수 있게 해주는 파일입니다. |
|
||||
|
||||
이 파일들은, npm ≥ 5.2.0 에서는 `npx dts-gen --dt --name my-package-name --template module` 명령으로,
|
||||
그 이하 경우에는 `npm install -g dts-gen` 와 `dts-gen --dt --name my-package-name --template module` 명령으로 만들 수 있습니다.
|
||||
`dts-gen` 의 모든 옵션(Option)을 보고싶으시면 [dts-gen](https://github.com/Microsoft/dts-gen) 저장소를 확인해주세요.
|
||||
|
||||
자료형(Typing) 패키지에 새 파일을 추가하거나, `async` 키워드를 사용하기 위해 `"target"` 을 `"es6"` 로 설정하거나, `"lib"` 를 추가하거나, `jsx` 지원을 추가하기 위해서 `tsconfig.json` 파일을 변경해야 할 수도 있습니다.
|
||||
|
||||
DefinitelyTyped 의 관리자들이 주기적으로 새로운 풀 리퀘스트(Pull request)들을 확인하기는 하지만,
|
||||
다른 풀 리퀘스트(Pull request)가 많을 경우 확인이 느려질 수 있다는 걸 알아주세요.
|
||||
|
||||
[base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js) 패키지는 좋은 예시 중 하나입니다.
|
||||
|
||||
|
||||
#### 많이 저지르는 실수들
|
||||
|
||||
* 우선, [안내서(Handbook)](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html)에 나와있는 내용들을 따라주세요.
|
||||
* 코드에서는 모든 곳에서 탭(Tab)을 사용하거나, 항상 4 개의 띄어쓰기를 사용해주세요.
|
||||
* `function sum(nums: number[]): number`의 경우, 만약 함수가 인자를 변경하지 않는다면 `ReadonlyArray` 를 사용해주세요.
|
||||
* `interface Foo { new(): Foo; }`의 경우,
|
||||
이런 선언은 이 형(Type)을 가진 객체(Object)에 `new` 를 사용할 수 있도록 만듭니다. 많은 경우 여러분은 `declare class Foo { constructor(); }` 를 사용하려는 것일 겁니다.
|
||||
* `const Class: { new(): IClass; }`의 경우,
|
||||
`new` 를 사용할 수 있는 상수를 만드는 대신, `class Class { constructor(); }` 와 같이 클래스 선언(Class declaration)을 사용하는 게 더 좋습니다.
|
||||
* `getMeAT<T>(): T`의 경우,
|
||||
만일 자료형 매개변수(Type parameter)가 함수의 매개변수에 등장하지 않는다면, 그런 제너릭(Generic) 함수를 사용할 필요가 없습니다.
|
||||
그 제너릭(Generic) 함수는 단순히 자료형 단언(Type assertion)을 위장시킨 것뿐입니다. 이 경우 `getMeAT() as number` 와 같이 진짜 자료형 단언(Type assertion) 을 사용하는 게 더 좋습니다.
|
||||
다음은 괜찮은 제너릭(Generic)의 예시입니다. `function id<T>(value: T): T;`.
|
||||
다음은 문제가 있는 제너릭(Generic)의 예시입니다. `function parseJson<T>(json: string): T;`.
|
||||
예외적으로, `new Map<string, number>()` 와 같은 경우는 괜찮습니다.
|
||||
* `Function` 이나 `Object` 와 같은 형(Type)을 사용하는 것은 대부분의 경우 문제를 일으킵니다. 99% 의 경우 더 구체적인 형(Type)을 사용하는게 가능합니다. [함수(Function)](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) 를 위해서는 `(x: number) => number` 와 같은, 객체를 위해서는 `{ x: number, y: number }` 와 같은 형(Type)들을 사용할 수 있습니다. 형(Type)에 대한 정보가 전혀 없을 경우에는, `Object` 형(Type)이 아니라 [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) 형(Type)을 사용해야 합니다. 만일 어떤 형(Type)이 객체라는 사실만 알고 있는 경우, `Object` 나 `{ [key: string]: any }` 가 아니라 [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type) 를 사용해주세요.
|
||||
* `var foo: string | any`의 경우,
|
||||
`any` 가 합 자료형(Union type)의 안에서 사용될 경우, 결과 형(Type)은 언제나 `any` 가 됩니다. 따라서 형(Type)의 `string` 부분이 유용해 보인다 하더라도, 사실은 자료형 검사(Type checking)의 측면에서 `any` 와 다른 것이 없습니다.
|
||||
대신, `any`, `string`, 나 `string | object` 중 하나를 필요에 맞게 골라서 사용해주세요.
|
||||
|
||||
|
||||
#### 패키지 삭제하기
|
||||
|
||||
패키지가 스스로의 형(Type)을 [포함](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html)하게 되면, DefinitelyTyped 에 있는 자료형(Typing) 패키지를 삭제하는 것이 좋습니다.
|
||||
|
||||
`npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]` 명령어를 사용하여 자료형(Typing) 패키지를 삭제할 수 있습니다.
|
||||
- `typingsPackageName` 는 삭제할 디렉토리의 이름입니다.
|
||||
- `asOfVersion` 는 새 스텁(Stub) 용 `@types/foo` 를 퍼블리시(Publish)할 버전입니다. 이 버전은 현재 NPM 에 올라간 버전보다 더 높은 버전이어야 합니다.
|
||||
- `sourceRepoURL` 는 자료형(Typing)을 포함하게 된 저장소의 주소입니다.
|
||||
- `libraryName` 는 패키지의 이름을 읽기 쉽게 쓴 것입니다. 즉, "angular2" 대신에 "Angular 2" 와 같이 쓰는 것이 좋습니다. (생략했을 경우에는 "typingsPackageName" 와 같은 것으로 취급됩니다.)
|
||||
|
||||
DefinitelyTyped 의 다른 패키지들이 삭제된 자료형(Typing) 패키지를 사용하고 있을 경우, 형(Type)을 포함하기 시작한 원래 패키지를 사용하도록 수정해야합니다. 삭제된 자료형(Typing) 패키지를 사용하는 각 DefinitelyTyped 패키지들의 `package.json` 파일에 `"dependencies": { "foo": "x.y.z" }` 를 추가해주시면 됩니다.
|
||||
|
||||
DefinitelyTyped 에 한 번도 올라온 적 없는 패키지가 형(Type)을 포함하게 되었다면, `notNeededPackages.json` 파일에 추가할 필요도 없습니다.
|
||||
|
||||
|
||||
#### 린트(Lint)하기
|
||||
|
||||
자료형(Typing) 패키지를 린트(Lint)하려면, 패키지 디렉토리에 `{ "extends": "dtslint/dt.json" }` 를 포함하고 있는 `tslint.json` 파일을 추가해주시면 됩니다. 모든 새 패키지는 해당 파일을 가지고 있어야 합니다.
|
||||
고쳐야 하지만 아직 고쳐지지 않은 린트(Lint) 결과가 있을 때에만 `tslint.json` 에서 린트 규칙(Lint rule)을 사용하지 않도록 설정할 수 있습니다. 예를 들어,
|
||||
|
||||
```js
|
||||
{
|
||||
"extends": "dtslint/dt.json",
|
||||
"rules": {
|
||||
// 이 패키지는 Function 형을 사용하고 있으며, 고치는 게 쉽지 않다.
|
||||
"ban-types": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
(린트 규칙(Lint rule)이 절대로 적용되서는 안되는 경우에는, `// tslint:disable rule-name` 나 `//tslint:disable-next-line rule-name` 를 사용하는 것이 좋습니다. 후자가 더 나은 방식입니다.)
|
||||
|
||||
어떤 표현식(Expression)이 특정한 형(Type)을 가진다고 단언(Assert)하고 싶을 때에는 `$ExpectType` 를 사용하시면 됩니다. 어떤 표현식(Expression)이 컴파일에 실패해야하는 경우에는 `$ExpectError` 를 하시면 됩니다.
|
||||
|
||||
```js
|
||||
// $ExpectType void
|
||||
f(1);
|
||||
|
||||
// $ExpectError
|
||||
f("one");
|
||||
```
|
||||
|
||||
[dtslint](https://github.com/Microsoft/dtslint#write-tests) 저장소의 README 파일에서 더 자세한 내용을 확인하실 수 있습니다.
|
||||
|
||||
이런 테스트들은 `npm run lint package-name` 명령으로 실행해볼 수 있습니다. 이 때, `package-name` 은 테스트하고 싶은 패키지의 이름입니다.
|
||||
테스트 스크립트는 [dtslint](https://github.com/Microsoft/dtslint) 를 사용하고 있습니다.
|
||||
|
||||
|
||||
## 자주 하는 질문들
|
||||
|
||||
#### 이 저장소와 `@types` 패키지들이 대체 무슨 관계가 있는 건가요?
|
||||
|
||||
`master` 브랜치(Branch)의 내용들이 [types-publisher](https://github.com/Microsoft/types-publisher) 를 사용해 자동으로 `@types` 퍼블리시(Publish)됩니다.
|
||||
|
||||
#### 풀 리퀘스트(Pull request)를 제출했습니다. 이게 합쳐질 때까지 얼마나 걸리나요?
|
||||
|
||||
상황에 따라 다르지만, 대부분의 풀 리퀘스트(Pull request)들은 일주일 안에 합쳐집니다. 머릿주석에 있는 저자 중 한명에 의해 승인된 풀 리퀘스트(Pull request)는 보통 더 빨리 합쳐집니다. 새로운 패키지에 대한 풀 리퀘스트(Pull request)는 관리자의 세세한 코드 리뷰를 필요로 하기 때문에 더 오래 걸리는 경우가 많습니다. 각 PR 들은 합쳐지기 전에 TypeScript or DefinitelyTyped 팀 구성원의 코드 리뷰를 받아야 하며, 이는 사람이 하는 일이기 때문에 느려질 수도 있으니 양해를 바랍니다. [풀 리퀘스트 번다운 보드(PR Burndown Board)](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen)에서 열린 풀 리퀘스트에 대한 관리자들의 진행도를 확인하실 수 있습니다.
|
||||
|
||||
#### 내 풀 리퀘스트(Pull request)는 합쳐졌습니다. 언제 NPM 에 `@types` 패키지가 갱신되나요?
|
||||
|
||||
NPM 의 패키지들은 수시간 안에 갱신될 겁니다. 만약 24 시간이 지나도 갱신되지 않으면, 문제를 파악하기 위해 @RyanCavanaugh 나 @andy-ms 를 풀 리퀘스트(Pull request)에서 호출해주세요.
|
||||
|
||||
#### 다른 자료형 정의(Type definition)에 의존하는 자료형 정의(Type definition)을 만들고 있습니다. `<reference types="" />` 와 임포트(import) 중 무엇을 사용해야하나요?
|
||||
|
||||
외부 모듈(`export` 를 사용하는 모듈)을 사용할 경우, 임포트(import)를 사용해주세요.
|
||||
환경과 관련된 모듈(ambient module)(`declare module` 를 쓰거나 전역 변수들을 선언한 모듈)을 사용할 경우, `<reference types="" />` 를 사용해주세요.
|
||||
|
||||
#### `package.json` 파일이 가끔 보이던데?
|
||||
|
||||
일반적으로는 `package.json` 파일을 사용할 필요가 없습니다. 패키지가 퍼블리시(Publish)될 때 패키지를 위한 `package.json` 파일은 자동으로 생성됩니다.
|
||||
가끔 보이는 `package.json` 파일은 의존하는 것들을 표시하기 위해 사용됩니다. [예시](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json)를 한 번 보세요.
|
||||
의존성을 제외한 다른 필드(Field)들, 그러니까 `"description"` 같은 것들은 사용해서는 안됩니다.
|
||||
옛날 `@types` 패키지를 사용하고 싶으실 경우에도 `"dependencies": { "@types/foo": "x.y.z" }` 와 같은 내용을 `package.json` 파일에 넣으셔야 합니다.
|
||||
|
||||
#### 어떤 패키지들에 `tslint.json` 이 없거나, `tsconfig.json` 에 `"noImplicitAny": true`, `"noImplicitThis": true`, 나 `"strictNullChecks": true` 가 없어요.
|
||||
|
||||
그럼 그 패키지들이 잘못된 겁니다. 고쳐서 풀 리퀘스트(Pull request)를 제출해주시면 고맙겠습니다.
|
||||
|
||||
#### 자료형 정의(Type definition)을 요청할 수 있나요?
|
||||
|
||||
이미 요청된 자료형 정의(Type definition)들을 [여기서](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest) 보실 수 있습니다.
|
||||
|
||||
#### DOM 을 위한 자료형 정의(Type definitions)는요?
|
||||
|
||||
웹 표준(Web standard)과 관련이 있는 자료형(Typing)들은 [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) 저장소에 기여해서 고치실 수 있습니다. 고쳐진 자료형(Typing)은 `lib.dom.d.ts` 파일에 포함될 겁니다.
|
||||
|
||||
#### 어떤 패키지가 `export =` 를 쓰고 있는데, 저는 디폴트 임포트(Default import)가 더 좋습니다. `export =` 를 `export default` 로 바꿔도 되나요?
|
||||
|
||||
타입스크립트(TypeScript) 2.7 이상을 사용하고 계시면 프로젝트 안에서 `--esModuleInterop` 를 사용해주세요.
|
||||
그 이하의 경우, 디폴트 임포트(Default import)가 동작하는 환경(Webpack, SystemJS, esm)에서 작업 중이시면 [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) 를 사용하는 걸 고려해보세요.
|
||||
자료형 정의(Type definition)가 맞는 경우에는 자료형 정의(Type definition)을 수정하지 마세요.
|
||||
NPM 패키지의 경우, `node -p 'require("foo")'` 가 원하는 값이라면 `export =` 이 맞고, `node -p 'require("foo").default'` 이 원하는 값이라면 `export default` 이 맞습니다.
|
||||
|
||||
#### 자료형 선언(Type declaration)에서 타입스크립트(TypeScript) 2.1 이상의 기능을 사용하고 싶습니다.
|
||||
|
||||
정의(Definition) 머릿주석(`// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`) 뒤에 `// TypeScript Version: 2.1` 를 추가해주시면 됩니다.
|
||||
|
||||
#### 타입스크립트(TypeScript)에 기본으로 포함되지 않은 DOM API 를 추가하고 싶어요.
|
||||
|
||||
[TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme) 저장소가 관련되어있을 가능성이 있습니다. 해당 저장소의 안내를 따라주세요.
|
||||
해당 표준이 아직 초안인 상태라면, 이 저장소와 관련된 일입니다.
|
||||
`dom-` 으로 시작하는 패키지를 만드신 뒤, "Project" 머릿주석 부분에 해당 표준의 링크를 써 주세요.
|
||||
다만 표준이 초안을 벗어나면 DefinitelyTyped 에서 삭제되고 `@types` 패키지가 지원이 중단된(Deprecated) 것으로 표시될 수도 있습니다.
|
||||
|
||||
#### 패키지를 새 메이저 버전(major version)에 맞게 갱신하고 싶어요.
|
||||
|
||||
옛날 버전도 계속해서 수정할 예정이라면, 이전 버전에 해당하는 새 디렉토리(예를 들어 `2.` 버전을 위해서는 `v2`)를 만들고 현재 파일들을 그 디렉토리로 옮겨야 합니다. 새 디렉토리로 옮긴 뒤에는
|
||||
|
||||
1. `tsconfig.json` 와 `tslint.json` 에 포함된 상대경로들을 수정해주어야 합니다.
|
||||
2. 경로 대응 규칙(Path mapping rule)을 추가하여 테스트가 올바른 버전을 검사하도록 해야합니다.
|
||||
|
||||
예를 들어, [history 패키지의 2 버전의 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) 파일은 다음과 같이 생겼습니다.
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": "../../",
|
||||
"typeRoots": ["../../"],
|
||||
"paths": {
|
||||
"history": [ "history/v2" ]
|
||||
},
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"history-tests.ts"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
수정 중인 패키지에 의존하는 DefinitelyTyped 의 다른 패키지들이 새 버전과 호환되지 않을 경우, 그 패키지들에도 옛날 버전으로의 경로 대응 규칙(Path mapping rule)을 추가해주어야 합니다. 수정 중인 패키지에 의존하는 패키지에 의존하는 패키지들에도 똑같은 작업을 해 주셔야 합니다.
|
||||
|
||||
예를 들어, `react-router` 패키지는 `history@2` 패키지에 의존하고 있기 때문에, [react-router 패키지의 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) 파일이 `"history": [ "history/v2" ]` 와 같은 경로 대응 규칙(Path mapping rule)을 가지고 있는 걸 볼 수 있습니다.
|
||||
이어서 (`react-router` 패키지에 의존하는 패키지인) `react-router-bootstrap` 또한 [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json) 파일 안에 경로 대응 규칙(Path mapping rule)을 가지고 있는 것을 보실 수 있습니다.
|
||||
|
||||
`/// <reference types=".." />` 에서는 경로 대응 규칙(Path mapping rule)이 동작하지 않기 때문에, DefinitelyTyped 패키지로에 의존할 때에는 임포트(import) 를 사용해야 합니다.
|
||||
|
||||
#### 전역적으로도 모듈로도 사용될 수 있는 패키지의 자료형 선언(Type declaration)은 어떻게 쓰나요?
|
||||
|
||||
타입스크립트 안내서(TypeScript Handbook)은 [선언(Declaration)을 쓰는 방법에 대한 전반적인 정보](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html)와 [예시들](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html)을 포함하고 있습니다. 이 내용에는 ES6 식의 모듈 문법을 사용할 수 있는 자료형 선언(Type declaration)을 만드는 방법과 객체를 전역에서 사용할 수 있도록 하는 방법이 포함되어 있습니다. [big.js 패키지의 자료형 선언(Type declaration)](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts)이 실례입니다. 이 패키지는 웹 페이지의 스크립트 태그를 사용해 불러올 수 있으며, 또한 ES6 식의 임포트(Import) 구문을 사용해서 불러올 수도 있습니다.
|
||||
|
||||
여러분의 패키지가 임포트(Import) 구문을 사용했을 때와 전역적으로 불렀을 때를 테스트 해보고 싶다면, `test` 디렉토리를 추가하고 `YourLibraryName-global.test.ts` 그리고 `YourLibraryName-module.test.ts` 라는 이름으로 테스트 파일 두 개를 추가해주세요. **전역(Global)** 테스트 파일은 웹 페이지에서 전역적으로 사용될 때를 테스트하는 파일입니다. 이 파일에서는 임포트(Import) 구문을 사용하지 않아야 합니다. **모듈(Module)** 테스트 파일은 임포트(Import) 구문을 사용할 때를 테스트 하는 파일입니다. 만약 여러분의 `tsconfig.json` 파일이 `files` 필드(Field)를 가지고 있다면, 이 필드(Field)는 반드시 두 테스트 파일을 모두 포함해야 합니다. [이 방식을 사용하는 실례](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) 또한 big.js 패키지의 자료형 선언(Type declaration)에서 확인해보실 수 있습니다.
|
||||
|
||||
각각의 테스트 파일에 모든 상황을 테스트할 필요는 없다는 걸 잊지마세요. 전역 테스트 파일에서는 전역적으로 사용될 때만 테스트하고, 모듈 테스트 파일에서 나머지 상황들을 모두 테스트 할 수 있으며, 그 반대의 경우도 괜찮습니다.
|
||||
|
||||
#### 지역 패키지(Scoped package)의 경우는 어떻게 하죠?
|
||||
|
||||
`@foo/bar` 패키지와 같은 지역 패키지(Scoped package)를 위한 자료형 패키지(Type package)는 `types/foo__bar` 디렉토리에 추가하면 됩니다. 밑줄 문자가 두 번 있는 것에 주의하세요.
|
||||
|
||||
지역 패키지(Scoped package)를 위한 자료형 패키지(Type package)를 생성하기 위해 `dts-gen` 를 사용한 경우에는,
|
||||
다음과 같이 생성된 `tsconfig.json` 안에 지역 패키지(Scoped package)를 위한 적절한 경로 대응 규칙(Path mapping rule)을 추가해주어야 합니다.
|
||||
|
||||
```json
|
||||
{
|
||||
"paths":{
|
||||
"@foo/bar": ["foo__bar"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### 깃헙(GitHub)이 보여주는 파일 히스토리(History)가 불완전해요.
|
||||
|
||||
깃헙은 이름이 바뀐 파일의 히스토리(History)를 [지원하지 않습니다](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames). 대신 [`git log --follow`](https://www.git-scm.com/docs/git-log) 명령을 사용하세요.
|
||||
|
||||
#### ES6 에서 사용하는 임포트(Import)를 사용하기 위해 모듈을 익스포트(Export)하지 않는 패키지들에 빈 이름공간을 추가해야 하나요?
|
||||
|
||||
[chai-http](https://github.com/chaijs/chai-http) 패키지와 같은 몇몇 패키지들은 함수를 익스포트(Export)합니다.
|
||||
|
||||
이런 패키지들을 `import * as foo from "foo";` 와 같이 임포트(Import)하면 다음과 같은 오류가 발생합니다.
|
||||
|
||||
> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct
|
||||
|
||||
이 오류는 함수의 이름과 똑같은 빈 이름공간(Namespace)을 정의해서 없앨 수 있으나, 좋은 방법은 아닙니다.
|
||||
[스택오버플로(Stack Overflow)의 이 질문의 답변](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this)이 이 문제와 관련되어 자주 언급됩니다.
|
||||
|
||||
`import foo = require("foo");` 를 사용하여 모듈을 임포트(Import)하거나, 환경에서 ES6 모듈 변환(Module interop)을 지원한다면 `--allowSyntheticDefaultImports` 와 함께 `import foo from "foo";` 같은 디폴트 임포트(Default import)를 사용하는 것이 더 나은 방법입니다.
|
||||
|
||||
## 라이센스
|
||||
|
||||
이 프로젝트는 MIT license 가 적용되어 있습니다.
|
||||
|
||||
각 자료형 정의(Type definition) 파일들의 저작권은 각 기여자들에게 있으며, 기여자들은 해당 자료형 정의(Type definition) 파일들의 맨 위에 나열되어 있습니다.
|
||||
|
||||
[](https://github.com/igrigorik/ga-beacon)
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
Also see the [definitelytyped.org](http://definitelytyped.org) website, although information in this README is more up-to-date.
|
||||
|
||||
*[You can also read this README in Spanish!](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md)*
|
||||
*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) and [Korean!](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md)*
|
||||
|
||||
## What are declaration files?
|
||||
|
||||
@@ -54,7 +54,7 @@ Before you share your improvement with the world, use it yourself.
|
||||
|
||||
#### Test editing an existing package
|
||||
|
||||
To add new features you can use [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html).
|
||||
To add new features you can use [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation).
|
||||
You can also directly edit the types in `node_modules/@types/foo/index.d.ts`, or copy them from there and follow the steps below.
|
||||
|
||||
|
||||
|
||||
@@ -144,6 +144,12 @@
|
||||
"sourceRepoURL": "https://github.com/Azure/azure-mobile-apps-node/",
|
||||
"asOfVersion": "3.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "@babel/parser",
|
||||
"typingsPackageName": "babel__parser",
|
||||
"sourceRepoURL": "https://github.com/babel/babel",
|
||||
"asOfVersion": "7.1.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "BabylonJS",
|
||||
"typingsPackageName": "babylonjs",
|
||||
@@ -156,12 +162,6 @@
|
||||
"sourceRepoURL": "https://github.com/brianloveswords/base64url",
|
||||
"asOfVersion": "2.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "better-scroll",
|
||||
"typingsPackageName": "better-scroll",
|
||||
"sourceRepoURL": "https://github.com/ustbhuangyi/better-scroll",
|
||||
"asOfVersion": "1.5.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "BigInteger.js",
|
||||
"typingsPackageName": "big-integer",
|
||||
@@ -180,6 +180,12 @@
|
||||
"sourceRepoURL": "https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions",
|
||||
"asOfVersion": "2.0.15"
|
||||
},
|
||||
{
|
||||
"libraryName": "bitwise",
|
||||
"typingsPackageName": "bitwise",
|
||||
"sourceRepoURL": "https://github.com/dodekeract/bitwise",
|
||||
"asOfVersion": "2.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "botvs",
|
||||
"typingsPackageName": "botvs",
|
||||
@@ -396,6 +402,18 @@
|
||||
"sourceRepoURL": "https://github.com/MikeMcl/decimal.js",
|
||||
"asOfVersion": "7.4.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "deepmerge",
|
||||
"typingsPackageName": "deepmerge",
|
||||
"sourceRepoURL": "git@github.com:KyleAMathews/deepmerge.git",
|
||||
"asOfVersion": "2.2.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "delay",
|
||||
"typingsPackageName": "delay",
|
||||
"sourceRepoURL": "https://github.com/sindresorhus/delay",
|
||||
"asOfVersion": "3.1.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "DevExtreme",
|
||||
"typingsPackageName": "devextreme",
|
||||
@@ -528,6 +546,12 @@
|
||||
"sourceRepoURL": "https://github.com/code-chris/extended-listbox",
|
||||
"asOfVersion": "4.0.1"
|
||||
},
|
||||
{
|
||||
"libraryName": "fast-diff",
|
||||
"typingsPackageName": "fast-diff",
|
||||
"sourceRepoURL": "https://github.com/jhchen/fast-diff",
|
||||
"asOfVersion": "1.2.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "JSON-Patch",
|
||||
"typingsPackageName": "fast-json-patch",
|
||||
@@ -570,6 +594,12 @@
|
||||
"sourceRepoURL": "https://github.com/acdlite/flux-standard-action",
|
||||
"asOfVersion": "1.1.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "fork-ts-checker-webpack-plugin",
|
||||
"typingsPackageName": "fork-ts-checker-webpack-plugin",
|
||||
"sourceRepoURL": "https://github.com/Realytics/fork-ts-checker-webpack-plugin",
|
||||
"asOfVersion": "0.4.5"
|
||||
},
|
||||
{
|
||||
"libraryName": "Foundation Sites",
|
||||
"typingsPackageName": "foundation-sites",
|
||||
@@ -606,6 +636,12 @@
|
||||
"sourceRepoURL": "https://github.com/mikedeboer/node-github",
|
||||
"asOfVersion": "7.1.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "gitlab",
|
||||
"typingsPackageName": "gitlab",
|
||||
"sourceRepoURL": "https://github.com/jdalrymple/node-gitlab",
|
||||
"asOfVersion": "2.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "graphene-pk11",
|
||||
"typingsPackageName": "graphene-pk11",
|
||||
@@ -678,6 +714,12 @@
|
||||
"sourceRepoURL": "https://github.com/facebook/immutable-js",
|
||||
"asOfVersion": "3.8.7"
|
||||
},
|
||||
{
|
||||
"libraryName": "interactjs",
|
||||
"typingsPackageName": "interact.js",
|
||||
"sourceRepoURL": "https://github.com/taye/interact.js",
|
||||
"asOfVersion": "1.3.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "inversify",
|
||||
"typingsPackageName": "inversify",
|
||||
@@ -906,12 +948,24 @@
|
||||
"sourceRepoURL": "https://github.com/blakeembrey/lower-case-first",
|
||||
"asOfVersion": "1.0.1"
|
||||
},
|
||||
{
|
||||
"libraryName": "mali",
|
||||
"typingsPackageName": "mali",
|
||||
"sourceRepoURL": "https://github.com/malijs/mali",
|
||||
"asOfVersion": "0.9.2"
|
||||
},
|
||||
{
|
||||
"libraryName": "maquette",
|
||||
"typingsPackageName": "maquette",
|
||||
"sourceRepoURL": "http://maquettejs.org/",
|
||||
"asOfVersion": "2.1.6"
|
||||
},
|
||||
{
|
||||
"libraryName": "maxmind",
|
||||
"typingsPackageName": "maxmind",
|
||||
"sourceRepoURL": "https://github.com/runk/node-maxmind",
|
||||
"asOfVersion": "2.0.5"
|
||||
},
|
||||
{
|
||||
"libraryName": "mendixmodelsdk",
|
||||
"typingsPackageName": "mendixmodelsdk",
|
||||
@@ -948,6 +1002,12 @@
|
||||
"sourceRepoURL": "https://github.com/mweststrate/mobservable-react",
|
||||
"asOfVersion": "1.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "Mobx Cookie",
|
||||
"typingsPackageName": "mobx-cookie",
|
||||
"sourceRepoURL": "https://github.com/will-stone/mobx-cookie",
|
||||
"asOfVersion": "1.1.1"
|
||||
},
|
||||
{
|
||||
"libraryName": "Moment",
|
||||
"typingsPackageName": "moment",
|
||||
@@ -966,6 +1026,12 @@
|
||||
"sourceRepoURL": "https://github.com/mqttjs/MQTT.js",
|
||||
"asOfVersion": "2.5.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "nano",
|
||||
"typingsPackageName": "nano",
|
||||
"sourceRepoURL": "https://github.com/apache/couchdb-nano",
|
||||
"asOfVersion": "7.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "ng-table",
|
||||
"typingsPackageName": "ng-table",
|
||||
@@ -1140,6 +1206,24 @@
|
||||
"sourceRepoURL": "https://github.com/gpbl/react-day-picker",
|
||||
"asOfVersion": "5.3.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-dnd",
|
||||
"typingsPackageName": "react-dnd",
|
||||
"sourceRepoURL": "https://github.com/react-dnd/react-dnd",
|
||||
"asOfVersion": "3.0.2"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-dnd-html5-backend",
|
||||
"typingsPackageName": "react-dnd-html5-backend",
|
||||
"sourceRepoURL": "https://github.com/react-dnd/react-dnd",
|
||||
"asOfVersion": "3.0.2"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-dnd-test-backend",
|
||||
"typingsPackageName": "react-dnd-test-backend",
|
||||
"sourceRepoURL": "https://github.com/react-dnd/react-dnd",
|
||||
"asOfVersion": "3.0.2"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-flip-move",
|
||||
"typingsPackageName": "react-flip-move",
|
||||
@@ -1152,6 +1236,12 @@
|
||||
"sourceRepoURL": "https://github.com/react-ga/react-ga",
|
||||
"asOfVersion": "2.3.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-i18next",
|
||||
"typingsPackageName": "react-i18next",
|
||||
"sourceRepoURL": "https://github.com/i18next/react-i18next",
|
||||
"asOfVersion": "8.1.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-monaco-editor",
|
||||
"typingsPackageName": "react-monaco-editor",
|
||||
@@ -1194,12 +1284,24 @@
|
||||
"sourceRepoURL": "https://github.com/react-native-community/react-native-modal",
|
||||
"asOfVersion": "4.1.1"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-native-navigation",
|
||||
"typingsPackageName": "react-native-navigation",
|
||||
"sourceRepoURL": "https://github.com/wix/react-native-navigation",
|
||||
"asOfVersion": "2.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-split-pane",
|
||||
"typingsPackageName": "react-split-pane",
|
||||
"sourceRepoURL": "https://github.com/tomkp/react-split-pane",
|
||||
"asOfVersion": "0.1.67"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-svg",
|
||||
"typingsPackageName": "react-svg",
|
||||
"sourceRepoURL": "https://github.com/tanem/react-svg",
|
||||
"asOfVersion": "5.0.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "realm",
|
||||
"typingsPackageName": "realm",
|
||||
@@ -1219,7 +1321,7 @@
|
||||
"asOfVersion": "0.1.5"
|
||||
},
|
||||
{
|
||||
"libraryName": "react-bootstrap",
|
||||
"libraryName": "redux-bootstrap",
|
||||
"typingsPackageName": "redux-bootstrap",
|
||||
"sourceRepoURL": "https://github.com/remojansen/redux-bootstrap",
|
||||
"asOfVersion": "1.1.0"
|
||||
@@ -1230,6 +1332,12 @@
|
||||
"sourceRepoURL": "https://github.com/zalmoxisus/redux-devtools-extension",
|
||||
"asOfVersion": "2.13.2"
|
||||
},
|
||||
{
|
||||
"libraryName": "redux-little-router",
|
||||
"typingsPackageName": "redux-little-router",
|
||||
"sourceRepoURL": "https://github.com/FormidableLabs/redux-little-router",
|
||||
"asOfVersion": "15.1.0"
|
||||
},
|
||||
{
|
||||
"libraryName": "redux-persist",
|
||||
"typingsPackageName": "redux-persist",
|
||||
@@ -1494,6 +1602,12 @@
|
||||
"sourceRepoURL": "https://github.com/samchon/tstl",
|
||||
"asOfVersion": "1.5.7"
|
||||
},
|
||||
{
|
||||
"libraryName": "typed.js",
|
||||
"typingsPackageName": "typed.js",
|
||||
"sourceRepoURL": "https://github.com/mattboldt/typed.js",
|
||||
"asOfVersion": "2.0.9"
|
||||
},
|
||||
{
|
||||
"libraryName": "TypeScript",
|
||||
"typingsPackageName": "typescript",
|
||||
@@ -1584,6 +1698,12 @@
|
||||
"sourceRepoURL": "http://webix.com",
|
||||
"asOfVersion": "5.1.1"
|
||||
},
|
||||
{
|
||||
"libraryName": "winston",
|
||||
"typingsPackageName": "winston",
|
||||
"sourceRepoURL": "https://github.com/winstonjs/winston.git",
|
||||
"asOfVersion": "2.4.4"
|
||||
},
|
||||
{
|
||||
"libraryName": "wolfy87-eventemitter",
|
||||
"typingsPackageName": "wolfy87-eventemitter",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "definitely-typed",
|
||||
"version": "0.0.2",
|
||||
"version": "0.0.3",
|
||||
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
30
types/a11y-dialog/a11y-dialog-tests.ts
Normal file
30
types/a11y-dialog/a11y-dialog-tests.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import A11yDialog = require('a11y-dialog');
|
||||
|
||||
const dialogEl = new A11yDialog(document.getElementById("test"));
|
||||
const dialogElTwo = new A11yDialog(document.getElementById("test"), document.getElementById("testContainer"));
|
||||
const dialogElThree = new A11yDialog(document.getElementById("test"), "dummy-element");
|
||||
|
||||
dialogEl.show();
|
||||
dialogEl.hide();
|
||||
dialogElTwo.destroy();
|
||||
dialogElThree.create();
|
||||
|
||||
// Test out interfaces that extends Element.
|
||||
dialogEl.on("show", (el: HTMLElement) => {
|
||||
el.textContent;
|
||||
});
|
||||
|
||||
// Test out element and event.
|
||||
dialogEl.on("create", (el: HTMLElement, evt) => {
|
||||
el.textContent;
|
||||
|
||||
evt.target;
|
||||
});
|
||||
|
||||
dialogEl.on('hide', () => {
|
||||
const t = 5;
|
||||
});
|
||||
|
||||
dialogEl.off("show", (el: HTMLElement) => {
|
||||
el.textContent;
|
||||
});
|
||||
31
types/a11y-dialog/index.d.ts
vendored
Normal file
31
types/a11y-dialog/index.d.ts
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
// Type definitions for a11y-dialog 5.2
|
||||
// Project: https://github.com/edenspiekermann/a11y-dialog
|
||||
// Definitions by: Yuto <https://github.com/Goyatuzo>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.8
|
||||
|
||||
type DialogEvents = "show" | "hide" | "destroy" | "create";
|
||||
declare class A11yDialog {
|
||||
constructor(el: Element | null, containers?: NodeList | Element | string | null);
|
||||
/**
|
||||
* Shows the dialog.
|
||||
*/
|
||||
show(): void;
|
||||
/**
|
||||
* Hides the dialog.
|
||||
*/
|
||||
hide(): void;
|
||||
/**
|
||||
* Unbind click listeners from dialog openers and closers and remove all bound custom event listeners registered with `.on()`
|
||||
*/
|
||||
destroy(): void;
|
||||
/**
|
||||
* Bind click listeners to dialog openers and closers.
|
||||
*/
|
||||
create(el?: Element | null, containers?: NodeList | Element | string | null): void;
|
||||
|
||||
on(evt: DialogEvents, callback: (dialogElement: any, event: Event) => void): void;
|
||||
off(evt: DialogEvents, callback: (dialogElement: any, event: Event) => void): void;
|
||||
}
|
||||
|
||||
export = A11yDialog;
|
||||
25
types/a11y-dialog/tsconfig.json
Normal file
25
types/a11y-dialog/tsconfig.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es6",
|
||||
"dom"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"baseUrl": "../",
|
||||
"typeRoots": [
|
||||
"../"
|
||||
],
|
||||
"types": [],
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"jsx": "react"
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"a11y-dialog-tests.ts"
|
||||
]
|
||||
}
|
||||
17
types/abstract-leveldown/abstract-leveldown-tests.ts
Normal file
17
types/abstract-leveldown/abstract-leveldown-tests.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { AbstractLevelDOWN } from 'abstract-leveldown';
|
||||
|
||||
const test = (levelDown: AbstractLevelDOWN<any, string>) => {
|
||||
levelDown.put("key", "value", (err?) => { });
|
||||
levelDown.put(1, "value", { something: true }, (err?) => { });
|
||||
|
||||
levelDown.get("key", (err?) => { });
|
||||
levelDown.get(1, { something: true }, (err?) => { });
|
||||
};
|
||||
// $ExpectType void
|
||||
test(new AbstractLevelDOWN('here'));
|
||||
// $ExpectType void
|
||||
test(AbstractLevelDOWN('there'));
|
||||
// $ExpectType void
|
||||
test(new AbstractLevelDOWN<any, string>('here'));
|
||||
// $ExpectType void
|
||||
test(AbstractLevelDOWN<any, string>('there'));
|
||||
114
types/abstract-leveldown/index.d.ts
vendored
Normal file
114
types/abstract-leveldown/index.d.ts
vendored
Normal file
@@ -0,0 +1,114 @@
|
||||
// Type definitions for abstract-leveldown 5.0
|
||||
// Project: https://github.com/Level/abstract-leveldown
|
||||
// Definitions by: Meirion Hughes <https://github.com/MeirionHughes>
|
||||
// Daniel Byrne <https://github.com/danwbyrne>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
|
||||
export interface AbstractOptions {
|
||||
readonly [k: string]: any;
|
||||
}
|
||||
|
||||
export type ErrorCallback = (err: Error | undefined) => void;
|
||||
export type ErrorValueCallback<V> = (err: Error | undefined, value: V) => void;
|
||||
export type ErrorKeyValueCallback<K, V> = (err: Error | undefined, key: K, value: V) => void;
|
||||
|
||||
export interface AbstractOpenOptions extends AbstractOptions {
|
||||
createIfMissing?: boolean;
|
||||
errorIfExists?: boolean;
|
||||
}
|
||||
|
||||
export interface AbstractGetOptions extends AbstractOptions {
|
||||
asBuffer?: boolean;
|
||||
}
|
||||
|
||||
export interface AbstractLevelDOWN<K = any, V = any> extends AbstractOptions {
|
||||
open(cb: ErrorCallback): void;
|
||||
open(options: AbstractOpenOptions, cb: ErrorCallback): void;
|
||||
|
||||
close(cb: ErrorCallback): void;
|
||||
|
||||
get(key: K, cb: ErrorValueCallback<V>): void;
|
||||
get(key: K, options: AbstractGetOptions, cb: ErrorValueCallback<V>): void;
|
||||
|
||||
put(key: K, value: V, cb: ErrorCallback): void;
|
||||
put(key: K, value: V, options: AbstractOptions, cb: ErrorCallback): void;
|
||||
|
||||
del(key: K, cb: ErrorCallback): void;
|
||||
del(key: K, options: AbstractOptions, cb: ErrorCallback): void;
|
||||
|
||||
batch(): AbstractChainedBatch<K, V>;
|
||||
batch(array: ReadonlyArray<AbstractBatch<K, V>>, cb: ErrorCallback): AbstractChainedBatch<K, V>;
|
||||
batch(
|
||||
array: ReadonlyArray<AbstractBatch<K, V>>,
|
||||
options: AbstractOptions,
|
||||
cb: ErrorCallback,
|
||||
): AbstractChainedBatch<K, V>;
|
||||
|
||||
iterator(options?: AbstractIteratorOptions<K>): AbstractIterator<K, V>;
|
||||
}
|
||||
|
||||
export interface AbstractLevelDOWNConstructor {
|
||||
// tslint:disable-next-line no-unnecessary-generics
|
||||
new <K = any, V = any>(location: string): AbstractLevelDOWN<K, V>;
|
||||
// tslint:disable-next-line no-unnecessary-generics
|
||||
<K = any, V = any>(location: string): AbstractLevelDOWN<K, V>;
|
||||
}
|
||||
|
||||
export interface AbstractIteratorOptions<K = any> extends AbstractOptions {
|
||||
gt?: K;
|
||||
gte?: K;
|
||||
lt?: K;
|
||||
lte?: K;
|
||||
reverse?: boolean;
|
||||
limit?: number;
|
||||
keys?: boolean;
|
||||
values?: boolean;
|
||||
keyAsBuffer?: boolean;
|
||||
valueAsBuffer?: boolean;
|
||||
}
|
||||
|
||||
export type AbstractBatch<K = any, V = any> = PutBatch<K, V> | DelBatch<K, V>;
|
||||
|
||||
export interface PutBatch<K = any, V = any> {
|
||||
readonly type: 'put';
|
||||
readonly key: K;
|
||||
readonly value: V;
|
||||
}
|
||||
|
||||
export interface DelBatch<K = any, V = any> {
|
||||
readonly type: 'del';
|
||||
readonly key: K;
|
||||
}
|
||||
|
||||
export interface AbstractChainedBatch<K = any, V = any> extends AbstractOptions {
|
||||
put: (key: K, value: V) => this;
|
||||
del: (key: K) => this;
|
||||
clear: () => this;
|
||||
write(cb: ErrorCallback): any;
|
||||
write(options: any, cb: ErrorCallback): any;
|
||||
}
|
||||
|
||||
export interface AbstractChainedBatchConstructor {
|
||||
// tslint:disable-next-line no-unnecessary-generics
|
||||
new <K = any, V = any>(db: any): AbstractChainedBatch<K, V>;
|
||||
// tslint:disable-next-line no-unnecessary-generics
|
||||
<K = any, V = any>(db: any): AbstractChainedBatch<K, V>;
|
||||
}
|
||||
|
||||
export interface AbstractIterator<K, V> extends AbstractOptions {
|
||||
db: AbstractLevelDOWN<K, V>;
|
||||
next(cb: ErrorKeyValueCallback<K, V>): this;
|
||||
end(cb: ErrorCallback): void;
|
||||
}
|
||||
|
||||
export interface AbstractIteratorConstructor {
|
||||
// tslint:disable-next-line no-unnecessary-generics
|
||||
new <K = any, V = any>(db: any): AbstractIterator<K, V>;
|
||||
// tslint:disable-next-line no-unnecessary-generics
|
||||
<K = any, V = any>(db: any): AbstractIterator<K, V>;
|
||||
}
|
||||
|
||||
export const AbstractLevelDOWN: AbstractLevelDOWNConstructor;
|
||||
export const AbstractIterator: AbstractIteratorConstructor;
|
||||
export const AbstractChainedBatch: AbstractChainedBatchConstructor;
|
||||
23
types/abstract-leveldown/tsconfig.json
Normal file
23
types/abstract-leveldown/tsconfig.json
Normal 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",
|
||||
"abstract-leveldown-tests.ts"
|
||||
]
|
||||
}
|
||||
3
types/abstract-leveldown/tslint.json
Normal file
3
types/abstract-leveldown/tslint.json
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "dtslint/dt.json"
|
||||
}
|
||||
3
types/ace/index.d.ts
vendored
3
types/ace/index.d.ts
vendored
@@ -832,8 +832,9 @@ declare namespace AceAjax {
|
||||
|
||||
/**
|
||||
* [Sets the value of the distance between the left of the editor and the leftmost part of the visible content.]{: #EditSession.setScrollLeft}
|
||||
* @param scrollLeft The new scroll left value
|
||||
**/
|
||||
setScrollLeft(): void;
|
||||
setScrollLeft(scrollLeft: number): void;
|
||||
|
||||
/**
|
||||
* [Returns the value of the distance between the left of the editor and the leftmost part of the visible content.]{: #EditSession.getScrollLeft}
|
||||
|
||||
@@ -18,6 +18,23 @@ function createFoldTestSession() {
|
||||
return session;
|
||||
}
|
||||
|
||||
function createScrollTestRenderer(): AceAjax.VirtualRenderer | null {
|
||||
var el = document.createElement("div");
|
||||
|
||||
if (!el.getBoundingClientRect) {
|
||||
console.log("Skipping test: This test only runs in the browser");
|
||||
return null;
|
||||
}
|
||||
|
||||
el.style.left = "20px";
|
||||
el.style.top = "30px";
|
||||
el.style.width = "300px";
|
||||
el.style.height = "100px";
|
||||
document.body.appendChild(el);
|
||||
|
||||
return new AceAjax.VirtualRenderer(el);
|
||||
}
|
||||
|
||||
function assertArray(a, b) {
|
||||
assert.equal(a + "", b + "");
|
||||
assert.ok(a.length == b.length);
|
||||
@@ -915,5 +932,25 @@ const aceEditSessionTests = {
|
||||
session = new AceAjax.EditSession(new Array(30).join("\n"));
|
||||
session.documentToScreenPosition(2, 0);
|
||||
session.documentToScreenPosition(2, 0);
|
||||
},
|
||||
|
||||
"test setScrollTop()": function() {
|
||||
var renderer = createScrollTestRenderer();
|
||||
var session = new AceAjax.EditSession(["1", "2", "3", "2", "3", "4"]);
|
||||
renderer.setSession(session);
|
||||
assert.equal(renderer.getScrollTop(), 0);
|
||||
session.setScrollTop(40);
|
||||
assert.equal(renderer.getScrollTop(), 40);
|
||||
renderer.getScrollTop()
|
||||
},
|
||||
|
||||
"test setScrollLeft()": function() {
|
||||
var renderer = createScrollTestRenderer();
|
||||
var session = new AceAjax.EditSession(["1", "2", "3", "2", "3", "4"]);
|
||||
renderer.setSession(session);
|
||||
assert.equal(renderer.getScrollLeft(), 0);
|
||||
session.setScrollLeft(40);
|
||||
assert.equal(renderer.getScrollLeft(), 40);
|
||||
renderer.getScrollLeft()
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
@@ -123,7 +123,7 @@ const aceSelectionTests = {
|
||||
},
|
||||
|
||||
"test: moveCursor word left with umlauts": function () {
|
||||
var session = new AceAjax.EditSession(" Fu<EFBFBD> F<EFBFBD><EFBFBD>e");
|
||||
var session = new AceAjax.EditSession(" Fu¢ F¢¢e");
|
||||
|
||||
var selection = session.getSelection();
|
||||
selection.moveCursorTo(0, 9)
|
||||
|
||||
3
types/acl/index.d.ts
vendored
3
types/acl/index.d.ts
vendored
@@ -2,9 +2,8 @@
|
||||
// Project: https://github.com/optimalbits/node_acl
|
||||
// Definitions by: Qubo <https://github.com/tkQubo>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
// TypeScript Version: 2.8
|
||||
|
||||
/// <reference types="bluebird" />
|
||||
/// <reference types="node"/>
|
||||
/// <reference types="express"/>
|
||||
|
||||
|
||||
14
types/actioncable/index.d.ts
vendored
14
types/actioncable/index.d.ts
vendored
@@ -1,13 +1,15 @@
|
||||
// Type definitions for ActionCable
|
||||
// Project: https://github.com/rails/rails/tree/master/actioncable
|
||||
// Type definitions for ActionCable 5.2
|
||||
// Project: https://github.com/rails/rails/tree/master/actioncable/app/assets/javascripts
|
||||
// Definitions by: Vincent Zhu <https://github.com/zhu1230>
|
||||
// Jared Szechy <https://github.com/szechyjs>
|
||||
// Definitions: https://github.com/zhu1230/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
|
||||
declare module ActionCable {
|
||||
interface Channel {
|
||||
unsubscribe(): void;
|
||||
perform(action: string, data: {}): void;
|
||||
send(data: Object): boolean;
|
||||
send(data: any): boolean;
|
||||
}
|
||||
|
||||
interface Subscriptions {
|
||||
@@ -16,12 +18,16 @@ declare module ActionCable {
|
||||
|
||||
interface Cable {
|
||||
subscriptions: Subscriptions;
|
||||
send(data: any): void;
|
||||
connect(): void;
|
||||
disconnect(): void;
|
||||
ensureActiveConnection(): void;
|
||||
}
|
||||
|
||||
interface CreateMixin {
|
||||
connected(): void;
|
||||
disconnected(): void;
|
||||
received(obj: Object): void;
|
||||
received(obj: any): void;
|
||||
[key: string]: Function;
|
||||
}
|
||||
|
||||
|
||||
14
types/activedirectory2/activedirectory2-tests.ts
Normal file
14
types/activedirectory2/activedirectory2-tests.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import ActiveDirectory = require("activedirectory2");
|
||||
|
||||
const ad = new ActiveDirectory({
|
||||
url: 'ldap://192.168.199.10',
|
||||
baseDN: 'OU=MyUsers,DC=mydomain,DC=com',
|
||||
username: 'service-user@mydomain.com',
|
||||
password: 'xxxxx000pw'
|
||||
});
|
||||
|
||||
ad.authenticate("test@mydomain.com", "yyyy111pw", (err, authed) => {
|
||||
console.log("hello");
|
||||
console.log(err);
|
||||
console.log(authed);
|
||||
});
|
||||
151
types/activedirectory2/index.d.ts
vendored
Normal file
151
types/activedirectory2/index.d.ts
vendored
Normal file
@@ -0,0 +1,151 @@
|
||||
// Type definitions for activedirectory2 1.2
|
||||
// Project: https://github.com/jsumners/node-activedirectory#readme
|
||||
// Definitions by: pas <https://github.com/pasthelod>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.5
|
||||
|
||||
import { Filter } from "ldapjs";
|
||||
|
||||
interface ADProperties {
|
||||
url: string;
|
||||
baseDN: string;
|
||||
username: string;
|
||||
password: string;
|
||||
pageSize?: 1000;
|
||||
entryParser?: (entry: object, raw: string, cb: (entry: object) => void) => void;
|
||||
referrals?: {
|
||||
enabled: false,
|
||||
exclude: [
|
||||
'ldaps?://ForestDnsZones\\..*/.*',
|
||||
'ldaps?://DomainDnsZones\\..*/.*',
|
||||
'ldaps?://.*/CN=Configuration,.*'
|
||||
]
|
||||
};
|
||||
attributes?: {
|
||||
user: [
|
||||
'dn', 'distinguishedName',
|
||||
'userPrincipalName', 'sAMAccountName', 'mail',
|
||||
'lockoutTime', 'whenCreated', 'pwdLastSet', 'userAccountControl',
|
||||
'employeeID', 'sn', 'givenName', 'initials', 'cn', 'displayName',
|
||||
'comment', 'description'
|
||||
],
|
||||
group: [
|
||||
'dn', 'cn', 'description', 'distinguishedName', 'objectCategory'
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
interface LDAPjsReqProps {
|
||||
url: string;
|
||||
tlsOptions: {
|
||||
host?: string;
|
||||
key?: string;
|
||||
cert?: string;
|
||||
ca?: string;
|
||||
rejectUnauthorized: boolean;
|
||||
};
|
||||
socketPath?: string;
|
||||
log?: any;
|
||||
timeout?: number;
|
||||
idleTimeout?: number;
|
||||
connectionTimeout?: number;
|
||||
strictDN?: boolean;
|
||||
}
|
||||
|
||||
type MembershipType = 'all'|'user'|'group';
|
||||
|
||||
interface ReqProps extends LDAPjsReqProps {
|
||||
baseDN?: string;
|
||||
bindDN?: string;
|
||||
bindCredentials?: string;
|
||||
scope?: 'base' | 'one' | 'sub';
|
||||
filter: string | Filter;
|
||||
attributes: AttributeSpec;
|
||||
sizeLimit: 0;
|
||||
timeLimit: 10;
|
||||
includeMembership: MembershipType[];
|
||||
}
|
||||
|
||||
interface AttributeSpec {
|
||||
user: UserAttributes[];
|
||||
group: GroupAttributes[];
|
||||
}
|
||||
|
||||
type GroupAttributes =
|
||||
| 'distinguishedName'
|
||||
| 'objectCategory'
|
||||
| 'cn'
|
||||
| 'description';
|
||||
|
||||
type UserAttributes =
|
||||
| 'distinguishedName'
|
||||
| 'userPrincipalName'
|
||||
| 'sAMAccountName'
|
||||
| 'mail'
|
||||
| 'lockoutTime'
|
||||
| 'whenCreated'
|
||||
| 'pwdLastSet'
|
||||
| 'userAccountControl'
|
||||
| 'employeeID'
|
||||
| 'sn'
|
||||
| 'givenName'
|
||||
| 'initials'
|
||||
| 'cn'
|
||||
| 'displayName'
|
||||
| 'comment'
|
||||
| 'description';
|
||||
|
||||
interface FindResult {
|
||||
groups: object[];
|
||||
users: object[];
|
||||
other: object[];
|
||||
}
|
||||
|
||||
declare class ActiveDirectory {
|
||||
constructor(props: ADProperties);
|
||||
authenticate(
|
||||
username: string,
|
||||
password: string,
|
||||
callback: (err: string, authenticated: boolean) => void
|
||||
): void;
|
||||
isUserMemberOf(
|
||||
opts: ReqProps,
|
||||
username: string,
|
||||
groupName: string,
|
||||
callback: (err: object, res: boolean) => void
|
||||
): void;
|
||||
find(
|
||||
opts: string | ReqProps,
|
||||
callback: (err: object, results: FindResult) => void
|
||||
): void;
|
||||
findDeletedObjects(
|
||||
opts: string | ReqProps,
|
||||
callback: (err: object, results: object[]) => void
|
||||
): void;
|
||||
findUser(
|
||||
opts: string | ReqProps,
|
||||
username: string,
|
||||
callback: (err: object, user: object) => void
|
||||
): void;
|
||||
findUsers(
|
||||
opts: string | ReqProps,
|
||||
callback: (err: object, users: object[]) => void
|
||||
): void;
|
||||
findGroup(
|
||||
opts: string | ReqProps,
|
||||
groupName: string,
|
||||
callback: (err: object, group: object) => void
|
||||
): void;
|
||||
findGroups(
|
||||
opts: string | ReqProps,
|
||||
groupName: string,
|
||||
callback: (err: object, groups: object[]) => void
|
||||
): void;
|
||||
getRootDSE(
|
||||
url: string,
|
||||
attributes: string[],
|
||||
callback: (err: object, result: object) => void
|
||||
): void;
|
||||
}
|
||||
|
||||
export = ActiveDirectory;
|
||||
24
types/activedirectory2/tsconfig.json
Normal file
24
types/activedirectory2/tsconfig.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"activedirectory2-tests.ts"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es6",
|
||||
"es2015.iterable"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"baseUrl": "../",
|
||||
"typeRoots": [
|
||||
"../"
|
||||
],
|
||||
"types": [],
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,17 @@ const inCollection = <T = any>(collection: { Item(index: any): T }, index: strin
|
||||
return item;
|
||||
};
|
||||
|
||||
{
|
||||
let app1: Excel.Application | null = new ActiveXObject('Excel.Application');
|
||||
app1.Visible = true;
|
||||
const book1 = app1.Workbooks.Add();
|
||||
|
||||
app1.Quit();
|
||||
app1 = null;
|
||||
|
||||
WScript.Quit();
|
||||
}
|
||||
|
||||
const app = new ActiveXObject('Excel.Application');
|
||||
|
||||
// create a workbook -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/create-a-workbook
|
||||
@@ -27,7 +38,7 @@ newBook.SaveAs('allsales.xls');
|
||||
// create or replace a worksheet -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/create-or-replace-a-worksheet
|
||||
const newOrExistingWorksheet = () => {
|
||||
const mySheetName = 'Sheet4';
|
||||
let mySheet = inCollection(newBook.Worksheets, mySheetName) as Excel.Worksheet | undefined;
|
||||
let mySheet = inCollection<Excel.Worksheet>(newBook.Worksheets, mySheetName);
|
||||
if (!mySheet) {
|
||||
WScript.Echo(`The sheet named "${mySheetName} doesn't exist, but will be created.`);
|
||||
mySheet = app.Worksheets.Add() as Excel.Worksheet;
|
||||
@@ -37,7 +48,7 @@ const newOrExistingWorksheet = () => {
|
||||
const replaceWorksheet = () => {
|
||||
const mySheetName = 'Sheet4';
|
||||
app.DisplayAlerts = false;
|
||||
let mySheet = inCollection<Excel.Worksheet | Excel.Chart | Excel.DialogSheet>(app.Worksheets, mySheetName);
|
||||
let mySheet = inCollection<Excel.Worksheet>(app.Worksheets, mySheetName);
|
||||
if (mySheet) { mySheet.Delete(); }
|
||||
app.DisplayAlerts = true;
|
||||
mySheet = app.Worksheets.Add() as Excel.Worksheet;
|
||||
@@ -46,9 +57,7 @@ const replaceWorksheet = () => {
|
||||
};
|
||||
|
||||
// referencing multiple sheets -- https://msdn.microsoft.com/VBA/Excel-VBA/articles/sheets-object-excel
|
||||
const moveMultipleSheets = () => {
|
||||
app.Worksheets.Item(toSafeArray<string | number>(1, 'Sheet2')).Move(4);
|
||||
};
|
||||
const moveMultipleSheets = () => app.Worksheets(toSafeArray<string | number>(1, 'Sheet2')).Move(4);
|
||||
|
||||
// sort worksheets alphanumerically by name -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/sort-worksheets-alphanumerically-by-name
|
||||
const sortSheetsTabName = () => {
|
||||
@@ -56,9 +65,9 @@ const sortSheetsTabName = () => {
|
||||
const sheets = app.ActiveWorkbook.Sheets;
|
||||
const sheetCount = sheets.Count;
|
||||
for (let i = 0; i < sheetCount; i += 1) {
|
||||
const sheetI = sheets.Item(i);
|
||||
const sheetI = sheets(i);
|
||||
for (let j = i; j < sheetCount; j += 1) {
|
||||
const sheetJ = sheets.Item(j);
|
||||
const sheetJ = sheets(j);
|
||||
if (sheetJ.Name < sheetI.Name) { sheetJ.Move(sheetI); }
|
||||
}
|
||||
}
|
||||
@@ -68,7 +77,7 @@ const sortSheetsTabName = () => {
|
||||
// fill a value down into blank cells in a column -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/fill-a-value-down-into-blank-cells-in-a-column
|
||||
const fillCellsFromAbove = () => {
|
||||
app.ScreenUpdating = false;
|
||||
const columnA = app.Columns.Item(1);
|
||||
const columnA = app.Columns(1);
|
||||
try {
|
||||
columnA.SpecialCells(Excel.XlCellType.xlCellTypeBlanks).Formula = '=R[-1]C';
|
||||
columnA.Value = columnA.Value;
|
||||
@@ -78,7 +87,7 @@ const fillCellsFromAbove = () => {
|
||||
|
||||
// hide and unhide columns -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/hide-and-unhide-columns
|
||||
const setColumnVisibility = (visible: boolean) => {
|
||||
const book = app.Workbooks.Item(1);
|
||||
const book = app.Workbooks(1);
|
||||
const sheet = inCollection<Excel.Worksheet | Excel.Chart | Excel.DialogSheet>(book.Worksheets, 'Sheet1');
|
||||
if (!sheet) { return; }
|
||||
|
||||
@@ -97,7 +106,7 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
};
|
||||
|
||||
// highlighting the active cell, row, or column -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/highlight-the-active-cell-row-or-column
|
||||
(() => {
|
||||
{
|
||||
const wks = app.ActiveSheet as Excel.Worksheet;
|
||||
|
||||
// highlight active cell
|
||||
@@ -120,10 +129,10 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
prm.Target.EntireColumn.Interior.ColorIndex = 8;
|
||||
app.ScreenUpdating = true;
|
||||
});
|
||||
})();
|
||||
}
|
||||
|
||||
// referencing cells -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/reference-cells-and-ranges
|
||||
(() => {
|
||||
{
|
||||
const wks = app.ActiveSheet as Excel.Worksheet;
|
||||
|
||||
// all the cells on a worksheet
|
||||
@@ -141,20 +150,19 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
wks.Range('A:A,C:C,F:F').Font.Bold = true;
|
||||
|
||||
// using index numbers
|
||||
wks.Cells.Item(6, 1).Value2 = 10;
|
||||
// Value is also a property with parameters
|
||||
ActiveXObject.set(wks.Cells.Item(6, 1), 'Value', 10);
|
||||
wks.Cells(6, 1).Value2 = 10;
|
||||
wks.Cells(6, 1).Value = 10;
|
||||
|
||||
// iterating through cells using index numbers
|
||||
for (let counter = 1; counter < 20; counter += 1) {
|
||||
ActiveXObject.set(wks.Cells.Item(counter, 1), 'Value', 10);
|
||||
wks.Cells(counter, 1).Value = 10;
|
||||
}
|
||||
|
||||
// relative to other cells
|
||||
wks.Cells.Item(1, 1).Font.Underline = Excel.XlUnderlineStyle.xlUnderlineStyleDouble;
|
||||
wks.Cells(1, 1).Font.Underline = Excel.XlUnderlineStyle.xlUnderlineStyleDouble;
|
||||
|
||||
// using a Range object
|
||||
const rng = wks.Cells.Item('A1:D5');
|
||||
const rng = wks.Cells('A1:D5');
|
||||
rng.Formula = '=RAND()';
|
||||
rng.Font.Bold = true;
|
||||
|
||||
@@ -166,23 +174,22 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
|
||||
// refer to multiple ranges using Areas
|
||||
WScript.Echo(union.Areas.Count);
|
||||
})();
|
||||
}
|
||||
|
||||
// looping through a range of cells -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/looping-through-a-range-of-cells
|
||||
(() => {
|
||||
{
|
||||
const wks = app.ActiveSheet as Excel.Worksheet;
|
||||
|
||||
// using for
|
||||
for (let x = 1; x < 20; x++) {
|
||||
const currentCell = wks.Cells.Item(x, 1);
|
||||
if (Math.abs(currentCell.Value()) < 0.01) {
|
||||
// because Value is typed as a method on the Excel.Range class, we have to treat it as a setter with parameters
|
||||
ActiveXObject.set(currentCell, 'Value', 0);
|
||||
const currentCell = wks.Cells(x, 1);
|
||||
if (Math.abs(currentCell.Value) < 0.01) {
|
||||
currentCell.Value = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// using Enumerator
|
||||
let enumerator = new Enumerator(wks.Cells.Item('A1:D10'));
|
||||
let enumerator = new Enumerator(wks.Cells('A1:D10'));
|
||||
enumerator.moveFirst();
|
||||
while (!enumerator.atEnd()) {
|
||||
const currentCell = enumerator.item();
|
||||
@@ -202,11 +209,11 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
}
|
||||
enumerator.moveNext();
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
// using selection -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/selecting-and-activating-cells
|
||||
(() => {
|
||||
const wks = app.ActiveWorkbook.Worksheets.Item(1) as Excel.Worksheet;
|
||||
{
|
||||
const wks = app.ActiveWorkbook.Worksheets(1);
|
||||
|
||||
// make a worksheet the active worksheet; otherwise code which uses the selection will fail
|
||||
wks.Select();
|
||||
@@ -219,24 +226,24 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
wks.Range("B1").Activate();
|
||||
|
||||
// working with 3-D ranges -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/working-with-3-d-ranges
|
||||
app.Sheets.Item(toSafeArray("Sheet2", "Sheet3", "Sheet4")).Select();
|
||||
app.Sheets(toSafeArray("Sheet2", "Sheet3", "Sheet4")).Select();
|
||||
app.Range("A1:H1").Select();
|
||||
(app.Selection as Excel.Range).Borders.Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlDouble;
|
||||
(app.Selection as Excel.Range).Borders(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlDouble;
|
||||
|
||||
// alternatively, use FillAcrossSheets to fill formatting and data across sheets
|
||||
const book = app.ActiveWorkbook;
|
||||
const wks2 = book.Sheets.Item("Sheet2") as Excel.Worksheet;
|
||||
const wks2 = book.Worksheets("Sheet2");
|
||||
const rng = wks2.Range("A1:H1");
|
||||
rng.Borders.Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlDouble;
|
||||
rng.Borders(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlDouble;
|
||||
book.Sheets.FillAcrossSheets(rng);
|
||||
})();
|
||||
}
|
||||
|
||||
// prevent duplicate entry -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/prevent-duplicate-entries-in-a-range
|
||||
(() => {
|
||||
const book = app.Workbooks.Item(1);
|
||||
{
|
||||
const book = app.Workbooks(1);
|
||||
|
||||
ActiveXObject.on(book, 'SheetChange', ['Sh', 'Target'], function(this, prm) {
|
||||
const EvalRange = this.ActiveSheet.Range("A1:B20");
|
||||
const EvalRange = (this.ActiveSheet as Excel.Worksheet).Range("A1:B20");
|
||||
|
||||
// If the cell where the value was entered is not in the defined range, if the value pasted is larger than a single cell, or if no value was entered in the cell, then exit the macro
|
||||
if (
|
||||
@@ -253,10 +260,11 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// const enumerator = new Enumerator<Excel.Worksheet | Excel.Chart | Excel.DialogSheet>(book.Worksheets);
|
||||
const enumerator = new Enumerator(book.Worksheets);
|
||||
enumerator.moveFirst();
|
||||
while (!enumerator.atEnd()) {
|
||||
const wks = enumerator.item() as Excel.Worksheet;
|
||||
const wks = enumerator.item();
|
||||
if (wks.Name === prm.Target.Name) { continue; }
|
||||
|
||||
// If the value entered already exists in the defined range on the current worksheet, undo the entry.
|
||||
@@ -267,14 +275,14 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
app.EnableEvents = true;
|
||||
}
|
||||
});
|
||||
})();
|
||||
}
|
||||
|
||||
// add a unique list of values to a combobox -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/add-a-unique-list-of-values-to-a-combo-box
|
||||
(() => {
|
||||
(() => {
|
||||
{
|
||||
{
|
||||
// using the AdvancedFilter property
|
||||
const book = app.ThisWorkbook;
|
||||
const sheet = book.Worksheets.Item("Sheet1") as Excel.Worksheet;
|
||||
const sheet = book.Worksheets("Sheet1");
|
||||
const dataRange = sheet.Range('A1', sheet.Range("A100").End(Excel.XlDirection.xlUp));
|
||||
dataRange.AdvancedFilter(Excel.XlFilterAction.xlFilterCopy, undefined, sheet.Range('L1'), true);
|
||||
const data = sheet.Range("L2", sheet.Range('L100').End(Excel.XlDirection.xlUp)).Value() as SafeArray;
|
||||
@@ -284,15 +292,17 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
combobox.Clear();
|
||||
ActiveXObject.set(combobox, 'List', [], data);
|
||||
combobox.ListIndex = -1;
|
||||
})();
|
||||
}
|
||||
|
||||
(() => {
|
||||
{
|
||||
// using a Dictionary
|
||||
const sheet = app.ThisWorkbook.Sheets.Item('Sheet2') as Excel.Worksheet;
|
||||
const sheet = app.ThisWorkbook.Sheets('Sheet2') as Excel.Worksheet;
|
||||
const data = sheet.Range('A2', sheet.Range('A100').End(Excel.XlDirection.xlUp)).Value2 as SafeArray;
|
||||
const arr = new VBArray(data).toArray();
|
||||
const dict = new ActiveXObject('Scripting.Dictionary');
|
||||
arr.forEach(x => ActiveXObject.set(dict, 'Item', [x], true));
|
||||
for (const x of arr) {
|
||||
ActiveXObject.set(dict, 'Item', [x], true);
|
||||
}
|
||||
|
||||
const combobox = sheet.OLEObjects('ComboBox1').Object as MSForms.ComboBox;
|
||||
combobox.Clear();
|
||||
@@ -307,21 +317,28 @@ const setColumnVisibility = (visible: boolean) => {
|
||||
|
||||
// alternatively, make a JS array out of the keys, and iterate using forEach
|
||||
// new VBArray(dict.Keys()).toArray().forEach(x => combobox.AddItem(x));
|
||||
})();
|
||||
})();
|
||||
|
||||
// animating a sparkline -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/animate-a-sparkline
|
||||
(() => {
|
||||
const wks = app.ActiveSheet as Excel.Worksheet;
|
||||
const oSparkGroup = wks.Cells.SparklineGroups.Item(1);
|
||||
|
||||
// Set the data source to the first year of data
|
||||
oSparkGroup.ModifySourceData('B2:M4');
|
||||
|
||||
// Loop through the data points for the subsequent two years
|
||||
for (let i = 1; i <= 24; i++) {
|
||||
// Move the reference for the sparkline group over one cell
|
||||
oSparkGroup.ModifySourceData(wks.Range(oSparkGroup.SourceData).Offset(0, 1).Address());
|
||||
WScript.Sleep(1000);
|
||||
}
|
||||
})();
|
||||
|
||||
// animating a sparkline -- https://msdn.microsoft.com/en-us/vba/excel-vba/articles/animate-a-sparkline
|
||||
{
|
||||
const wks = app.ActiveSheet as Excel.Worksheet;
|
||||
const oSparkGroup = wks.Cells.SparklineGroups(1);
|
||||
|
||||
// Set the data source to the first year of data
|
||||
oSparkGroup.ModifySourceData('B2:M4');
|
||||
|
||||
// Loop through the data points for the subsequent two years
|
||||
for (let i = 1; i <= 24; i++) {
|
||||
// Move the reference for the sparkline group over one cell
|
||||
oSparkGroup.ModifySourceData(wks.Range(oSparkGroup.SourceData).Offset(0, 1).Address());
|
||||
WScript.Sleep(1000);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
const formats = new VBArray(app.ClipboardFormats).toArray();
|
||||
for (const format of formats) {
|
||||
WScript.Echo(format);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
3907
types/activex-excel/index.d.ts
vendored
3907
types/activex-excel/index.d.ts
vendored
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,7 @@
|
||||
{
|
||||
"extends": "dtslint/dt.json"
|
||||
"extends": "dtslint/dt.json",
|
||||
"rules": {
|
||||
"no-const-enum": false,
|
||||
"max-line-length": false
|
||||
}
|
||||
}
|
||||
|
||||
1
types/activex-interop/index.d.ts
vendored
1
types/activex-interop/index.d.ts
vendored
@@ -51,7 +51,6 @@ interface Enumerator<T = any> {
|
||||
|
||||
interface EnumeratorConstructor {
|
||||
new <T = any>(collection: { Item(index: any): T }): Enumerator<T>;
|
||||
// new (collection: any): Enumerator;
|
||||
}
|
||||
|
||||
declare var Enumerator: EnumeratorConstructor;
|
||||
|
||||
2
types/activex-office/index.d.ts
vendored
2
types/activex-office/index.d.ts
vendored
@@ -10,6 +10,8 @@
|
||||
declare namespace Office {
|
||||
type MsoRGBType = number;
|
||||
|
||||
type ByteArray = SafeArray<number>;
|
||||
|
||||
const enum BackstageGroupStyle {
|
||||
BackstageGroupStyleError = 2,
|
||||
BackstageGroupStyleNormal = 0,
|
||||
|
||||
4
types/activex-outlook/index.d.ts
vendored
4
types/activex-outlook/index.d.ts
vendored
@@ -5886,7 +5886,3 @@ interface EnumeratorConstructor {
|
||||
new(col: Outlook.Reminders): Enumerator<Outlook.Reminder>;
|
||||
new(col: Outlook.Views): Enumerator<Outlook.View>;
|
||||
}
|
||||
|
||||
interface SafeArray<T = any> {
|
||||
_brand: SafeArray<T>;
|
||||
}
|
||||
|
||||
2
types/adone/glosses/utils.d.ts
vendored
2
types/adone/glosses/utils.d.ts
vendored
@@ -451,7 +451,7 @@ declare namespace adone {
|
||||
| encoding.Multibyte;
|
||||
}
|
||||
|
||||
const defaultCharUnicode: "<22>";
|
||||
const defaultCharUnicode: string;
|
||||
|
||||
const defaultCharSingleByte: "?";
|
||||
|
||||
|
||||
2
types/adone/index.d.ts
vendored
2
types/adone/index.d.ts
vendored
@@ -2,7 +2,7 @@
|
||||
// Project: https://github.com/ciferox/adone
|
||||
// Definitions by: am <https://github.com/s0m3on3>, Maximus <https://github.com/maxveres>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.4
|
||||
// TypeScript Version: 2.6
|
||||
|
||||
/// <reference path="./adone.d.ts" />
|
||||
/// <reference path="./glosses/app.d.ts" />
|
||||
|
||||
743
types/aframe/index.d.ts
vendored
743
types/aframe/index.d.ts
vendored
@@ -1,345 +1,476 @@
|
||||
// Type definitions for AFRAME 0.7
|
||||
// Type definitions for AFRAME 0.8
|
||||
// Project: https://aframe.io/
|
||||
// Definitions by: Paul Shannon <https://github.com/devpaul>
|
||||
// Roberto Ritger <https://github.com/bertoritger>
|
||||
// Trygve Wastvedt <https://github.com/twastvedt>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
// TypeScript Version: 2.8
|
||||
|
||||
/**
|
||||
* Extended tests available at https://github.com/devpaul/aframe-typings.git
|
||||
* Extended tests and examples available at https://github.com/devpaul/aframe-experiments.git
|
||||
*/
|
||||
|
||||
/// <reference types="three" />
|
||||
/// <reference types="tween.js" />
|
||||
|
||||
// Globals
|
||||
declare var AFRAME: AFrame.AFrameGlobal;
|
||||
declare var hasNativeWebVRImplementation: boolean;
|
||||
import * as three from 'three';
|
||||
import * as tween from '@tweenjs/tween.js';
|
||||
|
||||
interface Document {
|
||||
createElement(tagName: string): AFrame.Entity;
|
||||
querySelector(selectors: 'a-scene'): AFrame.Scene;
|
||||
querySelector(selectors: string): AFrame.Entity<any>;
|
||||
querySelectorAll(selectors: string): NodeListOf<AFrame.Entity<any> | Element>;
|
||||
export type ThreeLib = typeof three;
|
||||
export type TweenLib = typeof tween;
|
||||
|
||||
export interface ObjectMap<T = any> {
|
||||
[key: string]: T;
|
||||
}
|
||||
|
||||
// Interfaces
|
||||
declare namespace AFrame {
|
||||
interface ObjectMap<T = any> {
|
||||
[ key: string ]: T;
|
||||
}
|
||||
export interface Animation {
|
||||
attribute: string;
|
||||
begin: string | number;
|
||||
delay: number;
|
||||
direction: 'alternate' | 'alternateReverse' | 'normal' | 'reverse';
|
||||
dur: number;
|
||||
easing(): void;
|
||||
end: string;
|
||||
fill: 'backwards' | 'both' | 'forwards' | 'none';
|
||||
from: any; // TODO type
|
||||
repeat: number | 'indefinite';
|
||||
to: number;
|
||||
}
|
||||
|
||||
interface AFrameGlobal {
|
||||
AEntity: Entity;
|
||||
ANode: ANode;
|
||||
AScene: Scene;
|
||||
components: { [ key: string ]: ComponentDescriptor };
|
||||
geometries: { [ key: string ]: GeometryDescriptor };
|
||||
primitives: { [ key: string ]: Entity };
|
||||
registerComponent<T extends Component>(name: string, component: ComponentDefinition<T>): ComponentConstructor<T>;
|
||||
registerElement(name: string, element: ANode): void;
|
||||
registerGeometry<T extends Geometry>(name: string, geometry: GeometryDefinition<T>): GeometryConstructor<T>;
|
||||
registerPrimitive(name: string, primitive: PrimitiveDefinition): void;
|
||||
registerShader<T extends Shader>(name: string, shader: T): ShaderConstructor<T>;
|
||||
registerSystem<T extends System>(name: string, definition: SystemDefinition<T>): SystemConstructor<T>;
|
||||
schema: SchemaUtils;
|
||||
shaders: { [ key: string ]: ShaderDescriptor };
|
||||
systems: { [key: string]: SystemConstructor };
|
||||
THREE: typeof THREE;
|
||||
TWEEN: typeof TWEEN;
|
||||
utils: Utils;
|
||||
version: string;
|
||||
}
|
||||
export interface ANode extends HTMLElement {
|
||||
// Only public APIs added. Many methods intentionally left out.
|
||||
// createdCallback
|
||||
// attachedCallback
|
||||
// attributeChangedCallback
|
||||
closestScene(): Scene;
|
||||
closest(selector: string): ANode;
|
||||
// detachedCallback
|
||||
hasLoaded: boolean;
|
||||
load(cb?: () => void, childFilter?: (el: Element) => boolean): void;
|
||||
// updateMixins
|
||||
registerMixin(id: string): void;
|
||||
setAttribute(type: string, newValue: any): void;
|
||||
unregisterMixin(id: string): void;
|
||||
removeMixinListener(id: string): void;
|
||||
attachMixinListener(mixin: HTMLElement): void;
|
||||
emit(name: string, detail?: any, bubbles?: boolean): void;
|
||||
emitter(name: string, detail?: any, bubbles?: boolean): () => void;
|
||||
}
|
||||
|
||||
interface Animation {
|
||||
attribute: string;
|
||||
begin: string | number;
|
||||
delay: number;
|
||||
direction: 'alternate' | 'alternateReverse' | 'normal' | 'reverse';
|
||||
dur: number;
|
||||
easing(): void;
|
||||
end: string;
|
||||
fill: 'backwards' | 'both' | 'forwards' | 'none';
|
||||
from: any; // TODO type
|
||||
repeat: number | 'indefinite';
|
||||
to: number;
|
||||
}
|
||||
export interface Behavior {
|
||||
tick(): void;
|
||||
}
|
||||
|
||||
interface ANode extends HTMLElement {
|
||||
// Only public APIs added. Many methods intentionally left out.
|
||||
// createdCallback
|
||||
// attachedCallback
|
||||
// attributeChangedCallback
|
||||
closestScene(): Scene;
|
||||
closest(selector: string): ANode;
|
||||
// detachedCallback
|
||||
hasLoaded: boolean;
|
||||
load(cb?: () => void, childFilter?: (el: Element) => boolean): void;
|
||||
// updateMixins
|
||||
registerMixin(id: string): void;
|
||||
setAttribute(type: string, newValue: any): void;
|
||||
unregisterMixin(id: string): void;
|
||||
removeMixinListener(id: string): void;
|
||||
attachMixinListener(mixin: HTMLElement): void;
|
||||
emit(name: string, detail?: any, bubbles?: boolean): void;
|
||||
emitter(name: string, detail?: any, bubbles?: boolean): () => void;
|
||||
}
|
||||
export interface Component<T extends object = any, S extends System = System> {
|
||||
attrName?: string;
|
||||
data: T;
|
||||
dependencies?: string[];
|
||||
el: Entity;
|
||||
id: string;
|
||||
multiple?: boolean;
|
||||
name: string;
|
||||
schema: Schema<T>;
|
||||
system: S | undefined;
|
||||
|
||||
interface Behavior {
|
||||
tick(): void;
|
||||
}
|
||||
init(data?: T): void;
|
||||
pause(): void;
|
||||
play(): void;
|
||||
remove(): void;
|
||||
tick?(time: number, timeDelta: number): void;
|
||||
update(oldData: T): void;
|
||||
updateSchema?(): void;
|
||||
|
||||
interface Component<T extends { [key: string]: any } = any, S extends System = System> {
|
||||
attrName?: string;
|
||||
data: T;
|
||||
dependencies?: string[];
|
||||
el: Entity;
|
||||
id: string;
|
||||
multiple?: boolean;
|
||||
extendSchema(update: Schema): void;
|
||||
flushToDOM(): void;
|
||||
}
|
||||
|
||||
export interface ComponentConstructor<T extends object> {
|
||||
new (el: Entity, attrValue: string, id: string): T & Component;
|
||||
prototype: T & {
|
||||
name: string;
|
||||
schema: Schema<T>;
|
||||
system: S | undefined;
|
||||
|
||||
init(this: this, data?: T): void;
|
||||
pause(this: this): void;
|
||||
play(this: this): void;
|
||||
remove(this: this): void;
|
||||
tick?(this: this, time: number, timeDelta: number): void;
|
||||
update(this: this, oldData: T): void;
|
||||
updateSchema?(this: this): void;
|
||||
|
||||
extendSchema(this: this, update: Schema): void;
|
||||
flushToDOM(this: this): void;
|
||||
}
|
||||
|
||||
interface ComponentConstructor<T extends Component> {
|
||||
new (el: Entity, attrValue: string, id: string): T;
|
||||
}
|
||||
|
||||
type ComponentDefinition<T extends Component = Component> = Partial<T>;
|
||||
|
||||
interface ComponentDescriptor<T extends Component = Component> {
|
||||
Component: ComponentConstructor<T>;
|
||||
dependencies: string[] | undefined;
|
||||
multiple: boolean | undefined;
|
||||
|
||||
// internal APIs2
|
||||
// parse
|
||||
// parseAttrValueForCache
|
||||
// schema
|
||||
// stringify
|
||||
// type
|
||||
}
|
||||
|
||||
interface Coordinate {
|
||||
x: number;
|
||||
y: number;
|
||||
z: number;
|
||||
}
|
||||
|
||||
interface DefaultComponents {
|
||||
position: Component<Coordinate>;
|
||||
rotation: Component<Coordinate>;
|
||||
scale: Component<Coordinate>;
|
||||
}
|
||||
|
||||
interface Entity<C = ObjectMap<Component>> extends ANode {
|
||||
components: C & DefaultComponents;
|
||||
isPlaying: boolean;
|
||||
object3D: THREE.Object3D;
|
||||
object3DMap: ObjectMap<THREE.Object3D>;
|
||||
sceneEl?: Scene;
|
||||
|
||||
addState(name: string): void;
|
||||
flushToDOM(recursive?: boolean): void;
|
||||
/**
|
||||
* @deprecated since 0.4.0
|
||||
*/
|
||||
getComputedAttribute(attr: string): Component;
|
||||
getDOMAttribute(attr: string): any;
|
||||
getObject3D(type: string): THREE.Object3D;
|
||||
getOrCreateObject3D(type: string, construct: any): THREE.Object3D;
|
||||
is(stateName: string): boolean;
|
||||
pause(): void;
|
||||
system: System;
|
||||
play(): void;
|
||||
setObject3D(type: string, obj: THREE.Object3D): void;
|
||||
removeAttribute(attr: string, property?: string): void;
|
||||
removeObject3D(type: string): void;
|
||||
removeState(stateName: string): void;
|
||||
|
||||
// getAttribute specific usages
|
||||
getAttribute(type: string): any;
|
||||
getAttribute(type: 'position' | 'rotation' | 'scale'): Coordinate;
|
||||
|
||||
// setAttribute specific usages
|
||||
setAttribute(attr: string, value: any): void;
|
||||
setAttribute(attr: string, property: string, componentAttrValue?: any): void;
|
||||
setAttribute(type: 'position' | 'rotation' | 'scale', value: Coordinate): void;
|
||||
|
||||
// addEventListener specific usages
|
||||
addEventListener<K extends keyof EntityEventMap>(type: K, listener: (event: Event & EntityEventMap[K]) => void, useCapture?: boolean): void;
|
||||
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
|
||||
}
|
||||
|
||||
type DetailEvent<D> = Event & {
|
||||
detail: D;
|
||||
target: EventTarget & Entity;
|
||||
pause(): void;
|
||||
};
|
||||
}
|
||||
|
||||
interface EntityEventMap {
|
||||
'child-attached': DetailEvent<{ el: Element | Entity }>;
|
||||
'child-detached': DetailEvent<{ el: Element | Entity }>;
|
||||
'componentchanged': DetailEvent<{
|
||||
name: string,
|
||||
id: string
|
||||
}>;
|
||||
'componentremoved': DetailEvent<{
|
||||
name: string,
|
||||
id: string,
|
||||
newData: any,
|
||||
oldData: any
|
||||
}>;
|
||||
'loaded': EventListener;
|
||||
'pause': EventListener;
|
||||
'play': EventListener;
|
||||
'stateadded': DetailEvent<{ state: string }>;
|
||||
'stateremoved': DetailEvent<{ state: string }>;
|
||||
'schemachanged': DetailEvent<{ componentName: string }>;
|
||||
}
|
||||
export interface ComponentDescriptor<T extends Component = Component> {
|
||||
Component: ComponentConstructor<T>;
|
||||
dependencies: string[] | undefined;
|
||||
multiple: boolean | undefined;
|
||||
|
||||
interface Geometry {
|
||||
// internal APIs2
|
||||
// parse
|
||||
// parseAttrValueForCache
|
||||
// schema
|
||||
// stringify
|
||||
// type
|
||||
}
|
||||
|
||||
export interface Coordinate {
|
||||
x: number;
|
||||
y: number;
|
||||
z: number;
|
||||
}
|
||||
|
||||
export interface DefaultComponents {
|
||||
position: Component<Coordinate>;
|
||||
rotation: Component<Coordinate>;
|
||||
scale: Component<Coordinate>;
|
||||
}
|
||||
|
||||
export interface Entity<C = ObjectMap<Component>> extends ANode {
|
||||
components: C & DefaultComponents;
|
||||
isPlaying: boolean;
|
||||
object3D: THREE.Object3D;
|
||||
object3DMap: ObjectMap<THREE.Object3D>;
|
||||
sceneEl?: Scene;
|
||||
|
||||
addState(name: string): void;
|
||||
flushToDOM(recursive?: boolean): void;
|
||||
/**
|
||||
* @deprecated since 0.4.0
|
||||
*/
|
||||
getComputedAttribute(attr: string): Component;
|
||||
getDOMAttribute(attr: string): any;
|
||||
getObject3D(type: string): THREE.Object3D;
|
||||
getOrCreateObject3D(type: string, construct: any): THREE.Object3D;
|
||||
is(stateName: string): boolean;
|
||||
pause(): void;
|
||||
play(): void;
|
||||
setObject3D(type: string, obj: THREE.Object3D): void;
|
||||
removeAttribute(attr: string, property?: string): void;
|
||||
removeObject3D(type: string): void;
|
||||
removeState(stateName: string): void;
|
||||
|
||||
// getAttribute specific usages
|
||||
getAttribute(type: string): any;
|
||||
getAttribute(type: 'position' | 'rotation' | 'scale'): Coordinate;
|
||||
|
||||
// setAttribute specific usages
|
||||
setAttribute(attr: string, value: any): void;
|
||||
setAttribute(attr: string, property: string, componentAttrValue?: any): void;
|
||||
setAttribute(type: 'position' | 'rotation' | 'scale', value: Coordinate): void;
|
||||
|
||||
// addEventListener specific usages
|
||||
addEventListener<K extends keyof EntityEventMap>(
|
||||
type: K,
|
||||
listener: (event: Event & EntityEventMap[K]) => void,
|
||||
useCapture?: boolean
|
||||
): void;
|
||||
addEventListener(
|
||||
type: string,
|
||||
listener: EventListenerOrEventListenerObject,
|
||||
useCapture?: boolean
|
||||
): void;
|
||||
}
|
||||
|
||||
export type DetailEvent<D> = Event & {
|
||||
detail: D;
|
||||
target: EventTarget & Entity;
|
||||
};
|
||||
|
||||
export interface EntityEventMap {
|
||||
'child-attached': DetailEvent<{ el: Element | Entity }>;
|
||||
'child-detached': DetailEvent<{ el: Element | Entity }>;
|
||||
componentchanged: DetailEvent<{
|
||||
name: string;
|
||||
geometry: THREE.Geometry;
|
||||
schema: Schema<any>;
|
||||
id: string;
|
||||
}>;
|
||||
componentremoved: DetailEvent<{
|
||||
name: string;
|
||||
id: string;
|
||||
newData: any;
|
||||
oldData: any;
|
||||
}>;
|
||||
loaded: EventListener;
|
||||
pause: EventListener;
|
||||
play: EventListener;
|
||||
stateadded: DetailEvent<{ state: string }>;
|
||||
stateremoved: DetailEvent<{ state: string }>;
|
||||
schemachanged: DetailEvent<{ componentName: string }>;
|
||||
}
|
||||
|
||||
init(this: this, data: { [P in keyof this['schema']]: any }): void;
|
||||
// Would like the above to be:
|
||||
// init?(this: this, data?: { [P in keyof T['schema']]: T['schema'][P]['default'] } ): void;
|
||||
// I think this is prevented by the following issue: https://github.com/Microsoft/TypeScript/issues/21760.
|
||||
}
|
||||
export interface Geometry<T = any> {
|
||||
data: T;
|
||||
name: string;
|
||||
geometry: THREE.Geometry;
|
||||
schema: Schema<any>;
|
||||
|
||||
interface GeometryConstructor<T extends Geometry> {
|
||||
new (): T;
|
||||
}
|
||||
init(data: any): void;
|
||||
}
|
||||
|
||||
type GeometryDefinition<T extends Geometry = Geometry> = Partial<T>;
|
||||
export interface GeometryConstructor<T extends object = object> {
|
||||
new (): T & Geometry;
|
||||
}
|
||||
|
||||
interface GeometryDescriptor<T extends Geometry = Geometry> {
|
||||
Geometry: GeometryConstructor<T>;
|
||||
schema: Schema;
|
||||
}
|
||||
export interface GeometryDescriptor<T extends Geometry = Geometry> {
|
||||
Geometry: GeometryConstructor<T>;
|
||||
schema: Schema;
|
||||
}
|
||||
|
||||
type MultiPropertySchema<T extends { [key: string ]: any }> = {
|
||||
[P in keyof T]: SinglePropertySchema<T[P]> | T[P];
|
||||
export type MultiPropertySchema<T extends object> = {
|
||||
[P in keyof T]: SinglePropertySchema<T[P]> | T[P]
|
||||
};
|
||||
|
||||
export type PropertyTypes =
|
||||
| 'array'
|
||||
| 'asset'
|
||||
| 'audio'
|
||||
| 'boolean'
|
||||
| 'color'
|
||||
| 'int'
|
||||
| 'map'
|
||||
| 'model'
|
||||
| 'number'
|
||||
| 'selector'
|
||||
| 'selectorAll'
|
||||
| 'string'
|
||||
| 'vec2'
|
||||
| 'vec3'
|
||||
| 'vec4';
|
||||
|
||||
export type SceneEvents = 'enter-vr' | 'exit-vr' | 'loaded' | 'renderstart';
|
||||
|
||||
export interface Scene extends Entity {
|
||||
behaviors: Behavior[];
|
||||
camera: THREE.Camera;
|
||||
canvas: HTMLCanvasElement;
|
||||
effect: THREE.VREffect;
|
||||
isMobile: boolean;
|
||||
object3D: THREE.Scene;
|
||||
renderer: THREE.WebGLRenderer;
|
||||
renderStarted: boolean;
|
||||
systems: ObjectMap<System>;
|
||||
time: number;
|
||||
|
||||
enterVR(): Promise<void> | void;
|
||||
exitVR(): Promise<void> | void;
|
||||
reload(): void;
|
||||
|
||||
addEventListener(
|
||||
type: string,
|
||||
listener: EventListenerOrEventListenerObject,
|
||||
useCapture?: boolean
|
||||
): void;
|
||||
addEventListener(type: SceneEvents, listener: EventListener, useCapture?: boolean): void;
|
||||
}
|
||||
|
||||
export type Schema<T extends object = object> = SinglePropertySchema<T> | MultiPropertySchema<T>;
|
||||
|
||||
export interface SchemaUtils {
|
||||
isSingleProperty(schema: Schema): boolean;
|
||||
process(schema: Schema): boolean;
|
||||
}
|
||||
|
||||
export interface Shader {
|
||||
name: string;
|
||||
data: object;
|
||||
schema: Schema<this['data']>;
|
||||
material: THREE.Material;
|
||||
vertexShader: string;
|
||||
fragmentShader: string;
|
||||
|
||||
init(data?: this['data']): void;
|
||||
tick?(time: number, timeDelta: number): void;
|
||||
update(oldData: this['data']): void;
|
||||
}
|
||||
|
||||
export interface ShaderConstructor<T extends object> {
|
||||
new (): T;
|
||||
}
|
||||
|
||||
export interface ShaderDescriptor<T extends Shader = Shader> {
|
||||
Shader: ShaderConstructor<T>;
|
||||
schema: Schema;
|
||||
}
|
||||
|
||||
export interface SinglePropertySchema<T> {
|
||||
type?: PropertyTypes;
|
||||
default?: T;
|
||||
parse?(value: string): T;
|
||||
stringify?(value: T): string;
|
||||
}
|
||||
|
||||
export interface System<T extends object = any> {
|
||||
data: T;
|
||||
schema: Schema<T>;
|
||||
init(): void;
|
||||
pause(): void;
|
||||
play(): void;
|
||||
tick?(t: number, dt: number): void;
|
||||
}
|
||||
|
||||
export interface SystemConstructor<T extends object = object> {
|
||||
new (scene: Scene): T & System;
|
||||
}
|
||||
|
||||
export interface Utils {
|
||||
coordinates: {
|
||||
isCoordinate(value: string): boolean;
|
||||
parse(value: string): Coordinate;
|
||||
stringify(coord: Coordinate): string;
|
||||
};
|
||||
entity: {
|
||||
getComponentProperty(entity: Entity, componentName: string, delimiter?: string): any;
|
||||
setComponentProperty(
|
||||
entity: Entity,
|
||||
componentName: string,
|
||||
value: any,
|
||||
delimiter?: string
|
||||
): void;
|
||||
};
|
||||
styleParser: {
|
||||
parse(value: string): object;
|
||||
stringify(data: object): string;
|
||||
};
|
||||
deepEqual(a: any, b: any): boolean;
|
||||
diff(a: object, b: object): object;
|
||||
extend(target: object, ...source: object[]): object;
|
||||
extendDeep(target: object, ...source: object[]): object;
|
||||
|
||||
interface PrimitiveDefinition {
|
||||
defaultComponents?: any; // TODO cleanup type
|
||||
deprecated?: boolean;
|
||||
mappings?: any; // TODO cleanup type
|
||||
transforms?: any; // TODO cleanup type
|
||||
}
|
||||
throttle(
|
||||
tickFunction: () => void,
|
||||
minimumInterval: number,
|
||||
optionalContext?: {}
|
||||
): (t: number, dt: number) => void;
|
||||
throttleTick(
|
||||
tickFunction: (t: number, dt: number) => void,
|
||||
minimumInterval: number,
|
||||
optionalContext?: {}
|
||||
): (t: number, dt: number) => void;
|
||||
}
|
||||
|
||||
type PropertyTypes = 'array' | 'asset' | 'audio' | 'boolean' | 'color' |
|
||||
'int' | 'map' | 'model' | 'number' | 'selector' | 'selectorAll' |
|
||||
'string' | 'vec2' | 'vec3' | 'vec4';
|
||||
// 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 GeometryDefinition<T extends object = object, U = any> = T & Partial<Geometry<U>>;
|
||||
export type NodeDefinition<T extends object = object> = T & Partial<ANode>;
|
||||
export interface PrimitiveDefinition {
|
||||
defaultComponents?: any; // TODO cleanup type
|
||||
deprecated?: boolean;
|
||||
mappings?: any; // TODO cleanup type
|
||||
transforms?: any; // TODO cleanup type
|
||||
}
|
||||
export interface MinimalShaderDefinition {
|
||||
schema: Shader['schema'];
|
||||
}
|
||||
export type ShaderDefinition<T extends object = MinimalShaderDefinition & object> = T &
|
||||
Partial<Shader>;
|
||||
export type SystemDefinition<T extends object = object> = T & Partial<System>;
|
||||
|
||||
type SceneEvents = 'enter-vr' | 'exit-vr' | 'loaded' | 'renderstart';
|
||||
// root export
|
||||
export interface AFrame {
|
||||
AComponent: Component;
|
||||
AEntity: Entity;
|
||||
ANode: ANode;
|
||||
AScene: Scene;
|
||||
|
||||
interface Scene extends Entity {
|
||||
behaviors: Behavior[];
|
||||
camera: THREE.Camera;
|
||||
canvas: HTMLCanvasElement;
|
||||
effect: THREE.VREffect;
|
||||
isMobile: boolean;
|
||||
object3D: THREE.Scene;
|
||||
renderer: THREE.WebGLRenderer;
|
||||
renderStarted: boolean;
|
||||
systems: ObjectMap<System>;
|
||||
time: number;
|
||||
|
||||
enterVR(): Promise<void> | void;
|
||||
exitVR(): Promise<void> | void;
|
||||
reload(): void;
|
||||
|
||||
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
|
||||
addEventListener(type: SceneEvents, listener: EventListener, useCapture?: boolean): void;
|
||||
}
|
||||
|
||||
type Schema<T = { [key: string]: any }> = SinglePropertySchema<T> | MultiPropertySchema<T>;
|
||||
|
||||
interface SchemaUtils {
|
||||
isSingleProperty(schema: Schema): boolean;
|
||||
process(schema: Schema): boolean;
|
||||
}
|
||||
|
||||
interface Shader {
|
||||
name: string;
|
||||
data: { [key: string]: any };
|
||||
schema: Schema<this['data']>;
|
||||
material: THREE.Material;
|
||||
vertexShader: string;
|
||||
fragmentShader: string;
|
||||
|
||||
init(this: this, data?: this['data']): void;
|
||||
tick?(this: this, time: number, timeDelta: number): void;
|
||||
update(this: this, oldData: this['data']): void;
|
||||
}
|
||||
|
||||
interface ShaderConstructor<T extends Shader> {
|
||||
new (): T;
|
||||
}
|
||||
|
||||
type ShaderDefinition<T extends Shader = Shader> = Partial<T>;
|
||||
|
||||
interface ShaderDescriptor<T extends Shader = Shader> {
|
||||
Shader: ShaderConstructor<T>;
|
||||
schema: Schema;
|
||||
}
|
||||
|
||||
interface SinglePropertySchema<T> {
|
||||
type?: PropertyTypes;
|
||||
'default'?: T;
|
||||
parse?(value: string): T;
|
||||
stringify?(value: T): string;
|
||||
}
|
||||
|
||||
interface System {
|
||||
data: { [key: string]: any };
|
||||
schema: Schema<this['data']>;
|
||||
init(this: this): void;
|
||||
pause(this: this): void;
|
||||
play(this: this): void;
|
||||
tick?(this: this, t: number, dt: number): void;
|
||||
}
|
||||
|
||||
interface SystemConstructor<T extends System = System> {
|
||||
new (scene: Scene): T;
|
||||
}
|
||||
|
||||
type SystemDefinition<T extends System = System> = Partial<T>;
|
||||
|
||||
interface Utils {
|
||||
coordinates: {
|
||||
isCoordinate(value: string): boolean;
|
||||
parse(value: string): Coordinate;
|
||||
stringify(coord: Coordinate): string;
|
||||
components: ObjectMap<ComponentDescriptor>;
|
||||
geometries: ObjectMap<GeometryDescriptor>;
|
||||
primitives: {
|
||||
getMeshMixin(): {
|
||||
defaultComponents: { material: object };
|
||||
mappings: { [key: string]: any }; // TODO improve any type
|
||||
};
|
||||
entity: {
|
||||
getComponentProperty(entity: Entity, componentName: string, delimiter?: string): any;
|
||||
setComponentProperty(entity: Entity, componentName: string, value: any, delimiter?: string): void;
|
||||
};
|
||||
styleParser: {
|
||||
parse(value: string): object;
|
||||
stringify(data: object): string;
|
||||
};
|
||||
deepEqual(a: any, b: any): boolean;
|
||||
diff(a: object, b: object): object;
|
||||
extend(target: object, ... source: object[]): object;
|
||||
extendDeep(target: object, ... source: object[]): object;
|
||||
primitives: ObjectMap<Entity>;
|
||||
};
|
||||
scenes: Scene[];
|
||||
schema: SchemaUtils;
|
||||
shaders: ObjectMap<ShaderDescriptor>;
|
||||
systems: ObjectMap<SystemConstructor>;
|
||||
THREE: ThreeLib;
|
||||
TWEEN: TweenLib;
|
||||
utils: Utils;
|
||||
version: string;
|
||||
|
||||
throttle(tickFunction: () => void, minimumInterval: number, optionalContext?: {}): (t: number, dt: number) => void;
|
||||
throttleTick(tickFunction: (t: number, dt: number) => void, minimumInterval: number, optionalContext?: {}): (t: number, dt: number) => void;
|
||||
registerComponent<T extends object>(
|
||||
name: string,
|
||||
component: ComponentDefinition<T>
|
||||
): ComponentConstructor<T>;
|
||||
registerElement(name: string, element: object): void;
|
||||
registerGeometry<T extends object>(
|
||||
name: string,
|
||||
geometry: GeometryDefinition<T>
|
||||
): GeometryConstructor<T>;
|
||||
registerPrimitive(name: string, primitive: PrimitiveDefinition): void;
|
||||
registerShader<T extends MinimalShaderDefinition & object>(
|
||||
name: string,
|
||||
shader: ShaderDefinition<T>
|
||||
): ShaderConstructor<T>;
|
||||
registerSystem<T extends object>(
|
||||
name: string,
|
||||
definition: SystemDefinition<T>
|
||||
): SystemConstructor<T>;
|
||||
}
|
||||
|
||||
// module.exports
|
||||
export const AComponent: AFrame['AComponent'];
|
||||
export const AEntity: AFrame['AEntity'];
|
||||
export const ANode: AFrame['ANode'];
|
||||
export const AScene: AFrame['AScene'];
|
||||
export const components: AFrame['components'];
|
||||
export const geometries: AFrame['geometries'];
|
||||
export const primitives: AFrame['primitives'];
|
||||
export const scenes: AFrame['scenes'];
|
||||
export const schema: AFrame['schema'];
|
||||
export const shaders: AFrame['shaders'];
|
||||
export const systems: AFrame['systems'];
|
||||
export const THREE: AFrame['THREE'];
|
||||
export const TWEEN: AFrame['TWEEN'];
|
||||
export const utils: AFrame['utils'];
|
||||
export const version: AFrame['version'];
|
||||
export const registerComponent: AFrame['registerComponent'];
|
||||
export const registerElement: AFrame['registerElement'];
|
||||
export const registerGeometry: AFrame['registerGeometry'];
|
||||
export const registerPrimitive: AFrame['registerPrimitive'];
|
||||
export const registerShader: AFrame['registerShader'];
|
||||
export const registerSystem: AFrame['registerSystem'];
|
||||
|
||||
// global exports
|
||||
declare global {
|
||||
var hasNativeWebVRImplementation: boolean;
|
||||
|
||||
namespace AFRAME {
|
||||
const AComponent: AFrame['AComponent'];
|
||||
const AEntity: AFrame['AEntity'];
|
||||
const ANode: AFrame['ANode'];
|
||||
const AScene: AFrame['AScene'];
|
||||
const components: AFrame['components'];
|
||||
const geometries: AFrame['geometries'];
|
||||
const primitives: AFrame['primitives'];
|
||||
const scenes: AFrame['scenes'];
|
||||
const schema: AFrame['schema'];
|
||||
const shaders: AFrame['shaders'];
|
||||
const systems: AFrame['systems'];
|
||||
const THREE: AFrame['THREE'];
|
||||
const TWEEN: AFrame['TWEEN'];
|
||||
const utils: AFrame['utils'];
|
||||
const version: string;
|
||||
|
||||
const registerComponent: AFrame['registerComponent'];
|
||||
const registerElement: AFrame['registerElement'];
|
||||
const registerGeometry: AFrame['registerGeometry'];
|
||||
const registerPrimitive: AFrame['registerPrimitive'];
|
||||
const registerShader: AFrame['registerShader'];
|
||||
const registerSystem: AFrame['registerSystem'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom elements augment document methods to return custom HTML
|
||||
*/
|
||||
interface Document {
|
||||
createElement(tagName: string): Entity;
|
||||
querySelector(selectors: 'a-scene'): Scene;
|
||||
querySelector(selectors: string): Entity<any>;
|
||||
querySelectorAll(selectors: string): NodeListOf<Entity<any> | Element>;
|
||||
}
|
||||
|
||||
interface HTMLCollection extends HTMLCollectionBase {
|
||||
/**
|
||||
* Retrieves a select object or an object from an options collection.
|
||||
*/
|
||||
namedItem(name: string): Element | Entity | null;
|
||||
item(index: number): Element | Entity;
|
||||
[index: number]: Element | Entity;
|
||||
}
|
||||
}
|
||||
|
||||
1045
types/aframe/test/aframe-io-tests.ts
Normal file
1045
types/aframe/test/aframe-io-tests.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,14 @@
|
||||
import {
|
||||
Component,
|
||||
Entity,
|
||||
MultiPropertySchema,
|
||||
System,
|
||||
SystemDefinition,
|
||||
THREE,
|
||||
Geometry,
|
||||
registerComponent
|
||||
} from 'aframe';
|
||||
|
||||
// Global
|
||||
const threeCamera = new AFRAME.THREE.Camera();
|
||||
AFRAME.TWEEN.Easing;
|
||||
@@ -16,7 +27,7 @@ entity.setAttribute('material', 'color', 'red');
|
||||
|
||||
entity.components['geometry'].data;
|
||||
|
||||
type MyEntity = AFrame.Entity<{
|
||||
type MyEntity = Entity<{
|
||||
camera: THREE.Camera;
|
||||
material: THREE.Material;
|
||||
sound: { pause(): void };
|
||||
@@ -33,29 +44,31 @@ entity.setAttribute('light', {
|
||||
intensity: 2.0
|
||||
});
|
||||
|
||||
entity.addEventListener('child-detached', (event) => {
|
||||
entity.addEventListener('child-detached', event => {
|
||||
event.detail;
|
||||
});
|
||||
|
||||
// Components
|
||||
|
||||
interface TestComponent extends AFrame.Component {
|
||||
multiply: (f: number) => number;
|
||||
// interface TestComponent extends Component {
|
||||
// multiply: (f: number) => number;
|
||||
//
|
||||
// data: {
|
||||
// myProperty: any[],
|
||||
// string: string,
|
||||
// num: number
|
||||
// };
|
||||
//
|
||||
// system: TestSystem;
|
||||
// }
|
||||
|
||||
data: {
|
||||
myProperty: any[],
|
||||
string: string,
|
||||
num: number
|
||||
};
|
||||
|
||||
system: TestSystem;
|
||||
}
|
||||
|
||||
const Component = AFRAME.registerComponent<TestComponent>('test-component', {
|
||||
const Component = registerComponent('test-component', {
|
||||
schema: {
|
||||
myProperty: {
|
||||
default: [],
|
||||
parse() { return [true]; },
|
||||
parse() {
|
||||
return [true];
|
||||
}
|
||||
},
|
||||
string: { type: 'string' },
|
||||
num: 0
|
||||
@@ -69,9 +82,9 @@ const Component = AFRAME.registerComponent<TestComponent>('test-component', {
|
||||
pause() {},
|
||||
play() {},
|
||||
|
||||
multiply(this: TestComponent, f: number) {
|
||||
multiply(f: number) {
|
||||
// Reference to system because both were registered with the same name.
|
||||
return f * this.data.num * this.system.data.counter;
|
||||
return f * this.data.num * this.system!.data.counter;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -81,13 +94,7 @@ scene.hasLoaded;
|
||||
|
||||
// System
|
||||
|
||||
interface TestSystem extends AFrame.System {
|
||||
data: {
|
||||
counter: number;
|
||||
};
|
||||
}
|
||||
|
||||
const testSystem: AFrame.SystemDefinition<TestSystem> = {
|
||||
const testSystem: SystemDefinition = {
|
||||
schema: {
|
||||
counter: 0
|
||||
},
|
||||
@@ -101,13 +108,7 @@ AFRAME.registerSystem('test-component', testSystem);
|
||||
|
||||
// Register Custom Geometry
|
||||
|
||||
interface TestGeometry extends AFrame.Geometry {
|
||||
schema: AFrame.MultiPropertySchema<{
|
||||
groupIndex: number;
|
||||
}>;
|
||||
}
|
||||
|
||||
AFRAME.registerGeometry<TestGeometry>('a-test-geometry', {
|
||||
AFRAME.registerGeometry('a-test-geometry', {
|
||||
schema: {
|
||||
groupIndex: { default: 0 }
|
||||
},
|
||||
@@ -21,6 +21,7 @@
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"aframe-tests.ts"
|
||||
"test/aframe-tests.ts",
|
||||
"test/aframe-io-tests.ts"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,109 +1,110 @@
|
||||
import Agenda = require("agenda");
|
||||
import { Db, Server } from "mongodb";
|
||||
import { Db, Server, MongoClient } from "mongodb";
|
||||
|
||||
var mongoConnectionString = "mongodb://127.0.0.1/agenda";
|
||||
|
||||
var agenda = new Agenda({ db: { address: mongoConnectionString } });
|
||||
(async () => {
|
||||
var agenda = new Agenda({ db: { address: mongoConnectionString } });
|
||||
var agenda = new Agenda({
|
||||
mongo: (await MongoClient.connect(mongoConnectionString)).db(),
|
||||
db: { collection: 'agenda-jobs' },
|
||||
});
|
||||
|
||||
agenda.define<{ foo: Error }>('delete old users', (job, done) => {
|
||||
done(job.attrs.data.foo)
|
||||
agenda.define<{ foo: Error }>('delete old users', (job, done) => {
|
||||
done(job.attrs.data.foo)
|
||||
});
|
||||
|
||||
agenda.on('ready', () => {
|
||||
agenda.every('3 minutes', 'delete old users');
|
||||
|
||||
// Alternatively, you could also do:
|
||||
agenda.every('*/3 * * * *', 'delete old users');
|
||||
|
||||
agenda.start();
|
||||
});
|
||||
|
||||
agenda.define('send email report', { priority: 'high', concurrency: 10 }, (job, done) => {
|
||||
});
|
||||
|
||||
agenda.on('ready', () => {
|
||||
agenda.schedule('in 20 minutes', 'send email report', { to: 'admin@example.com' });
|
||||
agenda.start();
|
||||
});
|
||||
|
||||
agenda.on('ready', () => {
|
||||
var weeklyReport = agenda.create('send email report', { to: 'another-guy@example.com' });
|
||||
weeklyReport.repeatEvery('1 week').save();
|
||||
agenda.start();
|
||||
});
|
||||
|
||||
var agenda = new Agenda({ processEvery: '30 seconds' });
|
||||
|
||||
agenda.defaultConcurrency(5);
|
||||
|
||||
var agenda = new Agenda({ defaultConcurrency: 5 });
|
||||
|
||||
agenda.lockLimit(0);
|
||||
|
||||
var agenda = new Agenda({ lockLimit: 0 });
|
||||
|
||||
agenda.defaultLockLimit(0);
|
||||
|
||||
var agenda = new Agenda({ defaultLockLimit: 0 });
|
||||
|
||||
agenda.defaultLockLifetime(10000);
|
||||
|
||||
var agenda = new Agenda({ defaultLockLifetime: 10000 });
|
||||
|
||||
agenda.define('some long running job', function (job, done) {
|
||||
done();
|
||||
});
|
||||
|
||||
agenda.every('15 minutes', ['printAnalyticsReport', 'sendNotifications', 'updateUserRecords']);
|
||||
|
||||
agenda.schedule('tomorrow at noon', 'printAnalyticsReport', { userCount: 100 });
|
||||
|
||||
agenda.schedule('tomorrow at noon', ['printAnalyticsReport', 'sendNotifications', 'updateUserRecords']);
|
||||
|
||||
agenda.now('do the hokey pokey');
|
||||
|
||||
var job = agenda.create<{ userCount: number }>('printAnalyticsReport', { userCount: 100 });
|
||||
await job.save();
|
||||
|
||||
const jobs = await agenda.jobs({ name: 'printAnalyticsReport' });
|
||||
jobs.forEach((job) => {
|
||||
job.save();
|
||||
});
|
||||
|
||||
let numRemoved = await agenda.cancel({ name: 'printAnalyticsReport' });
|
||||
|
||||
numRemoved = await agenda.purge();
|
||||
|
||||
await agenda.stop();
|
||||
|
||||
await job.agenda.now('do the hokey pokey');
|
||||
|
||||
job.repeatEvery('10 minutes');
|
||||
|
||||
job.repeatEvery('10 minutes', { timezone: 'America/New_York' });
|
||||
|
||||
job.repeatEvery('10 minutes', { skipImmediate: true });
|
||||
|
||||
job.repeatAt('3:30pm');
|
||||
|
||||
job.schedule('tomorrow at 6pm');
|
||||
|
||||
job.priority('low');
|
||||
job.priority(10);
|
||||
|
||||
job.unique({ 'data.type': 'active', 'data.userId': '123' });
|
||||
job.fail('insuficient disk space');
|
||||
job.fail(new Error('insufficient disk space'));
|
||||
const job2 = await job.run();
|
||||
await job.remove();
|
||||
});
|
||||
|
||||
agenda.on('ready', () => {
|
||||
agenda.every('3 minutes', 'delete old users');
|
||||
|
||||
// Alternatively, you could also do:
|
||||
agenda.every('*/3 * * * *', 'delete old users');
|
||||
|
||||
agenda.start();
|
||||
});
|
||||
|
||||
agenda.define('send email report', { priority: 'high', concurrency: 10 }, (job, done) => {
|
||||
});
|
||||
|
||||
agenda.on('ready', () => {
|
||||
agenda.schedule('in 20 minutes', 'send email report', { to: 'admin@example.com' });
|
||||
agenda.start();
|
||||
});
|
||||
|
||||
agenda.on('ready', () => {
|
||||
var weeklyReport = agenda.create('send email report', { to: 'another-guy@example.com' });
|
||||
weeklyReport.repeatEvery('1 week').save();
|
||||
agenda.start();
|
||||
});
|
||||
|
||||
var agenda = new Agenda({ processEvery: '30 seconds' });
|
||||
|
||||
agenda.defaultConcurrency(5);
|
||||
|
||||
var agenda = new Agenda({ defaultConcurrency: 5 });
|
||||
|
||||
agenda.lockLimit(0);
|
||||
|
||||
var agenda = new Agenda({ lockLimit: 0 });
|
||||
|
||||
agenda.defaultLockLimit(0);
|
||||
|
||||
var agenda = new Agenda({ defaultLockLimit: 0 });
|
||||
|
||||
agenda.defaultLockLifetime(10000);
|
||||
|
||||
var agenda = new Agenda({ defaultLockLifetime: 10000 });
|
||||
|
||||
agenda.define('some long running job', function(job, done) {
|
||||
done();
|
||||
});
|
||||
|
||||
agenda.every('15 minutes', ['printAnalyticsReport', 'sendNotifications', 'updateUserRecords']);
|
||||
|
||||
agenda.schedule('tomorrow at noon', 'printAnalyticsReport', { userCount: 100 });
|
||||
|
||||
agenda.schedule('tomorrow at noon', ['printAnalyticsReport', 'sendNotifications', 'updateUserRecords']);
|
||||
|
||||
agenda.now('do the hokey pokey');
|
||||
|
||||
var job = agenda.create<{ userCount: number }>('printAnalyticsReport', { userCount: 100 });
|
||||
job.save(function(err) {
|
||||
console.log("Job successfully saved");
|
||||
});
|
||||
|
||||
agenda.jobs({ name: 'printAnalyticsReport' }, function(err, jobs) {
|
||||
// Work with jobs (see below)
|
||||
});
|
||||
|
||||
agenda.cancel({ name: 'printAnalyticsReport' }, function(err, numRemoved) {
|
||||
});
|
||||
|
||||
agenda.purge(function(err, numRemoved) {
|
||||
});
|
||||
|
||||
agenda.stop(function() {
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
job.agenda.now('do the hokey pokey');
|
||||
|
||||
job.repeatEvery('10 minutes');
|
||||
|
||||
job.repeatAt('3:30pm');
|
||||
|
||||
job.schedule('tomorrow at 6pm');
|
||||
|
||||
job.priority('low');
|
||||
job.priority(10);
|
||||
|
||||
job.unique({ 'data.type': 'active', 'data.userId': '123' });
|
||||
job.fail('insuficient disk space');
|
||||
job.fail(new Error('insufficient disk space'));
|
||||
job.run(function(err, job) {
|
||||
console.log("I don't know why you would need to do this...");
|
||||
});
|
||||
job.remove(function(err) {
|
||||
if (!err) console.log("Successfully removed job from collection");
|
||||
})
|
||||
|
||||
class ExtendedAgenda extends Agenda {
|
||||
async start() { }
|
||||
async start() { }
|
||||
}
|
||||
|
||||
const extendedAgenda: ExtendedAgenda = new ExtendedAgenda()
|
||||
|
||||
85
types/agenda/index.d.ts
vendored
85
types/agenda/index.d.ts
vendored
@@ -1,4 +1,4 @@
|
||||
// Type definitions for Agenda v1.0.3
|
||||
// Type definitions for Agenda v2.0.0
|
||||
// Project: https://github.com/agenda/agenda
|
||||
// Definitions by: Meir Gottlieb <https://github.com/meirgottlieb>
|
||||
// Jeff Principe <https://github.com/princjef>
|
||||
@@ -64,7 +64,7 @@ declare class Agenda extends EventEmitter {
|
||||
defaultConcurrency(value: number): this;
|
||||
|
||||
/**
|
||||
* Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is
|
||||
* Takes a number which specifies the max number jobs that can be locked at any given moment. By default it is
|
||||
* 0 for no max.
|
||||
* @param value The value to set.
|
||||
*/
|
||||
@@ -95,16 +95,14 @@ declare class Agenda extends EventEmitter {
|
||||
/**
|
||||
* Find all Jobs matching `query` and pass same back in cb().
|
||||
* @param query
|
||||
* @param cb
|
||||
*/
|
||||
jobs<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(query: any, cb: ResultCallback<Agenda.Job<T>[]>): void;
|
||||
jobs<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(query: any): Promise<Agenda.Job<T>[]>;
|
||||
|
||||
/**
|
||||
* Removes all jobs in the database without defined behaviors. Useful if you change a definition name and want
|
||||
* to remove old jobs.
|
||||
* @param cb Called with the number of jobs removed.
|
||||
*/
|
||||
purge(cb?: ResultCallback<number>): void;
|
||||
purge(): Promise<number>;
|
||||
|
||||
/**
|
||||
* Defines a job with the name of jobName. When a job of job name gets run, it will be passed to fn(job, done).
|
||||
@@ -123,46 +121,41 @@ declare class Agenda extends EventEmitter {
|
||||
* @param names The name or names of the job(s) to run.
|
||||
* @param data An optional argument that will be passed to the processing function under job.attrs.data.
|
||||
* @param options An optional argument that will be passed to job.repeatEvery.
|
||||
* @param cb An optional callback function which will be called when the job has been persisted in the database.
|
||||
*/
|
||||
every<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(interval: number | string, names: string, data?: T, options?: any, cb?: ResultCallback<Agenda.Job<T>>): Agenda.Job<T>;
|
||||
every<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(interval: number | string, names: string[], data?: T, options?: any, cb?: ResultCallback<Agenda.Job<T>[]>): Agenda.Job<T>[];
|
||||
every<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(interval: number | string, names: string, data?: T, options?: any): Promise<Agenda.Job<T>>;
|
||||
every<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(interval: number | string, names: string[], data?: T, options?: any): Promise<Agenda.Job<T>[]>;
|
||||
|
||||
/**
|
||||
* Schedules a job to run name once at a given time.
|
||||
* @param when A Date or a String such as tomorrow at 5pm.
|
||||
* @param names The name or names of the job(s) to run.
|
||||
* @param data An optional argument that will be passed to the processing function under job.attrs.data.
|
||||
* @param cb An optional callback function which will be called when the job has been persisted in the database.
|
||||
*/
|
||||
schedule<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(when: Date | string, names: string, data?: T, cb?: ResultCallback<Agenda.Job<T>>): Agenda.Job<T>;
|
||||
schedule<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(when: Date | string, names: string[], data?: T, cb?: ResultCallback<Agenda.Job<T>[]>): Agenda.Job<T>[];
|
||||
schedule<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(when: Date | string, names: string, data?: T): Promise<Agenda.Job<T>>;
|
||||
schedule<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(when: Date | string, names: string[], data?: T): Promise<Agenda.Job<T>[]>;
|
||||
|
||||
/**
|
||||
* Schedules a job to run name once immediately.
|
||||
* @param name The name of the job to run.
|
||||
* @param data An optional argument that will be passed to the processing function under job.attrs.data.
|
||||
* @param cb An optional callback function which will be called when the job has been persisted in the database.
|
||||
*/
|
||||
now<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(name: string, data?: T, cb?: ResultCallback<Agenda.Job<T>>): Agenda.Job<T>;
|
||||
now<T extends Agenda.JobAttributesData = Agenda.JobAttributesData>(name: string, data?: T): Promise<Agenda.Job<T>>;
|
||||
|
||||
/**
|
||||
* Cancels any jobs matching the passed mongodb-native query, and removes them from the database.
|
||||
* @param query Mongodb native query.
|
||||
* @param cb Called with the number of jobs removed.
|
||||
*/
|
||||
cancel(query: any, cb?: ResultCallback<number>): void;
|
||||
cancel(query: any): Promise<number>;
|
||||
|
||||
/**
|
||||
* Starts the job queue processing, checking processEvery time to see if there are new jobs.
|
||||
*/
|
||||
start(): void;
|
||||
start(): Promise<void>;
|
||||
|
||||
/**
|
||||
* Stops the job queue processing. Unlocks currently running jobs.
|
||||
* @param cb Called after the job processing queue shuts down and unlocks all jobs.
|
||||
*/
|
||||
stop(cb: Callback): void;
|
||||
stop(): Promise<void>;
|
||||
}
|
||||
|
||||
declare namespace Agenda {
|
||||
@@ -196,7 +189,7 @@ declare namespace Agenda {
|
||||
defaultLockLimit?: number;
|
||||
|
||||
/**
|
||||
* Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is
|
||||
* Takes a number which specifies the max number jobs that can be locked at any given moment. By default it is
|
||||
* 0 for no max.
|
||||
*/
|
||||
lockLimit?: number;
|
||||
@@ -210,17 +203,7 @@ declare namespace Agenda {
|
||||
/**
|
||||
* Specifies that Agenda should be initialized using and existing MongoDB connection.
|
||||
*/
|
||||
mongo?: {
|
||||
/**
|
||||
* The MongoDB database connection to use.
|
||||
*/
|
||||
db: Db;
|
||||
|
||||
/**
|
||||
* The name of the collection to use.
|
||||
*/
|
||||
collection?: string;
|
||||
}
|
||||
mongo?: Db;
|
||||
|
||||
/**
|
||||
* Specifies that Agenda should connect to MongoDB.
|
||||
@@ -228,8 +211,10 @@ declare namespace Agenda {
|
||||
db?: {
|
||||
/**
|
||||
* The connection URL.
|
||||
* Required when using `db` option to connect.
|
||||
* Not required when an existing connection is passed as `mongo` property.
|
||||
*/
|
||||
address: string;
|
||||
address?: string;
|
||||
|
||||
/**
|
||||
* The name of the collection to use.
|
||||
@@ -238,6 +223,7 @@ declare namespace Agenda {
|
||||
|
||||
/**
|
||||
* Connection options to pass to MongoDB.
|
||||
* Not required when an existing connection is passed as `mongo` property.
|
||||
*/
|
||||
options?: any;
|
||||
}
|
||||
@@ -350,57 +336,57 @@ declare namespace Agenda {
|
||||
/**
|
||||
* Specifies an interval on which the job should repeat.
|
||||
* @param interval A human-readable format String, a cron format String, or a Number.
|
||||
* @param options An optional argument that can include a timezone field. The timezone should be a string as
|
||||
* accepted by moment-timezone and is considered when using an interval in the cron string format.
|
||||
* @param options An optional argument that can include a timezone field or skipImmediate field.
|
||||
* The timezone should be a string as accepted by moment-timezone and is considered when using an interval in the cron string format.
|
||||
* Setting skipImmediate as true will skip the immediate run. The first run will occur only in configured interval.
|
||||
*/
|
||||
repeatEvery(interval: string | number, options?: { timezone?: string }): Job<T>
|
||||
repeatEvery(interval: string | number, options?: { timezone?: string, skipImmediate?: boolean }): this
|
||||
|
||||
/**
|
||||
* Specifies a time when the job should repeat. [Possible values](https://github.com/matthewmueller/date#examples).
|
||||
* @param time
|
||||
*/
|
||||
repeatAt(time: string): Job<T>
|
||||
repeatAt(time: string): this
|
||||
|
||||
/**
|
||||
* Disables the job.
|
||||
*/
|
||||
disable(): Job<T>;
|
||||
disable(): this;
|
||||
|
||||
/**
|
||||
* Enables the job.
|
||||
*/
|
||||
enable(): Job<T>;
|
||||
enable(): this;
|
||||
|
||||
/**
|
||||
* Ensure that only one instance of this job exists with the specified properties
|
||||
* @param value The properties associated with the job that must be unqiue.
|
||||
* @param opts
|
||||
*/
|
||||
unique(value: any, opts?: { insertOnly?: boolean }): Job<T>;
|
||||
unique(value: any, opts?: { insertOnly?: boolean }): this;
|
||||
|
||||
/**
|
||||
* Specifies the next time at which the job should run.
|
||||
* @param time The next time at which the job should run.
|
||||
*/
|
||||
schedule(time: string | Date): Job<T>;
|
||||
schedule(time: string | Date): this;
|
||||
|
||||
/**
|
||||
* Specifies the priority weighting of the job.
|
||||
* @param value The priority of the job (lowest|low|normal|high|highest|number).
|
||||
*/
|
||||
priority(value: string | number): Job<T>;
|
||||
priority(value: string | number): this;
|
||||
|
||||
/**
|
||||
* Sets job.attrs.failedAt to now, and sets job.attrs.failReason to reason.
|
||||
* @param reason A message or Error object that indicates why the job failed.
|
||||
*/
|
||||
fail(reason: string | Error): Job<T>;
|
||||
fail(reason: string | Error): this;
|
||||
|
||||
/**
|
||||
* Runs the given job and calls callback(err, job) upon completion. Normally you never need to call this manually
|
||||
* @param cb Called when the job is completed.
|
||||
*/
|
||||
run(cb?: ResultCallback<Job<T>>): Job<T>;
|
||||
run(): Promise<this>;
|
||||
|
||||
/**
|
||||
* Returns true if the job is running; otherwise, returns false.
|
||||
@@ -409,27 +395,24 @@ declare namespace Agenda {
|
||||
|
||||
/**
|
||||
* Saves the job into the database.
|
||||
* @param cb Called when the job is saved.
|
||||
*/
|
||||
save(cb?: ResultCallback<Job<T>>): Job<T>;
|
||||
save(): Promise<this>;
|
||||
|
||||
/**
|
||||
* Removes the job from the database and cancels the job.
|
||||
* @param cb Called after the job has beeb removed from the database.
|
||||
*/
|
||||
remove(cb?: Callback): void;
|
||||
remove(): Promise<void>;
|
||||
|
||||
/**
|
||||
* Resets the lock on the job. Useful to indicate that the job hasn't timed out when you have very long running
|
||||
* jobs.
|
||||
* @param cb Called after the job has been saved to the database.
|
||||
*/
|
||||
touch(cb?: Callback): void;
|
||||
touch(): Promise<this>;
|
||||
|
||||
/**
|
||||
* Calculates next time the job should run
|
||||
*/
|
||||
computeNextRunAt(): Job<T>;
|
||||
computeNextRunAt(): this;
|
||||
}
|
||||
|
||||
interface JobOptions {
|
||||
|
||||
23
types/agent-base/agent-base-tests.ts
Normal file
23
types/agent-base/agent-base-tests.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import agent = require('agent-base');
|
||||
|
||||
agent(); // $ExpectType Agent
|
||||
agent({ timeout: 1000 }); // $ExpectType Agent
|
||||
|
||||
agent((req, opts) => {}); // $ExpectType Agent
|
||||
agent((req, opts) => {}, { timeout: 1000 }); // $ExpectType Agent
|
||||
|
||||
agent(async (req, opts) => {}); // $ExpectType Agent
|
||||
agent(async (req, opts) => {}, { timeout: 1000 }); // $ExpectType Agent
|
||||
|
||||
agent(0); // $ExpectError
|
||||
agent(1); // $ExpectError
|
||||
agent(''); // $ExpectError
|
||||
agent(true); // $ExpectError
|
||||
agent(null); // $ExpectError
|
||||
|
||||
agent((req, opts) => {}, 0); // $ExpectError
|
||||
agent((req, opts) => {}, 1); // $ExpectError
|
||||
agent((req, opts) => {}, ''); // $ExpectError
|
||||
agent((req, opts) => {}, true); // $ExpectError
|
||||
agent((req, opts) => {}, null); // $ExpectError
|
||||
agent((req, opts) => {}, (req, opts) => {}); // $ExpectError
|
||||
44
types/agent-base/index.d.ts
vendored
Normal file
44
types/agent-base/index.d.ts
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
// Type definitions for agent-base 4.2
|
||||
// Project: https://github.com/TooTallNate/node-agent-base#readme
|
||||
// Definitions by: Christopher Quadflieg <https://github.com/Shinigami92>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
|
||||
/// <reference types="node" />
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
declare namespace Agent {
|
||||
type AgentCallback = (
|
||||
req?: any,
|
||||
opts?: {
|
||||
secureEndpoint: boolean;
|
||||
}
|
||||
) => void;
|
||||
|
||||
interface AgentOptions {
|
||||
timeout?: number;
|
||||
host?: string;
|
||||
port?: number;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
interface Agent extends EventEmitter {
|
||||
_promisifiedCallback: boolean;
|
||||
timeout: number | null;
|
||||
options?: AgentOptions;
|
||||
callback: AgentCallback;
|
||||
addRequest: (req?: any, opts?: any) => void;
|
||||
freeSocket: (socket: any, opts: any) => void;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Base `http.Agent` implementation.
|
||||
* No pooling/keep-alive is implemented by default.
|
||||
*/
|
||||
declare function Agent(opts?: Agent.AgentOptions): Agent.Agent;
|
||||
declare function Agent(
|
||||
callback: Agent.AgentCallback,
|
||||
opts?: Agent.AgentOptions
|
||||
): Agent.Agent;
|
||||
|
||||
export = Agent;
|
||||
24
types/agent-base/tsconfig.json
Normal file
24
types/agent-base/tsconfig.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"target": "es6",
|
||||
"lib": [
|
||||
"es6"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"baseUrl": "../",
|
||||
"typeRoots": [
|
||||
"../"
|
||||
],
|
||||
"types": [],
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"agent-base-tests.ts"
|
||||
]
|
||||
}
|
||||
27
types/agora-rtc-sdk/agora-rtc-sdk-tests.ts
Normal file
27
types/agora-rtc-sdk/agora-rtc-sdk-tests.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
let client = AgoraRTC.createClient({
|
||||
mode: 'live',
|
||||
codec: 'vp8'
|
||||
});
|
||||
|
||||
let stream = AgoraRTC.createStream({
|
||||
video: true,
|
||||
audio: true,
|
||||
streamID: 21230,
|
||||
screen: false
|
||||
});
|
||||
|
||||
client.init('74a0b7bb5d3e47c7abca0533d17b0afa', () => {
|
||||
client.join('74a0b7bb5d3e47c7abca0533d17b0afa', 'testyy', 21230, uid => {
|
||||
stream.init(() => {
|
||||
client.publish(stream, err => {
|
||||
throw(err);
|
||||
});
|
||||
}, err => {
|
||||
throw(err);
|
||||
});
|
||||
}, err => {
|
||||
throw(err);
|
||||
});
|
||||
}, err => {
|
||||
throw(err);
|
||||
});
|
||||
314
types/agora-rtc-sdk/index.d.ts
vendored
Normal file
314
types/agora-rtc-sdk/index.d.ts
vendored
Normal file
@@ -0,0 +1,314 @@
|
||||
// Type definitions for agora-rtc-sdk 2.3
|
||||
// Project: https://github.com/AgoraIO/web-archive#readme
|
||||
// Definitions by: Menthays <https://github.com/menthays>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.2
|
||||
|
||||
/*~ If this module is a UMD module that exposes a global variable 'myLib' when
|
||||
*~ loaded outside a module loader environment, declare that global here.
|
||||
*~ Otherwise, delete this declaration.
|
||||
*/
|
||||
export as namespace AgoraRTC;
|
||||
|
||||
/*~ If this module has methods, declare them as functions like so.
|
||||
*/
|
||||
export function createClient(config: ClientConfig): Client;
|
||||
export function createStream(spec: StreamSpec): Stream;
|
||||
export function checkSystemRequirements(): boolean;
|
||||
export function getDevices(callback: (devices: any[]) => void): void;
|
||||
|
||||
/*~ You can declare types that are available via importing the module */
|
||||
export interface ClientConfig {
|
||||
mode: 'live' | 'rtc';
|
||||
codec: 'vp8' | 'h264';
|
||||
proxyServer?: string;
|
||||
turnServer?: {
|
||||
turnServerURL: string;
|
||||
username: string;
|
||||
password: string;
|
||||
udpport: string;
|
||||
tcpport: string;
|
||||
forceturn: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface StreamSpec {
|
||||
streamID: number;
|
||||
audio: boolean;
|
||||
video: boolean;
|
||||
screen: boolean;
|
||||
cameraId?: string;
|
||||
microphoneId?: string;
|
||||
mirror?: boolean;
|
||||
extensionid?: string;
|
||||
mediaSource?: 'screen' | 'application' | 'window';
|
||||
audioProcessing?: {
|
||||
AGC: boolean;
|
||||
};
|
||||
attributes?: {
|
||||
resolution: string;
|
||||
minFrameRate: number;
|
||||
maxFrameRate: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface LocalStreamStats {
|
||||
audioSendBytes: string;
|
||||
audioSendPackets: string;
|
||||
videoSendBytes: string;
|
||||
videoSendPackets: string;
|
||||
videoSendPacketsLost: string;
|
||||
videoSendFrameRate: string;
|
||||
videoSendBandwidth: string;
|
||||
videoSendResolutionWidth?: string;
|
||||
videoSendResolutionHeight?: string;
|
||||
audioCodecName: string;
|
||||
videoCodecName: string;
|
||||
timestamp: string;
|
||||
startTime: string;
|
||||
duration: string;
|
||||
}
|
||||
|
||||
export interface RemoteStreamStats {
|
||||
audioReceiveBytes: string;
|
||||
audioReceivePackets: string;
|
||||
audioReceivePacketsLost: string;
|
||||
videoReceiveBytes: string;
|
||||
videoReceivePackets: string;
|
||||
videoReceivePacketsLost: string;
|
||||
videoReceiveFrameRate?: string;
|
||||
videoReceiveDecodeFrameRate?: string;
|
||||
videoReceiveBandwidth?: string;
|
||||
videoReceivedResolutionWidth?: string;
|
||||
videoReceivedResolutionHeight?: string;
|
||||
timestamp: string;
|
||||
startTime: string;
|
||||
duration: string;
|
||||
}
|
||||
|
||||
export type VideoProfile =
|
||||
| '120p'
|
||||
| '120p_1'
|
||||
| '120p_3'
|
||||
| '180p'
|
||||
| '180p_1'
|
||||
| '180p_3'
|
||||
| '180p_4'
|
||||
| '240p'
|
||||
| '240p_1'
|
||||
| '240p_3'
|
||||
| '240p_4'
|
||||
| '360p'
|
||||
| '360p_1'
|
||||
| '360p_3'
|
||||
| '360p_4'
|
||||
| '360p_6'
|
||||
| '360p_7'
|
||||
| '360p_8'
|
||||
| '360p_9'
|
||||
| '360p_10'
|
||||
| '360p_11'
|
||||
| '480p'
|
||||
| '480p_1'
|
||||
| '480p_2'
|
||||
| '480p_3'
|
||||
| '480p_4'
|
||||
| '480p_6'
|
||||
| '480p_8'
|
||||
| '480p_9'
|
||||
| '480p_10'
|
||||
| '720p'
|
||||
| '720p_1'
|
||||
| '720p_2'
|
||||
| '720p_3'
|
||||
| '720p_5'
|
||||
| '720p_6'
|
||||
| '1080p'
|
||||
| '1080p_1'
|
||||
| '1080p_2'
|
||||
| '1080p_3'
|
||||
| '1080p_5'
|
||||
| '1440p'
|
||||
| '1440p_1'
|
||||
| '1440p_2'
|
||||
| '4K'
|
||||
| '4K_1'
|
||||
| '4K_3';
|
||||
|
||||
export type FirefoxVideoProfile =
|
||||
| '480p'
|
||||
| '480p_1'
|
||||
| '480p_2'
|
||||
| '480p_3'
|
||||
| '480p_4'
|
||||
| '480p_6'
|
||||
| '480p_8'
|
||||
| '480p_9'
|
||||
| '480p_10'
|
||||
| '720p'
|
||||
| '720p_1'
|
||||
| '720p_2'
|
||||
| '720p_3'
|
||||
| '720p_5'
|
||||
| '720p_6';
|
||||
|
||||
export type SafariVideoProfile =
|
||||
| '480p'
|
||||
| '480p_1'
|
||||
| '480p_2'
|
||||
| '480p_3'
|
||||
| '480p_4'
|
||||
| '480p_6'
|
||||
| '480p_8'
|
||||
| '480p_9'
|
||||
| '480p_10'
|
||||
| '720p'
|
||||
| '720p_1'
|
||||
| '720p_2'
|
||||
| '720p_3'
|
||||
| '720p_5'
|
||||
| '720p_6'
|
||||
| '1080p'
|
||||
| '1080p_1'
|
||||
| '1080p_2'
|
||||
| '1080p_3'
|
||||
| '1080p_5'
|
||||
| '1440p'
|
||||
| '1440p_1'
|
||||
| '1440p_2'
|
||||
| '4K'
|
||||
| '4K_1'
|
||||
| '4K_3';
|
||||
|
||||
export type ScreenSharingProfile =
|
||||
| '480p_1'
|
||||
| '480p_2'
|
||||
| '720p_1'
|
||||
| '720p_2'
|
||||
| '1080p_1'
|
||||
| '1080p_2';
|
||||
|
||||
export type ClientEvent =
|
||||
| 'stream-published'
|
||||
| 'stream-added'
|
||||
| 'stream-removed'
|
||||
| 'stream-subscribed'
|
||||
| 'peer-leave'
|
||||
| 'mute-audio'
|
||||
| 'unmute-audio'
|
||||
| 'mute-video'
|
||||
| 'unmute-video'
|
||||
| 'client-banned'
|
||||
| 'active-speaker'
|
||||
| 'error';
|
||||
|
||||
export interface Stream {
|
||||
getStats(
|
||||
callback: (stats: LocalStreamStats | RemoteStreamStats) => void
|
||||
): void;
|
||||
init(onSuccess: () => void, onFailure: (err: any) => void): void;
|
||||
getId(): number;
|
||||
getAttributes(): any;
|
||||
getAudioLevel(): number;
|
||||
hasVideo(): boolean;
|
||||
hasAudio(): boolean;
|
||||
enableVideo(): void;
|
||||
disableVideo(): void;
|
||||
enableAudio(): void;
|
||||
disableAudio(): void;
|
||||
setVideoProfile(
|
||||
profile:
|
||||
| VideoProfile
|
||||
| FirefoxVideoProfile
|
||||
| SafariVideoProfile
|
||||
| ScreenSharingProfile
|
||||
): void;
|
||||
play(HTMLElementID: string): void;
|
||||
stop(): void;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
export interface Client {
|
||||
on(eventName: ClientEvent, callback: (evt: any) => void): void;
|
||||
init(
|
||||
appId: string,
|
||||
onSuccess: () => void,
|
||||
onFailure: (err: any) => void
|
||||
): void;
|
||||
join(
|
||||
tokenOrKey: string,
|
||||
channel: string,
|
||||
uid: number,
|
||||
onSuccess: (uid: number) => void,
|
||||
onFailure: (err: any) => void
|
||||
): void;
|
||||
renewChannelKey(
|
||||
key: string,
|
||||
onSuccess: () => void,
|
||||
onFailure: (err: any) => void
|
||||
): void;
|
||||
enableDualStream(
|
||||
onSuccess: () => void,
|
||||
onFailure: (err: any) => void
|
||||
): void;
|
||||
setRemoteVideoStreamType(stream: Stream, streamType: 0 | 1): void;
|
||||
setLowStreamParameter(param: {
|
||||
width: number;
|
||||
height: number;
|
||||
framerate: number;
|
||||
birate: number;
|
||||
}): void;
|
||||
disableDualStream(
|
||||
onSuccess: () => void,
|
||||
onFailure: (err: any) => void
|
||||
): void;
|
||||
leave(onSuccess: () => void, onFailure: (err: any) => void): void;
|
||||
publish(stream: Stream, onFailure: (err: any) => void): void;
|
||||
unpublish(stream: Stream, onFailure: (err: any) => void): void;
|
||||
subscribe(stream: Stream, onFailure: (err: any) => void): void;
|
||||
unsubscribe(stream: Stream, onFailure: (err: any) => void): void;
|
||||
setProxyServer(proxyServer: ClientConfig['proxyServer']): void;
|
||||
setTurnServer(turnServer: ClientConfig['turnServer']): void;
|
||||
setEncryptionSecret(password: string): void;
|
||||
setEncryptionMode(
|
||||
encryptionMode: 'aes-128-xts' | 'aes-256-xts' | 'aes-128-ecb'
|
||||
): void;
|
||||
}
|
||||
|
||||
/*~ You can declare properties of the module using const, let, or var */
|
||||
export const VERSION: string;
|
||||
|
||||
export const AUDIO_SAMPLE_RATE_32000: 32000;
|
||||
export const AUDIO_SAMPLE_RATE_44100: 44100;
|
||||
export const AUDIO_SAMPLE_RATE_48000: 48000;
|
||||
|
||||
export const VIDEO_CODEC_PROFILE_BASELINE: 66;
|
||||
export const VIDEO_CODEC_PROFILE_MAIN: 77;
|
||||
export const VIDEO_CODEC_PROFILE_HIGH: 100;
|
||||
|
||||
export const REMOTE_VIDEO_STREAM_HIGH: 0;
|
||||
export const REMOTE_VIDEO_STREAM_LOW: 1;
|
||||
export const REMOTE_VIDEO_STREAM_MEDIUM: 2;
|
||||
/*~ If there are types, properties, or methods inside dotted names
|
||||
*~ of the module, declare them inside a 'namespace'.
|
||||
*/
|
||||
export namespace Logger {
|
||||
/*~ For example, given this definition, someone could write:
|
||||
*~ import { subProp } from 'yourModule';
|
||||
*~ subProp.foo();
|
||||
*~ or
|
||||
*~ import * as yourMod from 'yourModule';
|
||||
*~ yourMod.subProp.foo();
|
||||
*/
|
||||
type DEBUG = 0;
|
||||
type INFO = 1;
|
||||
type WARNING = 2;
|
||||
type ERROR = 3;
|
||||
type NONE = 4;
|
||||
function setLogLevel(level: DEBUG|INFO|WARNING|NONE): void;
|
||||
function log(args: any): void;
|
||||
function debug(args: any): void;
|
||||
function info(args: any): void;
|
||||
function warning(args: any): void;
|
||||
function error(args: any): void;
|
||||
}
|
||||
23
types/agora-rtc-sdk/tsconfig.json
Normal file
23
types/agora-rtc-sdk/tsconfig.json
Normal 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",
|
||||
"agora-rtc-sdk-tests.ts"
|
||||
]
|
||||
}
|
||||
1
types/ajv-errors/index.d.ts
vendored
1
types/ajv-errors/index.d.ts
vendored
@@ -2,6 +2,7 @@
|
||||
// Project: https://github.com/epoberezkin/ajv-errors
|
||||
// Definitions by: Afshawn Lotfi <https://github.com/afshawnlotfi>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.2
|
||||
|
||||
import { Ajv } from "ajv";
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"styled-components": "2.x - 3.x"
|
||||
"ajv": "*"
|
||||
}
|
||||
}
|
||||
22
types/ale-url-parser/ale-url-parser-tests.ts
Normal file
22
types/ale-url-parser/ale-url-parser-tests.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { parse, stringify } from 'ale-url-parser';
|
||||
|
||||
let url;
|
||||
let urlObject;
|
||||
|
||||
url = stringify({});
|
||||
console.log(url);
|
||||
|
||||
url = stringify({
|
||||
protocol: 'protocol',
|
||||
host: 'host',
|
||||
path: ['foo', 'bar', 'baz'],
|
||||
hash: 'hash',
|
||||
query: {
|
||||
foo: 1,
|
||||
bar: [2, '3']
|
||||
}
|
||||
});
|
||||
console.log(url);
|
||||
|
||||
urlObject = parse('//any.dom.ain.co.m/foo/bar?test=1&test=2#hash');
|
||||
console.log(urlObject);
|
||||
29
types/ale-url-parser/index.d.ts
vendored
Normal file
29
types/ale-url-parser/index.d.ts
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
// Type definitions for ale-url-parser 0.10
|
||||
// Project: https://github.com/msn0/ale-url-parser#readme
|
||||
// Definitions by: Michał Jezierski <https://github.com/msn0>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.1
|
||||
|
||||
export interface QueryParams {
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface UrlObject {
|
||||
protocol?: string;
|
||||
host?: string;
|
||||
path?: string[];
|
||||
query?: QueryParams;
|
||||
hash?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse url string into url object.
|
||||
* @return UrlObject
|
||||
*/
|
||||
export function parse(url: string): UrlObject;
|
||||
|
||||
/**
|
||||
* Stringify url object into url string.
|
||||
* @return string
|
||||
*/
|
||||
export function stringify(urlObject: UrlObject): string;
|
||||
24
types/ale-url-parser/tsconfig.json
Normal file
24
types/ale-url-parser/tsconfig.json
Normal 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",
|
||||
"ale-url-parser-tests.ts"
|
||||
]
|
||||
}
|
||||
@@ -21,6 +21,7 @@ let _algoliaResponse: Response = {
|
||||
processingTimeMS: 32,
|
||||
query: '',
|
||||
params: '',
|
||||
index: '',
|
||||
};
|
||||
|
||||
let _clientOptions: ClientOptions = {
|
||||
@@ -103,7 +104,8 @@ let _algoliaQueryParameters: QueryParameters = {
|
||||
filters: '',
|
||||
attributesToRetrieve: [''],
|
||||
restrictSearchableAttributes: [''],
|
||||
facets: '',
|
||||
facets: [''],
|
||||
facetingAfterDistinct: true,
|
||||
maxValuesPerFacet: 2,
|
||||
attributesToHighlight: [''],
|
||||
attributesToSnippet: [''],
|
||||
@@ -120,28 +122,29 @@ let _algoliaQueryParameters: QueryParameters = {
|
||||
typoTolerance: false,
|
||||
allowTyposOnNumericTokens: false,
|
||||
ignorePlurals: false,
|
||||
disableTypoToleranceOnAttributes: '',
|
||||
disableTypoToleranceOnAttributes: [''],
|
||||
aroundLatLng: '',
|
||||
aroundLatLngViaIP: '',
|
||||
aroundRadius: 0,
|
||||
aroundPrecision: 0,
|
||||
minimumAroundRadius: 0,
|
||||
insideBoundingBox: [[0]],
|
||||
queryType: '',
|
||||
queryType: 'prefixAll',
|
||||
insidePolygon: [[0]],
|
||||
removeWordsIfNoResults: '',
|
||||
removeWordsIfNoResults: 'firstWords',
|
||||
advancedSyntax: false,
|
||||
optionalWords: [''],
|
||||
removeStopWords: [''],
|
||||
disableExactOnAttributes: [''],
|
||||
exactOnSingleWordQuery: '',
|
||||
alternativesAsExact: true,
|
||||
exactOnSingleWordQuery: 'attribute',
|
||||
alternativesAsExact: ["ignorePlurals"],
|
||||
distinct: 0,
|
||||
getRankingInfo: false,
|
||||
numericAttributesToIndex: [''],
|
||||
numericAttributesForFiltering: [''],
|
||||
numericFilters: [''],
|
||||
tagFilters: '',
|
||||
facetFilters: '',
|
||||
tagFilters: [''],
|
||||
facetFilters: [''],
|
||||
analytics: false,
|
||||
analyticsTags: [''],
|
||||
synonyms: true,
|
||||
@@ -171,8 +174,38 @@ index.partialUpdateObjects([{}], false).then(() => {});
|
||||
let indexName : string = index.indexName;
|
||||
|
||||
// complete copy
|
||||
client.copyIndex('from', 'to').then(()=>{})
|
||||
client.copyIndex('from', 'to', ()=> {})
|
||||
client.copyIndex('from', 'to').then(()=>{});
|
||||
client.copyIndex('from', 'to', ()=> {});
|
||||
// with scope
|
||||
client.copyIndex('from', 'to', ['settings']).then(()=>{})
|
||||
client.copyIndex('from', 'to', ['synonyms', 'rules'], ()=> {})
|
||||
client.copyIndex('from', 'to', ['settings']).then(()=>{});
|
||||
client.copyIndex('from', 'to', ['synonyms', 'rules'], ()=> {});
|
||||
|
||||
// Browsing
|
||||
const browser = index.browseAll();
|
||||
index.browseAll('query');
|
||||
index.browseAll('', {
|
||||
filters: 'dog',
|
||||
});
|
||||
|
||||
let hits: Object[] = [];
|
||||
|
||||
browser.on('result', function onResult(content) {
|
||||
hits = hits.concat(content.hits);
|
||||
});
|
||||
|
||||
browser.on('end', function onEnd() {
|
||||
const _message = `We got ${hits.length} hits`
|
||||
});
|
||||
|
||||
browser.on('error', function onError(err) {
|
||||
throw err;
|
||||
});
|
||||
|
||||
browser.stop();
|
||||
|
||||
index.browse("", {
|
||||
advancedSyntax: false,
|
||||
attributesToRetrieve: ['dogs']
|
||||
});
|
||||
client.copyIndex('from', 'to', ['settings']).then(()=>{});
|
||||
client.copyIndex('from', 'to', ['synonyms', 'rules'], ()=> {});
|
||||
|
||||
265
types/algoliasearch/index.d.ts
vendored
265
types/algoliasearch/index.d.ts
vendored
@@ -1,11 +1,14 @@
|
||||
// Type definitions for algoliasearch-client-js 3.27.0
|
||||
// Type definitions for algoliasearch-client-js 3.30.0
|
||||
// Project: https://github.com/algolia/algoliasearch-client-js
|
||||
// Definitions by: Baptiste Coquelle <https://github.com/cbaptiste>
|
||||
// Haroen Viaene <https://github.com/haroenv>
|
||||
// Aurélien Hervé <https://github.com/aherve>
|
||||
// Samuel Vaillant <https://github.com/samouss>
|
||||
// Kai Eichinger <https://github.com/keichinger>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.2
|
||||
// TypeScript Version: 2.8
|
||||
|
||||
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
|
||||
|
||||
declare namespace algoliasearch {
|
||||
/**
|
||||
@@ -611,6 +614,11 @@ declare namespace algoliasearch {
|
||||
options: SearchForFacetValues.Parameters,
|
||||
cb: (err: Error, res: SearchForFacetValues.Response) => void
|
||||
): void;
|
||||
/**
|
||||
* Browse an index
|
||||
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
|
||||
*/
|
||||
browse(query: string, parameters: BrowseParameters, cb: (err: Error, res: BrowseResponse) => void): void;
|
||||
/**
|
||||
* Browse an index
|
||||
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
|
||||
@@ -620,7 +628,7 @@ declare namespace algoliasearch {
|
||||
* Browse an index
|
||||
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
|
||||
*/
|
||||
browse(query: string): Promise<BrowseResponse>;
|
||||
browse(query: string, parameters?: BrowseParameters): Promise<BrowseResponse>;
|
||||
/**
|
||||
* Browse an index from a cursor
|
||||
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
|
||||
@@ -638,7 +646,7 @@ declare namespace algoliasearch {
|
||||
* Browse an entire index
|
||||
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
|
||||
*/
|
||||
browseAll(): Promise<Response>;
|
||||
browseAll(query?: string, parameters?: BrowseParameters): Browser;
|
||||
/**
|
||||
* Clear an index content
|
||||
* https://github.com/algolia/algoliasearch-client-js#clear-index---clearindex
|
||||
@@ -764,6 +772,11 @@ declare namespace algoliasearch {
|
||||
* https://github.com/algolia/algoliasearch-client-js#client-options
|
||||
*/
|
||||
hosts?: { read?: string[]; write?: string[] };
|
||||
/**
|
||||
* enable the experimental feature: caching requests instead of responses
|
||||
* see https://github.com/algolia/algoliasearch-client-javascript/pull/694
|
||||
*/
|
||||
_useRequestCache?: boolean
|
||||
}
|
||||
/**
|
||||
* Interface describing options available for gettings the logs
|
||||
@@ -961,6 +974,22 @@ declare namespace algoliasearch {
|
||||
query: string;
|
||||
processingTimeMS: number;
|
||||
}
|
||||
type BrowseParameters = Omit<
|
||||
QueryParameters,
|
||||
| "typoTolerance"
|
||||
| "distinct"
|
||||
| "facets"
|
||||
| "getRankingInfo"
|
||||
| "attributesToHighlight"
|
||||
| "attributesToSnippet"
|
||||
>
|
||||
interface Browser {
|
||||
on(type: "error", cb: (err: Error) => void): void
|
||||
on(type: "end", cb: () => void): void
|
||||
on(type: "stop", cb: () => void): void
|
||||
on(type: "result", cb: (content: BrowseResponse) => void): void
|
||||
stop(): void
|
||||
}
|
||||
/**
|
||||
* Describes a synonym object
|
||||
*/
|
||||
@@ -1094,112 +1123,121 @@ declare namespace algoliasearch {
|
||||
userToken?: string;
|
||||
}
|
||||
interface QueryParameters {
|
||||
/**
|
||||
* Query string used to perform the search
|
||||
* default: ''
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/query/
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* Filter the query with numeric, facet or/and tag filters
|
||||
* default: ""
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/filters/
|
||||
*/
|
||||
filters?: string;
|
||||
/**
|
||||
* A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer.
|
||||
* default: *
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/attributesToRetrieve/
|
||||
*/
|
||||
attributesToRetrieve?: string[];
|
||||
/**
|
||||
* List of attributes you want to use for textual search
|
||||
* default: attributeToIndex
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/restrictSearchableAttributes/
|
||||
*/
|
||||
restrictSearchableAttributes?: string[];
|
||||
/**
|
||||
* You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes
|
||||
* default: []
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/facets/
|
||||
*/
|
||||
facets?: string[];
|
||||
/**
|
||||
* Query string used to perform the search
|
||||
* default: ''
|
||||
* https://github.com/algolia/algoliasearch-client-js#query
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* Filter the query with numeric, facet or/and tag filters
|
||||
* default: ""
|
||||
* https://github.com/algolia/algoliasearch-client-js#filters
|
||||
*/
|
||||
filters?: string;
|
||||
/**
|
||||
* A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer.
|
||||
* default: *
|
||||
* https://github.com/algolia/algoliasearch-client-js#attributestoretrieve
|
||||
*/
|
||||
attributesToRetrieve?: string[];
|
||||
/**
|
||||
* List of attributes you want to use for textual search
|
||||
* default: attributeToIndex
|
||||
* https://github.com/algolia/algoliasearch-client-js#restrictsearchableattributes
|
||||
*/
|
||||
restrictSearchableAttributes?: string[];
|
||||
/**
|
||||
* You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes
|
||||
* default: ""
|
||||
* https://github.com/algolia/algoliasearch-client-js#facets
|
||||
*/
|
||||
facets?: string;
|
||||
* Force faceting to be applied after de-duplication (via the Distinct setting).
|
||||
* When using the distinct setting in combination with faceting, facet counts may be higher than expected.
|
||||
* This is because the engine, by default, computes faceting before applying de-duplication (distinct).
|
||||
* When facetingAfterDistinct is set to true, the engine calculates faceting after the de-duplication has been applied.
|
||||
* default ""
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/facetingAfterDistinct/
|
||||
*/
|
||||
facetingAfterDistinct?: boolean;
|
||||
/**
|
||||
* Limit the number of facet values returned for each facet.
|
||||
* default: ""
|
||||
* https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet
|
||||
* default: 100
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/maxValuesPerFacet/
|
||||
*/
|
||||
maxValuesPerFacet?: number;
|
||||
/**
|
||||
* Default list of attributes to highlight. If set to null, all indexed attributes are highlighted.
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#attributestohighlight
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/attributesToHighlight/
|
||||
*/
|
||||
attributesToHighlight?: string[];
|
||||
/**
|
||||
* Default list of attributes to snippet alongside the number of words to return
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#attributestosnippet
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/attributesToSnippet/
|
||||
*/
|
||||
attributesToSnippet?: string[];
|
||||
/**
|
||||
* Specify the string that is inserted before the highlighted parts in the query result
|
||||
* default: <em>
|
||||
* https://github.com/algolia/algoliasearch-client-js#highlightpretag
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/highlightPreTag/
|
||||
*/
|
||||
highlightPreTag?: string;
|
||||
/**
|
||||
* Specify the string that is inserted after the highlighted parts in the query result
|
||||
* default: </em>
|
||||
* https://github.com/algolia/algoliasearch-client-js#highlightposttag
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/highlightPostTag/
|
||||
*/
|
||||
highlightPostTag?: string;
|
||||
/**
|
||||
* String used as an ellipsis indicator when a snippet is truncated.
|
||||
* default: …
|
||||
* https://github.com/algolia/algoliasearch-client-js#snippetellipsistext
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/snippetEllipsisText/
|
||||
*/
|
||||
snippetEllipsisText?: string;
|
||||
/**
|
||||
* If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets
|
||||
* default: false
|
||||
* https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/restrictHighlightAndSnippetArrays/
|
||||
*/
|
||||
restrictHighlightAndSnippetArrays?: boolean;
|
||||
/**
|
||||
* Pagination parameter used to select the number of hits per page
|
||||
* default: 20
|
||||
* https://github.com/algolia/algoliasearch-client-js#hitsperpage
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/hitsPerPage/
|
||||
*/
|
||||
hitsPerPage?: number;
|
||||
/**
|
||||
* Pagination parameter used to select the page to retrieve.
|
||||
* default: 0
|
||||
* https://github.com/algolia/algoliasearch-client-js#page
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/page/
|
||||
*/
|
||||
page?: number;
|
||||
/**
|
||||
* Offset of the first hit to return
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#offset
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/offset/
|
||||
*/
|
||||
offset?: number;
|
||||
/**
|
||||
* Number of hits to return.
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#length
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/length/
|
||||
*/
|
||||
length?: number;
|
||||
/**
|
||||
* The minimum number of characters needed to accept one typo.
|
||||
* default: 4
|
||||
* https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor1Typo/
|
||||
*/
|
||||
minWordSizefor1Typo?: number;
|
||||
/**
|
||||
* The minimum number of characters needed to accept two typo.
|
||||
* fault: 8
|
||||
* https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor2Typos/
|
||||
*/
|
||||
minWordSizefor2Typos?: number;
|
||||
/**
|
||||
@@ -1209,62 +1247,62 @@ declare namespace algoliasearch {
|
||||
* 'false' The typo tolerance is disabled. All results with typos will be hidden.
|
||||
* 'min' Only keep results with the minimum number of typos
|
||||
* 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos.
|
||||
* https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/typoTolerance/
|
||||
*/
|
||||
typoTolerance?: boolean;
|
||||
/**
|
||||
* If set to false, disables typo tolerance on numeric tokens (numbers).
|
||||
* default:
|
||||
* https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/allowTyposOnNumericTokens/
|
||||
*/
|
||||
allowTyposOnNumericTokens?: boolean;
|
||||
/**
|
||||
* If set to true, plural won't be considered as a typo
|
||||
* default: false
|
||||
* https://github.com/algolia/algoliasearch-client-js#ignoreplurals
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/ignorePlurals/
|
||||
*/
|
||||
ignorePlurals?: boolean;
|
||||
/**
|
||||
* List of attributes on which you want to disable typo tolerance
|
||||
* default: ""
|
||||
* https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes
|
||||
* default: []
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/disableTypoToleranceOnAttributes/
|
||||
*/
|
||||
disableTypoToleranceOnAttributes?: string;
|
||||
disableTypoToleranceOnAttributes?: string[];
|
||||
/**
|
||||
* Search for entries around a given location
|
||||
* default: ""
|
||||
* https://github.com/algolia/algoliasearch-client-js#aroundlatlng
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLng/
|
||||
*/
|
||||
aroundLatLng?: string;
|
||||
/**
|
||||
* Search for entries around a given latitude/longitude automatically computed from user IP address.
|
||||
* default: ""
|
||||
* https://github.com/algolia/algoliasearch-client-js#aroundlatlngviaip
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLngViaIP/
|
||||
*/
|
||||
aroundLatLngViaIP?: string;
|
||||
/**
|
||||
* Control the radius associated with a geo search. Defined in meters.
|
||||
* default: null
|
||||
* You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area
|
||||
* https://github.com/algolia/algoliasearch-client-js#aroundradius
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/aroundRadius/
|
||||
*/
|
||||
aroundRadius?: number | 'all';
|
||||
/**
|
||||
* Control the precision of a geo search
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#aroundprecision
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/aroundPrecision/
|
||||
*/
|
||||
aroundPrecision?: number;
|
||||
/**
|
||||
* Define the minimum radius used for a geo search when aroundRadius is not set.
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#minimumaroundradius
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/minimumAroundRadius/
|
||||
*/
|
||||
minimumAroundRadius?: number;
|
||||
/**
|
||||
* Search entries inside a given area defined by the two extreme points of a rectangle
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#insideboundingbox
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/insideBoundingBox/
|
||||
*/
|
||||
insideBoundingBox?: number[][];
|
||||
/**
|
||||
@@ -1273,13 +1311,13 @@ declare namespace algoliasearch {
|
||||
* 'prefixAll' All query words are interpreted as prefixes. This option is not recommended.
|
||||
* 'prefixLast' Only the last word is interpreted as a prefix (default behavior).
|
||||
* 'prefixNone' No query word is interpreted as a prefix. This option is not recommended.
|
||||
* https://github.com/algolia/algoliasearch-client-js#querytype
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/queryType/
|
||||
*/
|
||||
queryType?: any;
|
||||
queryType?: "prefixAll"|"prefixLast"|"prefixNone";
|
||||
/**
|
||||
* Search entries inside a given area defined by a set of points
|
||||
* defauly: ''
|
||||
* https://github.com/algolia/algoliasearch-client-js#insidepolygon
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/insidePolygon/
|
||||
*/
|
||||
insidePolygon?: number[][];
|
||||
/**
|
||||
@@ -1289,19 +1327,19 @@ declare namespace algoliasearch {
|
||||
* 'firstWords' When a query does not return any results, the first word will be added as optional
|
||||
* 'allOptional' When a query does not return any results, a second trial will be made with all words as optional
|
||||
* 'none' No specific processing is done when a query does not return any results
|
||||
* https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/removeWordsIfNoResults/
|
||||
*/
|
||||
removeWordsIfNoResults?: string;
|
||||
removeWordsIfNoResults?: "none"|"lastWords"|"firstWords"|"allOptional";
|
||||
/**
|
||||
* Enables the advanced query syntax
|
||||
* default: false
|
||||
* https://github.com/algolia/algoliasearch-client-js#advancedsyntax
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/advancedSyntax/
|
||||
*/
|
||||
advancedSyntax?: boolean;
|
||||
/**
|
||||
* A string that contains the comma separated list of words that should be considered as optional when found in the query
|
||||
* default: []
|
||||
* https://github.com/algolia/algoliasearch-client-js#optionalwords
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/optionalWords/
|
||||
*/
|
||||
optionalWords?: string[];
|
||||
/**
|
||||
@@ -1309,13 +1347,13 @@ declare namespace algoliasearch {
|
||||
* default: false
|
||||
* true|false: enable or disable stop words for all 41 supported languages; or
|
||||
* a list of language ISO codes (as a comma-separated string) for which stop words should be enable
|
||||
* https://github.com/algolia/algoliasearch-client-js#removestopwords
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/removeStopWords/
|
||||
*/
|
||||
removeStopWords?: string[];
|
||||
removeStopWords?: boolean|string[];
|
||||
/**
|
||||
* List of attributes on which you want to disable the computation of exact criteria
|
||||
* default: []
|
||||
* https://github.com/algolia/algoliasearch-client-js#disableexactonattributes
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/disableExactOnAttributes/
|
||||
*/
|
||||
disableExactOnAttributes?: string[];
|
||||
/**
|
||||
@@ -1324,81 +1362,90 @@ declare namespace algoliasearch {
|
||||
* 'none': no exact on single word query
|
||||
* 'word': exact set to 1 if the query word is found in the record
|
||||
* 'attribute': exact set to 1 if there is an attribute containing a string equals to the query
|
||||
* https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/exactOnSingleWordQuery/
|
||||
*/
|
||||
exactOnSingleWordQuery?: string;
|
||||
exactOnSingleWordQuery?: "attribute"|"none"|"word";
|
||||
/**
|
||||
* Specify the list of approximation that should be considered as an exact match in the ranking formula
|
||||
* default: ['ignorePlurals', 'singleWordSynonym']
|
||||
* 'ignorePlurals': alternative words added by the ignorePlurals feature
|
||||
* 'singleWordSynonym': single-word synonym (For example "NY" = "NYC")
|
||||
* 'multiWordsSynonym': multiple-words synonym
|
||||
* https://github.com/algolia/algoliasearch-client-js#alternativesasexact
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/alternativesAsExact/
|
||||
*/
|
||||
alternativesAsExact?: any;
|
||||
alternativesAsExact?: Array<"ignorePlurals"|"singleWordSynonym"|"multiWordsSynonym">;
|
||||
/**
|
||||
* If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set.
|
||||
* https://github.com/algolia/algoliasearch-client-js#distinct
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/distinct/
|
||||
*/
|
||||
distinct?: any;
|
||||
distinct?: number|boolean;
|
||||
/**
|
||||
* If set to true, the result hits will contain ranking information in the _rankingInfo attribute.
|
||||
* default: false
|
||||
* https://github.com/algolia/algoliasearch-client-js#getrankinginfo
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/getRankingInfo/
|
||||
*/
|
||||
getRankingInfo?: boolean;
|
||||
/**
|
||||
* @deprecated Use `numericAttributesForFiltering` instead
|
||||
* All numerical attributes are automatically indexed as numerical filters
|
||||
* default: ''
|
||||
* https://github.com/algolia/algoliasearch-client-js#numericattributestoindex
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/
|
||||
*/
|
||||
numericAttributesToIndex?: string[];
|
||||
/**
|
||||
* All numerical attributes are automatically indexed as numerical filters
|
||||
* default: ''
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/
|
||||
*/
|
||||
numericAttributesForFiltering?: string[];
|
||||
/**
|
||||
* @deprecated please use filters instead
|
||||
* A string that contains the comma separated list of numeric filters you want to apply.
|
||||
* https://github.com/algolia/algoliasearch-client-js#numericfilters-deprecated
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/numericFilters/
|
||||
*/
|
||||
numericFilters?: string[];
|
||||
/**
|
||||
* @deprecated
|
||||
*
|
||||
* Filter the query by a set of tags.
|
||||
* https://github.com/algolia/algoliasearch-client-js#tagfilters-deprecated
|
||||
* Default: []
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/tagFilters/
|
||||
*/
|
||||
tagFilters?: string;
|
||||
tagFilters?: string[];
|
||||
/**
|
||||
* @deprecated
|
||||
* Filter the query by a set of facets.
|
||||
* https://github.com/algolia/algoliasearch-client-js#facetfilters-deprecated
|
||||
* Default: []
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/facetFilters/
|
||||
*/
|
||||
facetFilters?: string;
|
||||
facetFilters?: string[]|string[][];
|
||||
/**
|
||||
* If set to false, this query will not be taken into account in the analytics feature.
|
||||
* default true
|
||||
* https://github.com/algolia/algoliasearch-client-js#analytics
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/analytics/
|
||||
*/
|
||||
analytics?: boolean;
|
||||
/**
|
||||
* If set, tag your query with the specified identifiers
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#analyticstags
|
||||
* default: []
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/analyticsTags/
|
||||
*/
|
||||
analyticsTags?: string[];
|
||||
/**
|
||||
* If set to false, the search will not use the synonyms defined for the targeted index.
|
||||
* default: true
|
||||
* https://github.com/algolia/algoliasearch-client-js#synonyms
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/synonyms/
|
||||
*/
|
||||
synonyms?: boolean;
|
||||
/**
|
||||
* If set to false, words matched via synonym expansion will not be replaced by the matched synonym in the highlighted result.
|
||||
* default: true
|
||||
* https://github.com/algolia/algoliasearch-client-js#replacesynonymsinhighlight
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/replaceSynonymsInHighlight/
|
||||
*/
|
||||
replaceSynonymsInHighlight?: boolean;
|
||||
/**
|
||||
* Configure the precision of the proximity ranking criterion
|
||||
* default: 1
|
||||
* https://github.com/algolia/algoliasearch-client-js#minproximity
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/minProximity/
|
||||
*/
|
||||
minProximity?: number;
|
||||
|
||||
@@ -1416,6 +1463,10 @@ declare namespace algoliasearch {
|
||||
* The query for the search in this facet
|
||||
*/
|
||||
facetQuery: string;
|
||||
/**
|
||||
* The maximum number of facets to fetch
|
||||
*/
|
||||
maxFacetHits?: number;
|
||||
}
|
||||
|
||||
interface Response {
|
||||
@@ -1447,7 +1498,7 @@ declare namespace algoliasearch {
|
||||
interface Task {
|
||||
taskID: number;
|
||||
createdAt: string;
|
||||
objectID?: string;
|
||||
objectID?: string;
|
||||
}
|
||||
|
||||
interface TaskStatus {
|
||||
@@ -1730,47 +1781,65 @@ declare namespace algoliasearch {
|
||||
interface Response {
|
||||
/**
|
||||
* Contains all the hits matching the query
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
hits: any[];
|
||||
/**
|
||||
* Current page
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
page: number;
|
||||
/**
|
||||
* Number of total hits matching the query
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
nbHits: number;
|
||||
/**
|
||||
* Number of pages
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
nbPages: number;
|
||||
/**
|
||||
* Number of hits per pages
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
hitsPerPage: number;
|
||||
/**
|
||||
* Engine processing time (excluding network transfer)
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
processingTimeMS: number;
|
||||
/**
|
||||
* Query used to perform the search
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
query: string;
|
||||
/**
|
||||
* GET parameters used to perform the search
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
params: string;
|
||||
facets?: {
|
||||
[facetName: string]: { [facetValue: string]: number };
|
||||
};
|
||||
facets_stats?: {
|
||||
[facetName: string]: {
|
||||
avg: number,
|
||||
max: number,
|
||||
min: number,
|
||||
sum: number,
|
||||
};
|
||||
};
|
||||
/**
|
||||
* The index name is only set when searching multiple indices.
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/multiple-queries/?language=javascript#response
|
||||
*/
|
||||
index?: string;
|
||||
/**
|
||||
* The cursor is only set when browsing the index.
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/browse/
|
||||
*/
|
||||
cursor?: string;
|
||||
}
|
||||
|
||||
interface MultiResponse {
|
||||
|
||||
199
types/algoliasearch/lite/index.d.ts
vendored
199
types/algoliasearch/lite/index.d.ts
vendored
@@ -1,11 +1,15 @@
|
||||
// Type definitions for algoliasearch-client-js 3.27.0
|
||||
// Type definitions for algoliasearch-client-js 3.30.0
|
||||
// Project: https://github.com/algolia/algoliasearch-client-js
|
||||
// Definitions by: Baptiste Coquelle <https://github.com/cbaptiste>
|
||||
// Haroen Viaene <https://github.com/haroenv>
|
||||
// Aurélien Hervé <https://github.com/aherve>
|
||||
// Samuel Vaillant <https://github.com/samouss>
|
||||
// Claas Brüggemann <https://github.com/ClaasBrueggemann>
|
||||
// Kai Eichinger <https://github.com/keichinger>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.2
|
||||
// TypeScript Version: 2.8
|
||||
|
||||
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
|
||||
|
||||
declare namespace algoliasearch {
|
||||
/**
|
||||
@@ -129,6 +133,11 @@ declare namespace algoliasearch {
|
||||
options: SearchForFacetValues.Parameters,
|
||||
cb: (err: Error, res: SearchForFacetValues.Response) => void
|
||||
): void;
|
||||
/**
|
||||
* Browse an index
|
||||
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
|
||||
*/
|
||||
browse(query: string, parameters: BrowseParameters, cb: (err: Error, res: BrowseResponse) => void): void;
|
||||
/**
|
||||
* Browse an index
|
||||
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
|
||||
@@ -138,7 +147,7 @@ declare namespace algoliasearch {
|
||||
* Browse an index
|
||||
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
|
||||
*/
|
||||
browse(query: string): Promise<BrowseResponse>;
|
||||
browse(query: string, parameters?: BrowseParameters): Promise<BrowseResponse>;
|
||||
/**
|
||||
* Browse an index from a cursor
|
||||
* https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
|
||||
@@ -180,6 +189,11 @@ declare namespace algoliasearch {
|
||||
* https://github.com/algolia/algoliasearch-client-js#client-options
|
||||
*/
|
||||
hosts?: { read?: string[]; write?: string[] };
|
||||
/**
|
||||
* enable the experimental feature: caching requests instead of responses
|
||||
* see https://github.com/algolia/algoliasearch-client-javascript/pull/694
|
||||
*/
|
||||
_useRequestCache?: boolean
|
||||
}
|
||||
interface BrowseResponse {
|
||||
cursor?: string;
|
||||
@@ -188,114 +202,122 @@ declare namespace algoliasearch {
|
||||
query: string;
|
||||
processingTimeMS: number;
|
||||
}
|
||||
|
||||
type BrowseParameters = Omit<
|
||||
QueryParameters,
|
||||
| "typoTolerance"
|
||||
| "distinct"
|
||||
| "facets"
|
||||
| "getRankingInfo"
|
||||
| "attributesToHighlight"
|
||||
| "attributesToSnippet"
|
||||
>
|
||||
interface QueryParameters {
|
||||
/**
|
||||
* Query string used to perform the search
|
||||
* default: ''
|
||||
* https://github.com/algolia/algoliasearch-client-js#query
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/query/
|
||||
*/
|
||||
query?: string;
|
||||
/**
|
||||
* Filter the query with numeric, facet or/and tag filters
|
||||
* default: ""
|
||||
* https://github.com/algolia/algoliasearch-client-js#filters
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/filters/
|
||||
*/
|
||||
filters?: string;
|
||||
/**
|
||||
* A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer.
|
||||
* default: *
|
||||
* https://github.com/algolia/algoliasearch-client-js#attributestoretrieve
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/attributesToRetrieve/
|
||||
*/
|
||||
attributesToRetrieve?: string[];
|
||||
/**
|
||||
* List of attributes you want to use for textual search
|
||||
* default: attributeToIndex
|
||||
* https://github.com/algolia/algoliasearch-client-js#restrictsearchableattributes
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/restrictSearchableAttributes/
|
||||
*/
|
||||
restrictSearchableAttributes?: string[];
|
||||
/**
|
||||
* You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes
|
||||
* default: ""
|
||||
* https://github.com/algolia/algoliasearch-client-js#facets
|
||||
* default: []
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/facets/
|
||||
*/
|
||||
facets?: string;
|
||||
facets?: string[];
|
||||
/**
|
||||
* Limit the number of facet values returned for each facet.
|
||||
* default: ""
|
||||
* https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet
|
||||
* default: 100
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/maxValuesPerFacet/
|
||||
*/
|
||||
maxValuesPerFacet?: number;
|
||||
/**
|
||||
* Default list of attributes to highlight. If set to null, all indexed attributes are highlighted.
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#attributestohighlight
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/attributesToHighlight/
|
||||
*/
|
||||
attributesToHighlight?: string[];
|
||||
/**
|
||||
* Default list of attributes to snippet alongside the number of words to return
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#attributestosnippet
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/attributesToSnippet/
|
||||
*/
|
||||
attributesToSnippet?: string[];
|
||||
/**
|
||||
* Specify the string that is inserted before the highlighted parts in the query result
|
||||
* default: <em>
|
||||
* https://github.com/algolia/algoliasearch-client-js#highlightpretag
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/highlightPreTag/
|
||||
*/
|
||||
highlightPreTag?: string;
|
||||
/**
|
||||
* Specify the string that is inserted after the highlighted parts in the query result
|
||||
* default: </em>
|
||||
* https://github.com/algolia/algoliasearch-client-js#highlightposttag
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/highlightPostTag/
|
||||
*/
|
||||
highlightPostTag?: string;
|
||||
/**
|
||||
* String used as an ellipsis indicator when a snippet is truncated.
|
||||
* default: …
|
||||
* https://github.com/algolia/algoliasearch-client-js#snippetellipsistext
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/snippetEllipsisText/
|
||||
*/
|
||||
snippetEllipsisText?: string;
|
||||
/**
|
||||
* If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets
|
||||
* default: false
|
||||
* https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/restrictHighlightAndSnippetArrays/
|
||||
*/
|
||||
restrictHighlightAndSnippetArrays?: boolean;
|
||||
/**
|
||||
* Pagination parameter used to select the number of hits per page
|
||||
* default: 20
|
||||
* https://github.com/algolia/algoliasearch-client-js#hitsperpage
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/hitsPerPage/
|
||||
*/
|
||||
hitsPerPage?: number;
|
||||
/**
|
||||
* Pagination parameter used to select the page to retrieve.
|
||||
* default: 0
|
||||
* https://github.com/algolia/algoliasearch-client-js#page
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/page/
|
||||
*/
|
||||
page?: number;
|
||||
/**
|
||||
* Offset of the first hit to return
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#offset
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/offset/
|
||||
*/
|
||||
offset?: number;
|
||||
/**
|
||||
* Number of hits to return.
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#length
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/length/
|
||||
*/
|
||||
length?: number;
|
||||
/**
|
||||
* The minimum number of characters needed to accept one typo.
|
||||
* default: 4
|
||||
* https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor1Typo/
|
||||
*/
|
||||
minWordSizefor1Typo?: number;
|
||||
/**
|
||||
* The minimum number of characters needed to accept two typo.
|
||||
* fault: 8
|
||||
* https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor2Typos/
|
||||
*/
|
||||
minWordSizefor2Typos?: number;
|
||||
/**
|
||||
@@ -305,62 +327,62 @@ declare namespace algoliasearch {
|
||||
* 'false' The typo tolerance is disabled. All results with typos will be hidden.
|
||||
* 'min' Only keep results with the minimum number of typos
|
||||
* 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos.
|
||||
* https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/typoTolerance/
|
||||
*/
|
||||
typoTolerance?: boolean;
|
||||
/**
|
||||
* If set to false, disables typo tolerance on numeric tokens (numbers).
|
||||
* default:
|
||||
* https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/allowTyposOnNumericTokens/
|
||||
*/
|
||||
allowTyposOnNumericTokens?: boolean;
|
||||
/**
|
||||
* If set to true, plural won't be considered as a typo
|
||||
* default: false
|
||||
* https://github.com/algolia/algoliasearch-client-js#ignoreplurals
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/ignorePlurals/
|
||||
*/
|
||||
ignorePlurals?: boolean;
|
||||
/**
|
||||
* List of attributes on which you want to disable typo tolerance
|
||||
* default: ""
|
||||
* https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes
|
||||
* default: []
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/disableTypoToleranceOnAttributes/
|
||||
*/
|
||||
disableTypoToleranceOnAttributes?: string;
|
||||
disableTypoToleranceOnAttributes?: string[];
|
||||
/**
|
||||
* Search for entries around a given location
|
||||
* default: ""
|
||||
* https://github.com/algolia/algoliasearch-client-js#aroundlatlng
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLng/
|
||||
*/
|
||||
aroundLatLng?: string;
|
||||
/**
|
||||
* Search for entries around a given latitude/longitude automatically computed from user IP address.
|
||||
* default: ""
|
||||
* https://github.com/algolia/algoliasearch-client-js#aroundlatlngviaip
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLngViaIP/
|
||||
*/
|
||||
aroundLatLngViaIP?: string;
|
||||
/**
|
||||
* Control the radius associated with a geo search. Defined in meters.
|
||||
* default: null
|
||||
* You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area
|
||||
* https://github.com/algolia/algoliasearch-client-js#aroundradius
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/aroundRadius/
|
||||
*/
|
||||
aroundRadius?: number | 'all';
|
||||
/**
|
||||
* Control the precision of a geo search
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#aroundprecision
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/aroundPrecision/
|
||||
*/
|
||||
aroundPrecision?: number;
|
||||
/**
|
||||
* Define the minimum radius used for a geo search when aroundRadius is not set.
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#minimumaroundradius
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/minimumAroundRadius/
|
||||
*/
|
||||
minimumAroundRadius?: number;
|
||||
/**
|
||||
* Search entries inside a given area defined by the two extreme points of a rectangle
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#insideboundingbox
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/insideBoundingBox/
|
||||
*/
|
||||
insideBoundingBox?: number[][];
|
||||
/**
|
||||
@@ -369,13 +391,13 @@ declare namespace algoliasearch {
|
||||
* 'prefixAll' All query words are interpreted as prefixes. This option is not recommended.
|
||||
* 'prefixLast' Only the last word is interpreted as a prefix (default behavior).
|
||||
* 'prefixNone' No query word is interpreted as a prefix. This option is not recommended.
|
||||
* https://github.com/algolia/algoliasearch-client-js#querytype
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/queryType/
|
||||
*/
|
||||
queryType?: any;
|
||||
queryType?: "prefixAll"|"prefixLast"|"prefixNone";
|
||||
/**
|
||||
* Search entries inside a given area defined by a set of points
|
||||
* defauly: ''
|
||||
* https://github.com/algolia/algoliasearch-client-js#insidepolygon
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/insidePolygon/
|
||||
*/
|
||||
insidePolygon?: number[][];
|
||||
/**
|
||||
@@ -385,19 +407,19 @@ declare namespace algoliasearch {
|
||||
* 'firstWords' When a query does not return any results, the first word will be added as optional
|
||||
* 'allOptional' When a query does not return any results, a second trial will be made with all words as optional
|
||||
* 'none' No specific processing is done when a query does not return any results
|
||||
* https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/removeWordsIfNoResults/
|
||||
*/
|
||||
removeWordsIfNoResults?: string;
|
||||
removeWordsIfNoResults?: "none"|"lastWords"|"firstWords"|"allOptional";
|
||||
/**
|
||||
* Enables the advanced query syntax
|
||||
* default: false
|
||||
* https://github.com/algolia/algoliasearch-client-js#advancedsyntax
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/advancedSyntax/
|
||||
*/
|
||||
advancedSyntax?: boolean;
|
||||
/**
|
||||
* A string that contains the comma separated list of words that should be considered as optional when found in the query
|
||||
* default: []
|
||||
* https://github.com/algolia/algoliasearch-client-js#optionalwords
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/optionalWords/
|
||||
*/
|
||||
optionalWords?: string[];
|
||||
/**
|
||||
@@ -405,13 +427,13 @@ declare namespace algoliasearch {
|
||||
* default: false
|
||||
* true|false: enable or disable stop words for all 41 supported languages; or
|
||||
* a list of language ISO codes (as a comma-separated string) for which stop words should be enable
|
||||
* https://github.com/algolia/algoliasearch-client-js#removestopwords
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/removeStopWords/
|
||||
*/
|
||||
removeStopWords?: string[];
|
||||
removeStopWords?: boolean|string[];
|
||||
/**
|
||||
* List of attributes on which you want to disable the computation of exact criteria
|
||||
* default: []
|
||||
* https://github.com/algolia/algoliasearch-client-js#disableexactonattributes
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/disableExactOnAttributes/
|
||||
*/
|
||||
disableExactOnAttributes?: string[];
|
||||
/**
|
||||
@@ -420,81 +442,90 @@ declare namespace algoliasearch {
|
||||
* 'none': no exact on single word query
|
||||
* 'word': exact set to 1 if the query word is found in the record
|
||||
* 'attribute': exact set to 1 if there is an attribute containing a string equals to the query
|
||||
* https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/exactOnSingleWordQuery/
|
||||
*/
|
||||
exactOnSingleWordQuery?: string;
|
||||
exactOnSingleWordQuery?: "attribute"|"none"|"word";
|
||||
/**
|
||||
* Specify the list of approximation that should be considered as an exact match in the ranking formula
|
||||
* default: ['ignorePlurals', 'singleWordSynonym']
|
||||
* 'ignorePlurals': alternative words added by the ignorePlurals feature
|
||||
* 'singleWordSynonym': single-word synonym (For example "NY" = "NYC")
|
||||
* 'multiWordsSynonym': multiple-words synonym
|
||||
* https://github.com/algolia/algoliasearch-client-js#alternativesasexact
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/alternativesAsExact/
|
||||
*/
|
||||
alternativesAsExact?: any;
|
||||
alternativesAsExact?: Array<"ignorePlurals"|"singleWordSynonym"|"multiWordsSynonym">;
|
||||
/**
|
||||
* If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set.
|
||||
* https://github.com/algolia/algoliasearch-client-js#distinct
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/distinct/
|
||||
*/
|
||||
distinct?: any;
|
||||
distinct?: number|boolean;
|
||||
/**
|
||||
* If set to true, the result hits will contain ranking information in the _rankingInfo attribute.
|
||||
* default: false
|
||||
* https://github.com/algolia/algoliasearch-client-js#getrankinginfo
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/getRankingInfo/
|
||||
*/
|
||||
getRankingInfo?: boolean;
|
||||
/**
|
||||
* @deprecated Use `numericAttributesForFiltering` instead
|
||||
* All numerical attributes are automatically indexed as numerical filters
|
||||
* default: ''
|
||||
* https://github.com/algolia/algoliasearch-client-js#numericattributestoindex
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/
|
||||
*/
|
||||
numericAttributesToIndex?: string[];
|
||||
/**
|
||||
* All numerical attributes are automatically indexed as numerical filters
|
||||
* default: ''
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/
|
||||
*/
|
||||
numericAttributesForFiltering?: string[];
|
||||
/**
|
||||
* @deprecated please use filters instead
|
||||
* A string that contains the comma separated list of numeric filters you want to apply.
|
||||
* https://github.com/algolia/algoliasearch-client-js#numericfilters-deprecated
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/numericFilters/
|
||||
*/
|
||||
numericFilters?: string[];
|
||||
/**
|
||||
* @deprecated
|
||||
*
|
||||
* Filter the query by a set of tags.
|
||||
* https://github.com/algolia/algoliasearch-client-js#tagfilters-deprecated
|
||||
* Default: []
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/tagFilters/
|
||||
*/
|
||||
tagFilters?: string;
|
||||
tagFilters?: string[];
|
||||
/**
|
||||
* @deprecated
|
||||
* Filter the query by a set of facets.
|
||||
* https://github.com/algolia/algoliasearch-client-js#facetfilters-deprecated
|
||||
* Default: []
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/facetFilters/
|
||||
*/
|
||||
facetFilters?: string;
|
||||
facetFilters?: string[]|string[][];
|
||||
/**
|
||||
* If set to false, this query will not be taken into account in the analytics feature.
|
||||
* default true
|
||||
* https://github.com/algolia/algoliasearch-client-js#analytics
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/analytics/
|
||||
*/
|
||||
analytics?: boolean;
|
||||
/**
|
||||
* If set, tag your query with the specified identifiers
|
||||
* default: null
|
||||
* https://github.com/algolia/algoliasearch-client-js#analyticstags
|
||||
* default: []
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/analyticsTags/
|
||||
*/
|
||||
analyticsTags?: string[];
|
||||
/**
|
||||
* If set to false, the search will not use the synonyms defined for the targeted index.
|
||||
* default: true
|
||||
* https://github.com/algolia/algoliasearch-client-js#synonyms
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/synonyms/
|
||||
*/
|
||||
synonyms?: boolean;
|
||||
/**
|
||||
* If set to false, words matched via synonym expansion will not be replaced by the matched synonym in the highlighted result.
|
||||
* default: true
|
||||
* https://github.com/algolia/algoliasearch-client-js#replacesynonymsinhighlight
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/replaceSynonymsInHighlight/
|
||||
*/
|
||||
replaceSynonymsInHighlight?: boolean;
|
||||
/**
|
||||
* Configure the precision of the proximity ranking criterion
|
||||
* default: 1
|
||||
* https://github.com/algolia/algoliasearch-client-js#minproximity
|
||||
* https://www.algolia.com/doc/api-reference/api-parameters/minProximity/
|
||||
*/
|
||||
minProximity?: number;
|
||||
|
||||
@@ -524,47 +555,65 @@ declare namespace algoliasearch {
|
||||
interface Response {
|
||||
/**
|
||||
* Contains all the hits matching the query
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
hits: any[];
|
||||
/**
|
||||
* Current page
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
page: number;
|
||||
/**
|
||||
* Number of total hits matching the query
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
nbHits: number;
|
||||
/**
|
||||
* Number of pages
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
nbPages: number;
|
||||
/**
|
||||
* Number of hits per pages
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
hitsPerPage: number;
|
||||
/**
|
||||
* Engine processing time (excluding network transfer)
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
processingTimeMS: number;
|
||||
/**
|
||||
* Query used to perform the search
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
query: string;
|
||||
/**
|
||||
* GET parameters used to perform the search
|
||||
* https://github.com/algolia/algoliasearch-client-js#response-format
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response
|
||||
*/
|
||||
params: string;
|
||||
facets?: {
|
||||
[facetName: string]: { [facetValue: string]: number };
|
||||
};
|
||||
facets_stats?: {
|
||||
[facetName: string]: {
|
||||
avg: number,
|
||||
max: number,
|
||||
min: number,
|
||||
sum: number,
|
||||
};
|
||||
};
|
||||
/**
|
||||
* The index name is only set when searching multiple indices.
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/multiple-queries/?language=javascript#response
|
||||
*/
|
||||
index?: string;
|
||||
/**
|
||||
* The cursor is only set when browsing the index.
|
||||
* https://www.algolia.com/doc/api-reference/api-methods/browse/
|
||||
*/
|
||||
cursor?: string;
|
||||
}
|
||||
|
||||
interface MultiResponse {
|
||||
|
||||
2153
types/ali-app/ali-app-tests.ts
Normal file
2153
types/ali-app/ali-app-tests.ts
Normal file
File diff suppressed because it is too large
Load Diff
3265
types/ali-app/index.d.ts
vendored
Normal file
3265
types/ali-app/index.d.ts
vendored
Normal file
File diff suppressed because it is too large
Load Diff
28
types/ali-app/tsconfig.json
Normal file
28
types/ali-app/tsconfig.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"esnext",
|
||||
"dom"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"baseUrl": "../",
|
||||
"typeRoots": [
|
||||
"../"
|
||||
],
|
||||
"types": [],
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"esModuleInterop": true
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"ali-app-tests.ts"
|
||||
],
|
||||
"exclude": [
|
||||
".prettierrc"
|
||||
]
|
||||
}
|
||||
7
types/ali-app/tslint.json
Normal file
7
types/ali-app/tslint.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": "dtslint/dt.json",
|
||||
"rules": {
|
||||
"no-mergeable-namespace": false,
|
||||
"no-unnecessary-generics": false
|
||||
}
|
||||
}
|
||||
63
types/ali-oss/Cluster.d.ts
vendored
Normal file
63
types/ali-oss/Cluster.d.ts
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
import {
|
||||
ACLType,
|
||||
CopyAndPutMetaResult,
|
||||
CopyObjectOptions,
|
||||
DeleteMultiOptions,
|
||||
DeleteMultiResult,
|
||||
GetObjectOptions,
|
||||
GetObjectResult,
|
||||
GetStreamOptions,
|
||||
GetStreamResult,
|
||||
HeadObjectOptions,
|
||||
HeadObjectResult,
|
||||
ListObjectResult,
|
||||
ListObjectsQuery,
|
||||
NormalSuccessResponse,
|
||||
PutObjectOptions,
|
||||
PutObjectResult,
|
||||
PutStreamOptions,
|
||||
RequestOptions,
|
||||
SignatureUrlOptions,
|
||||
UserMeta
|
||||
} from "./index";
|
||||
|
||||
export interface ClusterType {
|
||||
host: string;
|
||||
accessKeyId: string;
|
||||
accessKeySecret: string;
|
||||
}
|
||||
|
||||
export interface ClusterOptions {
|
||||
clusters: ClusterType[];
|
||||
schedule?: string;
|
||||
}
|
||||
|
||||
export class Cluster {
|
||||
constructor(options: ClusterOptions)
|
||||
|
||||
list(query: ListObjectsQuery | null, options: RequestOptions): Promise<ListObjectResult>;
|
||||
|
||||
put(name: string, file: any, options?: PutObjectOptions): Promise<PutObjectResult>;
|
||||
|
||||
putStream(name: string, stream: any, options?: PutStreamOptions): Promise<{ name: string, res: NormalSuccessResponse }>;
|
||||
|
||||
head(name: string, options?: HeadObjectOptions): Promise<HeadObjectResult>;
|
||||
|
||||
get(name: string, file?: any, options?: GetObjectOptions): Promise<GetObjectResult>;
|
||||
|
||||
getStream(name?: string, options?: GetStreamOptions): Promise<GetStreamResult>;
|
||||
|
||||
delete(name: string, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
copy(name: string, sourceName: string, options?: CopyObjectOptions): Promise<CopyAndPutMetaResult>;
|
||||
|
||||
putMeta(name: string, meta: UserMeta, options: RequestOptions): Promise<CopyAndPutMetaResult>;
|
||||
|
||||
deleteMulti(names: string[], options?: DeleteMultiOptions): Promise<DeleteMultiResult>;
|
||||
|
||||
signatureUrl(name: string, options?: SignatureUrlOptions): string;
|
||||
|
||||
putACL(name: string, acl: ACLType, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
restore(name: string, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
}
|
||||
71
types/ali-oss/ImageClient.d.ts
vendored
Normal file
71
types/ali-oss/ImageClient.d.ts
vendored
Normal file
@@ -0,0 +1,71 @@
|
||||
import { NormalSuccessResponse, RequestOptions } from "./index";
|
||||
|
||||
export interface ImageClientOptions {
|
||||
imageHost: string; // your image service domain that binding to a OSS bucket
|
||||
accessKeyId: string; // access key you create on aliyun console website
|
||||
accessKeySecret: string; // access secret you create
|
||||
bucket: string; // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first.
|
||||
region?: string; // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou
|
||||
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.
|
||||
timeout?: string | number; // instance level timeout for all operations, default is 60s
|
||||
}
|
||||
|
||||
export interface ImageGetOptions {
|
||||
timeout?: number;
|
||||
headers?: object;
|
||||
}
|
||||
|
||||
export interface StyleData {
|
||||
Name: string; // style name
|
||||
Content: string; // style content
|
||||
CreateTime: string; // style create time
|
||||
LastModifyTime: string; // style last modify time
|
||||
}
|
||||
export class ImageClient {
|
||||
constructor(options: ImageClientOptions)
|
||||
|
||||
/**
|
||||
* Get an image from the image channel.
|
||||
*/
|
||||
get(name: string, file?: any, options?: ImageGetOptions): Promise<{ content: any, res: NormalSuccessResponse }>;
|
||||
|
||||
/**
|
||||
* Get an image read stream.
|
||||
*/
|
||||
getStream(name: string, options?: ImageGetOptions): Promise<{ stream: any, res: NormalSuccessResponse }>;
|
||||
|
||||
/**
|
||||
* Get a image exif info by image object name from the image channel.
|
||||
*/
|
||||
getExif(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>;
|
||||
|
||||
/**
|
||||
* Get a image info and exif info by image object name from the image channel.
|
||||
*/
|
||||
getInfo(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>;
|
||||
|
||||
/**
|
||||
* todo
|
||||
*/
|
||||
putStyle(name: string, style: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>;
|
||||
|
||||
/**
|
||||
* Get a style by name from the image channel.
|
||||
*/
|
||||
getStyle(name: string, options?: RequestOptions): Promise<{ data: StyleData, res: NormalSuccessResponse}>;
|
||||
|
||||
/**
|
||||
* Get all styles from the image channel.
|
||||
*/
|
||||
listStyle(options?: RequestOptions): Promise<StyleData[]>;
|
||||
|
||||
/**
|
||||
* todo
|
||||
*/
|
||||
deleteStyle(styleName: string, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
/**
|
||||
* Create a signature url for directly download.
|
||||
*/
|
||||
signatureUrl(name: string, options?: { expires?: string, timeout?: string }): string;
|
||||
}
|
||||
34
types/ali-oss/ali-oss-tests.ts
Normal file
34
types/ali-oss/ali-oss-tests.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import OSS from "ali-oss";
|
||||
|
||||
const client = new OSS({
|
||||
accessKeyId: 'your access key',
|
||||
accessKeySecret: 'your access secret',
|
||||
bucket: 'your bucket name',
|
||||
region: 'oss-cn-hangzhou'
|
||||
});
|
||||
|
||||
const ImageClient = OSS.ImageClient({
|
||||
imageHost: 'host',
|
||||
accessKeySecret: "secret",
|
||||
accessKeyId: 'id',
|
||||
bucket: "",
|
||||
internal: false,
|
||||
region: "",
|
||||
timeout: 2000
|
||||
});
|
||||
|
||||
const cluster = OSS.Cluster({
|
||||
clusters: [
|
||||
{
|
||||
accessKeyId: 'id',
|
||||
accessKeySecret: 'secret',
|
||||
host: ""
|
||||
},
|
||||
{
|
||||
accessKeyId: 'id',
|
||||
accessKeySecret: 'secret',
|
||||
host: ""
|
||||
},
|
||||
],
|
||||
schedule: 'masterSlave',
|
||||
});
|
||||
760
types/ali-oss/index.d.ts
vendored
Normal file
760
types/ali-oss/index.d.ts
vendored
Normal file
@@ -0,0 +1,760 @@
|
||||
// Type definitions for ali-oss 6.0
|
||||
// Project: https://github.com/ali-sdk/ali-oss
|
||||
// Definitions by: Ptrdu <https://github.com/ptrdu>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
|
||||
import * as ImageClientDefinition from './ImageClient';
|
||||
import * as ClusterDefinition from "./Cluster";
|
||||
|
||||
export * from './ImageClient';
|
||||
export * from './Cluster';
|
||||
|
||||
export interface Options {
|
||||
accessKeyId: string; // access secret you create
|
||||
accessKeySecret: string; // access secret you create
|
||||
stsToken?: string; // used by temporary authorization
|
||||
bucket?: string; // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first.
|
||||
endpoint?: string; // oss region domain. It takes priority over region.
|
||||
region?: string; // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou.
|
||||
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
|
||||
}
|
||||
|
||||
export interface Bucket {
|
||||
name: string;
|
||||
region: string;
|
||||
creationDate: string;
|
||||
StorageClass: StorageType;
|
||||
}
|
||||
|
||||
export type StorageType = "Standard" | "IA" | "Archive";
|
||||
|
||||
export type ACLType = "public-read-write" | "public-read" | "and private";
|
||||
|
||||
export type HTTPMethods = "GET" | "POST" | "DELETE" | "PUT";
|
||||
|
||||
export interface RequestOptions {
|
||||
// the operation timeout
|
||||
timeout?: number;
|
||||
}
|
||||
|
||||
export type RuleStatusType = "Enabled" | "Disabled";
|
||||
|
||||
export interface LifecycleRule {
|
||||
id?: string; // rule id, if not set, OSS will auto create it with random string.
|
||||
prefix: string; // store prefix
|
||||
status: RuleStatusType; // rule status, allow values: Enabled or Disabled
|
||||
days?: number | string; // expire after the days
|
||||
date: string; // expire date, e.g.: 2022-10-11T00:00:00.000Z date and days only set one.
|
||||
}
|
||||
|
||||
export interface CORSRule {
|
||||
allowedOrigin: string | string[]; // configure for Access-Control-Allow-Origin header
|
||||
allowedMethod: string | string[]; // configure for Access-Control-Allow-Methods header
|
||||
allowedHeader?: string | string[]; // configure for Access-Control-Allow-Headers header
|
||||
exposeHeader?: string | string[]; // configure for Access-Control-Expose-Headers header
|
||||
maxAgeSeconds?: string | string[]; // configure for Access-Control-Max-Age header
|
||||
}
|
||||
|
||||
export interface OwnerType {
|
||||
id: string;
|
||||
displayName: string;
|
||||
}
|
||||
|
||||
export interface ObjectMeta {
|
||||
name: string; // object name on oss
|
||||
lastModified: string; // object last modified GMT date, e.g.: 2015-02-19T08:39:44.000Z
|
||||
etag: string; // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE"
|
||||
type: string; // object type, e.g.: Normal
|
||||
size: number; // object size, e.g.: 344606
|
||||
storageClass: StorageType;
|
||||
owner: OwnerType;
|
||||
}
|
||||
|
||||
export interface NormalSuccessResponse {
|
||||
// response status
|
||||
status: number;
|
||||
// response headers
|
||||
headers: object; // todo the object in detail
|
||||
// response size
|
||||
size: number;
|
||||
// request total use time (ms)
|
||||
rt: number;
|
||||
}
|
||||
|
||||
export interface UserMeta {
|
||||
uid: number;
|
||||
pid: number;
|
||||
}
|
||||
|
||||
export interface ObjectCallback {
|
||||
url: string; // After a file is uploaded successfully, the OSS sends a callback request to this URL.
|
||||
host?: string; // The host header value for initiating callback requests.
|
||||
body: string; // The value of the request body when a callback is initiated, for example, key=$(key)&etag=$(etag)&my_var=$(x:my_var).
|
||||
contentType?: string; // The Content-Type of the callback requests initiatiated, It supports application/x-www-form-urlencoded and application/json, and the former is the default value.
|
||||
customValue?: object;
|
||||
headers?: object; // extra headers, detail see RFC 2616
|
||||
}
|
||||
|
||||
export interface ModifyData {
|
||||
lastModified: string; // object last modified GMT string
|
||||
etag: string; // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE"
|
||||
}
|
||||
|
||||
export interface Checkpoint {
|
||||
file: any; // The file object selected by the user, if the browser is restarted, it needs the user to manually trigger the settings
|
||||
name: string; // object key
|
||||
fileSize: number;
|
||||
partSize: number;
|
||||
uploadId: string;
|
||||
doneParts: Array<{ number: number, etag: string }>;
|
||||
}
|
||||
|
||||
export interface ObjectPart {
|
||||
PartNumber: number;
|
||||
LastModified: any; // {Date} Time when a part is uploaded.
|
||||
ETag: string;
|
||||
size: number;
|
||||
}
|
||||
|
||||
export interface Upload {
|
||||
name: string;
|
||||
uploadId: string;
|
||||
initiated: any;
|
||||
}
|
||||
|
||||
export interface Channel {
|
||||
Name: string;
|
||||
Description: string;
|
||||
Status: string;
|
||||
LastModified: string;
|
||||
PublishUrls: string[];
|
||||
PlayUrls: string[];
|
||||
}
|
||||
|
||||
export interface ChannelHistory {
|
||||
StartTime: string; //
|
||||
EndTime: string;
|
||||
RemoteAddr: string; // the remote addr
|
||||
}
|
||||
// parameters type
|
||||
export interface ListBucketsQueryType {
|
||||
prefix?: string; // search buckets using prefix key
|
||||
marker?: string; // search start from marker, including marker key
|
||||
'max-keys'?: string | number; // max buckets, default is 100, limit to 1000
|
||||
}
|
||||
|
||||
export interface PutBucketOptions {
|
||||
timeout: number;
|
||||
storageClass: StorageType;
|
||||
}
|
||||
|
||||
export interface PutBucketWebsiteConfig {
|
||||
index: string; // default page, e.g.: index.html
|
||||
error?: string; // error page, e.g.: 'error.html'
|
||||
}
|
||||
|
||||
export interface ListObjectsQuery {
|
||||
prefix?: string; // search object using prefix key
|
||||
marker?: string; // search start from marker, including marker key
|
||||
delimiter?: string; // delimiter search scope e.g. / only search current dir, not including subdir
|
||||
'max-keys': string | number; // max objects, default is 100, limit to 1000
|
||||
}
|
||||
|
||||
export interface ListObjectResult {
|
||||
objects: ObjectMeta[];
|
||||
prefixes: string[];
|
||||
isTruncated: boolean;
|
||||
nextMarker: string;
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface PutObjectOptions {
|
||||
timeout?: number; // the operation timeout
|
||||
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;
|
||||
}
|
||||
|
||||
export interface PutObjectResult {
|
||||
name: string;
|
||||
data: object;
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface PutStreamOptions {
|
||||
contentLength?: number; // the stream length, chunked encoding will be used if absent
|
||||
timeout: number; // the operation timeout
|
||||
mime: string; // custom mime, will send with Content-Type entity header
|
||||
meta: UserMeta;
|
||||
callback: ObjectCallback;
|
||||
}
|
||||
|
||||
export interface AppendObjectOptions {
|
||||
position?: string; // specify the position which is the content length of the latest object
|
||||
timeout?: number; // the operation timeout
|
||||
mime?: string; // custom mime, will send with Content-Type entity header
|
||||
meta?: UserMeta;
|
||||
headers?: object;
|
||||
}
|
||||
|
||||
export interface AppendObjectResult {
|
||||
name: string;
|
||||
url: string; // the url of oss
|
||||
res: NormalSuccessResponse;
|
||||
nextAppendPosition: string; // the next position
|
||||
}
|
||||
|
||||
export interface HeadObjectOptions {
|
||||
timeout?: number;
|
||||
headers?: object;
|
||||
}
|
||||
|
||||
export interface HeadObjectResult {
|
||||
status: number; // response status, maybe 200 or 304
|
||||
meta: UserMeta;
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface GetObjectOptions {
|
||||
timeout?: number;
|
||||
process?: string; // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'}
|
||||
headers?: object;
|
||||
}
|
||||
|
||||
export interface GetObjectResult {
|
||||
content?: any; // file content buffer if file parameter is null or ignore
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface GetStreamOptions {
|
||||
timeout?: number;
|
||||
process?: string; // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'}
|
||||
headers?: object;
|
||||
}
|
||||
|
||||
export interface GetStreamResult {
|
||||
stream?: any; // readable stream instance if response status is not 200, stream will be null.
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface CopyObjectOptions {
|
||||
timeout?: number;
|
||||
meta?: UserMeta;
|
||||
headers?: object;
|
||||
}
|
||||
|
||||
export interface CopyAndPutMetaResult {
|
||||
data: ModifyData;
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface DeleteMultiOptions {
|
||||
quite?: boolean; // quiet mode or verbose mode, default is false
|
||||
timeout?: number;
|
||||
}
|
||||
|
||||
export interface DeleteMultiResult {
|
||||
deleted?: string[]; // deleted object names list
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface ResponseHeaderType {
|
||||
'content-type'?: string;
|
||||
'content-disposition'?: string;
|
||||
'cache-control'?: string;
|
||||
}
|
||||
|
||||
export interface SignatureUrlOptions {
|
||||
expires?: number; // after expires seconds, the url will become invalid, default is 1800
|
||||
method?: HTTPMethods; // the HTTP method, default is 'GET'
|
||||
'Content-Type'?: string; // set the request content type
|
||||
process?: string;
|
||||
response?: ResponseHeaderType; // set the response headers for download
|
||||
callback?: ObjectCallback;
|
||||
}
|
||||
|
||||
export interface GetACLResult {
|
||||
acl: ACLType;
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface InitMultipartUploadOptions {
|
||||
timeout?: number;
|
||||
mime?: string; // Mime file type
|
||||
meta?: UserMeta;
|
||||
headers?: object;
|
||||
}
|
||||
|
||||
export interface InitMultipartUploadResult {
|
||||
res: { status: number, headers: object, size: number, rt: number };
|
||||
bucket: string; // bucket name
|
||||
name: string; // object name store on OSS
|
||||
uploadId: string; // upload id, use for uploadPart, completeMultipart
|
||||
}
|
||||
|
||||
export interface UploadPartResult {
|
||||
name: string;
|
||||
etag: string;
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface CompleteMultipartUploadOptions {
|
||||
timeout?: number;
|
||||
callback?: ObjectCallback;
|
||||
headers?: object;
|
||||
}
|
||||
|
||||
export interface CompleteMultipartUploadResult {
|
||||
bucket: string;
|
||||
name: string;
|
||||
etag: string;
|
||||
data: object;
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface MultipartUploadOptions {
|
||||
parallel?: number; // the number of parts to be uploaded in parallel
|
||||
partSize?: number; // the suggested size for each part
|
||||
progress?: (...args: any[]) => any; // the progress callback called after each successful upload of one part
|
||||
checkpoint?: Checkpoint; // the checkpoint to resume upload, if this is provided, it will continue the upload from where interrupted, otherwise a new multipart upload will be created.
|
||||
meta?: UserMeta;
|
||||
mime?: string;
|
||||
callback?: ObjectCallback;
|
||||
headers?: object;
|
||||
timeout?: number;
|
||||
copyheaders?: object; // {Object} only uploadPartCopy api used, detail
|
||||
}
|
||||
|
||||
export interface MultipartUploadResult {
|
||||
bucket: string;
|
||||
name: string;
|
||||
etag: string;
|
||||
data: object;
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface MultipartUploadCopyResult {
|
||||
bucket: string;
|
||||
name: string;
|
||||
etag: string;
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface MultipartUploadCopySourceData {
|
||||
sourceKey: string; // the source object name
|
||||
sourceBucketName: string; // sourceData. the source bucket name
|
||||
startOffset: number; // data copy start byte offset, e.g: 0
|
||||
endOffset: number; // data copy end byte offset, e.g: 102400
|
||||
}
|
||||
|
||||
export interface ListPartsQuery {
|
||||
'max-parts': number; // The maximum part number in the response of the OSS. default value: 1000.
|
||||
'part-number-marker': number; // Starting position of a specific list. A part is listed only when the part number is greater than the value of this parameter.
|
||||
'encoding-type': string; // Specify the encoding of the returned content and the encoding type. Optional value: url
|
||||
}
|
||||
|
||||
export interface ListPartsResult {
|
||||
uploadId: string;
|
||||
bucket: string;
|
||||
name: string;
|
||||
PartNumberMarker: number;
|
||||
nextPartNumberMarker: number;
|
||||
maxParts: number;
|
||||
isTruncated: boolean;
|
||||
parts: ObjectPart[];
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface ListUploadsQuery {
|
||||
prefix?: string;
|
||||
'max-uploads'?: number;
|
||||
'key-marker'?: string;
|
||||
'upload-id-marker'?: string;
|
||||
}
|
||||
|
||||
export interface ListUploadsResult {
|
||||
res: NormalSuccessResponse;
|
||||
bucket: string;
|
||||
nextKeyMarker: any;
|
||||
nextUploadIdMarker: any;
|
||||
isTruncated: boolean;
|
||||
uploads: Upload[];
|
||||
}
|
||||
|
||||
export interface PutChannelConf {
|
||||
Description?: string;
|
||||
Status?: string;
|
||||
Target?: {
|
||||
Type: string,
|
||||
FragDuration: number,
|
||||
FragCount: number,
|
||||
PlaylistName: string
|
||||
};
|
||||
}
|
||||
|
||||
export interface PutChannelResult {
|
||||
publishUrls: string[];
|
||||
playUrls: string[];
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface GetChannelResult {
|
||||
Status: string;
|
||||
ConnectedTime?: string;
|
||||
RemoteAddr?: string;
|
||||
Video?: object;
|
||||
Audio?: object;
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface ListChannelsQuery {
|
||||
prefix: string; // the channel id prefix (returns channels with this prefix)
|
||||
marker: string; // the channel id marker (returns channels after this id)
|
||||
'max-keys ': number; // max number of channels to return
|
||||
}
|
||||
|
||||
export interface ListChannelsResult {
|
||||
channels: Channel[];
|
||||
nextMarker: string | null;
|
||||
isTruncated: boolean;
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface ChannelHistoryResult {
|
||||
records: ChannelHistory;
|
||||
res: NormalSuccessResponse;
|
||||
}
|
||||
|
||||
export interface GetRtmpUrlOptions {
|
||||
expires?: number; // the expire time in seconds of the url
|
||||
params?: object; // the additional parameters for url, e.g.: {playlistName: 'play.m3u8'}
|
||||
timeout?: number; // the operation timeout
|
||||
}
|
||||
|
||||
export default class OSS {
|
||||
// the image client
|
||||
static ImageClient: (options: ImageClientDefinition.ImageClientOptions) => ImageClientDefinition.ImageClient;
|
||||
static Cluster: (options: ClusterDefinition.ClusterOptions) => ClusterDefinition.Cluster;
|
||||
|
||||
constructor(options: Options)
|
||||
|
||||
/******************************************* the bucket operations *************************************************/
|
||||
|
||||
// base operators
|
||||
/**
|
||||
* List buckets in this account.
|
||||
*/
|
||||
listBuckets(query: ListBucketsQueryType | null, options?: RequestOptions): Promise<Bucket[]>;
|
||||
|
||||
/**
|
||||
* Create a new bucket.
|
||||
*/
|
||||
putBucket(name: string, options?: PutBucketOptions): Promise<{ bucket: string, res: NormalSuccessResponse }>;
|
||||
|
||||
/**
|
||||
* Use the bucket.
|
||||
*/
|
||||
useBucket(name: string): void;
|
||||
|
||||
/**
|
||||
* Delete an empty bucket.
|
||||
*/
|
||||
deleteBucket(name: string, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
/**
|
||||
* Get bucket information,include CreationDate、ExtranetEndpoint、IntranetEndpoint、Location、Name、StorageClass、 Owner、AccessControlList
|
||||
*/
|
||||
getBucketInfo(name: string): Promise<any>;
|
||||
|
||||
/**
|
||||
* Get bucket location
|
||||
*/
|
||||
getBucketLocation(name: string): Promise<any>;
|
||||
|
||||
// ACL operations
|
||||
/**
|
||||
* Update the bucket ACL.
|
||||
*/
|
||||
putBucketACL(name: string, acl: ACLType, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
/**
|
||||
* Get the bucket ACL.
|
||||
* acl - acl settings string
|
||||
*/
|
||||
getBucketACL(name: string, options?: RequestOptions): Promise<{ acl: string, res: NormalSuccessResponse }>;
|
||||
|
||||
// logging operations
|
||||
/**
|
||||
* Update the bucket logging settings. Log file will create every one hour and name format: <prefix><bucket>-YYYY-mm-DD-HH-MM-SS-UniqueString.
|
||||
*/
|
||||
putBucketLogging(name: string, prefix?: string, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
/**
|
||||
* Get the bucket logging settings.
|
||||
*/
|
||||
getBucketLogging(name: string, options?: RequestOptions): Promise<{ enable: boolean, prefix: string | null, res: NormalSuccessResponse }>;
|
||||
|
||||
/**
|
||||
* Delete the bucket logging settings.
|
||||
*/
|
||||
deleteBucketLogging(name: string, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
// Website operations
|
||||
/**
|
||||
* Set the bucket as a static website.
|
||||
*/
|
||||
putBucketWebsite(name: string, config: PutBucketWebsiteConfig): Promise<NormalSuccessResponse>;
|
||||
|
||||
/**
|
||||
* Get the bucket website config.
|
||||
*/
|
||||
getBucketWebsite(name: string, options?: RequestOptions): Promise<{ index: string, error: string, res: NormalSuccessResponse }>;
|
||||
|
||||
/**
|
||||
* Delete the bucket website config.
|
||||
*/
|
||||
deleteBucketWebsite(name: string, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
// referer operations
|
||||
/**
|
||||
* Set the bucket request Referer white list.
|
||||
*/
|
||||
putBucketReferer(name: string, allowEmpty: boolean, referers: string[], options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
/**
|
||||
* Get the bucket request Referer white list.
|
||||
*/
|
||||
getBucketReferer(name: string, options?: RequestOptions): Promise<{ allowEmpty: boolean, referers: string[], res: NormalSuccessResponse }>;
|
||||
|
||||
/**
|
||||
* Delete the bucket request Referer white list.
|
||||
*/
|
||||
deleteBucketReferer(name: string, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
// lifecycle operations
|
||||
/**
|
||||
* Set the bucket object lifecycle.
|
||||
*/
|
||||
putBucketLifecycle(name: string, rules: LifecycleRule[], options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
/**
|
||||
* Get the bucket object lifecycle.
|
||||
*/
|
||||
getBucketLifecycle(name: string, options?: RequestOptions): Promise<{ rules: LifecycleRule[], res: NormalSuccessResponse }>;
|
||||
|
||||
/**
|
||||
* Delete the bucket object lifecycle.
|
||||
*/
|
||||
deleteBucketLifecycle(name: string, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
// CORS operations
|
||||
/**
|
||||
* Set CORS rules of the bucket object
|
||||
*/
|
||||
putBucketCORS(name: string, rules: CORSRule[], options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
/**
|
||||
* Get CORS rules of the bucket object.
|
||||
*/
|
||||
getBucketCORS(name: string): Promise<{ rules: CORSRule[], res: NormalSuccessResponse }>;
|
||||
|
||||
/**
|
||||
* Delete CORS rules of the bucket object.
|
||||
*/
|
||||
deleteBucketCORS(name: string): Promise<NormalSuccessResponse>;
|
||||
|
||||
/********************************************************** Object operations ********************************************/
|
||||
/**
|
||||
* List objects in the bucket.
|
||||
*/
|
||||
list(query: ListObjectsQuery | null, options: RequestOptions): Promise<ListObjectResult>;
|
||||
|
||||
/**
|
||||
* Add an object to the bucket.
|
||||
*/
|
||||
put(name: string, file: any, options?: PutObjectOptions): Promise<PutObjectResult>;
|
||||
|
||||
/**
|
||||
* Add a stream object to the bucket.
|
||||
*/
|
||||
putStream(name: string, stream: any, options?: PutStreamOptions): Promise<{ name: string, res: NormalSuccessResponse }>;
|
||||
|
||||
/**
|
||||
* Append an object to the bucket, it's almost same as put, but it can add content to existing object rather than override it.
|
||||
*/
|
||||
append(name: string, file: any, options?: AppendObjectOptions): Promise<AppendObjectResult>;
|
||||
|
||||
/**
|
||||
* Get the Object url. If provide baseUrl, will use baseUrl instead the default endpoint.
|
||||
*/
|
||||
getObjectUrl(name: string, baseUrl?: string): string;
|
||||
|
||||
/**
|
||||
* Get the Object url. If provide baseUrl, will use baseUrl instead the default bucket and endpoint. Suggest use generateObjectUrl instead of getObjectUrl.
|
||||
*/
|
||||
generateObjectUrl(name: string, baseUrl?: string): string;
|
||||
|
||||
/**
|
||||
* Head an object and get the meta info.
|
||||
*/
|
||||
head(name: string, options?: HeadObjectOptions): Promise<HeadObjectResult>;
|
||||
|
||||
/**
|
||||
* Get an object from the bucket.
|
||||
*/
|
||||
get(name: string, file?: any, options?: GetObjectOptions): Promise<GetObjectResult>;
|
||||
|
||||
/**
|
||||
* Get an object read stream.
|
||||
*/
|
||||
getStream(name?: string, options?: GetStreamOptions): Promise<GetStreamResult>;
|
||||
|
||||
/**
|
||||
* Delete an object from the bucket.
|
||||
*/
|
||||
delete(name: string, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
/**
|
||||
* Copy an object from sourceName to name.
|
||||
*/
|
||||
copy(name: string, sourceName: string, options?: CopyObjectOptions): Promise<CopyAndPutMetaResult>;
|
||||
|
||||
/**
|
||||
* Set an exists object meta.
|
||||
*/
|
||||
putMeta(name: string, meta: UserMeta, options: RequestOptions): Promise<CopyAndPutMetaResult>;
|
||||
|
||||
/**
|
||||
* Delete multi objects in one request.
|
||||
*/
|
||||
deleteMulti(names: string[], options?: DeleteMultiOptions): Promise<DeleteMultiResult>;
|
||||
|
||||
/**
|
||||
* Create a signature url for download or upload object. When you put object with signatureUrl ,you need to pass Content-Type.Please look at the example.
|
||||
*/
|
||||
signatureUrl(name: string, options?: SignatureUrlOptions): string;
|
||||
|
||||
/**
|
||||
* Set object's ACL.
|
||||
*/
|
||||
putACL(name: string, acl: ACLType, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
/**
|
||||
* Get object's ACL.
|
||||
*/
|
||||
getACL(name: string, options?: RequestOptions): Promise<GetACLResult>;
|
||||
|
||||
/**
|
||||
* Restore Object.
|
||||
*/
|
||||
restore(name: string, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
/**
|
||||
* multi upload
|
||||
*/
|
||||
initMultipartUpload(name: string, options?: InitMultipartUploadOptions): Promise<InitMultipartUploadResult>;
|
||||
|
||||
/**
|
||||
* After initiating a Multipart Upload event, you can upload data in parts based on the specified object name and Upload ID.
|
||||
*/
|
||||
uploadPart(name: string, uploadId: string, partNo: number, file: any, start: number, end: number, options?: RequestOptions): Promise<UploadPartResult>;
|
||||
|
||||
/**
|
||||
* Using Upload Part Copy, you can copy data from an existing object and upload a part of the data.
|
||||
* When copying a file larger than 1 GB, you must use the Upload Part Copy method. If you want to copy a file smaller than 1 GB, see Copy Object.
|
||||
*/
|
||||
uploadPartCopy(
|
||||
name: string,
|
||||
uploadId: string,
|
||||
partNo: number,
|
||||
range: string,
|
||||
sourceData: { sourceKey: string, sourceBucketName: string },
|
||||
options: { timeout?: number, headers?: object }
|
||||
): Promise<UploadPartResult>;
|
||||
|
||||
/**
|
||||
* After uploading all data parts, you must call the Complete Multipart Upload API to complete Multipart Upload for the entire file.
|
||||
*/
|
||||
completeMultipartUpload(
|
||||
name: string,
|
||||
uploadId: string,
|
||||
parts: Array<{ number: number, etag: string }>,
|
||||
options?: CompleteMultipartUploadOptions
|
||||
): Promise<CompleteMultipartUploadResult>;
|
||||
|
||||
/**
|
||||
* Upload file with OSS multipart.
|
||||
*/
|
||||
multipartUpload(name: string, file: any, options: MultipartUploadOptions): Promise<MultipartUploadResult>;
|
||||
|
||||
/**
|
||||
* Copy file with OSS multipart.
|
||||
* this function contains head, initMultipartUpload, uploadPartCopy, completeMultipartUpload.
|
||||
* When copying a file larger than 1 GB, you should use the Upload Part Copy method. If you want to copy a file smaller than 1 GB, see Copy Object.
|
||||
*/
|
||||
multipartUploadCopy(name: string, sourceData: MultipartUploadCopySourceData, options?: MultipartUploadOptions): Promise<MultipartUploadCopyResult>;
|
||||
|
||||
/**
|
||||
* The ListParts command can be used to list all successfully uploaded parts mapped to a specific upload ID, i.e.: those not completed and not aborted.
|
||||
*/
|
||||
listParts(name: string, uploadId: string, query?: ListPartsQuery, options?: RequestOptions): Promise<ListPartsResult>;
|
||||
|
||||
/**
|
||||
* List on-going multipart uploads, i.e.: those not completed and not aborted.
|
||||
*/
|
||||
listUploads(query: ListUploadsQuery, options?: RequestOptions): Promise<ListUploadsResult>;
|
||||
|
||||
/**
|
||||
* Abort a multipart upload for object.
|
||||
*/
|
||||
abortMultipartUpload(name: string, uploadId: string, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
/************************************************ RTMP Operations *************************************************************/
|
||||
/**
|
||||
* Create a live channel.
|
||||
*/
|
||||
putChannel(id: string, conf: PutChannelConf, options?: RequestOptions): Promise<PutChannelResult>;
|
||||
|
||||
/**
|
||||
* Get live channel info.
|
||||
*/
|
||||
getChannel(id: string, options?: RequestOptions): Promise<{ data: PutChannelConf, res: NormalSuccessResponse }>;
|
||||
|
||||
/**
|
||||
* Delete a live channel.
|
||||
*/
|
||||
deleteChannel(id: string, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
/**
|
||||
* Change the live channel status.
|
||||
*/
|
||||
putChannelStatus(id: string, status?: string, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
/**
|
||||
* Get the live channel status.
|
||||
*/
|
||||
getChannelStatus(id: string, options?: RequestOptions): Promise<GetChannelResult>;
|
||||
|
||||
/**
|
||||
* List channels.
|
||||
*/
|
||||
listChannels(query: ListChannelsQuery, options?: RequestOptions): Promise<ListChannelsResult>;
|
||||
|
||||
/**
|
||||
* Get the live channel history.
|
||||
*/
|
||||
getChannelHistory(id: string, options?: RequestOptions): Promise<ChannelHistoryResult>;
|
||||
|
||||
/**
|
||||
* Create a VOD playlist for the channel.
|
||||
*/
|
||||
createVod(id: string, name: string, time: { startTime: number, endTime: number }, options?: RequestOptions): Promise<NormalSuccessResponse>;
|
||||
|
||||
/**
|
||||
* Get signatured rtmp url for publishing.
|
||||
*/
|
||||
getRtmpUrl(channelId?: string, options?: GetRtmpUrlOptions): string;
|
||||
}
|
||||
25
types/ali-oss/tsconfig.json
Normal file
25
types/ali-oss/tsconfig.json
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es6"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"baseUrl": "../",
|
||||
"typeRoots": [
|
||||
"../"
|
||||
],
|
||||
"types": [],
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"ImageClient.d.ts",
|
||||
"Cluster.d.ts",
|
||||
"ali-oss-tests.ts"
|
||||
]
|
||||
}
|
||||
7
types/almost-equal/almost-equal-tests.ts
Normal file
7
types/almost-equal/almost-equal-tests.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import * as almostEqual from 'almost-equal';
|
||||
|
||||
const res1 = almostEqual(1.999999, 2.0);
|
||||
|
||||
const res2 = almostEqual(1.999999, 2.0, almostEqual.DBL_EPSILON);
|
||||
|
||||
const res3 = almostEqual(1.999999, 2.0, almostEqual.FLT_EPSILON, almostEqual.FLT_EPSILON);
|
||||
11
types/almost-equal/index.d.ts
vendored
Normal file
11
types/almost-equal/index.d.ts
vendored
Normal file
@@ -0,0 +1,11 @@
|
||||
// Type definitions for almost-equal 1.1
|
||||
// Project: https://github.com/mikolalysenko/almost-equal#readme
|
||||
// Definitions by: Curtis Maddalozzo <https://github.com/cmaddalozzo>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
|
||||
declare function almostEqual(value: number, other: number, absoluteTolerance?: number, relativeTolerance?: number): boolean;
|
||||
declare namespace almostEqual {
|
||||
const FLT_EPSILON: number;
|
||||
const DBL_EPSILON: number;
|
||||
}
|
||||
export = almostEqual;
|
||||
23
types/almost-equal/tsconfig.json
Normal file
23
types/almost-equal/tsconfig.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es6"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
"strictNullChecks": true,
|
||||
"baseUrl": "../",
|
||||
"typeRoots": [
|
||||
"../"
|
||||
],
|
||||
"strictFunctionTypes": true,
|
||||
"types": [],
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"almost-equal-tests.ts"
|
||||
]
|
||||
}
|
||||
2
types/alt/index.d.ts
vendored
2
types/alt/index.d.ts
vendored
@@ -2,7 +2,7 @@
|
||||
// Project: https://github.com/goatslacker/alt
|
||||
// Definitions by: Michael Shearer <https://github.com/Shearerbeard>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.6
|
||||
// TypeScript Version: 2.8
|
||||
|
||||
///<reference types="react"/>
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
"max-line-length": false,
|
||||
"member-access": false,
|
||||
"new-parens": false,
|
||||
"no-angle-bracket-type-assertion": false,
|
||||
"no-any-union": false,
|
||||
"no-boolean-literal-compare": false,
|
||||
"no-conditional-assignment": false,
|
||||
|
||||
@@ -32,7 +32,7 @@ new Stream({
|
||||
highWaterMark: 1,
|
||||
decodeStrings: true,
|
||||
objectMode: true,
|
||||
destroy: (error?: Error) => {
|
||||
destroy: (error: Error | null) => {
|
||||
return 'handle error';
|
||||
},
|
||||
final: (callback: (error?: Error) => void) => {
|
||||
|
||||
@@ -1,85 +1,110 @@
|
||||
// Tests for Amplitude SDK TypeScript definitions
|
||||
|
||||
module Amplitude.Tests {
|
||||
|
||||
function all() {
|
||||
amplitude.init('YOUR_API_KEY_HERE', null, {
|
||||
// optional configuration options
|
||||
var client: amplitude.AmplitudeClient = new amplitude.AmplitudeClient();
|
||||
var identify: amplitude.Identify = new amplitude.Identify();
|
||||
var revenue: amplitude.Revenue = new amplitude.Revenue();
|
||||
|
||||
client = amplitude.getInstance();
|
||||
client = amplitude.getInstance('some name');
|
||||
|
||||
amplitude.__VERSION__ === '1.2.3';
|
||||
amplitude.options.logLevel = 'WARN';
|
||||
|
||||
amplitude.init('API_KEY', 'USER_ID', {
|
||||
saveEvents: true,
|
||||
includeUtm: true,
|
||||
includeReferrer: true,
|
||||
batchEvents: true,
|
||||
eventUploadThreshold: 50
|
||||
});
|
||||
amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE', null, () => {});
|
||||
}, function () { });
|
||||
amplitude.init('API_KEY', 'USER_ID', { includeReferrer: true, includeUtm: true });
|
||||
amplitude.init('API_KEY', 'USER_ID');
|
||||
amplitude.init('API_KEY');
|
||||
|
||||
amplitude.logEvent('EVENT_IDENTIFIER_HERE');
|
||||
amplitude.setUserId('USER_ID_HERE');
|
||||
amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE');
|
||||
amplitude.setUserId(null); // not string 'null'
|
||||
amplitude.setVersionName('VERSION_NAME_HERE');
|
||||
|
||||
amplitude.regenerateDeviceId();
|
||||
amplitude.setDeviceId('CUSTOM_DEVICE_ID');
|
||||
|
||||
amplitude.logEvent('EVENT_IDENTIFIER_HERE', {
|
||||
'color': 'blue',
|
||||
'age': 20,
|
||||
'key': 'value'
|
||||
});
|
||||
amplitude.logEvent('Clicked Homepage Button', { 'finished_flow': false, 'clicks': 15 });
|
||||
amplitude.logEvent('EVENT_IDENTIFIER_HERE', { 'color': 'blue', 'age': 20, 'key': 'value' });
|
||||
amplitude.logEvent("EVENT_IDENTIFIER_HERE", null, (httpCode, response) => { });
|
||||
amplitude.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' });
|
||||
|
||||
amplitude.setDeviceId('45f0954f-eb79-4463-ac8a-233a6f45a8f0');
|
||||
amplitude.setDomain('.amplitude.com');
|
||||
amplitude.setGroup('orgId', '15');
|
||||
amplitude.setGroup('orgId', ['15', '16']);
|
||||
amplitude.setUserId('joe@gmail.com');
|
||||
amplitude.setUserProperties({ 'gender': 'female', 'sign_up_complete': true })
|
||||
amplitude.setVersionName('1.12.3');
|
||||
amplitude.isNewSession();
|
||||
amplitude.getSessionId() === 123;
|
||||
|
||||
let identify = new amplitude.Identify().set('gender', 'female').set('age', 20);
|
||||
amplitude.identify(identify);
|
||||
amplitude.logRevenue(3.99, 1, 'product_1234');
|
||||
amplitude.logRevenueV2(revenue);
|
||||
|
||||
identify = new amplitude.Identify().setOnce('sign_up_date', '08/24/2015');
|
||||
amplitude.identify(identify);
|
||||
|
||||
identify = new amplitude.Identify().setOnce('sign_up_date', '09/14/2015');
|
||||
amplitude.identify(identify);
|
||||
client.init('API_KEY', 'USER_ID', {
|
||||
saveEvents: true,
|
||||
includeUtm: true,
|
||||
includeReferrer: true,
|
||||
batchEvents: true,
|
||||
eventUploadThreshold: 50
|
||||
}, function () { });
|
||||
client.init('API_KEY', 'USER_ID', { includeReferrer: true, includeUtm: true });
|
||||
client.init('API_KEY', 'USER_ID');
|
||||
client.init('API_KEY');
|
||||
|
||||
identify = new amplitude.Identify().unset('gender').unset('age');
|
||||
amplitude.identify(identify);
|
||||
client.logEvent('Clicked Homepage Button', { 'finished_flow': false, 'clicks': 15 });
|
||||
client.logEvent('EVENT_IDENTIFIER_HERE', { 'color': 'blue', 'age': 20, 'key': 'value' });
|
||||
client.logEvent("EVENT_IDENTIFIER_HERE", null, (httpCode, response) => { });
|
||||
client.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' });
|
||||
client.logEventWithTimestamp('EVENT_IDENTIFIER_HERE', { 'key': 'value' }, 1505430378000, (httpCode, response) => { });
|
||||
|
||||
|
||||
client.setDeviceId('45f0954f-eb79-4463-ac8a-233a6f45a8f0');
|
||||
client.setDomain('.amplitude.com');
|
||||
client.setUserId('joe@gmail.com');
|
||||
client.setOptOut(true);
|
||||
client.setGroup('type', 'name');
|
||||
client.setGroup('type', ['name', 'name2']);
|
||||
client.setUserProperties({ 'gender': 'female', 'sign_up_complete': true });
|
||||
client.setGlobalUserProperties({ 'gender': 'female', 'sign_up_complete': true });
|
||||
client.setVersionName('1.12.3');
|
||||
client.setSessionId(1505430378000);
|
||||
|
||||
client.options.logLevel = 'WARN';
|
||||
client.getSessionId() === 123;
|
||||
client.isNewSession() === true;
|
||||
client.regenerateDeviceId();
|
||||
client.clearUserProperties();
|
||||
|
||||
client.identify(identify);
|
||||
client.logRevenue(3.99, 1, 'product_1234');
|
||||
client.logRevenueV2(revenue);
|
||||
|
||||
|
||||
identify = new amplitude.Identify().set('colors', ['rose', 'gold']).add('karma', 1).setOnce('sign_up_date', '2016-03-31');
|
||||
identify = new amplitude.Identify().add('karma', 1).add('friends', 1);
|
||||
amplitude.identify(identify);
|
||||
|
||||
identify = new amplitude.Identify().append('ab-tests', 'new-user-test').append('some_list', [1, 2, 3, 4, 'values']);
|
||||
amplitude.identify(identify);
|
||||
|
||||
identify = new amplitude.Identify().prepend('ab-tests', 'new-user-test').prepend('some_list', [1, 2, 3, 4, 'values']);
|
||||
amplitude.identify(identify);
|
||||
|
||||
identify = new amplitude.Identify()
|
||||
.set('karma', 10)
|
||||
.add('karma', 1)
|
||||
.unset('karma');
|
||||
amplitude.identify(identify);
|
||||
|
||||
identify = new amplitude.Identify().set('karma', 10).add('karma', 1).unset('karma');
|
||||
identify = new amplitude.Identify().append('ab-tests', 'new-user-tests');
|
||||
identify.append('some_list', [1, 2, 3, 4, 'values']);
|
||||
identify = new amplitude.Identify().prepend('ab-tests', 'new-user-tests');
|
||||
identify.prepend('some_list', [1, 2, 3, 4, 'values']);
|
||||
identify = new amplitude.Identify().set('user_type', 'beta');
|
||||
identify.set('name', { 'first': 'John', 'last': 'Doe' });
|
||||
identify = new amplitude.Identify().setOnce('sign_up_date', '2016-04-01');
|
||||
identify = new amplitude.Identify().unset('user_type').unset('age');
|
||||
identify = new amplitude.Identify()
|
||||
.set('colors', ['rose', 'gold'])
|
||||
.append('ab-tests', 'campaign_a')
|
||||
.append('existing_list', [4, 5]);
|
||||
amplitude.identify(identify);
|
||||
|
||||
amplitude.setUserProperties({
|
||||
gender: 'female',
|
||||
age: 20
|
||||
});
|
||||
|
||||
amplitude.clearUserProperties();
|
||||
|
||||
amplitude.setOptOut(true);
|
||||
amplitude.setOptOut(false);
|
||||
|
||||
amplitude.setGroup('orgId', '15');
|
||||
amplitude.setGroup('sport', ['soccer', 'tennis']);
|
||||
|
||||
// TODO: Implement those.
|
||||
/*
|
||||
var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3);
|
||||
amplitude.logRevenueV2(revenue);
|
||||
|
||||
amplitude.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' });
|
||||
*/
|
||||
revenue = new amplitude.Revenue().setProductId('productIdentifier').setPrice(10.99);
|
||||
revenue = new amplitude.Revenue().setProductId('productIdentifier').setPrice(10.99).setEventProperties({ 'city': 'San Francisco' });
|
||||
revenue = new amplitude.Revenue().setProductId('productIdentifier').setPrice(10.99).setQuantity(5);
|
||||
revenue = new amplitude.Revenue().setProductId('productIdentifier').setPrice(10.99).setRevenueType('purchase');
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
109
types/amplitude-js/index.d.ts
vendored
109
types/amplitude-js/index.d.ts
vendored
@@ -1,61 +1,146 @@
|
||||
// Type definitions for Amplitude SDK 2.12.1
|
||||
// Type definitions for Amplitude SDK 4.4.0
|
||||
// Project: https://github.com/amplitude/Amplitude-Javascript
|
||||
// Definitions by: Arvydas Sidorenko <https://github.com/Asido>
|
||||
// Definitions: https://github.com/Asido/DefinitelyTyped
|
||||
// Dan Manastireanu <https://github.com/danmana>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
|
||||
declare module amplitude {
|
||||
|
||||
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): 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 function init(apiKey: string): void;
|
||||
export function init(apiKey: string, userId: string): void;
|
||||
export function init(apiKey: string, userId: string, options: Config): void;
|
||||
export function init(apiKey: string, userId: string, options: Config, callback: () => void): void;
|
||||
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): void;
|
||||
export function identify(identify: Identify, callback?: Callback): void;
|
||||
|
||||
export function setUserProperties(properties: Object): 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): void;
|
||||
export function logEvent(event: string, data: Object): void;
|
||||
export function logEvent(event: string, data: Object, callback: (httpCode: number, response: any) => void): 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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import * as amqp from "amqplib";
|
||||
import * as amqpConMgr from 'amqp-connection-manager';
|
||||
|
||||
// from README.md
|
||||
const connection = amqpConMgr.connect(['amqp://localhost']);
|
||||
const channelWrapper: amqpConMgr.ChannelWrapper = connection.createChannel({
|
||||
json: true,
|
||||
setup: async (channel: amqp.ConfirmChannel): Promise<void> => {
|
||||
// `channel` here is a regular amqplib `ConfirmChannel`. Unfortunately its typings make it return a bluebird-specific promise
|
||||
// tslint:disable-next-line:await-promise
|
||||
await channel.assertQueue('rxQueueName', {durable: true});
|
||||
}
|
||||
});
|
||||
|
||||
connection.on("connect", (_arg: { connection: amqp.Connection, url: string }): void => undefined);
|
||||
connection.on("disconnect", (_arg: { err: Error }): void => undefined);
|
||||
|
||||
channelWrapper.on("close", () => undefined);
|
||||
channelWrapper.on("connect", () => undefined);
|
||||
channelWrapper.on("error", (_error: Error) => undefined);
|
||||
|
||||
channelWrapper.sendToQueue("foo", Buffer.from("bar"))
|
||||
.catch((error: Error): void => {
|
||||
// nothing
|
||||
});
|
||||
184
types/amqp-connection-manager/index.d.ts
vendored
Normal file
184
types/amqp-connection-manager/index.d.ts
vendored
Normal file
@@ -0,0 +1,184 @@
|
||||
// Type definitions for amqp-connection-manager 2.0
|
||||
// Project: https://github.com/benbria/node-amqp-connection-manager
|
||||
// Definitions by: rogierschouten <https://github.com/rogierschouten>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.8
|
||||
|
||||
import { ConfirmChannel, Connection, Message, Options, Replies } from "amqplib";
|
||||
import { EventEmitter } from "events";
|
||||
import { SecureContextOptions } from "tls";
|
||||
|
||||
/**
|
||||
* connect() options
|
||||
*/
|
||||
export interface AmqpConnectionManagerOptions {
|
||||
/**
|
||||
* Interval to send heartbeats to broker. Defaults to 5 seconds.
|
||||
*/
|
||||
heartbeatIntervalInSeconds?: number;
|
||||
|
||||
/**
|
||||
* The time to wait before trying to reconnect. If not specified, defaults to heartbeatIntervalInSeconds
|
||||
*/
|
||||
reconnectTimeInSeconds?: number;
|
||||
|
||||
/**
|
||||
* is a function which returns one or more servers to connect to. This should return either a single URL or an array of URLs.
|
||||
* This is handy when you're using a service discovery mechanism such as Consul or etcd. Instead of taking a callback, this can also
|
||||
* return a Promise. Note that if this is supplied, then urls is ignored.
|
||||
*/
|
||||
findServers?: ((callback: (urls: string | string[]) => void) => void) | (() => Promise<string | string[]>);
|
||||
|
||||
/**
|
||||
* TLS options
|
||||
*/
|
||||
connectionOptions?: SecureContextOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new AmqpConnectionManager, which will connect to one of the URLs provided in urls.
|
||||
* If a broker is unreachable or dies, then AmqpConnectionManager will try the next available broker, round-robin.
|
||||
* @param urls
|
||||
* @param options
|
||||
*/
|
||||
export function connect(urls: string[], options?: AmqpConnectionManagerOptions): AmqpConnectionManager;
|
||||
|
||||
export type SetupFunc = ((channel: ConfirmChannel, callback: (error?: Error) => void) => void) | ((channel: ConfirmChannel) => Promise<void>);
|
||||
|
||||
export interface CreateChannelOpts {
|
||||
/**
|
||||
* Name for this channel. Used for debugging.
|
||||
*/
|
||||
name?: string;
|
||||
/**
|
||||
* A function to call whenever we reconnect to the broker (and therefore create a new underlying channel.)
|
||||
* This function should either accept a callback, or return a Promise. See addSetup below
|
||||
*/
|
||||
setup?: SetupFunc;
|
||||
/**
|
||||
* if true, then ChannelWrapper assumes all messages passed to publish() and sendToQueue() are plain JSON objects.
|
||||
* These will be encoded automatically before being sent.
|
||||
*/
|
||||
json?: boolean;
|
||||
}
|
||||
|
||||
export interface AmqpConnectionManager extends EventEmitter {
|
||||
addListener(event: string, listener: (...args: any[]) => void): this;
|
||||
addListener(event: "connect", listener: (arg: { connection: Connection, url: string }) => void): this;
|
||||
addListener(event: "disconnect", listener: (arg: {err: Error}) => void): this;
|
||||
|
||||
on(event: string, listener: (...args: any[]) => void): this;
|
||||
on(event: "connect", listener: (arg: { connection: Connection, url: string }) => void): this;
|
||||
on(event: "disconnect", listener: (arg: {err: Error}) => void): this;
|
||||
|
||||
once(event: string, listener: (...args: any[]) => void): this;
|
||||
once(event: "connect", listener: (arg: { connection: Connection, url: string }) => void): this;
|
||||
once(event: "disconnect", listener: (arg: {err: Error}) => void): this;
|
||||
|
||||
prependListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependListener(event: "connect", listener: (arg: { connection: Connection, url: string }) => void): this;
|
||||
prependListener(event: "disconnect", listener: (arg: {err: Error}) => void): this;
|
||||
|
||||
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependOnceListener(event: "connect", listener: (arg: { connection: Connection, url: string }) => void): this;
|
||||
prependOnceListener(event: "disconnect", listener: (arg: {err: Error}) => void): this;
|
||||
|
||||
/**
|
||||
* Create a new ChannelWrapper. This is a proxy for the actual channel (which may or may not exist at any moment, depending on whether or not we are currently connected.)
|
||||
* @param opts
|
||||
*/
|
||||
createChannel(opts: CreateChannelOpts): ChannelWrapper;
|
||||
|
||||
/**
|
||||
* Returns true if the AmqpConnectionManager is connected to a broker, false otherwise.
|
||||
*/
|
||||
isConnected(): boolean;
|
||||
|
||||
/**
|
||||
* Close this AmqpConnectionManager and free all associated resources.
|
||||
*/
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface ChannelWrapper extends EventEmitter {
|
||||
addListener(event: string, listener: (...args: any[]) => void): this;
|
||||
addListener(event: "connect", listener: () => void): this;
|
||||
addListener(event: "error", listener: (err: Error, info: { name: string }) => void): this;
|
||||
addListener(event: "close", listener: () => void): this;
|
||||
|
||||
on(event: string, listener: (...args: any[]) => void): this;
|
||||
on(event: "connect", listener: () => void): this;
|
||||
on(event: "error", listener: (err: Error, info: { name: string }) => void): this;
|
||||
on(event: "close", listener: () => void): this;
|
||||
|
||||
once(event: string, listener: (...args: any[]) => void): this;
|
||||
once(event: "connect", listener: () => void): this;
|
||||
once(event: "error", listener: (err: Error, info: { name: string }) => void): this;
|
||||
once(event: "close", listener: () => void): this;
|
||||
|
||||
prependListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependListener(event: "connect", listener: () => void): this;
|
||||
prependListener(event: "error", listener: (err: Error, info: { name: string }) => void): this;
|
||||
prependListener(event: "close", listener: () => void): this;
|
||||
|
||||
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependOnceListener(event: "connect", listener: () => void): this;
|
||||
prependOnceListener(event: "error", listener: (err: Error, info: { name: string }) => void): this;
|
||||
prependOnceListener(event: "close", listener: () => void): this;
|
||||
|
||||
/**
|
||||
* Adds a new 'setup handler'. setup(channel, [cb]) is a function to call when a new underlying channel is created -
|
||||
* handy for asserting exchanges and queues exists, and whatnot. The channel object here is a ConfirmChannel from amqplib.
|
||||
* The setup function should return a Promise (or optionally take a callback) - no messages will be sent until this Promise resolves.
|
||||
* If there is a connection, setup() will be run immediately, and the addSetup Promise/callback won't resolve until setup is complete.
|
||||
* Note that in this case, if the setup throws an error, no 'error' event will be emitted, since you can just handle the error here
|
||||
* (although the setup will still be added for future reconnects, even if it throws an error.)
|
||||
* Setup functions should, ideally, not throw errors, but if they do then the ChannelWrapper will emit an 'error' event.
|
||||
* @param func
|
||||
*/
|
||||
addSetup(func: SetupFunc): Promise<void>;
|
||||
|
||||
/**
|
||||
* @see amqplib
|
||||
* @param exchange
|
||||
* @param routingKey
|
||||
* @param content
|
||||
* @param options
|
||||
* @param callback
|
||||
*/
|
||||
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): Promise<void>;
|
||||
|
||||
/**
|
||||
* @see amqplib
|
||||
* @param queue
|
||||
* @param content
|
||||
* @param options
|
||||
* @param callback
|
||||
*/
|
||||
sendToQueue(queue: string, content: Buffer, options?: Options.Publish, callback?: (err: any, ok: Replies.Empty) => void): Promise<void>;
|
||||
|
||||
/**
|
||||
* @see amqplib
|
||||
* @param message
|
||||
* @param allUpTo
|
||||
*/
|
||||
ack(message: Message, allUpTo?: boolean): void;
|
||||
|
||||
/**
|
||||
* @see amqplib
|
||||
* @param message
|
||||
* @param allUpTo
|
||||
* @param requeue
|
||||
*/
|
||||
nack(message: Message, allUpTo?: boolean, requeue?: boolean): void;
|
||||
|
||||
/**
|
||||
* Returns a count of messages currently waiting to be sent to the underlying channel.
|
||||
*/
|
||||
queueLength(): number;
|
||||
|
||||
/**
|
||||
* Close a channel, clean up resources associated with it.
|
||||
*/
|
||||
close(): Promise<void>;
|
||||
}
|
||||
23
types/amqp-connection-manager/tsconfig.json
Normal file
23
types/amqp-connection-manager/tsconfig.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es6"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
"strictFunctionTypes": true,
|
||||
"strictNullChecks": true,
|
||||
"baseUrl": "../",
|
||||
"typeRoots": [
|
||||
"../"
|
||||
],
|
||||
"types": [],
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"amqp-connection-manager-tests.ts"
|
||||
]
|
||||
}
|
||||
8
types/amqp-connection-manager/tslint.json
Normal file
8
types/amqp-connection-manager/tslint.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "dtslint/dt.json",
|
||||
"rules": {
|
||||
"strict-export-declare-modifiers": false,
|
||||
"unified-signatures": false,
|
||||
"void-return": false
|
||||
}
|
||||
}
|
||||
8
types/amqplib/index.d.ts
vendored
8
types/amqplib/index.d.ts
vendored
@@ -2,13 +2,13 @@
|
||||
// Project: https://github.com/squaremo/amqp.node
|
||||
// Definitions by: Michael Nahkies <https://github.com/mnahkies>, Ab Reitsma <https://github.com/abreits>, Nicolás Fantone <https://github.com/nfantone>, Nick Zelei <https://github.com/zelein>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
// TypeScript Version: 2.8
|
||||
|
||||
/// <reference types="node" />
|
||||
|
||||
import * as Promise from 'bluebird';
|
||||
import * as events from 'events';
|
||||
import { Replies, Options, Message } from './properties';
|
||||
import { Replies, Options, Message, GetMessage, ConsumeMessage } from './properties';
|
||||
export * from './properties';
|
||||
|
||||
export interface Connection extends events.EventEmitter {
|
||||
@@ -40,10 +40,10 @@ export interface Channel extends events.EventEmitter {
|
||||
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean;
|
||||
sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean;
|
||||
|
||||
consume(queue: string, onMessage: (msg: Message | null) => any, options?: Options.Consume): Promise<Replies.Consume>;
|
||||
consume(queue: string, onMessage: (msg: ConsumeMessage | null) => any, options?: Options.Consume): Promise<Replies.Consume>;
|
||||
|
||||
cancel(consumerTag: string): Promise<Replies.Empty>;
|
||||
get(queue: string, options?: Options.Get): Promise<Message | false>;
|
||||
get(queue: string, options?: Options.Get): Promise<GetMessage | false>;
|
||||
|
||||
ack(message: Message, allUpTo?: boolean): void;
|
||||
ackAll(): void;
|
||||
|
||||
24
types/amqplib/properties.d.ts
vendored
24
types/amqplib/properties.d.ts
vendored
@@ -145,12 +145,32 @@ export interface Message {
|
||||
properties: MessageProperties;
|
||||
}
|
||||
|
||||
export interface MessageFields {
|
||||
export interface GetMessage extends Message {
|
||||
fields: GetMessageFields;
|
||||
}
|
||||
|
||||
export interface ConsumeMessage extends Message {
|
||||
fields: ConsumeMessageFields;
|
||||
}
|
||||
|
||||
export interface CommonMessageFields {
|
||||
deliveryTag: number;
|
||||
redelivered: boolean;
|
||||
exchange: string;
|
||||
routingKey: string;
|
||||
messageCount: string;
|
||||
}
|
||||
|
||||
export interface MessageFields extends CommonMessageFields {
|
||||
messageCount?: number;
|
||||
consumerTag?: string;
|
||||
}
|
||||
|
||||
export interface GetMessageFields extends CommonMessageFields {
|
||||
messageCount: number;
|
||||
}
|
||||
|
||||
export interface ConsumeMessageFields extends CommonMessageFields {
|
||||
deliveryTag: number;
|
||||
}
|
||||
|
||||
export interface MessageProperties {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"extends": "dtslint/dt.json",
|
||||
"rules": {
|
||||
// All are TODOs
|
||||
"no-any-union": false,
|
||||
"no-empty-interface": false,
|
||||
"prefer-const": false
|
||||
}
|
||||
|
||||
@@ -36,6 +36,13 @@ app.controller('Ctrl', ($scope: ng.IScope, blockUI: angular.blockUI.BlockUIServi
|
||||
blockUI.stop();
|
||||
blockUI.reset();
|
||||
blockUI.message("Hello Types");
|
||||
blockUI.done();
|
||||
blockUI.done(() => {
|
||||
console.log("blockUI stopped");
|
||||
});
|
||||
const b: boolean = blockUI.isBlocking();
|
||||
|
||||
const myBlockUI = blockUI.instances.get("myBlockUI");
|
||||
myBlockUI.start();
|
||||
myBlockUI.reset();
|
||||
myBlockUI.stop();
|
||||
});
|
||||
|
||||
49
types/angular-block-ui/index.d.ts
vendored
49
types/angular-block-ui/index.d.ts
vendored
@@ -1,6 +1,8 @@
|
||||
// Type definitions for angular-block-ui 0.2
|
||||
// Project: https://github.com/McNull/angular-block-ui
|
||||
// Definitions by: Lasse Nørregaard <https://github.com/lassebn>, Stephan Classen <https://github.com/sclassen>
|
||||
// Definitions by: Lasse Nørregaard <https://github.com/lassebn>
|
||||
// Stephan Classen <https://github.com/sclassen>
|
||||
// Soner Köksal <https://github.com/renjfk>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
|
||||
@@ -48,6 +50,8 @@ declare module 'angular' {
|
||||
*
|
||||
* If you don't want this behaviour and want to do all the
|
||||
* blocking manually you can change this value to false.
|
||||
*
|
||||
* The default value is 'true'
|
||||
*/
|
||||
autoBlock?: boolean;
|
||||
|
||||
@@ -56,6 +60,8 @@ declare module 'angular' {
|
||||
* hide the overlay whenever an exception has occurred.
|
||||
*
|
||||
* You can set this value to false if you don't want this behaviour.
|
||||
*
|
||||
* The default value is 'true'
|
||||
*/
|
||||
resetOnException?: boolean;
|
||||
|
||||
@@ -74,33 +80,42 @@ declare module 'angular' {
|
||||
|
||||
/**
|
||||
* When the module is started it will inject the main block element
|
||||
* by adding the block-ui directive to the body element.
|
||||
* by adding the "block-ui" directive to the <body> element.
|
||||
*
|
||||
* Set this to false if there no need for any fullscreen blocking or if there's
|
||||
* more control required. For instance when your ng-app directive is a child
|
||||
* element of the body element it is impossible for the blockUI resolve the main
|
||||
* instance. In such a case the auto injection of the main block scope should
|
||||
* be disabled and the main block element should be relocated.
|
||||
*
|
||||
* The default value is 'true'
|
||||
*/
|
||||
autoInjectBodyBlock?: boolean;
|
||||
|
||||
/**
|
||||
* A string containing the default css classes, separated by spaces,
|
||||
* A string containing the default css classes (separated by spaces)
|
||||
* that should be applied to each block-ui element.
|
||||
*
|
||||
* The default value is `block-ui block-ui-anim-fade`
|
||||
* The default value is "block-ui block-ui-anim-fade"
|
||||
*/
|
||||
cssClass?: string;
|
||||
|
||||
/**
|
||||
* Whenever a user interface block is active, because the single page
|
||||
* application is still waiting for a response from the backend server,
|
||||
* the user can still navigate away using the back and forward buttons
|
||||
* of the browser.
|
||||
* While a user interface block is active the user can still navigate
|
||||
* away using the back and forward buttons of the browser.
|
||||
*
|
||||
* Callbacks registered to handle the responses from the server will
|
||||
* be executed even if a different view/controller is currently active.
|
||||
* By setting the blockBrowserNavigation property to true the
|
||||
* angular-block-ui module will prevent navigation while a fullscreen
|
||||
* Callbacks registered to handle responses from the server will
|
||||
* be executed even if a different view/controller is active at the
|
||||
* time the response arrives.
|
||||
*
|
||||
* You can set this value to true if you want to prevent navigation
|
||||
* with the browser back and forward buttons while a fullscreen
|
||||
* block is active.
|
||||
*
|
||||
* Programatic location changes via the $location service are still
|
||||
* allowed however.
|
||||
* The navigation block is disabled by default.
|
||||
*
|
||||
* The default value is 'false'
|
||||
*/
|
||||
blockBrowserNavigation?: boolean;
|
||||
}
|
||||
@@ -150,7 +165,7 @@ declare module 'angular' {
|
||||
* This can be useful whenever you wish to redirect the user
|
||||
* to a different location while there are still pending AJAX requests.
|
||||
*/
|
||||
done(): void;
|
||||
done(doneCallback: () => void): void;
|
||||
|
||||
/**
|
||||
* Allows the message shown in the overlay to be updated
|
||||
@@ -164,6 +179,12 @@ declare module 'angular' {
|
||||
* Returns whether currently a block is shown for the instance or not.
|
||||
*/
|
||||
isBlocking(): boolean;
|
||||
|
||||
instances: BlockUIInstances;
|
||||
}
|
||||
|
||||
interface BlockUIInstances {
|
||||
get(id: string): BlockUIService;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,4 +21,4 @@
|
||||
"index.d.ts",
|
||||
"angular-block-ui-tests.ts"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
"max-line-length": false,
|
||||
"member-access": false,
|
||||
"new-parens": false,
|
||||
"no-angle-bracket-type-assertion": false,
|
||||
"no-any-union": false,
|
||||
"no-boolean-literal-compare": false,
|
||||
"no-conditional-assignment": false,
|
||||
|
||||
@@ -22,7 +22,7 @@ declare module 'angular' {
|
||||
* This is an experimental technology
|
||||
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/badge
|
||||
*/
|
||||
badge?: USVString;
|
||||
badge?: string;
|
||||
|
||||
/**
|
||||
* The data read-only property of the Notification interface returns a structured clone of the notification's data,
|
||||
@@ -40,7 +40,7 @@ declare module 'angular' {
|
||||
* Note: This feature is available in Web Workers.
|
||||
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/image
|
||||
*/
|
||||
image?: USVString;
|
||||
image?: string;
|
||||
|
||||
/**
|
||||
* The renotify read-only property of the Notification interface specifies whether the user should be notified after a
|
||||
@@ -101,7 +101,7 @@ declare module 'angular' {
|
||||
* Note: This property is not currently supported in any browser.
|
||||
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/Notification/vibrate
|
||||
*/
|
||||
vibrate?: boolean;
|
||||
vibrate?: any;
|
||||
|
||||
/**
|
||||
* The onclick property of the Notification interface specifies an event listener to receive click events.
|
||||
|
||||
@@ -24,6 +24,8 @@ angular.module("myApp").controller("helloController", function (gettextCatalog:
|
||||
|
||||
angular.module("myApp").controller("helloController", function (gettextCatalog: angular.gettext.gettextCatalog) {
|
||||
var myString2: string = gettextCatalog.getPlural(3, "Bird", "Birds");
|
||||
var myStringWithScope: string = gettextCatalog.getPlural(4, "{{color}} Bird", "{{color}} Birds", {color: 'Blue'});
|
||||
var myStringWithContext: string = gettextCatalog.getPlural(5, "pick", "picks", null, 'noun');
|
||||
});
|
||||
|
||||
angular.module("myApp").controller("helloController", function (gettextCatalog: angular.gettext.gettextCatalog) {
|
||||
|
||||
5
types/angular-gettext/index.d.ts
vendored
5
types/angular-gettext/index.d.ts
vendored
@@ -1,4 +1,4 @@
|
||||
// Type definitions for angular-gettext v2.1.0
|
||||
// Type definitions for angular-gettext v2.1.1
|
||||
// Project: https://angular-gettext.rocketeer.be/
|
||||
// Definitions by: Ákos Lukács <https://github.com/AkosLukacs>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
import * as angular from 'angular';
|
||||
|
||||
export type gettextCatalog = angular.gettext.gettextCatalog;
|
||||
|
||||
declare module 'angular' {
|
||||
export namespace gettext {
|
||||
@@ -65,7 +66,7 @@ declare module 'angular' {
|
||||
getString(string: string, scope?: any, context?: string): string;
|
||||
|
||||
/** Translate a plural string with the given context. */
|
||||
getPlural(n: number, string: string, stringPlural: string, context?: any): string;
|
||||
getPlural(n: number, string: string, stringPlural: string, scope?: any, context?: string): string;
|
||||
|
||||
/** Load a set of translation strings from a given URL.This should be a JSON catalog generated with grunt-angular-gettext. More details https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ */
|
||||
loadRemote(url: string): ng.IHttpPromise<any>;
|
||||
|
||||
4
types/angular-local-storage/index.d.ts
vendored
4
types/angular-local-storage/index.d.ts
vendored
@@ -8,6 +8,10 @@
|
||||
|
||||
import * as angular from 'angular';
|
||||
|
||||
export type ILocalStorageServiceProvider = angular.local.storage.ILocalStorageServiceProvider;
|
||||
export type ILocalStorageService = angular.local.storage.ILocalStorageService;
|
||||
export type ICookie = angular.local.storage.ICookie;
|
||||
|
||||
declare module 'angular' {
|
||||
export namespace local.storage {
|
||||
interface ILocalStorageServiceProvider extends angular.IServiceProvider {
|
||||
|
||||
2
types/angular-material/index.d.ts
vendored
2
types/angular-material/index.d.ts
vendored
@@ -76,6 +76,7 @@ declare module 'angular' {
|
||||
|
||||
interface IConfirmDialog extends IPresetDialog<IConfirmDialog> {
|
||||
cancel(cancel: string): IConfirmDialog;
|
||||
multiple(multiple: boolean): IConfirmDialog;
|
||||
}
|
||||
|
||||
interface IPromptDialog extends IPresetDialog<IPromptDialog> {
|
||||
@@ -340,6 +341,7 @@ declare module 'angular' {
|
||||
|
||||
interface IMenuService {
|
||||
hide(response?: any, options?: any): IPromise<any>;
|
||||
open(event?: MouseEvent): void;
|
||||
}
|
||||
|
||||
interface IColorPalette {
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
"max-line-length": false,
|
||||
"member-access": false,
|
||||
"new-parens": false,
|
||||
"no-angle-bracket-type-assertion": false,
|
||||
"no-any-union": false,
|
||||
"no-boolean-literal-compare": false,
|
||||
"no-conditional-assignment": false,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
742
types/angular-mocks/index.d.ts
vendored
742
types/angular-mocks/index.d.ts
vendored
@@ -1,10 +1,11 @@
|
||||
// Type definitions for Angular JS (ngMock, ngMockE2E module) 1.5
|
||||
// Type definitions for Angular JS (ngMock, ngMockE2E module) 1.7
|
||||
// Project: http://angularjs.org
|
||||
// Definitions by: Diego Vilar <https://github.com/diegovilar>, Tony Curtis <https://github.com/daltin>
|
||||
// Definitions by: Diego Vilar <https://github.com/diegovilar>
|
||||
// Tony Curtis <https://github.com/daltin>
|
||||
// Georgii Dolzhykov <https://github.com/thorn0>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
// TypeScript Version: 2.4
|
||||
|
||||
/// <reference types="angular" />
|
||||
/// <reference path="mocks.d.ts" />
|
||||
|
||||
import * as angular from 'angular';
|
||||
@@ -13,7 +14,6 @@ import * as angular from 'angular';
|
||||
// ngMock module (angular-mocks.js)
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
declare module 'angular' {
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// AngularStatic
|
||||
// We reopen it to add the MockStatic definition
|
||||
@@ -23,27 +23,27 @@ declare module 'angular' {
|
||||
}
|
||||
|
||||
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject
|
||||
// Depending on context, it might return a function, however having `void | (() => void)`
|
||||
// as a return type seems to be not useful. E.g. it requires type assertions in `beforeEach(inject(...))`.
|
||||
interface IInjectStatic {
|
||||
(...fns: Function[]): any;
|
||||
(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works
|
||||
strictDi(val?: boolean): void;
|
||||
(...fns: Array<Injectable<(...args: any[]) => void>>): any; // void | (() => void);
|
||||
strictDi(val?: boolean): any; // void | (() => void);
|
||||
}
|
||||
|
||||
interface IMockStatic {
|
||||
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.dump
|
||||
dump(obj: any): string;
|
||||
|
||||
inject: IInjectStatic
|
||||
inject: IInjectStatic;
|
||||
|
||||
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.module
|
||||
module: {
|
||||
(...modules: any[]): any;
|
||||
sharedInjector(): void;
|
||||
}
|
||||
};
|
||||
|
||||
// see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate
|
||||
TzDate(offset: number, timestamp: number): Date;
|
||||
TzDate(offset: number, timestamp: string): Date;
|
||||
TzDate(offset: number, timestamp: number | string): Date;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
@@ -61,8 +61,38 @@ declare module 'angular' {
|
||||
// Augments the original service
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
interface ITimeoutService {
|
||||
/**
|
||||
* **Deprecated** since version 1.7.3. (Use `$flushPendingTasks` instead.)
|
||||
*
|
||||
* ---
|
||||
* Flushes the queue of pending tasks.
|
||||
*
|
||||
* _This method is essentially an alias of `$flushPendingTasks`._
|
||||
*
|
||||
* > For historical reasons, this method will also flush non-`$timeout` pending tasks, such as
|
||||
* > `$q` promises and tasks scheduled via `$applyAsync` and `$evalAsync`.
|
||||
*
|
||||
* @param delay - The maximum timeout amount to flush up until.
|
||||
*/
|
||||
flush(delay?: number): void;
|
||||
flushNext(expectedDelay?: number): void;
|
||||
|
||||
/**
|
||||
* **Deprecated** since version 1.7.3. (Use `$verifyNoPendingTasks` instead.)
|
||||
*
|
||||
* ---
|
||||
* Verifies that there are no pending tasks that need to be flushed. It throws an error if there
|
||||
* are still pending tasks.
|
||||
*
|
||||
* _This method is essentially an alias of `$verifyNoPendingTasks` (called with no arguments)._
|
||||
*
|
||||
* > For historical reasons, this method will also verify non-`$timeout` pending tasks, such as
|
||||
* > pending `$http` requests, in-progress `$route` transitions, unresolved `$q` promises and
|
||||
* > tasks scheduled via `$applyAsync` and `$evalAsync`.
|
||||
* >
|
||||
* > It is recommended to use `$verifyNoPendingTasks` instead, which additionally supports
|
||||
* > verifying a specific type of tasks. For example, you can verify there are no pending
|
||||
* > timeouts with `$verifyNoPendingTasks('$timeout')`.
|
||||
*/
|
||||
verifyNoPendingTasks(): void;
|
||||
}
|
||||
|
||||
@@ -72,7 +102,13 @@ declare module 'angular' {
|
||||
// Augments the original service
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
interface IIntervalService {
|
||||
flush(millis?: number): number;
|
||||
/**
|
||||
* Runs interval tasks scheduled to be run in the next `millis` milliseconds.
|
||||
*
|
||||
* @param millis - The maximum timeout amount to flush up until.
|
||||
* @return The amount of time moved forward.
|
||||
*/
|
||||
flush(millis: number): number;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
@@ -96,9 +132,11 @@ declare module 'angular' {
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
interface IControllerService {
|
||||
// Although the documentation doesn't state this, locals are optional
|
||||
<T>(controllerConstructor: new (...args: any[]) => T, locals?: any, bindings?: any): T;
|
||||
<T>(controllerConstructor: Function, locals?: any, bindings?: any): T;
|
||||
<T>(controllerName: string, locals?: any, bindings?: any): T;
|
||||
<T>(
|
||||
controllerConstructor: (new (...args: any[]) => T) | ((...args: any[]) => T) | string,
|
||||
locals?: any,
|
||||
bindings?: any
|
||||
): T;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
@@ -108,268 +146,538 @@ declare module 'angular' {
|
||||
interface IComponentControllerService {
|
||||
// TBinding is an interface exposed by a component as per John Papa's style guide
|
||||
// https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#accessible-members-up-top
|
||||
<T, TBinding>(componentName: string, locals: { $scope?: IScope, [key: string]: any }, bindings?: TBinding, ident?: string): T;
|
||||
<T, TBinding>(
|
||||
componentName: string,
|
||||
locals: { $scope?: IScope; [key: string]: any },
|
||||
bindings?: TBinding,
|
||||
ident?: string
|
||||
): T;
|
||||
}
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// HttpBackendService
|
||||
// see https://docs.angularjs.org/api/ngMock/service/$httpBackend
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
interface IHttpBackendService {
|
||||
/**
|
||||
* Flushes pending requests using the trained responses. Requests are flushed in the order they were made, but it is also possible to skip one or more requests (for example to have them flushed later). This is useful for simulating scenarios where responses arrive from the server in any order.
|
||||
*
|
||||
* If there are no pending requests to flush when the method is called, an exception is thrown (as this is typically a sign of programming error).
|
||||
* @param count Number of responses to flush. If undefined/null, all pending requests (starting after `skip`) will be flushed.
|
||||
* @param skip Number of pending requests to skip. For example, a value of 5 would skip the first 5 pending requests and start flushing from the 6th onwards. _(default: 0)_
|
||||
*/
|
||||
* Flushes pending requests using the trained responses. Requests are flushed in the order they
|
||||
* were made, but it is also possible to skip one or more requests (for example to have them
|
||||
* flushed later). This is useful for simulating scenarios where responses arrive from the server
|
||||
* in any order.
|
||||
*
|
||||
* If there are no pending requests to flush when the method is called, an exception is thrown (as
|
||||
* this is typically a sign of programming error).
|
||||
*
|
||||
* @param count Number of responses to flush. If undefined/null, all pending requests (starting
|
||||
* after `skip`) will be flushed.
|
||||
* @param skip Number of pending requests to skip. For example, a value of 5 would skip the first 5 pending requests and start flushing from the 6th onwards. _(default: 0)_
|
||||
*/
|
||||
flush(count?: number, skip?: number): void;
|
||||
|
||||
/**
|
||||
* Resets all request expectations, but preserves all backend definitions.
|
||||
*/
|
||||
* Resets all request expectations, but preserves all backend definitions.
|
||||
*/
|
||||
resetExpectations(): void;
|
||||
|
||||
/**
|
||||
* Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.
|
||||
* @param digest Do digest before checking expectation. Pass anything except false to trigger digest. NOTE this flag is purposely undocumented by Angular, which means it's not to be used in normal client code.
|
||||
*/
|
||||
* Verifies that all of the requests defined via the `expect` api were made. If any of the
|
||||
* requests were not made, verifyNoOutstandingExpectation throws an exception.
|
||||
* @param digest Do digest before checking expectation. Pass anything except false to trigger digest.
|
||||
* NOTE: this flag is purposely undocumented by Angular, which means it's not to be used in normal client code.
|
||||
*/
|
||||
verifyNoOutstandingExpectation(digest?: boolean): void;
|
||||
|
||||
/**
|
||||
* Verifies that there are no outstanding requests that need to be flushed.
|
||||
*/
|
||||
* Verifies that there are no outstanding requests that need to be flushed.
|
||||
*/
|
||||
verifyNoOutstandingRequest(): void;
|
||||
|
||||
/**
|
||||
* Creates a new request expectation.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param method HTTP method.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
|
||||
/**
|
||||
* Creates a new request expectation.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param method HTTP method.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
expect(
|
||||
method: string,
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
data?: string | RegExp | object | ((data: string) => boolean),
|
||||
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new request expectation for DELETE requests.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected.
|
||||
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
|
||||
/**
|
||||
* Creates a new request expectation for DELETE requests.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
expectDELETE(
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new request expectation for GET requests.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
|
||||
/**
|
||||
* Creates a new request expectation for GET requests.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
expectGET(
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new request expectation for HEAD requests.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
/**
|
||||
* Creates a new request expectation for HEAD requests.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
|
||||
expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
|
||||
expectHEAD(
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new request expectation for JSONP requests.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
expectJSONP(url: string | RegExp | ((url: string) => boolean), keys?: Object[]): mock.IRequestHandler;
|
||||
/**
|
||||
* Creates a new request expectation for JSONP requests.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
expectJSONP(
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new request expectation for PATCH requests.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
|
||||
/**
|
||||
* Creates a new request expectation for PATCH requests.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
expectPATCH(
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
data?: string | RegExp | object | ((data: string) => boolean),
|
||||
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new request expectation for POST requests.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
|
||||
/**
|
||||
* Creates a new request expectation for POST requests.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
expectPOST(
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
data?: string | RegExp | object | ((data: string) => boolean),
|
||||
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new request expectation for PUT requests.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;
|
||||
/**
|
||||
* Creates a new request expectation for PUT requests.
|
||||
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
expectPUT(
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
data?: string | RegExp | object | ((data: string) => boolean),
|
||||
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new backend definition.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param method HTTP method.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
|
||||
/**
|
||||
* Creates a new request expectation that compares only with the requested route.
|
||||
* This method offers colon delimited matching of the url path, ignoring the query string.
|
||||
* This allows declarations similar to how application routes are configured with `$routeProvider`.
|
||||
* As this method converts the definition url to regex, declaration order is important.
|
||||
* @param method HTTP method
|
||||
* @param url HTTP url string that supports colon param matching
|
||||
*/
|
||||
expectRoute(method: string, url: string): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new backend definition for DELETE requests.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
|
||||
/**
|
||||
* Creates a new backend definition.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param method HTTP method.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
when(
|
||||
method: string,
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
data?: string | RegExp | object | ((data: string) => boolean),
|
||||
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new backend definition for GET requests.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in request url described above
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
|
||||
/**
|
||||
* Creates a new backend definition for DELETE requests.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
whenDELETE(
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new backend definition for HEAD requests.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
|
||||
/**
|
||||
* Creates a new backend definition for GET requests.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in request url described above
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
whenGET(
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new backend definition for JSONP requests.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
whenJSONP(url: string | RegExp | ((url: string) => boolean), keys?: Object[]): mock.IRequestHandler;
|
||||
/**
|
||||
* Creates a new backend definition for HEAD requests.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
whenHEAD(
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new backend definition for PATCH requests.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
|
||||
/**
|
||||
* Creates a new backend definition for JSONP requests.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
whenJSONP(
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new backend definition for POST requests.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
|
||||
/**
|
||||
* Creates a new backend definition for PATCH requests.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
whenPATCH(
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
data?: string | RegExp | object | ((data: string) => boolean),
|
||||
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new backend definition for PUT requests.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
|
||||
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;
|
||||
/**
|
||||
* Creates a new backend definition for POST requests.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true
|
||||
* if the url matches the current definition.
|
||||
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
|
||||
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
whenPOST(
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
data?: string | RegExp | object | ((data: string) => boolean),
|
||||
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new backend definition for PUT requests.
|
||||
* Returns an object with respond method that controls how a matched request is handled.
|
||||
* @param url HTTP url string, regular expression or function that receives a url and returns true
|
||||
* if the url matches the current definition.
|
||||
* @param data HTTP request body or function that receives data string and returns true if the data
|
||||
* is as expected.
|
||||
* @param headers HTTP headers or function that receives http header object and returns true if the
|
||||
* headers match the current definition.
|
||||
* @param keys Array of keys to assign to regex matches in the request url.
|
||||
*/
|
||||
whenPUT(
|
||||
url: string | RegExp | ((url: string) => boolean),
|
||||
data?: string | RegExp | object | ((data: string) => boolean),
|
||||
headers?: mock.IHttpHeaders | ((headers: mock.IHttpHeaders) => boolean),
|
||||
keys?: string[]
|
||||
): mock.IRequestHandler;
|
||||
|
||||
/**
|
||||
* Creates a new backend definition that compares only with the requested route.
|
||||
* This method offers colon delimited matching of the url path, ignoring the query string.
|
||||
* This allows declarations similar to how application routes are configured with `$routeProvider`.
|
||||
* As this method converts the definition url to regex, declaration order is important.
|
||||
* @param method HTTP method.
|
||||
* @param url HTTP url string that supports colon param matching.
|
||||
*/
|
||||
whenRoute(method: string, url: string): mock.IRequestHandler;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// FlushPendingTasksService
|
||||
// see https://docs.angularjs.org/api/ngMock/service/$flushPendingTasks
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
interface IFlushPendingTasksService {
|
||||
/**
|
||||
* Flushes all currently pending tasks and executes the corresponding callbacks.
|
||||
*
|
||||
* Optionally, you can also pass a `delay` argument to only flush tasks that are scheduled to be
|
||||
* executed within `delay` milliseconds. Currently, `delay` only applies to timeouts, since all
|
||||
* other tasks have a delay of 0 (i.e. they are scheduled to be executed as soon as possible, but
|
||||
* still asynchronously).
|
||||
*
|
||||
* If no delay is specified, it uses a delay such that all currently pending tasks are flushed.
|
||||
*
|
||||
* The types of tasks that are flushed include:
|
||||
*
|
||||
* - Pending timeouts (via `$timeout`).
|
||||
* - Pending tasks scheduled via `$applyAsync`.
|
||||
* - Pending tasks scheduled via `$evalAsync`.
|
||||
* These include tasks scheduled via `$evalAsync()` indirectly (such as `$q` promises).
|
||||
*
|
||||
* > Periodic tasks scheduled via `$interval` use a different queue and are not flushed by
|
||||
* > `$flushPendingTasks()`. Use `$interval.flush(millis)` instead.
|
||||
*
|
||||
* @param millis - The number of milliseconds to flush.
|
||||
*/
|
||||
(delay?: number): void;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// VerifyNoPendingTasksService
|
||||
// see https://docs.angularjs.org/api/ngMock/service/$verifyNoPendingTasks
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
interface IVerifyNoPendingTasksService {
|
||||
/**
|
||||
* Verifies that there are no pending tasks that need to be flushed. It throws an error if there
|
||||
* are still pending tasks.
|
||||
*
|
||||
* You can check for a specific type of tasks only, by specifying a `taskType`.
|
||||
*
|
||||
* Available task types:
|
||||
*
|
||||
* - `$timeout`: Pending timeouts (via `$timeout`).
|
||||
* - `$http`: Pending HTTP requests (via `$http`).
|
||||
* - `$route`: In-progress route transitions (via `$route`).
|
||||
* - `$applyAsync`: Pending tasks scheduled via `$applyAsync`.
|
||||
* - `$evalAsync`: Pending tasks scheduled via `$evalAsync`.
|
||||
* These include tasks scheduled via `$evalAsync()` indirectly (such as `$q` promises).
|
||||
*
|
||||
* > Periodic tasks scheduled via `$interval` use a different queue and are not taken into
|
||||
* > account by `$verifyNoPendingTasks()`. There is currently no way to verify that there are no
|
||||
* > pending `$interval` tasks.
|
||||
*
|
||||
* @param taskType - The type of tasks to check for.
|
||||
*/
|
||||
(taskType?: string): void;
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// AnimateService
|
||||
// see https://docs.angularjs.org/api/ngMock/service/$animate
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
module animate {
|
||||
namespace animate {
|
||||
interface IAnimateService {
|
||||
|
||||
/**
|
||||
* This method will close all pending animations (both Javascript and CSS) and it will also flush any remaining animation frames and/or callbacks.
|
||||
* This method will close all pending animations (both Javascript and CSS) and it will also flush any remaining
|
||||
* animation frames and/or callbacks.
|
||||
*/
|
||||
closeAndFlush(): void;
|
||||
|
||||
/**
|
||||
* This method is used to flush the pending callbacks and animation frames to either start an animation or conclude an animation. Note that this will not actually close an actively running animation (see `closeAndFlush()` for that).
|
||||
* This method is used to flush the pending callbacks and animation frames to either start
|
||||
* an animation or conclude an animation. Note that this will not actually close an
|
||||
* actively running animation (see `closeAndFlush()`} for that).
|
||||
*/
|
||||
flush(): void;
|
||||
}
|
||||
}
|
||||
|
||||
export module mock {
|
||||
// returned interface by the the mocked HttpBackendService expect/when methods
|
||||
namespace mock {
|
||||
/** Object returned by the the mocked HttpBackendService expect/when methods */
|
||||
interface IRequestHandler {
|
||||
|
||||
/**
|
||||
* Controls the response for a matched request using a function to construct the response.
|
||||
* Returns the RequestHandler object for possible overrides.
|
||||
* @param func Function that receives the request HTTP method, url, data, headers, and an array of keys to regex matches in the request url and returns an array containing response status (number), data, headers, and status text.
|
||||
*/
|
||||
respond(func: ((method: string, url: string, data: string | Object, headers: Object, params?: any) => [number, string | Object, Object, string])): IRequestHandler;
|
||||
|
||||
/**
|
||||
* Controls the response for a matched request using supplied static data to construct the response.
|
||||
* Returns the RequestHandler object for possible overrides.
|
||||
* @param status HTTP status code to add to the response.
|
||||
* @param data Data to add to the response.
|
||||
* @param headers Headers object to add to the response.
|
||||
* @param responseText Response text to add to the response.
|
||||
*/
|
||||
respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler;
|
||||
|
||||
/**
|
||||
* Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response.
|
||||
* Returns the RequestHandler object for possible overrides.
|
||||
* @param data Data to add to the response.
|
||||
* @param headers Headers object to add to the response.
|
||||
* @param responseText Response text to add to the response.
|
||||
*/
|
||||
respond(data: string | Object, headers?: Object, responseText?: string): IRequestHandler;
|
||||
|
||||
// Available when ngMockE2E is loaded
|
||||
/**
|
||||
* Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.)
|
||||
*/
|
||||
* Controls the response for a matched request using a function to construct the response.
|
||||
* Returns the RequestHandler object for possible overrides.
|
||||
* @param func Function that receives the request HTTP method, url, data, headers, and an array of keys
|
||||
* to regex matches in the request url and returns an array containing response status (number), data,
|
||||
* headers, and status text.
|
||||
*/
|
||||
respond(
|
||||
func: ((
|
||||
method: string,
|
||||
url: string,
|
||||
data: string | object,
|
||||
headers: IHttpHeaders,
|
||||
params: { [key: string]: string }
|
||||
) => [number, string | object, IHttpHeaders, string])
|
||||
): IRequestHandler;
|
||||
|
||||
/**
|
||||
* Controls the response for a matched request using supplied static data to construct the response.
|
||||
* Returns the RequestHandler object for possible overrides.
|
||||
* @param status HTTP status code to add to the response.
|
||||
* @param data Data to add to the response.
|
||||
* @param headers Headers object to add to the response.
|
||||
* @param responseText Response text to add to the response.
|
||||
*/
|
||||
respond(
|
||||
status: number,
|
||||
data?: string | object,
|
||||
headers?: IHttpHeaders,
|
||||
responseText?: string
|
||||
): IRequestHandler;
|
||||
|
||||
/**
|
||||
* Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response.
|
||||
* Returns the RequestHandler object for possible overrides.
|
||||
* @param data Data to add to the response.
|
||||
* @param headers Headers object to add to the response.
|
||||
* @param responseText Response text to add to the response.
|
||||
*/
|
||||
respond(
|
||||
data: string | object,
|
||||
headers?: IHttpHeaders,
|
||||
responseText?: string
|
||||
): IRequestHandler;
|
||||
|
||||
/**
|
||||
* Any request matching a backend definition or expectation with passThrough handler will be
|
||||
* passed through to the real backend (an XHR request will be made to the server.)
|
||||
* Available when ngMockE2E is loaded
|
||||
*/
|
||||
passThrough(): IRequestHandler;
|
||||
}
|
||||
|
||||
interface IHttpHeaders {
|
||||
[headerName: string]: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* Contains additional event data used by the `browserTrigger` function when creating an event.
|
||||
*/
|
||||
interface IBrowserTriggerEventData {
|
||||
/**
|
||||
* [Event.bubbles](https://developer.mozilla.org/docs/Web/API/Event/bubbles).
|
||||
* Not applicable to all events.
|
||||
*/
|
||||
bubbles?: boolean;
|
||||
/**
|
||||
* [Event.cancelable](https://developer.mozilla.org/docs/Web/API/Event/cancelable).
|
||||
* Not applicable to all events.
|
||||
*/
|
||||
cancelable?: boolean;
|
||||
/**
|
||||
* [charCode](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/charcode)
|
||||
* for keyboard events (keydown, keypress, and keyup).
|
||||
*/
|
||||
charcode?: number;
|
||||
/**
|
||||
* [data](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent/data) for
|
||||
* [CompositionEvents](https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent).
|
||||
*/
|
||||
data?: string;
|
||||
/**
|
||||
* The elapsedTime for
|
||||
* [TransitionEvent](https://developer.mozilla.org/docs/Web/API/TransitionEvent)
|
||||
* and [AnimationEvent](https://developer.mozilla.org/docs/Web/API/AnimationEvent).
|
||||
*/
|
||||
elapsedTime?: number;
|
||||
/**
|
||||
* [keyCode](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/keycode)
|
||||
* for keyboard events (keydown, keypress, and keyup).
|
||||
*/
|
||||
keycode?: number;
|
||||
/**
|
||||
* An array of possible modifier keys (ctrl, alt, shift, meta) for
|
||||
* [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent) and
|
||||
* keyboard events (keydown, keypress, and keyup).
|
||||
*/
|
||||
keys?: Array<'ctrl' | 'alt' | 'shift' | 'meta'>;
|
||||
/**
|
||||
* The [relatedTarget](https://developer.mozilla.org/docs/Web/API/MouseEvent/relatedTarget)
|
||||
* for [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent).
|
||||
*/
|
||||
relatedTarget?: Node;
|
||||
/**
|
||||
* [which](https://developer.mozilla.org/docs/Web/API/KeyboardEvent/which)
|
||||
* for keyboard events (keydown, keypress, and keyup).
|
||||
*/
|
||||
which?: number;
|
||||
/**
|
||||
* x-coordinates for [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent)
|
||||
* and [TouchEvent](https://developer.mozilla.org/docs/Web/API/TouchEvent).
|
||||
*/
|
||||
x?: number;
|
||||
/**
|
||||
* y-coordinates for [MouseEvent](https://developer.mozilla.org/docs/Web/API/MouseEvent)
|
||||
* and [TouchEvent](https://developer.mozilla.org/docs/Web/API/TouchEvent).
|
||||
*/
|
||||
y?: number;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// functions attached to global object (window)
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
//Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs.
|
||||
//declare var module: (...modules: any[]) => any;
|
||||
// Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs.
|
||||
// declare var module: (...modules: any[]) => any;
|
||||
declare global {
|
||||
export var inject: angular.IInjectStatic;
|
||||
const inject: angular.IInjectStatic;
|
||||
|
||||
/**
|
||||
* This is a global (window) function that is only available when the `ngMock` module is included.
|
||||
* It can be used to trigger a native browser event on an element, which is useful for unit testing.
|
||||
*
|
||||
* @param element Either a wrapped jQuery/jqLite node or a DOM element.
|
||||
* @param eventType Optional event type. If none is specified, the function tries to determine the
|
||||
* right event type for the element, e.g. `change` for `input[text]`.
|
||||
* @param eventData An optional object which contains additional event data used when creating the
|
||||
* event.
|
||||
*/
|
||||
function browserTrigger(
|
||||
element: JQuery | Element,
|
||||
eventType?: string,
|
||||
eventData?: angular.mock.IBrowserTriggerEventData
|
||||
): void;
|
||||
}
|
||||
|
||||
8
types/angular-mocks/mocks.d.ts
vendored
8
types/angular-mocks/mocks.d.ts
vendored
@@ -1,14 +1,14 @@
|
||||
declare module "angular-mocks/ngMock" {
|
||||
var _: string;
|
||||
const _: string;
|
||||
export = _;
|
||||
}
|
||||
|
||||
declare module "angular-mocks/ngMockE2E" {
|
||||
var _: string;
|
||||
const _: string;
|
||||
export = _;
|
||||
}
|
||||
|
||||
declare module "angular-mocks/ngAnimateMock" {
|
||||
var _: string;
|
||||
const _: string;
|
||||
export = _;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,79 +1,10 @@
|
||||
{
|
||||
"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",
|
||||
"rules": {
|
||||
"callable-types": false,
|
||||
"interface-name": false,
|
||||
"no-declare-current-package": false,
|
||||
"no-unnecessary-generics": false,
|
||||
"only-arrow-functions": false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es6"
|
||||
"es6",
|
||||
"dom"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
angular.module('promise-tracker-tests', []).run(['$q', 'promiseTracker',
|
||||
($q: angular.IQService, promiseTracker: angular.promisetracker.PromiseTrackerService) => {
|
||||
angular.module('promise-tracker-tests', []).run(['$q', '$http', 'promiseTracker',
|
||||
($q: angular.IQService, $http: angular.IHttpService, promiseTracker: angular.promisetracker.PromiseTrackerService) => {
|
||||
const trackerWithoutOptions = promiseTracker();
|
||||
|
||||
const options = {
|
||||
@@ -19,4 +19,8 @@ angular.module('promise-tracker-tests', []).run(['$q', 'promiseTracker',
|
||||
const addedPromise: angular.IDeferred<void> = trackerWithOptions.addPromise(promiseToAdd);
|
||||
|
||||
const trackerWithSomeOptions = promiseTracker({activationDelay: 500});
|
||||
|
||||
$http.post('/foo', {}, { });
|
||||
$http.post('/foo', {}, { tracker: trackerWithOptions });
|
||||
$http.post('/foo', {}, { tracker: [trackerWithoutOptions, trackerWithOptions] });
|
||||
}]);
|
||||
|
||||
4
types/angular-promise-tracker/index.d.ts
vendored
4
types/angular-promise-tracker/index.d.ts
vendored
@@ -28,4 +28,8 @@ declare module 'angular' {
|
||||
(options?: PromiseTrackerOptions): PromiseTracker;
|
||||
}
|
||||
}
|
||||
|
||||
interface IRequestShortcutConfig {
|
||||
tracker?: angular.promisetracker.PromiseTracker | angular.promisetracker.PromiseTracker[];
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user