Merge pull request #10 from DefinitelyTyped/master

Update to latest
This commit is contained in:
Dolan
2018-03-05 17:09:33 +00:00
committed by GitHub
3520 changed files with 146442 additions and 182369 deletions
+327 -141
View File
File diff suppressed because it is too large Load Diff
+335
View File
@@ -0,0 +1,335 @@
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
[![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
> El repositorio de definiciones de TypeScript de alta calidad.
Vea también el sitio web [definitelytyped.org](http://definitelytyped.org), aunque la información en este README está más actualizada.
## ¿Qué son los `declaration files`?
Vea el [Manual de TypeScript](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).
## ¿Cómo los obtengo?
### npm
Este es el método preferido. Solo está disponible para usuarios TypeScript 2.0+. Por ejemplo:
```sh
npm install --save-dev @types/node
```
Los types deberían ser incluidos automaticamente 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".
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="" />`.
### Otros métodos
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
Tal vez debas añadir manualmente las [referencias](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
## ¿Cómo puedo contribuir?
¡DefinitelyTyped solo trabaja gracias a contribuidores como tú!
### Prueba
Antes de compartir tu mejora con el mundo, úselo usted mismo.
#### Prueba editando un paquete existente
Para agregar nuevas funciones puedes usar el [module augmentation](http://www.typescriptlang.org/docs/handbook/declaration-merging.html).
También puedes editar directamente los types en `node_modules/@types/foo/index.d.ts`, o copiarlos de ahí y seguir los pasos explicados a continuación.
#### Prueba un nuevo paquete
Añade a tu `tsconfig.json`:
```json
"baseUrl": "types",
"typeRoots": ["types"],
```
(También puedes usar `src/types`.)
Crea un `types/foo/index.d.ts` que contenga declaraciones del módulo "foo".
Ahora deberías poder importar desde `"foo"` a tu código y te enviara a un nuevo tipo de definición.
Entonces compila *y* ejecuta el código para asegurarte que el tipo de definición en realidad corresponde a lo que suceda en el momento de la ejecución.
Una vez que hayas probado tus definiciones con el código real, haz un [PR](#make-a-pull-request)
luego sigue las instrucciones para [editar un paquete existente](#edit-an-existing-package) o
[crear un nuevo paquete](#create-a-new-package).
### Haz un pull request
Una vez que hayas probado tu paquete, podrás compartirlo en DefinitelyTyped.
Primero, haz un [fork](https://guides.github.com/activities/forking/) en este repositorio, instala [node](https://nodejs.org/), y luego ejecuta la `npm install`.
#### Editar un paquete existente
* `cd types/my-package-to-edit`
* Haz cambios. Recuerda editar las pruebas.
* También puede que quieras añadirte 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
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* Si hay un `tslint.json`, ejecuta `npm run lint package-name`. De lo contrario, ejecuta `tsc` en el directorio del paquete.
Cuando hagas un PR para editar un paquete existente, `dt-bot` deberá @-mencionar a los autores previos.
Si no lo hace, puedes hacerlo en el comentario asociado con el PR.
#### Crear un nuevo paquete
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.
(Puedes usar `npm info foo` para verificar la existencia del paquete `foo`.)
Tu paquete debería tener esta estructura:
| Archivo | Propósito |
| --- | --- |
| index.d.ts | Este contiene los typings del paquete. |
| foo-tests.ts | Este contiene una muestra del código con el que se realiza la prueba de escritura. Este código *no* es ejecutable, pero sí es type-checked. |
| tsconfig.json | Este permite ejecutar `tsc` dentro del paquete. |
| tslint.json | Permite linting. |
Generalas ejecutando `npm install -g dts-gen` y `dts-gen --dt --name my-package-name --template module`.
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.
Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js).
#### Errores comunes
* 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.
* `interface Foo { new(): Foo; }`:
Este define el tipo de objeto que esten nuevos. Probablemente quieras `declare class Foo { constructor(); }`.
* `const Class: { new(): IClass; }`:
Prefiere usar una declaración de clase `class Class { constructor(); }` En vez de una nueva constante.
* `getMeAT<T>(): T`:
Si un tipo de parámetro no aparece en los tipos de ningún parámetro, no tienes una función genérica, solo tienes un afirmación del tipo disfrazado.
Prefiera utilizar una afirmación de tipo real, p.ej. `getMeAT() as number`.
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 }`.
* `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`.
#### Remover un paquete
Cuando un paquete [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) sus propios tipos, estos tipos deberán ser removidos de DefinitelyTyped para evitar que generen confusión.
Se puede remover ejecutando `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`.
- `typingsPackageName`: Este es el nombre del directorio que tienes que eliminar.
- `asOfVersion`: Un stub será publicado a `@types/foo` con esta versión. Debería ser más grande que cualquier versión publicada actualmente.
- `sourceRepoURL`: Esto debería señalar el repositorio que contiene los typings.
- `libraryName`: Un nombre descriptivo de la librería, p.ej. "Angular 2" en vez de "angular2". (Si es omitido, será idéntico a "typingsPackageName".)
Cualquier otro paquete en DefinitelyTyped que referencie el paquete eliminado deberá ser actualizado para referenciar los tipos bundled. para hacer esto, añade `package.json` con `"dependencies": { "foo": "x.y.z" }`.
Si un paquete nunca estuvo en DefinitelyTyped, no será necesario añadirlo a `notNeededPackages.json`.
#### Lint
Para realizar el lint a un paquete, solo añade `tslint.json` al paquete que contiene `{ "extends": "dtslint/dt.json" }`. Todos los paquetes nuevos deberán pasar por el proceso de linted.
Si el `tslint.json` deshabilita algunas reglas esto se debe a que aún no se ha acomodado. Por ejemplo:
```js
{
"extends": "dtslint/dt.json",
"rules": {
// This package uses the Function type, and it will take effort to fix.
"ban-types": false
}
}
```
(Para indicar que la regla lint realmente no es utilizada, usa `// tslint:disable rule-name` o mejor, `//tslint:disable-next-line rule-name`.)
Para afirmar que una expresión es de un tipo dado, utilice `$ExpectType`. Para afirmar que una expresión causa un error de compilación, utilice `$ExpectError`.
```js
// $ExpectType void
f(1);
// $ExpectError
f("one");
```
Para más detalles, vea el [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme.
Realiza una prueba ejecutando `npm run lint package-name` donde `package-name` es el nombre de tu paquete.
Este script utiliza [dtslint](https://github.com/Microsoft/dtslint).
## FAQ
#### ¿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).
#### 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.
#### Mi PR ha sido merged; ¿cuándo será actualizado el paquete de `@types` NPM?
Los paquetes NPM deberán ser actualizados en unas cuantas horas. Si ha pasado más de 24 horas, menciona a @RyanCavanaugh y/o a @andy-ms en el PR para investigar.
#### 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 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.
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.
#### Algunos paquetes no tienen `tslint.json`, y algunos `tsconfig.json` no contienen `"noImplicitAny": true`, `"noImplicitThis": true`, o `"strictNullChecks": true`.
Entonces están equivocados. Puedes ayudar enviando un pull request para arreglarlos.
#### Puedo pedir una definition?
Aquí están las [definiciones solicitadas actualmente](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest).
#### ¿Qué pasa con las type definitions para el DOM?
Si las types son parte de los estándares web, estas deberán ser contribuidas a [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) para que se hagan parte de la librería predeterminada `lib.dom.d.ts`.
#### Un paquete utiliza `export =`, pero prefiero utilizar las import predeterminadas. ¿Puedo cambiar `export =` por `export default`?
Si la import predeterminada trabaja en tu ambiente, considera hacer un cambio en la opción de compilación [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html) opción compilar.
No cambies la type definition si es preciso.
Para un paquete NPM, `export =` es exacto si `node -p 'require("foo")'` es la export, y `export default` es exacto si `node -p 'require("foo").default'` es el export.
#### Quiero usar las características de TypeScript 2.1 o superior.
Entonces deberás añadir un comentario a la última línea de la definición en el encabezado (despues de `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`.
#### Quiero añadir un DOM API que no está presente en TypeScript por defecto.
Esto puede pertenecer a [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). Vea las guías allí.
Si el estándar sigue siendo un borrador, este pertenece aquí.
Utilice un nombre que empiece con `dom-` e incluya un link al estándar como el "Project" con el link en el encabezado.
Cuando ya no sea un borrador, lo podremos eliminar desde DefinitelyType y hacer obsoleto el paquete `@types` asociado.
#### Quiero actualizar un paquete a una nueva versión principal
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.
Por ejemplo [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) se ve así:
```json
{
"compilerOptions": {
"baseUrl": "../../",
"typeRoots": ["../../"],
"paths": {
"history": [ "history/v2" ]
},
},
"files": [
"index.d.ts",
"history-tests.ts"
]
}
```
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.
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`.
#### ¿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.
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.
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.
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:
```json
{
"paths":{
"@foo/bar": ["foo__bar"]
}
}
```
#### El historial de archivos en GitHub parece incompleto.
GitHub no le hace [support](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) historial de archivos para archivos renombrados. Utilice [`git log --follow`](https://www.git-scm.com/docs/git-log) en su lugar.
#### Debería añadir un namespace que no exporte un módulo que utilice que utilice imports estilo ES6?
Algunos paquetes, como [chai-http](https://github.com/chaijs/chai-http), exportan una función.
importar este módulo con un ES6 style import de forma `import * as foo from "foo";` conduce al error:
> error ts2497: El módulo 'foo' se resuelve en una entidad que no es un módulo y no se puede importar mediante esta construcción
Este error puede ser suprimido al unir la declaración de una función con un namespace vacío del mismo nombre pero esta práctica no es recomendable.
Esto es un citado común [Respuestas de Stack Overflow](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) con respecto a este asunto.
Es más apropiado importar este módulo utilizando la sintaxis `import foo = require("foo");`, o utilizando una importación predeterminada como `import foo from "foo";` si usas la bandera `--allowSyntheticDefaultImports` si la ejecución de tu módulo soporta un esquema de interoperación para módulos no ECMAScript como tal.
## Licencia
Este proyecto es licenciado bajo la licencia MIT.
Los derechos de autor de cada archivo de definición son respectivos de cada contribuidor listado al comienzo de cada archivo de definición.
[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon)
+4 -3
View File
@@ -6,12 +6,12 @@
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)*
## What are declaration files?
See the [TypeScript handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).
## How do I get them?
### npm
@@ -256,7 +256,7 @@ When it graduates draft mode, we may remove it from DefinitelyTyped and deprecat
#### I want to update a package to a new major version
Before making your change, please create a new subfolder with the current version e.g. `v2`, and copy existing files to it. You will need to:
If you intend to continue updating the older version of the package, you may create a new subfolder with the current version e.g. `v2`, and copy existing files to it. If so, you will need to:
1. Update the relative paths in `tsconfig.json` as well as `tslint.json`.
2. Add path mapping rules to ensure that tests are running against the intended version.
@@ -279,7 +279,8 @@ For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi
}
```
Please note that unless upgrading something backwards-compatible like `node`, all packages depending of the updated package need a path mapping to it, as well as packages depending on *those*.
If there are other packages on DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this for packages depending on packages depending on the old version.
For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`;
transitively `react-router-bootstrap` (which depends on `react-router`) also adds a path mapping in its [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
+78
View File
@@ -6,6 +6,12 @@
"sourceRepoURL": "https://github.com/betterwaysystems/packer",
"asOfVersion": "1.1.3"
},
{
"libraryName": "Ably Realtime and Rest client library",
"typingsPackageName": "ably",
"sourceRepoURL": "https://www.ably.io/",
"asOfVersion": "1.0.0"
},
{
"libraryName": "ag-grid",
"typingsPackageName": "ag-grid",
@@ -18,6 +24,12 @@
"sourceRepoURL": "https://github.com/epoberezkin/ajv",
"asOfVersion": "1.0.0"
},
{
"libraryName": "angular-touchspin",
"typingsPackageName": "angular-touchspin",
"sourceRepoURL": "https://github.com/nkovacic/angular-touchspin",
"asOfVersion": "1.8.2"
},
{
"libraryName": "angular-ui-router-default",
"typingsPackageName": "angular-ui-router-default",
@@ -78,6 +90,12 @@
"sourceRepoURL": "https://github.com/AlexTeixeira/Askmethat-Rating",
"asOfVersion": "0.4.0"
},
{
"libraryName": "assertion-error",
"typingsPackageName": "assertion-error",
"sourceRepoURL": "https://github.com/chaijs/assertion-error",
"asOfVersion": "1.1.0"
},
{
"libraryName": "asyncblock",
"typingsPackageName": "asyncblock",
@@ -546,6 +564,12 @@
"sourceRepoURL": "http://arshaw.com/fullcalendar/",
"asOfVersion": "3.8.0"
},
{
"libraryName": "fuse",
"typingsPackageName": "fuse",
"sourceRepoURL": "https://github.com/krisk/Fuse",
"asOfVersion": "2.6.0"
},
{
"libraryName": "gaea-model",
"typingsPackageName": "gaea-model",
@@ -582,6 +606,12 @@
"sourceRepoURL": "https://github.com/panuhorsmalahti/gulp-tslint",
"asOfVersion": "4.2.0"
},
{
"libraryName": "gulp-typedoc",
"typingsPackageName": "gulp-typedoc",
"sourceRepoURL": "https://github.com/rogierschouten/gulp-typedoc",
"asOfVersion": "2.2.0"
},
{
"libraryName": "gulp-typescript",
"typingsPackageName": "gulp-typescript",
@@ -798,6 +828,12 @@
"sourceRepoURL": "https://linqjs.codeplex.com/",
"asOfVersion": "2.2.33"
},
{
"libraryName": "Linq4JS",
"typingsPackageName": "linq4js",
"sourceRepoURL": "https://github.com/morrisjdev/Linq4JS",
"asOfVersion": "2.1.8"
},
{
"libraryName": "LinqSharp",
"typingsPackageName": "linqsharp",
@@ -810,6 +846,12 @@
"sourceRepoURL": "https://github.com/localForage/localForage",
"asOfVersion": "0.0.34"
},
{
"libraryName": "localforage-cordovasqlitedriver",
"typingsPackageName": "localforage-cordovasqlitedriver",
"sourceRepoURL": "https://github.com/thgreasi/localForage-cordovaSQLiteDriver",
"asOfVersion": "1.5.0"
},
{
"libraryName": "lodash-decorators",
"typingsPackageName": "lodash-decorators",
@@ -912,6 +954,12 @@
"sourceRepoURL": "https://github.com/theoephraim/node-pg-migrate#readme",
"asOfVersion": "2.15.0"
},
{
"libraryName": "node-waves",
"typingsPackageName": "node-waves",
"sourceRepoURL": "http://fian.my.id/Waves",
"asOfVersion": "0.7.6"
},
{
"libraryName": "Normalizr",
"typingsPackageName": "normalizr",
@@ -1194,6 +1242,12 @@
"sourceRepoURL": "https://github.com/EnoF/rest-io",
"asOfVersion": "4.1.0"
},
{
"libraryName": "rollup",
"typingsPackageName": "rollup",
"sourceRepoURL": "https://github.com/rollup/rollup",
"asOfVersion": "0.54.0"
},
{
"libraryName": "route-recognizer",
"typingsPackageName": "route-recognizer",
@@ -1482,6 +1536,12 @@
"sourceRepoURL": "https://webgme.org",
"asOfVersion": "2.11.0"
},
{
"libraryName": "Webix UI",
"typingsPackageName": "webix",
"sourceRepoURL": "http://webix.com",
"asOfVersion": "5.1.1"
},
{
"libraryName": "wolfy87-eventemitter",
"typingsPackageName": "wolfy87-eventemitter",
@@ -1512,6 +1572,12 @@
"sourceRepoURL": "https://github.com/PeculiarVentures/xadesjs",
"asOfVersion": "2.0.2"
},
{
"libraryName": "xhr-mock",
"typingsPackageName": "xhr-mock",
"sourceRepoURL": "https://github.com/jameslnewell/xhr-mock#readme",
"asOfVersion": "2.0.0"
},
{
"libraryName": "xlsx",
"typingsPackageName": "xlsx",
@@ -1530,6 +1596,18 @@
"sourceRepoURL": "github.com/node-xmpp/node-xmpp/",
"asOfVersion": "1.2.0"
},
{
"libraryName": "xterm.js",
"typingsPackageName": "xterm",
"sourceRepoURL": "https://github.com/sourcelair/xterm.js/",
"asOfVersion": "3.0.0"
},
{
"libraryName": "yFiles for HTML",
"typingsPackageName": "yfiles",
"sourceRepoURL": "none",
"asOfVersion": "2.1.0"
},
{
"libraryName": "zetapush-js",
"typingsPackageName": "zetapush-js",
+1 -1
View File
@@ -5,7 +5,7 @@
import * as fs from 'fs';
import * as path from 'path';
const home = path.join(__dirname, '..');
const home = path.join(__dirname, "..", "types");
for (const dirName of fs.readdirSync(home)) {
if (dirName.startsWith(".") || dirName === "node_modules" || dirName === "scripts") {
-253
View File
@@ -1,253 +0,0 @@
import * as Ably from 'ably';
declare const console: { log(message: any): void };
const ApiKey = 'appId.keyId:secret';
const client = new Ably.Realtime(ApiKey);
const restClient = new Ably.Rest(ApiKey);
// Connection
// Successful connection:
client.connection.on('connected', () => {
// successful connection
});
// Failed connection:
client.connection.on('failed', () => {
// failed connection
});
// Subscribing to a channel
const channel = client.channels.get('test');
channel.subscribe(message => {
message.name; // 'greeting'
message.data; // 'Hello World!'
});
// Only certain events:
channel.subscribe('myEvent', message => {
message.name; // 'myEvent'
message.data; // 'myData'
});
// Publishing to a channel
// Publish a single message with name and data
channel.publish('greeting', 'Hello World!');
// Optionally, you can use a callback to be notified of success or failure
channel.publish('greeting', 'Hello World!', err => {
if (err) {
console.log('publish failed with error ' + err);
} else {
console.log('publish succeeded');
}
});
// Publish several messages at once
channel.publish([{name: 'greeting', data: 'Hello World!'}], () => { });
// Querying the History
channel.history((err, messagesPage) => {
messagesPage.items; // array of Message
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(nextPage => { nextPage; }); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards'}, (err, messagesPage) => {
console.log(messagesPage.items.length);
});
// Presence on a channel
// Getting presence:
channel.presence.get(presenceSet => {
presenceSet; // array of PresenceMessages
});
// Note that presence#get on a realtime channel does not return a PaginatedResult, as the library maintains a local copy of the presence set.
// Entering (and leaving) the presence set:
channel.presence.enter('my status', err => {
// now I am entered
});
channel.presence.update('new status', err => {
// my presence data is updated
});
channel.presence.leave(null, err => {
// I've left the presence set
});
channel.presence.enterClient('myClientId', 'status', err => {
});
// and similiarly, updateClient and leaveClient
// Querying the Presence History
channel.presence.history((err, messagesPage) => { // PaginatedResult
messagesPage.items; // array of PresenceMessage
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(nextPage => { }); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
channel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {});
// Symmetrical end-to-end encrypted payloads on a channel
// When a 128 bit or 256 bit key is provided to the library, the data attributes of all messages are encrypted and decrypted automatically using that key.
// The secret key is never transmitted to Ably. See https://www.ably.io/documentation/realtime/encryption
// Generate a random 256-bit key for demonstration purposes (in
// practice you need to create one and distribute it to clients yourselves)
Ably.Realtime.Crypto.generateRandomKey((err, key) => {
const channel = client.channels.get('channelName', { cipher: { key } });
channel.subscribe(message => {
message.name; // 'name is not encrypted'
message.data; // 'sensitive data is encrypted'
});
channel.publish('name is not encrypted', 'sensitive data is encrypted');
});
// You can also change the key on an existing channel using setOptions (which takes a callback which is called after the new encryption settings have taken effect):
channel.setOptions({cipher: {key: '<KEY>'}}, () => {
// New encryption settings are in effect
});
// Using the REST API
const restChannel = restClient.channels.get('test');
// Publishing to a channel
// Publish a single message with name and data
restChannel.publish('greeting', 'Hello World!');
// Optionally, you can use a callback to be notified of success or failure
restChannel.publish('greeting', 'Hello World!', err => {
if (err) {
console.log('publish failed with error ' + err);
} else {
console.log('publish succeeded');
}
});
// Publish several messages at once
restChannel.publish([{name: 'greeting', data: 'Hello World!'}], () => {});
// Querying the History
restChannel.history((err, messagesPage) => {
messagesPage; // PaginatedResult
messagesPage.items; // array of Message
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(nextPage => {}); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {});
// Presence on a channel
restChannel.presence.get((err, presencePage) => { // PaginatedResult
presencePage.items; // array of PresenceMessage
presencePage.items[0].data; // payload for first message
presencePage.items.length; // number of messages in the current page of members
presencePage.hasNext(); // true if there are further pages
presencePage.isLast(); // true if this page is the last page
presencePage.next(nextPage => {}); // retrieves the next page as PaginatedResult
});
// Querying the Presence History
restChannel.presence.history((err, messagesPage) => { // PaginatedResult
messagesPage.items; // array of PresenceMessage
messagesPage.items[0].data; // payload for first message
messagesPage.items.length; // number of messages in the current page of history
messagesPage.hasNext(); // true if there are further pages
messagesPage.isLast(); // true if this page is the last page
messagesPage.next(nextPage => { }); // retrieves the next page as PaginatedResult
});
// Can optionally take an options param, see https://www.ably.io/documentation/rest-api/#message-history
restChannel.history({ start: Date.now() - 10000, end: Date.now(), limit: 100, direction: 'forwards' }, (err, messagesPage) => {});
// Generate Token and Token Request
// See https://www.ably.io/documentation/general/authentication for an explanation of Ably's authentication mechanism.
// Requesting a token:
client.auth.requestToken((err, tokenDetails) => {
// tokenDetails is instance of TokenDetails
// see https://www.ably.io/documentation/rest/authentication/#token-details for its properties
// Now we have the token, we can send it to someone who can instantiate a client with it:
const clientUsingToken = new Ably.Realtime(tokenDetails.token);
});
// requestToken can take two optional params
// tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params
// authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options
client.auth.requestToken({}, {}, (err, tokenDetails) => { });
// Creating a token request (for example, on a server in response to a request by a client using the authCallback or authUrl mechanisms):
client.auth.createTokenRequest((err, tokenRequest) => {
// now send the tokenRequest back to the client, which will
// use it to request a token and connect to Ably
});
// createTokenRequest can take two optional params
// tokenParams: https://www.ably.io/documentation/rest/authentication/#token-params
// authOptions: https://www.ably.io/documentation/rest/authentication/#auth-options
client.auth.createTokenRequest({}, {}, (err, tokenRequest) => { });
// Fetching your application's stats
client.stats({ limit: 50 }, (err, statsPage) => { // statsPage as PaginatedResult
statsPage.items; // array of Stats
statsPage.items[0].inbound.rest.messages.count; // total messages published over REST
statsPage.items.length; // number of stats in the current page of history
statsPage.hasNext(); // true if there are wrther pages
statsPage.isLast(); // true if this page is the last page
statsPage.next((nextPage) => {}); // retrieves the next page as PaginatedResult
});
// Fetching the Ably service time
client.time({}, (err, time) => {}); // time is in ms since epoch
// Getting decoded Message objects from JSON
const messages = Ably.Realtime.Message.fromEncodedArray([{ id: 'foo' }]);
console.log(messages[0].id);
const message = Ably.Rest.Message.fromEncoded({ id: 'foo' });
console.log(message.id);
// Getting decoded PresenceMessage objects from JSON
const presenceMessages = Ably.Realtime.PresenceMessage.fromEncodedArray([{ id: 'foo' }]);
console.log(presenceMessages[0].action);
const presenceMessage = Ably.Rest.PresenceMessage.fromEncoded({ id: 'foo' });
console.log(presenceMessage.action);
-473
View File
@@ -1,473 +0,0 @@
// Type definitions for Ably Realtime and Rest client library 0.9
// Project: https://www.ably.io/
// Definitions by: Ably <https://github.com/ably>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export namespace ablyLib {
namespace ChannelState {
type INITIALIZED = 'initialized';
type ATTACHING = 'attaching';
type ATTACHED = "attached";
type DETACHING = "detaching";
type DETACHED = "detached";
type SUSPENDED = "suspended";
type FAILED = "failed";
}
type ChannelState = ChannelState.FAILED | ChannelState.INITIALIZED | ChannelState.SUSPENDED | ChannelState.ATTACHED | ChannelState.ATTACHING | ChannelState.DETACHED | ChannelState.DETACHING;
namespace ConnectionState {
type INITIALIZED = "initialized";
type CONNECTING = "connecting";
type CONNECTED = "connected";
type DISCONNECTED = "disconnected";
type SUSPENDED = "suspended";
type CLOSING = "closing";
type CLOSED = "closed";
type FAILED = "failed";
}
type ConnectionState = ConnectionState.INITIALIZED | ConnectionState.CONNECTED | ConnectionState.CONNECTING | ConnectionState.DISCONNECTED |
ConnectionState.SUSPENDED | ConnectionState.CLOSED | ConnectionState.CLOSING | ConnectionState.FAILED;
namespace ConnectionEvent {
type INITIALIZED = "initialized";
type CONNECTING = "connecting";
type CONNECTED = "connected";
type DISCONNECTED = "disconnected";
type SUSPENDED = "suspended";
type CLOSING = "closing";
type CLOSED = "closed";
type FAILED = "failed";
type UPDATE = "update";
}
type ConnectionEvent = ConnectionEvent.INITIALIZED | ConnectionEvent.CONNECTED | ConnectionEvent.CONNECTING | ConnectionEvent.DISCONNECTED |
ConnectionEvent.SUSPENDED | ConnectionEvent.CLOSED | ConnectionEvent.CLOSING | ConnectionEvent.FAILED | ConnectionEvent.UPDATE;
namespace PresenceAction {
type ABSENT = "absent";
type PRESENT = "present";
type ENTER = "enter";
type LEAVE = "leave";
type UPDATE = "update";
}
type PresenceAction = PresenceAction.ABSENT | PresenceAction.PRESENT | PresenceAction.ENTER | PresenceAction.LEAVE | PresenceAction.UPDATE;
namespace StatsIntervalGranularity {
type MINUTE = "minute";
type HOUR = "hour";
type DAY = "day";
type MONTH = "month";
}
type StatsIntervalGranularity = StatsIntervalGranularity.MINUTE | StatsIntervalGranularity.HOUR | StatsIntervalGranularity.DAY | StatsIntervalGranularity.MONTH;
namespace HTTPMethods {
type POST = "POST";
type GET = "GET";
}
type HTTPMethods = HTTPMethods.GET | HTTPMethods.POST;
// Interfaces
interface ClientOptions extends AuthOptions {
/**
* When true will automatically connect to Ably when library is instanced. This is true by default
*/
autoConnect?: boolean;
/**
* Optional clientId that can be used to specify the identity for this client. In most cases
* it is preferable to instead specift a clientId in the token issued to this client.
*/
clientId?: string;
defaultTokenParams?: TokenParams;
/**
* When true, messages published on channels by this client will be echoed back to this client.
* This is true by default
*/
echoMessages?: boolean;
/**
* Use this only if you have been provided a dedicated environment by Ably
*/
environment?: string;
/**
* Logger configuration
*/
log?: LogInfo;
port?: number;
/**
* When true, messages will be queued whilst the connection is disconnected. True by default.
*/
queueMessages?: boolean;
restHost?: string;
realtimeHost?: string;
fallbackHosts?: string[];
/**
* Can be used to explicitly recover a connection.
* See https://www.ably.io/documentation/realtime/connection#connection-state-recovery
*/
recover?: standardCallback | string;
/**
* Use a non-secure connection connection. By default, a TLS connection is used to connect to Ably
*/
tls?: boolean;
tlsPort?: number;
/**
* When true, the more efficient MsgPack binary encoding is used.
* When false, JSON text encoding is used.
*/
useBinaryProtocol?: boolean;
}
interface AuthOptions {
/**
* A function which is called when a new token is required.
* The role of the callback is to either generate a signed TokenRequest which may then be submitted automatically
* by the library to the Ably REST API requestToken; or to provide a valid token in as a TokenDetails object.
*/
authCallback?(data: TokenParams, callback: (error: ErrorInfo | string, tokenRequestOrDetails: TokenDetails | TokenRequest | string) => void): void;
authHeaders?: { [index: string]: string };
authMethod?: HTTPMethods;
authParams?: { [index: string]: string };
/**
* A URL that the library may use to obtain a token string (in plain text format), or a signed TokenRequest or TokenDetails (in JSON format).
*/
authUrl?: string;
key?: string;
queryTime?: boolean;
token?: TokenDetails | string;
tokenDetails?: TokenDetails;
useTokenAuth?: boolean;
}
interface TokenParams {
capability?: string;
clientId?: string;
nonce?: string;
timestamp?: number;
ttl?: number;
}
interface CipherParams {
algorithm: string;
key: any;
keyLength: number;
mode: string;
}
interface ErrorInfo {
code: number;
message: string;
statusCode: number;
}
interface StatsMessageCount {
count: number;
data: number;
}
interface StatsMessageTypes {
all: StatsMessageCount;
messages: StatsMessageCount;
presence: StatsMessageCount;
}
interface StatsRequestCount {
failed: number;
refused: number;
succeeded: number;
}
interface StatsResourceCount {
mean: number;
min: number;
opened: number;
peak: number;
refused: number;
}
interface StatsConnectionTypes {
all: StatsResourceCount;
plain: StatsResourceCount;
tls: StatsResourceCount;
}
interface StatsMessageTraffic {
all: StatsMessageTypes;
realtime: StatsMessageTypes;
rest: StatsMessageTypes;
webhook: StatsMessageTypes;
}
interface TokenDetails {
capability: string;
clientId?: string;
expires: number;
issued: number;
token: string;
}
interface TokenRequest {
capability: string;
clientId?: string;
keyName: string;
mac: string;
nonce: string;
timestamp: number;
ttl?: number;
}
interface ChannelOptions {
cipher: any;
}
interface RestPresenceHistoryParams {
start?: number;
end?: number;
direction?: string;
limit?: number;
}
interface RestPresenceParams {
limit?: number;
clientId?: string;
connectionId?: string;
}
interface RealtimePresenceParams {
waitForSync?: boolean;
clientId?: string;
connectionId?: string;
}
interface RealtimePresenceHistoryParams {
start?: number;
end?: number;
direction?: string;
limit?: number;
untilAttach?: boolean;
}
interface LogInfo {
/**
* A number controlling the verbosity of the output. Valid values are: 0 (no logs), 1 (errors only),
* 2 (errors plus connection and channel state changes), 3 (high-level debug output), and 4 (full debug output).
*/
level?: number;
/**
* A function to handle each line of log output. If handler is not specified, console.log is used.
*/
handler?(...args: any[]): void;
}
interface ChannelEvent {
state: ChannelState;
}
interface ChannelStateChange {
current: ChannelState;
previous: ChannelState;
reason?: ErrorInfo;
resumed: boolean;
}
interface ConnectionStateChange {
current: ConnectionState;
previous: ConnectionState;
reason?: ErrorInfo;
retryIn?: number;
}
// Common Listeners
type paginatedResultCallback<T> = (error: ErrorInfo, results: PaginatedResult<T>) => void;
type standardCallback = (error: ErrorInfo, results: any) => void;
type messageCallback<T> = (message: T) => void;
type errorCallback = (error: ErrorInfo) => void;
type channelEventCallback = (channelEvent: ChannelEvent, changeStateChange: ChannelStateChange) => void;
type connectionEventCallback = (connectionEvent: ConnectionEvent, connectionStateChange: ConnectionStateChange) => void;
type timeCallback = (error: ErrorInfo, time: number) => void;
type realtimePresenceGetCallback = (error: ErrorInfo, messages: PresenceMessage[]) => void;
type tokenDetailsCallback = (error: ErrorInfo, Results: TokenDetails) => void;
type tokenRequestCallback = (error: ErrorInfo, Results: TokenRequest) => void;
type fromEncoded<T> = (JsonObject: any, channelOptions?: ChannelOptions) => T;
type fromEncodedArray<T> = (JsonArray: any[], channelOptions?: ChannelOptions) => T[];
// Internal Classes
class EventEmitter<T> {
on: (eventOrCallback: string | T, callback?: T) => void;
once: (eventOrCallback: string | T, callback?: T) => void;
off: (eventOrCallback?: string | T, callback?: T) => void;
}
// Classes
class Auth {
clientId: string;
authorize: (tokenParams?: TokenParams | tokenDetailsCallback, authOptions?: AuthOptions | tokenDetailsCallback, callback?: tokenDetailsCallback) => void;
createTokenRequest: (tokenParams?: TokenParams | tokenRequestCallback, authOptions?: AuthOptions | tokenRequestCallback, callback?: tokenRequestCallback) => void;
requestToken: (TokenParams?: TokenParams | tokenDetailsCallback, authOptions?: AuthOptions | tokenDetailsCallback, callback?: tokenDetailsCallback) => void;
}
class Presence {
get: (params: RestPresenceParams | paginatedResultCallback<PresenceMessage>, callback?: paginatedResultCallback<PresenceMessage>) => void;
history: (params: RestPresenceHistoryParams | paginatedResultCallback<PresenceMessage>, callback?: paginatedResultCallback<PresenceMessage>) => void;
}
class RealtimePresence {
syncComplete: () => boolean;
get: (Params: realtimePresenceGetCallback | RealtimePresenceParams, callback?: realtimePresenceGetCallback) => void;
history: (ParamsOrCallback: RealtimePresenceHistoryParams | paginatedResultCallback<PresenceMessage>, callback?: paginatedResultCallback<PresenceMessage>) => void;
subscribe: (presenceOrCallback: PresenceAction | messageCallback<PresenceMessage>, listener?: messageCallback<PresenceMessage>) => void;
unsubscribe: (presence?: PresenceAction, listener?: messageCallback<PresenceMessage>) => void;
enter: (data?: errorCallback | any, callback?: errorCallback) => void;
update: (data?: errorCallback | any, callback?: errorCallback) => void;
leave: (data?: errorCallback | any, callback?: errorCallback) => void;
enterClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void;
updateClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void;
leaveClient: (clientId: string, data?: errorCallback | any, callback?: errorCallback) => void;
}
class Channel {
name: string;
presence: Presence;
history: (paramsOrCallback?: RestPresenceHistoryParams | paginatedResultCallback<Message>, callback?: paginatedResultCallback<Message>) => void;
publish: (messagesOrName: any, messagedataOrCallback?: errorCallback | any, callback?: errorCallback) => void;
}
class RealtimeChannel extends EventEmitter<channelEventCallback> {
name: string;
errorReason: ErrorInfo;
state: ChannelState;
presence: RealtimePresence;
attach: (callback?: standardCallback) => void;
detach: (callback?: standardCallback) => void;
history: (paramsOrCallback?: RealtimePresenceHistoryParams | paginatedResultCallback<Message>, callback?: paginatedResultCallback<Message>) => void;
subscribe: (eventOrCallback: messageCallback<Message> | string, listener?: messageCallback<Message>) => void;
unsubscribe: (eventOrCallback?: messageCallback<Message> | string, listener?: messageCallback<Message>) => void;
publish: (messagesOrName: any, messageDataOrCallback?: errorCallback | any, callback?: errorCallback) => void;
setOptions: (options: any, callback?: errorCallback) => void;
}
class Channels<T> {
get: (name: string, channelOptions?: ChannelOptions) => T;
release: (name: string) => void;
}
class Message {
constructor();
static fromEncoded: fromEncoded<Message>;
static fromEncodedArray: fromEncodedArray<Message>;
clientId: string;
connectionId: string;
data: any;
encoding: string;
extras: any;
id: string;
name: string;
timestamp: number;
}
interface MessageStatic {
fromEncoded: fromEncoded<Message>;
fromEncodedArray: fromEncodedArray<Message>;
}
class PresenceMessage {
constructor();
static fromEncoded: fromEncoded<PresenceMessage>;
static fromEncodedArray: fromEncodedArray<PresenceMessage>;
action: PresenceAction;
clientId: string;
connectionId: string;
data: any;
encoding: string;
id: string;
timestamp: number;
}
interface PresenceMessageStatic {
fromEncoded: fromEncoded<PresenceMessage>;
fromEncodedArray: fromEncodedArray<PresenceMessage>;
}
interface Crypto {
generateRandomKey(callback: (error: ErrorInfo, key: string) => void): void;
}
class Connection extends EventEmitter<connectionEventCallback> {
errorReason: ErrorInfo;
id: string;
key: string;
recoveryKey: string;
serial: number;
state: ConnectionState;
close: () => void;
connect: () => void;
ping: (callback?: (error: ErrorInfo, responseTime: number) => void) => void;
}
class Stats {
all: StatsMessageTypes;
apiRequests: StatsRequestCount;
channels: StatsResourceCount;
connections: StatsConnectionTypes;
inbound: StatsMessageTraffic;
intervalId: string;
outbound: StatsMessageTraffic;
persisted: StatsMessageTypes;
tokenRequests: StatsRequestCount;
}
class PaginatedResult<T> {
items: T[];
first: (results: paginatedResultCallback<T>) => void;
next: (results: paginatedResultCallback<T>) => void;
current: (results: paginatedResultCallback<T>) => void;
hasNext: () => boolean;
isLast: () => boolean;
}
class HttpPaginatedResponse extends PaginatedResult<any> {
items: string[];
statusCode: number;
success: boolean;
errorCode: number;
errorMessage: string;
headers: any;
}
}
export class Rest {
constructor(options: ablyLib.ClientOptions | string);
static Crypto: ablyLib.Crypto;
static Message: ablyLib.MessageStatic;
static PresenceMessage: ablyLib.PresenceMessageStatic;
auth: ablyLib.Auth;
channels: ablyLib.Channels<ablyLib.Channel>;
request: (method: string, path: string, params?: any, body?: any[] | any, headers?: any, callback?: (error: ablyLib.ErrorInfo, response: ablyLib.HttpPaginatedResponse) => void) => void;
stats: (paramsOrCallback?: ablyLib.paginatedResultCallback<ablyLib.Stats> | any, callback?: ablyLib.paginatedResultCallback<ablyLib.Stats>) => void;
time: (paramsOrCallback?: ablyLib.timeCallback | any, callback?: ablyLib.timeCallback) => void;
}
export class Realtime {
constructor(options: ablyLib.ClientOptions | string);
static Crypto: ablyLib.Crypto;
static Message: ablyLib.MessageStatic;
static PresenceMessage: ablyLib.PresenceMessageStatic;
auth: ablyLib.Auth;
channels: ablyLib.Channels<ablyLib.RealtimeChannel>;
clientId: string;
connection: ablyLib.Connection;
request: (method: string, path: string, params?: any, body?: any[] | any, headers?: any, callback?: (error: ablyLib.ErrorInfo, response: ablyLib.HttpPaginatedResponse) => void) => void;
stats: (paramsOrCallback?: ablyLib.paginatedResultCallback<ablyLib.Stats> | any, callback?: ablyLib.paginatedResultCallback<ablyLib.Stats>) => void;
close: () => void;
connect: () => void;
time: (paramsOrCallback?: ablyLib.timeCallback | any, callback?: ablyLib.timeCallback) => void;
}
+42 -3
View File
@@ -12,36 +12,75 @@ declare namespace accepts {
interface Accepts {
/**
* Return the first accepted charset. If nothing in `charsets` is accepted, then `false` is returned.
* If no charsets are supplied, all accepted charsets are returned, in the order of the client's preference
* (most preferred first).
*/
charset(): string[];
charset(charsets: string[]): string | false;
charset(...charsets: string[]): string | false;
/**
* Return the charsets that the request accepts, in the order of the client's preference (most preferred first).
* Return the first accepted charset. If nothing in `charsets` is accepted, then `false` is returned.
* If no charsets are supplied, all accepted charsets are returned, in the order of the client's preference
* (most preferred first).
*/
charsets(): string[];
charsets(charsets: string[]): string | false;
charsets(...charsets: string[]): string | false;
/**
* Return the first accepted encoding. If nothing in `encodings` is accepted, then `false` is returned.
* If no encodings are supplied, all accepted encodings are returned, in the order of the client's preference
* (most preferred first).
*/
encoding(): string[];
encoding(encodings: string[]): string | false;
encoding(...encodings: string[]): string | false;
/**
* Return the encodings that the request accepts, in the order of the client's preference (most preferred first).
* Return the first accepted encoding. If nothing in `encodings` is accepted, then `false` is returned.
* If no encodings are supplied, all accepted encodings are returned, in the order of the client's preference
* (most preferred first).
*/
encodings(): string[];
encodings(encodings: string[]): string | false;
encodings(...encodings: string[]): string | false;
/**
* Return the first accepted language. If nothing in `languages` is accepted, then `false` is returned.
* If no languaes are supplied, all accepted languages are returned, in the order of the client's preference
* (most preferred first).
*/
language(): string[];
language(languages: string[]): string | false;
language(...languages: string[]): string | false;
/**
* Return the languages that the request accepts, in the order of the client's preference (most preferred first).
* Return the first accepted language. If nothing in `languages` is accepted, then `false` is returned.
* If no languaes are supplied, all accepted languages are returned, in the order of the client's preference
* (most preferred first).
*/
languages(): string[];
languages(languages: string[]): string | false;
languages(...languages: string[]): string | false;
/**
* Return the first accepted language. If nothing in `languages` is accepted, then `false` is returned.
* If no languaes are supplied, all accepted languages are returned, in the order of the client's preference
* (most preferred first).
*/
lang(): string[];
lang(languages: string[]): string | false;
lang(...languages: string[]): string | false;
/**
* Return the first accepted language. If nothing in `languages` is accepted, then `false` is returned.
* If no languaes are supplied, all accepted languages are returned, in the order of the client's preference
* (most preferred first).
*/
langs(): string[];
langs(languages: string[]): string | false;
langs(...languages: string[]): string | false;
/**
* Return the first accepted type (and it is returned as the same text as what appears in the `types` array). If nothing in `types` is accepted, then `false` is returned.
@@ -1,6 +1,6 @@
import { ActionsSdkApp, ActionsSdkAppOptions, DialogflowApp, DialogflowAppOptions, AssistantApp,
Responses, Transactions } from 'actions-on-google';
import * as express from 'express';
import express = require('express');
function testActionsSdk(request: express.Request, response: express.Response) {
const app = new ActionsSdkApp({request, response});
+12 -2
View File
@@ -263,8 +263,8 @@ export interface UserName {
* User's permissioned device location.
*/
export interface DeviceLocation {
/** {latitude, longitude}. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */
coordinates: object;
/** Coordinates: {latitude, longitude}. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */
coordinates: Coordinates;
/** Full, formatted street address. Requested with SupportedPermissions.DEVICE_PRECISE_LOCATION. */
address: string;
/** Zip code. Requested with SupportedPermissions.DEVICE_COARSE_LOCATION. */
@@ -273,6 +273,16 @@ export interface DeviceLocation {
city: string;
}
/**
* Coordinates containing latitude and longitude
*/
export interface Coordinates {
/** Latitude coordinate. */
latitude: number;
/** Longitude coordinate. */
longitude: number;
}
/**
* User object.
*/
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for actions-on-google 1.7
// Type definitions for actions-on-google 1.8
// Project: https://github.com/actions-on-google/actions-on-google-nodejs
// Definitions by: Joel Hegg <https://github.com/joelhegg>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+3 -1
View File
@@ -20,7 +20,9 @@ export enum ImageDisplays {
*/
WHITE,
/**
* Image is centered and resized so the image fits perfectly in the container.
* Image is scaled such that the image width matches the container width. This may crop the top
* and bottom of the image if the scaled image height is greater than the container height. This
* is similar to "Zoom Mode" on a widescreen TV when playing a 4:3 video.
*/
CROPPED
}
+6 -1
View File
@@ -594,7 +594,12 @@ export namespace TransactionValues {
/**
* Use external payment gateway tokenization API to tokenize selected payment method.
*/
PAYMENT_GATEWAY
PAYMENT_GATEWAY,
/**
* Allows payment service to pass public key for payment info encryption and receive encrypted
* response.
*/
DIRECT
}
}
+1 -1
View File
@@ -25,4 +25,4 @@
"transactions.d.ts",
"actions-on-google-tests.ts"
]
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}
+6 -1
View File
@@ -1 +1,6 @@
{ "extends": "dtslint/dt.json" }
{
"extends": "dtslint/dt.json",
"rules": {
"no-const-enum": false
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}
@@ -0,0 +1,44 @@
const collectionToArray = <T>(col: any) => { // tslint:disable-line no-unnecessary-generics
const results: T[] = [];
const enumerator = new Enumerator<T>(col);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
results.push(enumerator.item());
enumerator.moveNext();
}
return results;
};
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787925(v=vs.85).aspx
(() => {
const enumUsers = (label: string) => {
const volume = new ActiveXObject('Microsoft.DiskQuota');
volume.Initialize(label, true);
collectionToArray<DiskQuotaTypeLibrary.DIDiskQuotaUser>(volume).forEach(x => {
// Use the QuotaUser object to retrieve or set one or more of the user's disk quota properties
});
};
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787916(v=vs.85).aspx
(() => {
const volume = new ActiveXObject('Microsoft.DiskQuota');
volume.Initialize('MYDISK', true);
ActiveXObject.on(volume, 'OnUserNameChanged', ['pUser'], p => {
// Code to handle the event.
});
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787904(v=vs.85).aspx
(() => {
const dqc = new ActiveXObject('Microsoft.DiskQuota');
dqc.Initialize('MYDISK', true);
const findName = (name: string) => {
try {
return dqc.FindUser(name);
} catch { }
try {
return dqc.FindUser(dqc.TranslateLogonNameToSID(name));
} catch { }
};
})();
+152
View File
@@ -0,0 +1,152 @@
// Type definitions for DiskQuotaTypeLibrary 1.0
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773938(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.5
declare namespace DiskQuotaTypeLibrary {
// tslint:disable-next-line no-const-enum
const enum AccountStatusConstants {
dqAcctDeleted = 2,
dqAcctInvalid = 3,
dqAcctResolved = 0,
dqAcctUnavailable = 1,
dqAcctUnknown = 4,
dqAcctUnresolved = 5,
}
// tslint:disable-next-line no-const-enum
const enum QuotaStateConstants {
dqStateDisable = 0,
dqStateEnforce = 2,
dqStateTrack = 1,
}
// tslint:disable-next-line no-const-enum
const enum UserNameResolutionConstants {
dqResolveAsync = 2,
dqResolveNone = 0,
dqResolveSync = 1,
}
/** Automation interface for DiskQuotaUser */
class DIDiskQuotaUser {
private 'DiskQuotaTypeLibrary.DIDiskQuotaUser_typekey': DIDiskQuotaUser;
private constructor();
/** Name of user's account container */
readonly AccountContainerName: string;
/** Status of user's account */
readonly AccountStatus: AccountStatusConstants;
/** User's display name */
readonly DisplayName: string;
/** Unique ID number */
readonly ID: number;
/** Invalidate data cached in user object */
Invalidate(): void;
/** User's logon account name */
readonly LogonName: string;
/** User's quota limit (bytes) */
QuotaLimit: number;
/** User's quota limit (text) */
readonly QuotaLimitText: string;
/** User's quota warning threshold (bytes) */
QuotaThreshold: number;
/** User's quota warning threshold (text) */
readonly QuotaThresholdText: string;
/** Quota charged to user (bytes) */
readonly QuotaUsed: number;
/** Quota charged to user (text) */
readonly QuotaUsedText: string;
}
/** Microsoft Disk Quota */
class DiskQuotaControl {
private 'DiskQuotaTypeLibrary.DiskQuotaControl_typekey': DiskQuotaControl;
private constructor();
/** Add a user quota entry by Name */
AddUser(LogonName: string): DIDiskQuotaUser;
/** Default quota limit applied to new volume users (byte value) */
DefaultQuotaLimit: number;
/** Default quota limit applied to new volume users (text string) */
readonly DefaultQuotaLimitText: string;
/** Default warning threshold applied to new volume users (byte value) */
DefaultQuotaThreshold: number;
/** Default warning threshold applied to new volume users (text string) */
readonly DefaultQuotaThresholdText: string;
/** Delete a user quota entry */
DeleteUser(pUser: DIDiskQuotaUser): void;
/** Find a user quota entry by Name */
FindUser(LogonName: string): DIDiskQuotaUser;
/** Promote a user quota entry to the head of the name resolution queue */
GiveUserNameResolutionPriority(pUser: DIDiskQuotaUser): void;
/** Initialize the quota control object for a specified volume */
Initialize(path: string, bReadWrite: boolean): void;
/** Invalidate the cache of user name information */
InvalidateSidNameCache(): void;
/** Write event log entry when user exceeds quota limit */
LogQuotaLimit: boolean;
/** Write event log entry when user exceeds quota warning threshold */
LogQuotaThreshold: boolean;
/** Indicates if quota information is out of date */
readonly QuotaFileIncomplete: boolean;
/** Indicates if quota information is being rebuilt */
readonly QuotaFileRebuilding: boolean;
/** State of the volume's disk quota system */
QuotaState: QuotaStateConstants;
/** Terminate the user name resolution thread */
ShutdownNameResolution(): void;
/** Translates a user logon name to a security ID */
TranslateLogonNameToSID(LogonName: string): string;
/** Control the resolution of user Security IDs to user Names */
UserNameResolution: UserNameResolutionConstants;
}
}
interface ActiveXObject {
on(
obj: DiskQuotaTypeLibrary.DiskQuotaControl, event: 'OnUserNameChanged', argNames: ['pUser'], handler: (
this: DiskQuotaTypeLibrary.DiskQuotaControl, parameter: {readonly pUser: DiskQuotaTypeLibrary.DIDiskQuotaUser}) => void): void;
new<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
}
interface ActiveXObjectNameMap {
'Microsoft.DiskQuota': DiskQuotaTypeLibrary.DiskQuotaControl;
}
interface EnumeratorConstructor {
new(col: DiskQuotaTypeLibrary.DiskQuotaControl): Enumerator<DiskQuotaTypeLibrary.DIDiskQuotaUser>;
}
interface SafeArray<T = any> {
_brand: SafeArray<T>;
}
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-diskquota-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+349 -112
View File
File diff suppressed because it is too large Load Diff
+2 -5
View File
@@ -1,6 +1,3 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
}
}
"extends": "dtslint/dt.json"
}
@@ -0,0 +1,729 @@
/// <reference types="activex-iwshruntimelibrary" />
const collectionToArray = <T>(col: { Item(index: any): T } | SafeArray<T>) => {
const results: T[] = [];
const enumerator = new Enumerator<T>(col);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
results.push(enumerator.item());
enumerator.moveNext();
}
return results;
};
const toSafeArray = <T>(...items: T[]): SafeArray<T> => {
const dict = new ActiveXObject('Scripting.Dictionary');
items.forEach((x, index) => dict.Add(index, x));
return dict.Items() as SafeArray<T>;
};
const VB = {
InputBox: (prompt: string): string => ''
};
const getServer = () => {
const server = new ActiveXObject('FaxComEx.FaxServer');
server.Connect('');
return server;
};
{
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693376(v=vs.85).aspx
const server = new ActiveXObject('FaxComEx.FaxServer');
const document = new ActiveXObject('FaxComEx.FaxDocument');
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692919(v=vs.85).aspx
server.Connect('');
server.Connect('computername');
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693502(v=vs.85).aspx
{
const getInitializedDevice = () => {
const ret = getServer().GetDevices().ItemById(1);
ret.ReceiveMode = FAXCOMEXLib.FAX_DEVICE_RECEIVE_MODE_ENUM.fdrmAUTO_ANSWER;
ret.RingsBeforeAnswer = 5;
ret.SendEnabled = true;
return ret;
};
// saving configuration
let device = getInitializedDevice();
device.Save();
// abandoning changes to configuration, using the Refresh method
device = getInitializedDevice();
device.Refresh();
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693502(v=vs.85).aspx
{
const incomingJob = getServer().Folders.IncomingQueue.GetJobs().Item(1);
incomingJob.Refresh();
const currentPage = incomingJob.CurrentPage;
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692922(v=vs.85).aspx
{
const server = getServer();
WScript.Echo(`Server information:
API Version: ${server.APIVersion}
Debug: ${server.Debug}
Build and version: ${server.MajorBuild}.${server.MinorBuild}.${server.MajorVersion}.${server.MinorVersion}
Server name: ${server.ServerName}`);
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693455(v=vs.85).aspx
{
const activity = getServer().Activity;
activity.Refresh();
WScript.Echo(`
${activity.IncomingMessages} incoming messages
${activity.OutgoingMessages} outgoing messages
${activity.RoutingMessages} routing messages
${activity.QueuedMessages} queued messages`);
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693400(v=vs.85).aspx
{
const device = getServer().GetDevices().Item(1);
device.CSID = 'Accounts payable';
device.Description = 'Primary fax device';
device.ReceiveMode = FAXCOMEXLib.FAX_DEVICE_RECEIVE_MODE_ENUM.fdrmAUTO_ANSWER;
device.RingsBeforeAnswer = 5;
device.SendEnabled = true;
device.TSID = 'Accounts payable';
device.Save();
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692985(v=vs.85).aspx
{
const devices = getServer().GetDevices();
WScript.Echo(`This server has ${devices.Count} fax devices`);
for (let i = 1; i <= devices.Count; i++) {
WScript.Echo(`Device ID for device number ${i} is ${devices.Item(i).Id}`);
}
collectionToArray(devices).forEach(device => {
device.Refresh();
WScript.Echo(`
Device name: ${device.DeviceName}
Provider unique name: ${device.ProviderUniqueName}
Powered off: ${device.PoweredOff}
Receiving now: ${device.ReceivingNow}
Ringing now: ${device.RingingNow}
Sending now: ${device.SendingNow}`);
const routingMethods = new VBArray(device.UsedRoutingMethods).toArray();
routingMethods.forEach((guid, index) => {
WScript.Echo(`Method number ${index} = ${guid}`);
});
device.UseRoutingMethod(routingMethods[0], false);
device.Save();
});
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693486(v=vs.85).aspx
{
const outputRuleInfo = (rule: FAXCOMEXLib.FaxOutboundRoutingRule, index?: number) => {
WScript.Echo(`
Outbound routing rule number: ${index || 'unknown'}
Area code: ${rule.AreaCode}
Country/region code: ${rule.CountryCode}
Device ID: ${rule.DeviceId}
Group name: ${rule.GroupName}
Status: ${rule.Status}
Is device used: ${rule.UseDevice}`
.trim());
};
const server = getServer();
const device = server.GetDevices().Item(1);
const id = device.Id;
const rules = server.OutboundRouting.GetRules();
const outboundRoutingRules = server.OutboundRouting.GetRules();
WScript.Echo(`There are ${outboundRoutingRules.Count} outbound routing rules on this server.`);
collectionToArray(outboundRoutingRules).forEach((rule, index) => {
rule.Refresh();
outputRuleInfo(rule, index);
if (!rule.UseDevice) { return; }
if (VB.InputBox('Do you want to change the device for this rule (Y/N)?') === 'Y') {
const newDeviceID = parseInt(VB.InputBox('Enter new device ID'), 10);
rule.DeviceId = newDeviceID;
rule.Save();
}
});
const msg = `
Do you want to:
1) display an item based on its country/region and area code,
2) remove an item based on its country/region and area code,
3) remove an item based on its item number, or
4) add a rule?
Input 1, 2, 3, 4, or 0 to exit
`.trim();
const result = parseInt(VB.InputBox(msg), 10);
let countryCode: number;
let areaCode: number;
let itemNumber: number;
let rule: FAXCOMEXLib.FaxOutboundRoutingRule;
switch (result) {
case 1:
countryCode = parseInt(VB.InputBox('Enter the country/region code'), 10);
areaCode = parseInt(VB.InputBox('Enter the area code'), 10);
rule = outboundRoutingRules.ItemByCountryAndArea(countryCode, areaCode);
outputRuleInfo(rule);
break;
case 2:
countryCode = parseInt(VB.InputBox('Enter the country/region code'), 10);
areaCode = parseInt(VB.InputBox('Enter the area code'), 10);
outboundRoutingRules.RemoveByCountryAndArea(countryCode, areaCode);
break;
case 3:
itemNumber = parseInt(VB.InputBox('Enter the item number'), 10);
outboundRoutingRules.Remove(itemNumber);
break;
case 4:
countryCode = parseInt(VB.InputBox('Enter the country/region code'), 10);
areaCode = parseInt(VB.InputBox('Enter the area code'), 10);
rule = outboundRoutingRules.Add(countryCode, areaCode, true, '', id);
break;
}
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693408(v=vs.85).aspx
{
const server = getServer();
const outboundRouting = server.OutboundRouting;
const outboundRoutingGroups = outboundRouting.GetGroups();
const groupName = VB.InputBox('Provide a name for the outbound routing group');
const outboundRoutingGroup = outboundRoutingGroups.Add(groupName);
const devices = collectionToArray(server.GetDevices());
// add the devices to the routing group
devices.forEach(device => outboundRoutingGroup.DeviceIds.Add(device.Id));
// move the last device to the top of the order
outboundRoutingGroup.DeviceIds.SetOrder(devices[devices.length - 1].Id, 1);
// display the number of devices, and the device ID of the first device,to confirm its location in the order
const msg = `
Number of devices: ${outboundRoutingGroup.DeviceIds.Count}
ID of first device: ${outboundRoutingGroup.DeviceIds.Item(1)}
`.trim();
WScript.Echo(msg);
// remove the first device
outboundRoutingGroup.DeviceIds.Remove(1);
WScript.Echo(`There are now ${outboundRoutingGroups.Count} routing groups on the server`);
collectionToArray(outboundRoutingGroups).forEach((routingGroup, index) => {
const msg = `
Routing group number: ${index}
Outbound routing group name: ${routingGroup.Name}
Device status: ${routingGroup.Status}
`.trim();
});
// allow user to remove a routing group
if (VB.InputBox('Do you want to remove a routing group (Y/N)?') === 'Y') {
const itemNumber = VB.InputBox('Enter the item number for the group you want to remove');
outboundRoutingGroups.Remove(itemNumber);
}
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa964960(v=vs.85).aspx
{
const accountSet = getServer().FaxAccountSet;
const accounts = collectionToArray(accountSet.GetAccounts());
WScript.Echo(`Number of accounts: ${accounts.length}`);
accounts.forEach(account => WScript.Echo(account.AccountName));
const accountName = VB.InputBox('Enter an account name');
accountSet.AddAccount(accountName);
accountSet.RemoveAccount(accountName);
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692952(v=vs.85).aspx
{
const incomingJobs = collectionToArray(getServer().Folders.IncomingQueue.GetJobs());
WScript.Echo(`There are ${incomingJobs.length} jobs in the incoming queue.`);
const n = parseInt(VB.InputBox('Input the number of a job for which you want information'), 10);
const job = incomingJobs[n - 1];
WScript.Echo(`
Available operations: ${job.AvailableOperations}
Caller ID: ${job.CallerId}
CSID: ${job.CSID}
Current page: ${job.CurrentPage}
Device ID: ${job.DeviceId}
Extended status: ${job.ExtendedStatus}
Extended status code: ${job.ExtendedStatusCode}
Job ID: ${job.Id}
Job type: ${job.JobType}
Retries: ${job.Retries}
Routing information: ${job.RoutingInformation}
Size: ${job.Size}
Status: ${job.Status}
Transmission start: ${new Date(job.TransmissionStart)}
Transmission end: ${new Date(job.TransmissionEnd)}
TSID: ${job.TSID}
`.trim());
if (VB.InputBox('Cancel this fax (Y/N)?') === 'Y') {
job.Cancel();
}
if (VB.InputBox('Open this fax (Y/N)?') === 'Y') {
const fileName = VB.InputBox('Enter path to save');
job.CopyTiff(fileName);
new ActiveXObject('WScript.Shell').Run(fileName);
}
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692914(v=vs.85).aspx
{
const server = new ActiveXObject('FaxComEx.FaxServer');
server.Connect('');
const outgoingQueue = server.Folders.OutgoingQueue;
outgoingQueue.AgeLimit = 2;
outgoingQueue.AllowPersonalCoverPages = true;
outgoingQueue.Blocked = false;
outgoingQueue.Paused = false;
outgoingQueue.Branding = true;
outgoingQueue.DiscountRateStart = new Date(0, 0, 0, 0).getVarDate();
outgoingQueue.DiscountRateStart = new Date(0, 0, 0, 1).getVarDate();
outgoingQueue.UseDeviceTSID = true;
outgoingQueue.Save();
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693393(v=vs.85).aspx
{
const outgoingQueue = getServer().Folders.OutgoingQueue;
outgoingQueue.Refresh();
WScript.Echo(`There are ${outgoingQueue.GetJobs().Count} faxes in the outgoing queue`);
const inputResult = VB.InputBox('Which fax should be displayed (item number or job name)?');
const itemNumber = parseInt(inputResult, 10);
const job =
isNaN(itemNumber) ?
outgoingQueue.GetJob(inputResult) :
outgoingQueue.GetJobs().Item(itemNumber);
WScript.Echo(`
Available operations: ${job.AvailableOperations}
Broadcast receipts grouped? ${job.GroupBroadcastReceipts}
CSID: ${job.CSID}
Current page: ${job.CurrentPage}
Device ID: ${job.DeviceId}
Document name: ${job.DocumentName}
Extended status: ${job.ExtendedStatus}
Extended status code: ${job.ExtendedStatusCode}
Job ID: ${job.Id}
Original scheduled time: ${new Date(job.OriginalScheduledTime)}
Pages: ${job.Pages}
Priority: ${job.Priority}
Receipt type: ${job.ReceiptType}
`.trim());
const fileName = VB.InputBox('Enter path to save');
job.CopyTiff(fileName);
new ActiveXObject('WScript.Shell').Run(fileName);
const answer = VB.InputBox(`
Do you want to:
(C) cancel
(P) pause
(R) restart
(E) resume
the job?
`.trim());
switch (answer) {
case 'C':
job.Cancel();
break;
case 'P':
job.Pause();
break;
case 'R':
job.Restart();
break;
case 'E':
job.Resume();
break;
}
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692936(v=vs.85).aspx
{
const document = new ActiveXObject('FaxComEx.FaxDocument');
document.Body = 'C:\\docs\\body.txt';
document.DocumentName = 'My First Fax';
document.Priority = FAXCOMEXLib.FAX_PRIORITY_TYPE_ENUM.fptHIGH;
document.Recipients.Add('12225550100', 'Bud');
document.AttachFaxToReceipt = true;
document.CoverPageType = FAXCOMEXLib.FAX_COVERPAGE_TYPE_ENUM.fcptSERVER;
document.Note = 'Here is the info you requested';
document.ReceiptAddress = 'someone@example.com';
document.ReceiptType = FAXCOMEXLib.FAX_RECEIPT_TYPE_ENUM.frtMAIL;
document.ScheduleType = FAXCOMEXLib.FAX_SCHEDULE_TYPE_ENUM.fstSPECIFIC_TIME;
document.ScheduleTime = new Date(0, 0, 0, 16, 35, 47).getVarDate();
document.Subject = 'Today\'s fax';
// set sender properties
const sender = document.Sender;
sender.Title = 'Mr.';
sender.Name = 'Bob';
sender.City = 'Cleveland Heights';
sender.State = 'Ohio';
sender.Company = 'Microsoft';
sender.Country = 'USA';
sender.Email = 'someone@microsoft.com';
sender.FaxNumber = '12165555554';
sender.HomePhone = '12165555555';
sender.OfficeLocation = 'Downtown';
sender.OfficePhone = '12165555553';
sender.StreetAddress = '123 Main Street';
sender.TSID = 'Office fax machine';
sender.ZipCode = '44118';
sender.BillingCode = '23A54';
sender.Department = 'Accts Payable';
sender.SaveDefaultSender();
const server = getServer();
const jobID = document.ConnectedSubmit(server);
WScript.Echo(`The job ID is ${jobID}`);
server.Disconnect();
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693479(v=vs.85).aspx
{
const document = new ActiveXObject('FaxComEx.FaxDocument');
document.Body = 'C:\\docs\\body.txt';
document.DocumentName = 'My First Fax';
const recipients = document.Recipients;
recipients.Add('12225550105', 'H');
recipients.Add('12225550104', 'N');
recipients.Add('12225550103', 'G');
WScript.Echo(`Number of recipients: ${recipients.Count}`);
collectionToArray(recipients).forEach((recipient, index) =>
WScript.Echo(`Recipient number ${index}: ${recipient.Name}, ${recipient.FaxNumber}`)
);
document.Sender.LoadDefaultSender();
document.GroupBroadcastReceipts = true;
const jobIDs = document.Submit('');
collectionToArray(jobIDs).forEach(jobID => WScript.Echo(`The job ID is ${jobID}`));
while (recipients.Count > 0) {
recipients.Remove(1);
}
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa964962(v=vs.85).aspx
{
const server = getServer();
const prefetchCount = parseInt(VB.InputBox('How many messages should be prefetched?'), 10);
server.CurrentAccount.Folders.IncomingArchive.Refresh();
const messageIterator = server.Folders.IncomingArchive.GetMessages(prefetchCount);
messageIterator.MoveFirst();
for (let i = 1; i <= prefetchCount; i++) {
if (i > 1 && VB.InputBox('View next message? (Y/N)') !== 'Y') { break; }
const message = messageIterator.Message as FAXCOMEXLib.FaxIncomingMessage;
if (messageIterator.AtEOF) {
WScript.Echo(`End of file reached`);
break;
}
if (!message.WasReAssigned) {
if (VB.InputBox('Message not reassigned. Reassign (Y/N)?') === 'Y') {
message.Subject = 'Reassigning message';
message.SenderName = 'Test user';
message.Recipients = VB.InputBox('Enter username, e.g. Domain\\UserName');
message.SenderFaxNumber = '1234';
message.ReAssign();
}
}
messageIterator.MoveNext();
}
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693402(v=vs.85).aspx
{
const server = getServer();
const prefetchCount = parseInt(VB.InputBox('How many messages should be prefetched?'), 10);
server.Folders.OutgoingArchive.Refresh();
const messageIterator = server.Folders.OutgoingArchive.GetMessages(prefetchCount);
messageIterator.MoveFirst();
for (let i = 1; i <= prefetchCount; i++) {
if (i > 1 && VB.InputBox('View next message? (Y/N)') !== 'Y') { break; }
if (messageIterator.AtEOF) {
WScript.Echo(`End of file reached`);
break;
}
const message = messageIterator.Message as FAXCOMEXLib.FaxOutgoingMessage;
const fileName = VB.InputBox('Enter path to save');
message.CopyTiff(fileName);
new ActiveXObject('WScript.Shell').Run(fileName);
WScript.Echo(`Message information:
CSID: ${message.CSID}
Device name: ${message.DeviceName}
Document name: ${message.DocumentName}
Message ID: ${message.Id}
Original scheduled time: ${new Date(message.OriginalScheduledTime)}
Pages: ${message.Pages}
Recipient fax number: ${message.Recipient.FaxNumber}
Retries: ${message.Retries}
Sender name: ${message.Sender.Name}
Size: ${message.Size}
Subject: ${message.Subject}
Submission ID: ${message.SubmissionId}
Submission time: ${new Date(message.SubmissionTime)}
Transmission end time: ${new Date(message.TransmissionEnd)}
Transmission start time: ${new Date(message.TransmissionStart)}
TSID: ${message.TSID}`);
if (VB.InputBox('Delete this fax from the archive (Y/N)?') === 'Y') {
message.Delete();
}
}
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693472(v=vs.85).aspx
{
const server = getServer();
const outgoingArchive = server.Folders.OutgoingArchive;
WScript.Echo(`
Age limit: ${outgoingArchive.AgeLimit}
Archive folder: ${outgoingArchive.ArchiveFolder}
High quota mark: ${outgoingArchive.HighQuotaWaterMark}
Low quota water mark: ${outgoingArchive.LowQuotaWaterMark}
Size high: ${outgoingArchive.SizeHigh}
Size low: ${outgoingArchive.SizeLow}
Size quota warning: ${outgoingArchive.SizeQuotaWarning}
Is archive used? ${outgoingArchive.UseArchive}`.trim()
);
const newLimit = VB.InputBox('Set new age limit (enter empty value or Cancel to leave unchanged');
if (newLimit) {
outgoingArchive.AgeLimit = parseInt(newLimit, 10);
}
const messageID = VB.InputBox('Retrieve a message by ID (enter an empty value or press Cancel to exit');
if (messageID) {
const fileName = VB.InputBox('Enter path to save');
outgoingArchive.GetMessage(messageID).CopyTiff(fileName);
new ActiveXObject('WScript.Shell').Run(fileName);
}
}
{
const server = getServer();
const messageIterator = server.Folders.OutgoingArchive.GetMessages();
messageIterator.MoveFirst();
while (!messageIterator.AtEOF) {
const message = messageIterator.Message;
WScript.Echo(`
Document name: ${message.DocumentName}
ID: ${message.Id}
Transmission end: ${new Date(message.TransmissionEnd)}
Transmission start: ${new Date(message.TransmissionStart)}
`.trim());
messageIterator.MoveNext();
}
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms692976(v=vs.85).aspx
{
const server = getServer();
const prefetchCount = parseInt(VB.InputBox('How many messages should be prefetched?'), 10);
server.Folders.IncomingArchive.Refresh();
const messageIterator = server.Folders.IncomingArchive.GetMessages(prefetchCount);
messageIterator.MoveFirst();
for (let i = 1; i <= prefetchCount; i++) {
if (i > 1 && VB.InputBox('View next message? (Y/N)') !== 'Y') { break; }
const message = messageIterator.Message as FAXCOMEXLib.FaxIncomingMessage;
if (messageIterator.AtEOF) {
WScript.Echo(`End of file reached`);
break;
}
const fileName = VB.InputBox('Enter path to save TIFF file');
message.CopyTiff(fileName);
new ActiveXObject('WScript.Shell').Run(fileName);
messageIterator.MoveNext();
}
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693406(v=vs.85).aspx
{
const server = getServer();
const incomingArchive = server.Folders.IncomingArchive;
incomingArchive.Refresh();
WScript.Echo(`
High quota water mark: ${incomingArchive.HighQuotaWaterMark}
Low quota water mark: ${incomingArchive.LowQuotaWaterMark}
Archive folder: ${incomingArchive.ArchiveFolder}
Age limit: ${incomingArchive.AgeLimit}
Size high: ${incomingArchive.SizeHigh}
Size low: ${incomingArchive.SizeLow}
Is size quota warning on? ${incomingArchive.SizeQuotaWarning}
Is archive used? ${incomingArchive.UseArchive}
`.trim());
incomingArchive.AgeLimit = 4;
incomingArchive.Save();
const messageID = VB.InputBox('Message ID to retrieve information? (Leave empty, or Cancel, to exit)');
if (messageID !== '') {
const message = incomingArchive.GetMessage(messageID);
WScript.Echo(`
Caller ID: ${message.CallerId}
CSID: ${message.CSID}
Device name: ${message.DeviceName}
Message ID: ${message.Id}
Number of pages: ${message.Pages}
Retries: ${message.Retries}
Routing information: ${message.RoutingInformation}
Size: ${message.Size}
Transmission start: ${new Date(message.TransmissionStart)}
Transmission end: ${new Date(message.TransmissionEnd)}
TSID: ${message.TSID}
`.trim());
if (VB.InputBox('Delete this message from the archive (Y/N)?') === 'Y') {
message.Delete();
}
}
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693401(v=vs.85).aspx
{
const server = getServer();
const loggingOptions = server.LoggingOptions;
const activityLogging = loggingOptions.ActivityLogging;
const eventLogging = loggingOptions.EventLogging;
activityLogging.Refresh();
activityLogging.LogIncoming = true;
activityLogging.LogOutgoing = true;
activityLogging.Save();
eventLogging.Refresh();
eventLogging.GeneralEventsLevel = FAXCOMEXLib.FAX_LOG_LEVEL_ENUM.fllMED;
eventLogging.InboundEventsLevel = FAXCOMEXLib.FAX_LOG_LEVEL_ENUM.fllMAX;
eventLogging.InitEventsLevel = FAXCOMEXLib.FAX_LOG_LEVEL_ENUM.fllMAX;
eventLogging.OutboundEventsLevel = FAXCOMEXLib.FAX_LOG_LEVEL_ENUM.fllNONE;
eventLogging.Save();
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693387(v=vs.85).aspx
{
const server = getServer();
const receiptOptions = server.ReceiptOptions;
receiptOptions.Refresh();
WScript.Echo(`
Allowed receipt types: ${receiptOptions.AllowedReceipts}
Authentication types: ${receiptOptions.AuthenticationType}
SMTP port: ${receiptOptions.SMTPPort}
SMTP sender: ${receiptOptions.SMTPSender}
SMTP server: ${receiptOptions.SMTPSender}
Use for inbound routing? ${receiptOptions.UseForInboundRouting}
`.trim());
receiptOptions.AllowedReceipts = FAXCOMEXLib.FAX_RECEIPT_TYPE_ENUM.frtMAIL;
receiptOptions.AuthenticationType = FAXCOMEXLib.FAX_SMTP_AUTHENTICATION_TYPE_ENUM.fsatBASIC;
receiptOptions.SMTPPort = 25;
receiptOptions.SMTPSender = 'someone@example.com';
receiptOptions.SMTPServer = 'My SMTP Server';
receiptOptions.UseForInboundRouting = true;
receiptOptions.Save();
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693462(v=vs.85).aspx
{
const server = getServer();
collectionToArray(server.GetDeviceProviders()).forEach((provider, index) => {
WScript.Echo(`
Debug: ${provider.Debug}
Name: ${provider.FriendlyName}
Image name: ${provider.ImageName}
Init error code: ${provider.InitErrorCode}
Build and version: ${provider.MajorBuild}.${provider.MajorVersion}.${provider.MinorBuild}.${provider.MinorVersion}
Status: ${provider.Status}
TAPI provider: ${provider.TapiProviderName}
Unique name: ${provider.UniqueName}
`.trim());
new VBArray(provider.DeviceIds).toArray().forEach(id => WScript.Echo(id));
});
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693437(v=vs.85).aspx -- for a fax device
{
const server = getServer();
const device = server.GetDevices().Item(1);
const deviceProperty = toSafeArray(1, 2, 3);
const propertyName = '{B1F944B9-9A16-45d1-933A-4060A4871AB0}';
device.SetExtensionProperty(propertyName, deviceProperty);
new VBArray(device.GetExtensionProperty(propertyName)).toArray().forEach(x => WScript.Echo(x));
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693437(v=vs.85).aspx -- for a fax device
{
const server = getServer();
const serverProperty = toSafeArray(4, 2, 3);
const propertyName = `{AC7D0DEE-B6E5-4a44-AF45-835C58CB44D2}`;
server.SetExtensionProperty(propertyName, serverProperty);
new VBArray(server.GetExtensionProperty(propertyName)).toArray().forEach(x => WScript.Echo(x));
}
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms693013(v=vs.85).aspx
{
const server = getServer();
ActiveXObject.on(server, 'OnOutgoingJobAdded', ['pFaxServer', 'bstrJobId'], prm => WScript.Echo('New job added to queue'));
ActiveXObject.on(server, 'OnOutgoingJobChanged', ['pFaxServer', 'bstrJobId', 'pJobStatus'], prm => {
const status = prm.pJobStatus;
WScript.Echo(`
Available operations: ${status.AvailableOperations}
Caller ID: ${status.CallerId}
CSID: ${status.CSID}
Current page: ${status.CurrentPage}
Device ID: ${status.DeviceId}
Extended status: ${status.ExtendedStatus}
Extended status code: ${status.ExtendedStatusCode}
Job type: ${status.JobType}
Pages: ${status.Pages}
Retries: ${status.Retries}
Routing information: ${status.RoutingInformation}
Scheduled time: ${new Date(status.ScheduledTime)}
Size: ${status.Size}
Status: ${status.Status}
Transmission start: ${new Date(status.TransmissionStart)}
TSID: ${status.TSID}
`.trim());
try {
WScript.Echo(`Transmission end: ${new Date(status.TransmissionEnd)}`);
} catch {}
});
ActiveXObject.on(server, 'OnServerShutDown', ['pFaxServer'], prm => WScript.Echo('The local fax server has been shut down'));
server.ListenToServerEvents(
FAXCOMEXLib.FAX_SERVER_EVENTS_TYPE_ENUM.fsetFXSSVC_ENDED +
FAXCOMEXLib.FAX_SERVER_EVENTS_TYPE_ENUM.fsetOUT_QUEUE
);
}
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-faxcomexlib-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}
@@ -0,0 +1,49 @@
const wshn = new ActiveXObject('WScript.Network');
// https://msdn.microsoft.com/en-us/library/s6wt333f(v=vs.84).aspx
// https://msdn.microsoft.com/en-us/library/wck0hkd7(v=vs.84).aspx
// https://msdn.microsoft.com/en-us/library/tte130y1(v=vs.84).aspx
// https://msdn.microsoft.com/en-us/library/3fxhka75(v=vs.84).aspx
{
WScript.Echo('Domain = ' + wshn.UserDomain);
WScript.Echo('Computer Name = ' + wshn.ComputerName);
WScript.Echo('User Name = ' + wshn.UserName);
}
// https://msdn.microsoft.com/en-us/library/zsdh7hkb(v=vs.84).aspx
wshn.AddWindowsPrinterConnection('\\\\printserv\\DefaultPrinter');
// https://msdn.microsoft.com/en-us/library/kxsdca3c(v=vs.84).aspx
wshn.AddPrinterConnection("LPT1", "\\\\Server\\Print1");
// https://msdn.microsoft.com/en-us/library/t9zt39at(v=vs.84).aspx
// https://msdn.microsoft.com/en-us/library/zhds6k80(v=vs.84).aspx
{
const drives = wshn.EnumNetworkDrives();
const printers = wshn.EnumPrinterConnections();
WScript.Echo("Network drive mappings:");
for (let i = 0; i < drives.length; i += 2) {
WScript.Echo(`Drive ${drives.Item(i)} = ${drives.Item(i + 1)}`);
}
WScript.Echo('');
WScript.Echo("Network printer mappings:");
for (let i = 0; i < printers.length; i += 2) {
WScript.Echo(`Port ${printers.Item(i)} = ${printers.Item(i + 1)}`);
}
}
// https://msdn.microsoft.com/en-us/library/8kst88h6(v=vs.84).aspx
wshn.MapNetworkDrive('E:', '\\\\Server\\Public');
// https://msdn.microsoft.com/en-us/library/d16d7wbf(v=vs.84).aspx
wshn.RemoveNetworkDrive('E:');
// https://msdn.microsoft.com/en-us/library/tsbh2yy7(v=vs.84).aspx
wshn.RemovePrinterConnection('\\\\PRN-CORP1\\B41-4523-A', true, true);
// https://msdn.microsoft.com/en-us/library/2ccwwdct(v=vs.84).aspx
{
const printerPath = "\\\\research\\library1";
wshn.AddWindowsPrinterConnection(printerPath);
wshn.SetDefaultPrinter(printerPath);
}
+348
View File
@@ -0,0 +1,348 @@
// Type definitions for Windows Script Host Object Model - IWshRuntimeLibrary 1.0
// Project: https://msdn.microsoft.com/en-us/library/9bbdkx3k(v=vs.84).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
declare namespace IWshRuntimeLibrary {
type WindowStyle = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
type ShortcutWindowStyle = 1 | 3 | 7;
// tslint:disable-next-line no-const-enum
const enum ButtonType {
OK,
OKCancel,
AbortRetryIgnore,
YesNoCancel,
YesNo,
RetryCancel,
CancelTryagainContinue
}
// tslint:disable-next-line no-const-enum
const enum EventType {
AuditFailure = 5,
AuditSuccess = 4,
Error = 1,
Information = 3,
Success = 0,
Warning = 2
}
// tslint:disable-next-line no-const-enum
const enum IconType {
Stop = 16,
QuestionMark = 32,
ExclamationMakr = 48,
InformationMark = 64,
}
// tslint:disable-next-line no-const-enum
const enum PopupType {
SecondButtonDefault = 256,
ThirdButtonDefault = 512,
Modal = 4096,
RightJustified = 524288,
RTL = 1048576,
}
// tslint:disable-next-line no-const-enum
const enum PopupSelection {
NoButton = -1,
OK = 1,
Cancel = 2,
Abort = 3,
Retry = 4,
Ignore = 5,
Yes = 6,
No = 7,
TryAgain = 10,
Continue = 11,
}
// tslint:disable-next-line no-const-enum
const enum WshExecStatus {
WshFailed = 2,
WshFinished = 1,
WshRunning = 0,
}
// tslint:disable-next-line no-const-enum
const enum WshWindowStyle {
WshHide = 0,
WshMaximizedFocus = 3,
WshMinimizedFocus = 2,
WshMinimizedNoFocus = 6,
WshNormalFocus = 1,
WshNormalNoFocus = 4,
}
class TextStream {
private 'IWshRuntimeLibrary.TextStream_typekey': TextStream;
private constructor();
readonly AtEndOfLine: boolean;
readonly AtEndOfStream: boolean;
Close(): void;
readonly Column: number;
readonly Line: number;
Read(Characters: number): string;
ReadAll(): string;
ReadLine(): string;
Skip(Characters: number): void;
SkipLine(): void;
Write(Text: string): void;
WriteBlankLines(Lines: number): void;
/** @param string [Text=''] */
WriteLine(Text?: string): void;
}
/** Generic Collection Object */
interface WshCollection {
Count(): number;
Item(Index: any): any;
readonly length: number;
(Index: any): any;
}
/** Environment Variables Collection Object */
interface WshEnvironment {
Count(): number;
Item(Name: string): string;
readonly length: number;
Remove(Name: string): void;
(Name: string): string;
}
/** WSHExec object */
class WshExec {
private 'IWshRuntimeLibrary.WshExec_typekey': WshExec;
private constructor();
readonly ExitCode: number;
readonly ProcessID: number;
readonly Status: WshExecStatus;
readonly StdErr: TextStream;
readonly StdIn: TextStream;
readonly StdOut: TextStream;
Terminate(): void;
}
/** Network Object */
class WshNetwork {
private 'IWshRuntimeLibrary.WshNetwork_typekey': WshNetwork;
private constructor();
/**
* Adds a remote MS-DOS-based printer connection to your computer system.
* @param LocalName Local name to assign to the connected printer.
* @param RemoteName Name of the remote printer.
* @param UpdateProfile [false] Whether the printer mapping is stored in the current user's profile.
*
* If you are mapping a remote printer using the profile of someone other than current user, you can specify _UserName_ and _Password_.
*/
AddPrinterConnection(LocalName: string, RemoteName: string, UpdateProfile?: boolean, UserName?: string, Password?: string): void;
/**
* @param string Path to printer connection
* @param string [DriverName='']
* @param string [Port='LPT1']
*
* Unlike the **AddPrinterConnection** method, this method allows you to create a printer connection without directing it to a specific port, such as LPT1.
*/
AddWindowsPrinterConnection(PrinterName: string, DriverName?: string, Port?: string): void;
readonly ComputerName: string;
EnumNetworkDrives(): WshCollection;
EnumPrinterConnections(): WshCollection;
/**
* Adds a remote MS-DOS-based printer connection to your computer system.
* @param LocalName Name by which the mapped drive will be known locally
* @param RemoteName Share's UNC name (\\xxx\yyy)
* @param UpdateProfile [false] Whether the printer mapping is stored in the current user's profile.
*
* If you are mapping a network drive using the profile of someone other than current user, you can specify _UserName_ and _Password_.
*/
MapNetworkDrive(LocalName: string, RemoteName: string, UpdateProfile?: boolean, UserName?: string, Password?: string): void;
readonly Organization: string;
/**
* Removes a shared network drive from your computer system
* @param Name Name of the mapped drive you want to remove. This will be the drive letter if the drive has a mapping between a local name (drive letter) and a remote name (UNC name);
* it will be the UNC path if there is no such mapping
* @param Force [false] Remove the connections even if the resource is in use
* @param UpdateProfile [false] Remove the mapping from the user's profile
*/
RemoveNetworkDrive(Name: string, Force?: boolean, UpdateProfile?: boolean): void;
/**
* Removes a shared network printer connection from your computer system
* @param Name Name that identifies the printer. Can be a UNC name (in the form `\\xxx\yyy`) or a local name (such as `LPT1`)
* @param Force [false] Remove printer connection even if a user is still connected
* @param UpdateProfile [false] Remove the printer connection from the user's profile
*
* The **RemovePrinterConnection** method removes both Windows and MS-DOS based printer connections. If the printer was connected using the method **AddPrinterConnection**,
* _Name_ must be the printer's local name. If the printer was connected using the **AddWindowsPrinterConnection** method or was added manually (using the Add Printer wizard),
* then _Name_ must be the printer's UNC name.
*/
RemovePrinterConnection(Name: string, Force?: true, UpdateProfile?: true): void;
SetDefaultPrinter(Name: string): void;
readonly Site: string;
readonly UserDomain: string;
readonly UserName: string;
readonly UserProfile: string;
}
/** Shell Object */
class WshShell {
private 'IWshRuntimeLibrary.WshShell_typekey': WshShell;
private constructor();
/**
* Activates an application window
* @param App Title of application as it appears in the title bar, or the process ID
* @param Wait
*
* This method changes the focus to the named application or window. The window must be attached to the calling thread's message queue. It does not affect whether it is maximized or
* minimized. Focus moves from the activated application window when the user takes action to change the focus (or closes the window).
*
* In determining which application to activate, the specified title is compared to the title string of each running application. If no exact match exists, any application whose title
* string begins with title is activated. If an application still cannot be found, any application whose title string ends with title is activated. If more than one instance of the
* application named by title exists, one instance is arbitrarily activated.
*
* The method might return `false` under the following conditions:
*
* * The window is not brought to the foreground.
* * The window is brought to the foreground but is not given keyboard focus.
* * A Command Prompt window (`cmd.exe`) is brought to the foreground and is given keyboard focus.
*/
AppActivate(App: string | number, Wait?: any): boolean;
/**
* Creates a shortcut
* @param PathLink Path where the shortcut should be created
*
* The shortcut object exists in memory until you save it to disk with the **Save** method.
*/
CreateShortcut(PathLink: string): WshShortcut | WshURLShortcut;
CurrentDirectory: string;
/**
* Note that **Environment** doesn't actually return a callable object; the call is only usable in the context of the **Environment** property. The following:
*
* let env = new ActiveXObject('WScript.Shell').Environment;
* WScript.Echo(env('System'));
*
* will return an empty string, unless there is an environment variable named `System`
*/
Environment: WshEnvironment & ((Type: 'System' | 'User' | 'Process' | 'Volatile') => WshEnvironment);
Exec(Command: string): WshExec;
ExpandEnvironmentStrings(Src: string): string;
/** @param string [Target=''] Name of the computer system where the event should be logged; default is the local computer system */
LogEvent(Type: EventType, Message: string, Target?: string): boolean;
Popup(Text: string, SecondsToWait?: number, Title?: string, Type?: ButtonType | IconType | PopupType): PopupSelection;
RegDelete(Name: string): void;
/**
* Returns the value of a key or value-name from the registry
* @param Name Key (ends with a final `\`) or value-name (doesn't end with a final `\`)
*
* Returns one of the following, based on the registry value type:
*
* * **REG_SZ** -- a string
* * **REG_DWORD** -- a number
* * **REG_SBINARY** -- a binary value, as a COM SafeArray containing integers
* * **REG_EXPAND_SZ** -- an expandable string
* * **REG_MULTI_SZ** -- an array of srings, as a COM SafeArray
*/
RegRead(Name: string): string | number | SafeArray<string> | SafeArray<number>;
/**
* Creates a new key, adds another value-name to an existing key and assigns it a value, or changes the value of an existing value-name
* @param Name Key (ends with a final `\`) or value-name (doesn't end with a final `\`)
* @param Value Will be coerced to `string` or `integer` based on the value-name type:
* `REG_SZ | REG_EXPAND_SZ` will be converted to `string`;
* `REG_DWORD | REG_BINARY` will be converted to `integer`
* @param Type
*/
RegWrite(Name: string, Value: any, Type?: 'REG_SZ' | 'REG_DWORD' | 'REG_BINARY' | 'REG_EXPAND_SZ'): void;
/**
* Runs a program in a new process.
* @param Command Command-line, including any parameters you want to pass to the executable file.
* @param WindowStyle Appearance of the program window. Not all programs make use of this information.
* @param WaitOnReturn Block script until program finishes executing.
*
* If `false` is passed into **WaitOnReturn**, the **Run** method will return 0 immediately. If `true` is passed in, **Run** will return the program's error code, if any.
*
* Environment variables will be expanded within the command line.
*
* Passing a registered file type will automatically open the program registered to the file type.
*
* Possible values for **WindowStyle**:
*
* * **0** -- Hides the window and activates another window.
* * **1** -- Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag
* when displaying the window for the first time.
* * **2** -- Activates the window and displays it as a minimized window.
* * **3** -- Activates the window and displays it as a maximized window.
* * **4** -- Displays a window in its most recent size and position. The active window remains active.
* * **5** -- Activates the window and displays it in its current size and position.
* * **6** -- Minimizes the specified window and activates the next top-level window in the Z order.
* * **7** -- Displays the window as a minimized window. The active window remains active.
* * **8** -- Displays the window in its current state. The active window remains active.
* * **9** -- Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag
* when restoring a minimized window.
* * **10** -- Sets the show-state based on the state of the program that started the application.
*/
Run(Command: string, WindowStyle?: WindowStyle, WaitOnReturn?: boolean): number;
SendKeys(Keys: string, Wait?: boolean): void;
readonly SpecialFolders: WshCollection;
}
/** Shortcut Object */
class WshShortcut {
private 'IWshRuntimeLibrary.WshShortcut_typekey': WshShortcut;
private constructor();
Arguments: string;
Description: string;
readonly FullName: string;
Hotkey: string;
IconLocation: string;
Load(PathLink: string): void;
readonly RelativePath: string;
Save(): void;
TargetPath: string;
/**
* Possible values:
*
* * **1** -- Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag
* when displaying the window for the first time.
* * **3** -- Activates the window and displays it as a maximized window.
* * **7** -- Displays the window as a minimized window. The active window remains active.
*/
WindowStyle: ShortcutWindowStyle;
WorkingDirectory: string;
}
/** URLShortcut Object */
class WshURLShortcut {
private 'IWshRuntimeLibrary.WshURLShortcut_typekey': WshURLShortcut;
private constructor();
readonly FullName: string;
Load(PathLink: string): void;
Save(): void;
TargetPath: string;
}
}
interface ActiveXObject {
set(obj: IWshRuntimeLibrary.WshEnvironment, propertyName: 'Item', parameterTypes: [string], newValue: string): void;
new <K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
}
interface ActiveXObjectNameMap {
'WScript.Network': IWshRuntimeLibrary.WshNetwork;
'WScript.Shell': IWshRuntimeLibrary.WshShell;
}
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-iwshruntimelibrary-tests.ts"
]
}
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+1 -1
View File
@@ -1,8 +1,8 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false],
"ban-types": false,
"no-const-enum": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-unnecessary-qualifier": false
+2 -2
View File
@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}
@@ -1,60 +1,324 @@
// source -- https://msdn.microsoft.com/en-us/library/ebkhfaaz.aspx
// Note -- running these tests under cscript requires some ES5 polyfills
// Generates a string describing the drive type of a given Drive object.
function showDriveType(drive: Scripting.Drive) {
switch (drive.DriveType) {
case Scripting.DriveTypeConst.Removable:
return 'Removeable';
case Scripting.DriveTypeConst.Fixed:
return 'Fixecd';
case Scripting.DriveTypeConst.Remote:
return 'Network';
case Scripting.DriveTypeConst.CDRom:
return 'CD-ROM';
case Scripting.DriveTypeConst.RamDisk:
return 'RAM Disk';
default:
return 'Unknown';
const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
const results: T[] = [];
const enumerator = new Enumerator<T>(col);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
results.push(enumerator.item());
enumerator.moveNext();
}
}
return results;
};
// Generates a string describing the attributes of a file or folder.
function showFileAttributes(file: Scripting.File) {
const attr = file.Attributes;
if (attr === 0) {
return 'Normal';
const fso = new ActiveXObject('Scripting.FileSystemObject');
// https://msdn.microsoft.com/en-us/library/ebkhfaaz(v=vs.84).aspx
{
/** Generates a string describing the drive type of a given Drive object. */
const driveTypeString = (drive: Scripting.Drive) => {
switch (drive.DriveType) {
case Scripting.DriveTypeConst.Removable:
return 'Removeable';
case Scripting.DriveTypeConst.Fixed:
return 'Fixecd';
case Scripting.DriveTypeConst.Remote:
return 'Network';
case Scripting.DriveTypeConst.CDRom:
return 'CD-ROM';
case Scripting.DriveTypeConst.RamDisk:
return 'RAM Disk';
default:
return 'Unknown';
}
};
/** Generates a string describing the attributes of a file or folder. */
const attributesString = (f: Scripting.File | Scripting.Folder) => {
const attr = f.Attributes;
if (attr === 0) {
return 'Normal';
}
const attributeStrings: string[] = [];
if (attr & Scripting.FileAttribute.Directory) { attributeStrings.push('Directory'); }
if (attr & Scripting.FileAttribute.ReadOnly) { attributeStrings.push('Read-only'); }
if (attr & Scripting.FileAttribute.Hidden) { attributeStrings.push('Hidden'); }
if (attr & Scripting.FileAttribute.System) { attributeStrings.push('System'); }
if (attr & Scripting.FileAttribute.Volume) { attributeStrings.push('Volume'); }
if (attr & Scripting.FileAttribute.Archive) { attributeStrings.push('Archive'); }
if (attr & Scripting.FileAttribute.Alias) { attributeStrings.push('Alias'); }
if (attr & Scripting.FileAttribute.Compressed) { attributeStrings.push('Compressed'); }
return attributeStrings.join(',');
};
const drivesInfoReport = () => {
const driveLine = (d: Scripting.Drive) => {
let parts: Array<string | number> = [
d.DriveLetter,
d.Path,
driveTypeString(d),
d.IsReady ? 'true' : 'false'
];
if (d.IsReady) {
parts = parts.concat([
d.DriveType === Scripting.DriveTypeConst.Remote ? d.ShareName : d.VolumeName,
d.FileSystem,
d.TotalSize,
d.FreeSpace,
d.AvailableSpace,
d.SerialNumber.toString(16)
]);
}
return parts.join(' ');
};
const ret = `
Number of drives: ${fso.Drives.Count}
Drive File Total Free Available Serial
Letter Path Type Ready? Name System Space Space Space Number
${new Array(106).join('-')}
${collectionToArray(fso.Drives).map(driveLine).join('\n')}`
.trim().replace(' ', '\t');
};
type fiileFolderKey = keyof Scripting.File & keyof Scripting.Folder;
type keys = fiileFolderKey | 'Attribs' | 'Created' | 'Accessed' | 'Modified';
const detailBuilder = (f: Scripting.File | Scripting.Folder, x: fiileFolderKey | 'Attribs' | 'Created' | 'Accessed' | 'Modified') => {
if (x === 'Attribs') { return attributesString(f); }
const label = x;
switch (x) {
case 'Created':
x = 'DateCreated';
break;
case 'Accessed':
x = 'DateLastAccessed';
break;
case 'Modified':
x = 'DateLastModified';
break;
}
return `${label}\t${f[x]}\n`;
};
const fileDetailsString = (f: Scripting.File) => {
const keys: keys[] = ['Path', 'Name', 'Type', 'Attribs', 'Created', 'Accessed', 'Modified', 'Size'];
return keys.map(x => detailBuilder(f, x)).join('');
};
const folderDetailsString = (f: Scripting.Folder) => {
const keys: keys[] = ['Path', 'Name', 'Attribs', 'Created', 'Accessed', 'Modified', 'Size'];
return keys.map(x => detailBuilder(f, x)).join('');
};
const folderContentsString = (f: Scripting.Folder): string => {
const files = collectionToArray(f.Files);
const subfolders = collectionToArray(f.SubFolders);
return `
Folder: ${f.Path}
There ${files.length === 1 ? 'is 1 file' : `are ${files.length} files`}
${files.map(fileDetailsString).join('')}
There ${subfolders.length === 1 ? 'is 1 subfolder' : `are ${subfolders.length} subfolders`}
${subfolders.map(folderDetailsString).join('')}
${subfolders.map(folderContentsString).join('')}`
.trim().replace(' ', '\t');
};
const testDrive = 'C:\\';
const testPath = 'C:\\test';
const testfolderInfo = () => {
if (!fso.DriveExists(testDrive) || !fso.FolderExists(testPath)) { return ''; }
return folderContentsString(fso.GetFolder(testPath));
};
const deleteTestFolder = () => {
// two ways to delete a file:
const filepathToDelete = `${testPath}\\LoremIpsum\\Paragraph1.txt`;
fso.DeleteFile(filepathToDelete);
// fso.GetFile(filepathToDelete).Delete();
// two ways to delete a folder:
fso.DeleteFolder(`${testPath}\\LoremIpsum`);
fso.GetFolder(testPath).Delete();
};
const createLyrics = (folder: Scripting.Folder) => {
let stream = folder.CreateTextFile('Paragraph1.txt');
stream.Write('Lorem Ipsum - Paragraph 1');
stream.WriteBlankLines(1);
stream.WriteLine('Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas sem.');
stream.WriteLine('Donec ante. Nulla facilisi. Phasellus interdum nulla a nunc. Morbi laoreet nunc.');
stream.WriteBlankLines(2);
stream.Close();
stream = folder.CreateTextFile('Paragraph2.txt');
stream.WriteLine('Lorem Ipsum - Paragraph 2');
stream.WriteBlankLines(1);
stream.WriteLine('Nullam nulla quam, sollicitudin ut, lobortis ornare, tristique a, augue.');
stream.WriteLine('Vestibulum sem felis, fermentum eu, volutpat eu, vulputate eget, elit. ');
stream.WriteBlankLines(2);
stream.Close();
};
const getLyrics = () => {
const folderPath = `${testPath}\\LoremIpsum`;
let lyrics = '';
// One way to read from a file
let stream = fso.OpenTextFile(fso.BuildPath(folderPath, 'Paragraph1.txt'));
lyrics = stream.ReadAll() + '\n\n';
stream.Close();
// Another way to read from a file
stream = fso.GetFile(fso.BuildPath(folderPath, 'Paragraph2.txt')).OpenAsTextStream();
while (!stream.AtEndOfStream) {
lyrics += stream.ReadLine() + '\n';
}
stream.Close();
return lyrics;
};
const buildTestFolder = () => {
// Bail out if the drive doesn't exists ...
if (!fso.DriveExists(testDrive)) { return false; }
// or the directory already exists
if (fso.FolderExists(testPath)) { return false; }
const testFolder = fso.CreateFolder(testPath);
const stream = fso.CreateTextFile(fso.BuildPath(testPath, 'readme.txt'));
stream.WriteLine('My sample text collection');
stream.Close();
const subfolder = testFolder.SubFolders.Add('LoremIpsum');
createLyrics(subfolder);
return true;
};
const echoLines = (linecount = 1) => new Array(linecount).forEach(() => WScript.Echo(''));
if (!buildTestFolder()) {
WScript.Echo('Test directory already exists or cannot be created. Cannot continue.');
} else {
drivesInfoReport();
echoLines(2);
WScript.Echo(testfolderInfo());
echoLines(2);
WScript.Echo(getLyrics());
echoLines(2);
deleteTestFolder();
}
const attributeStrings: string[] = [];
if (attr & Scripting.FileAttribute.Directory) { attributeStrings.push('Directory'); }
if (attr & Scripting.FileAttribute.ReadOnly) { attributeStrings.push('Read-only'); }
if (attr & Scripting.FileAttribute.Hidden) { attributeStrings.push('Hidden'); }
if (attr & Scripting.FileAttribute.System) { attributeStrings.push('System'); }
if (attr & Scripting.FileAttribute.Volume) { attributeStrings.push('Volume'); }
if (attr & Scripting.FileAttribute.Archive) { attributeStrings.push('Archive'); }
if (attr & Scripting.FileAttribute.Alias) { attributeStrings.push('Alias'); }
if (attr & Scripting.FileAttribute.Compressed) { attributeStrings.push('Compressed'); }
return attributeStrings.join(',');
}
// source --https://msdn.microsoft.com/en-us/library/ts2t8ybh(v=vs.84).aspx
function showFreeSpace(drvPath: string) {
const fso = new ActiveXObject('Scripting.FileSystemObject');
const d = fso.GetDrive(fso.GetDriveName(drvPath));
let s = `Drive ${drvPath} - `;
s += d.VolumeName + '<br>';
s += `Free Space: ${d.FreeSpace / 1024} Kbytes`;
return (s);
{
const showFreeSpace = (drvPath: string) => {
const d = fso.GetDrive(fso.GetDriveName(drvPath));
let s = `Drive ${drvPath} - `;
s += d.VolumeName + '<br>';
s += `Free Space: ${d.FreeSpace / 1024} Kbytes`;
return (s);
};
}
// source -- https://msdn.microsoft.com/en-us/library/kaf6yaft(v=vs.84).aspx
function getALine(filespec: string) {
const fso = new ActiveXObject('Scripting.FileSystemObject');
const file = fso.OpenTextFile(filespec, Scripting.IOMode.ForReading, false);
{
const getALine = (filespec: string) => {
const file = fso.OpenTextFile(filespec, Scripting.IOMode.ForReading, false);
let s = '';
while (!file.AtEndOfLine) {
s += file.Read(1);
}
file.Close();
return (s);
let s = '';
while (!file.AtEndOfLine) {
s += file.Read(1);
}
file.Close();
return (s);
};
}
// https://msdn.microsoft.com/en-us/library/ch28h2s7(v=vs.84).aspx
{
const showDriveInfo = (path: string) => {
const bytesPerGB = 1024 * 1024 * 1024;
const drv = fso.GetDrive(fso.GetDriveName(path));
const ret =
drv.IsReady ?
`${drv.Path} - ${drv.FreeSpace / bytesPerGB} GB free of ${drv.TotalSize / bytesPerGB} GB` :
'Not ready';
WScript.Echo(ret);
};
const showFolderInfo = () => {
const fldr = fso.GetFolder("c:\\");
let ret = `
Folder: ${fldr.Path}
Drive: ${fldr.Drive}
${fldr.IsRootFolder ? 'Is root folder' : `Parent folder: ${fldr.ParentFolder}`}
`.trim();
// Create and delete a folder.
const newFolderName = 'C:\\TempFolder1';
fso.CreateFolder(newFolderName);
ret += `Base Name of Added Folder: ${fso.GetBaseName(newFolderName)}`;
fso.DeleteFolder(newFolderName);
WScript.Echo(ret);
};
}
// https://msdn.microsoft.com/en-us/library/czxefwt8(v=vs.84).aspx
{
const readFiles = () => {
const file = fso.CreateTextFile("c:\\testfile.txt", true);
// Write a line.
WScript.Echo('Writing file');
file.WriteLine("Hello World");
file.WriteBlankLines(1);
file.Close();
// Read the contents of the file.
WScript.Echo('Reading file');
const textStream = fso.OpenTextFile("c:\\testfile.txt", Scripting.IOMode.ForReading);
WScript.Echo(`File contents = "${textStream.ReadLine()}"`);
textStream.Close();
};
const manipulateFiles = () => {
const file = fso.CreateTextFile("c:\\testfile.txt", true);
WScript.Echo('Writing file');
// Write a line.
file.Write("This is a test.");
// Close the file to writing.
file.Close();
WScript.Echo('Moving file to c:\\tmp');
// Get a handle to the file in root of C:\.
let file2 = fso.GetFile("c:\\testfile.txt");
// Move the file to \tmp directory.
file2.Move("c:\\tmp\\testfile.txt");
WScript.Echo('Copying file to c:\\temp <br>');
// Copy the file to \temp.
file2.Copy('c:\\temp\\testfile.txt');
WScript.Echo('Deleting files <br>');
// Get handles to files' current location.
file2 = fso.GetFile('c:\\tmp\\testfile.txt');
const file3 = fso.GetFile('c:\\temp\\testfile.txt');
// Delete the files.
file2.Delete();
file3.Delete();
WScript.Echo('All done!');
};
}
+80 -45
View File
@@ -1,24 +1,28 @@
// Type definitions for Microsoft Scripting Runtime 1.0
// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7.aspx
// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7(v=vs.84).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
declare namespace Scripting {
// tslint:disable-next-line:no-const-enum
const enum CompareMethod {
BinaryCompare = 0,
DatabaseCompare = 2,
TextCompare = 1
TextCompare = 1,
}
// tslint:disable-next-line:no-const-enum
const enum DriveTypeConst {
CDRom = 4,
Fixed = 2,
RamDisk = 5,
Remote = 3,
Removable = 1,
UnknownType = 0
UnknownType = 0,
}
// tslint:disable-next-line:no-const-enum
const enum FileAttribute {
Alias = 1024,
Archive = 32,
@@ -28,38 +32,42 @@ declare namespace Scripting {
Normal = 0,
ReadOnly = 1,
System = 4,
Volume = 8
Volume = 8,
}
// tslint:disable-next-line:no-const-enum
const enum IOMode {
ForAppending = 8,
ForReading = 1,
ForWriting = 2
ForWriting = 2,
}
// tslint:disable-next-line:no-const-enum
const enum SpecialFolderConst {
SystemFolder = 1,
TemporaryFolder = 2,
WindowsFolder = 0
WindowsFolder = 0,
}
// tslint:disable-next-line:no-const-enum
const enum StandardStreamTypes {
StdErr = 2,
StdIn = 0,
StdOut = 1
StdOut = 1,
}
// tslint:disable-next-line:no-const-enum
const enum Tristate {
TristateFalse = 0,
TristateMixed = -2,
TristateTrue = -1,
TristateUseDefault = -2
TristateUseDefault = -2,
}
/** Scripting.Dictionary */
interface Dictionary {
interface Dictionary<TKey = any, TItem = any> {
/** Add a new key and item to the dictionary. */
Add(Key: any, Item: any): void;
Add(Key: TKey, Item: TItem): void;
/** Set or get the string comparison method. */
CompareMode: CompareMethod;
@@ -68,32 +76,38 @@ declare namespace Scripting {
readonly Count: number;
/** Determine if a given key is in the dictionary. */
Exists(Key: any): boolean;
HashVal(Key: any): any;
Exists(Key: TKey): boolean;
HashVal(Key: TKey): any;
/** Set or get the item for a given key */
Item(Key: any): any;
Item(Key: TKey): TItem;
/** Get an array containing all items in the dictionary. */
Items(): any;
Items(): SafeArray<TItem>;
/** Change a key to a different key. */
Key(Key: any): any;
Key(Key: TKey): TKey;
/** Get an array containing all keys in the dictionary. */
Keys(): any;
Keys(): SafeArray<TKey>;
/** Remove a given key from the dictionary. */
Remove(Key: any): void;
Remove(Key: TKey): void;
/** Remove all information from the dictionary. */
RemoveAll(): void;
/** Set or get the item for a given key */
(Key: TKey): TItem;
}
/** Drive Object */
interface Drive {
class Drive {
private constructor();
private 'Scripting.Drive_typekey': Drive;
/** Get available space */
readonly AvailableSpace: any;
readonly AvailableSpace: number;
/** Drive letter */
readonly DriveLetter: string;
@@ -105,7 +119,7 @@ declare namespace Scripting {
readonly FileSystem: string;
/** Get drive free space */
readonly FreeSpace: any;
readonly FreeSpace: number;
/** Check if disk is available */
readonly IsReady: boolean;
@@ -123,7 +137,7 @@ declare namespace Scripting {
readonly ShareName: string;
/** Get total drive size */
readonly TotalSize: any;
readonly TotalSize: number;
/** Name of volume */
VolumeName: string;
@@ -134,18 +148,27 @@ declare namespace Scripting {
/** Number of drives */
readonly Count: number;
/** Get drive */
Item(Key: any): Drive;
/** Get drive using the drive letter (`C`) or path (`C:\\`) */
Item(Key: string): Drive;
/** Get drive using the drive letter (`C`) or path (`C:\\`) */
(Key: string): Drive;
}
/** Script Encoder Object */
interface Encoder {
/** Call the Encoder determined by szExt, passing bstrStreamIn and optional arguments */
EncodeScriptFile(szExt: string, bstrStreamIn: string, cFlags: number, bstrDefaultLang: string): string;
/** Call the Encoder determined by szExt, passing bstrStreamIn and optional arguments */
(szExt: string, bstrStreamIn: string, cFlags: number, bstrDefaultLang: string): string;
}
/** File object */
interface File {
class File {
private constructor();
private 'Scripting.File_typekey': File;
/** File attributes */
Attributes: FileAttribute;
@@ -166,7 +189,7 @@ declare namespace Scripting {
/**
* Delete this file
* @param boolean [Force=false]
* @param boolean [Force=false] Pass `true` to delete the file even if the read-only attribute is set
*/
Delete(Force?: boolean): void;
@@ -199,7 +222,7 @@ declare namespace Scripting {
readonly ShortPath: string;
/** File size */
readonly Size: any;
readonly Size: number;
/** Type description */
readonly Type: string;
@@ -210,12 +233,18 @@ declare namespace Scripting {
/** Number of folders */
readonly Count: number;
/** Get file object using the name and extension of the file */
Item(Key: string): File;
/** Get file */
Item(Key: any): File;
(Key: string): File;
}
/** FileSystem Object */
interface FileSystemObject {
class FileSystemObject {
private constructor();
private 'Scripting.FileSystemObject_typekey': FileSystemObject;
/** Generate a path from an existing path and a name */
BuildPath(Path: string, Name: string): string;
@@ -243,13 +272,13 @@ declare namespace Scripting {
/**
* Delete a file
* @param boolean [Force=false]
* @param boolean [Force=false] Pass `true` to also delete files with the read-only attribute set
*/
DeleteFile(FileSpec: string, Force?: boolean): void;
/**
* Delete a folder
* @param boolean [Force=false]
* @param boolean [Force=false] Pass `true` to also delete folders with the read-only attribute set
*/
DeleteFolder(FolderSpec: string, Force?: boolean): void;
@@ -317,13 +346,16 @@ declare namespace Scripting {
* Open a file as a TextStream
* @param Scripting.IOMode [IOMode=1]
* @param boolean [Create=false]
* @param Scripting.Tristate [Format=0]
* @param Scripting.Tristate [Format=0] **TristateTrue** opens the file as Unicode; **TristateFalse** opens the file as ASCII; **TristateUseDefault** opens the file with the system default
*/
OpenTextFile(FileName: string, IOMode?: IOMode, Create?: boolean, Format?: Tristate): TextStream;
}
/** Folder object */
interface Folder {
class Folder {
private constructor();
private 'Scripting.Folder_typekey': Folder;
/** Folder attributes */
Attributes: FileAttribute;
@@ -351,7 +383,7 @@ declare namespace Scripting {
/**
* Delete this folder
* @param boolean [Force=false]
* @param boolean [Force=false] Pass `true` to delete the folder even if the read-only attribute set
*/
Delete(Force?: boolean): void;
@@ -383,7 +415,7 @@ declare namespace Scripting {
readonly ShortPath: string;
/** Sum of files and subfolders */
readonly Size: any;
readonly Size: number;
/** Get folders collection */
readonly SubFolders: Folders;
@@ -400,12 +432,18 @@ declare namespace Scripting {
/** Number of folders */
readonly Count: number;
/** Get folder */
Item(Key: any): Folder;
/** Get folder in collection using the folder's name */
Item(Key: string): Folder;
/** Get folder in collection using the folder's name */
(Key: string): Folder;
}
/** TextStream object */
interface TextStream {
class TextStream {
private constructor();
private 'Scripting.TextStream_typekey': TextStream;
/** Is the current position at the end of a line? */
readonly AtEndOfLine: boolean;
@@ -451,15 +489,12 @@ declare namespace Scripting {
}
interface ActiveXObject {
new <K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
set(obj: Scripting.Dictionary, propertyName: 'Item', parameterTypes: [any], newValue: any): void;
new(progid: 'Scripting.Dictionary'): Scripting.Dictionary;
new(progid: 'Scripting.Encoder'): Scripting.Encoder;
new(progid: 'Scripting.FileSystemObject'): Scripting.FileSystemObject;
}
interface EnumeratorConstructor {
new(col: Scripting.Dictionary): any;
new(col: Scripting.Drives): Scripting.Drive;
new(col: Scripting.Files): Scripting.File;
new(col: Scripting.Folders): Scripting.Folder;
interface ActiveXObjectNameMap {
'Scripting.Dictionary': Scripting.Dictionary;
'Scripting.Encoder': Scripting.Encoder;
'Scripting.FileSystemObject': Scripting.FileSystemObject;
}
+3 -1
View File
@@ -1 +1,3 @@
{ "extends": "dtslint/dt.json" }
{
"extends": "dtslint/dt.json"
}
@@ -0,0 +1,12 @@
// https://msdn.microsoft.com/en-us/library/aa752044(v=vs.85).aspx
(() => {
const ie = new ActiveXObject('InternetExplorer.Application');
ie.Navigate('http://contoso.com');
ie.Visible = true;
})();
let obj1 = new ActiveXObject('ShellNameSpace.ShellNameSpace');
let obj2 = new ActiveXObject('Shell.UIHelper');
let obj3 = new ActiveXObject('Shell.Explorer');
+1577
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-shdocvw-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+489
View File
@@ -0,0 +1,489 @@
/// <reference types="activex-iwshruntimelibrary" />
const shell = new ActiveXObject('Shell.Application');
const getWindowsFolder = () => shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfWINDOWS);
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537735(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
if (!folder) { return; }
const folderItem = folder.ParseName('system.ini');
if (!folderItem) { return; }
shell.AddToRecent(folderItem.Path);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774065(v=vs.85).aspx
(() => {
const folder = shell.BrowseForFolder(0, 'Example', 0, Shell32.ShellSpecialFolderConstants.ssfWINDOWS);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537736(v=vs.85).aspx
const canStartStop = shell.CanStartStopService('service name');
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774069(v=vs.85).aspx
shell.ControlPanelItem('desk.cpl');
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774073(v=vs.85).aspx
shell.Explore('C:\\');
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537737(v=vs.85).aspx
const explorerPolicy = shell.ExplorerPolicy('ValueName');
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537739(v=vs.85).aspx
const settingValue = shell.GetSetting(Shell32.SettingKey.SSF_SHOWALLOBJECTS);
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537740(v=vs.85).aspx
const processorLevel = shell.GetSystemInformation('ProcessorLevel');
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537741(v=vs.85).aspx
const isRestricted = shell.IsRestricted('system', 'undockwithoutlogon');
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537742(v=vs.85).aspx
const isServiceRunning = shell.IsServiceRunning('Themes');
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774086(v=vs.85).aspx
shell.Open(Shell32.ShellSpecialFolderConstants.ssfWINDOWS);
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537743(v=vs.85).aspx
shell.ServiceStart('Messenger', true);
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537744(v=vs.85).aspx
shell.ServiceStop('Messenger', true);
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537745(v=vs.85).aspx
shell.ShellExecute("notepad.exe", "", "", "open", Shell32.ShellExecuteShow.Normal);
// https://msdn.microsoft.com/en-us/library/windows/desktop/gg537746(v=vs.85).aspx?cs-save-lang=1&cs-lang=jscript#code-snippet-1
shell.ShowBrowserBar(Shell32.ExplorerBarCLSID.Favorites, true);
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774107(v=vs.85).aspx
const wshShell = new ActiveXObject('WScript.Shell');
wshShell.Popup(shell.Windows().Count.toString());
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787866(v=vs.85).aspx
shell.NameSpace(`c:\\windows`)!.CopyHere('c:\\autoexec.bat');
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787870(v=vs.85).aspx
(() => {
const folder = shell.NameSpace('c:\\windows');
const folderItem = folder ? folder.ParseName('clock.avi') : undefined;
if (folder && folderItem) {
const info = folder.GetDetailsOf(folderItem, Shell32.FileSystemDetails.Type);
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787874(v=vs.85).aspx
shell.NameSpace('c:\\windows')!.MoveHere('c:\\temp.txt', Shell32.FileOperationFlag.FOF_NOCONFIRMATION);
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787876(v=vs.85).aspx
shell.NameSpace('c:\\')!.NewFolder('TestFolder');
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787858(v=vs.85).aspx
(() => {
const folder = shell.NameSpace("\\\\server\\share\\folder");
const offlineStatus = folder ? folder.OfflineStatus : undefined;
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787880(v=vs.85).aspx
(() => {
const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS);
WScript.Echo(folder!.ParentFolder.Title);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787860(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787816(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787850(v=vs.85).aspx
(() => {
const folder = shell.NameSpace('C:\\WINDOWS');
const folderItem = folder ? folder.Self : undefined;
if (folderItem) {
const verbs = folderItem.Verbs();
folderItem.InvokeVerb();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787812(v=vs.85).aspx
(() => {
const parentFolder = getWindowsFolder();
const folderItem = parentFolder ? parentFolder.ParseName('system32') : undefined;
const folder = folderItem ? folderItem.GetFolder : undefined;
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787814(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787824(v=vs.85).aspx
(() => {
const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS);
const folderItem = folder ? folder.ParseName('Internet Explorer.lnk') : undefined;
if (folderItem && folderItem.IsLink) {
const link = folderItem.GetLink;
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787818(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787819(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787821(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItem = folder ? folder.Self : undefined;
if (folderItem) {
const isBrowsable = folderItem.IsBrowsable;
const isFileSystem = folderItem.IsFileSystem;
const isFolder = folderItem.IsFolder;
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787825(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItem = folder!.ParseName('notepad.exe');
if (folderItem) {
const oldDate = folderItem.ModifyDate;
folderItem.ModifyDate = new Date(1900, 1, 1, 18, 5).getVarDate();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787827(v=vs.85).aspx
(() => {
const rootFolder = shell.NameSpace('C:\\');
const folderItem = rootFolder ? rootFolder.ParseName('autoexec.bat') : undefined;
if (folderItem) {
const oldName = folderItem.Name;
folderItem.Name = 'test.bat';
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787829(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItem = folder ? folder.Self : undefined;
const parent = folderItem ? folderItem.Parent : undefined;
if (parent) {
WScript.Echo('Got parent object');
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787844(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItem = folder ? folder.Self : undefined;
const path = folderItem ? folderItem.Path : '';
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787846(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItem = folder!.ParseName('notepad.exe');
const size = folderItem ? folderItem.Size : undefined;
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787848(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
if (folder) {
WScript.Echo(folder.Self.Type);
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787798(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItems = folder ? folder.Items() : undefined;
const count = folderItems ? folderItems.Count : undefined;
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787794(v=vs.85).aspx
(() => {
const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfDRIVES);
if (folder) {
folder.Items().InvokeVerbEx();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774170(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774174(v=vs.85).aspx
(() => {
const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS);
const verbs = folder ? folder.Self.Verbs() : undefined;
if (verbs) {
const verb = verbs.Item(0);
WScript.Echo(verb.Name);
verb.DoIt();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787787(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
if (folder) {
const folderItems = folder.Items();
WScript.Echo(folderItems.Count);
folderItems.Filter(Shell32.ShellFolderEnumerationFlags.SHCONTF_NONFOLDERS, '*.txt');
WScript.Echo(folderItems.Count);
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb787791(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774162(v=vs.85).aspx
(() => {
const echoFirstVerbName = (folder: Shell32.Folder3 | null) => {
if (!folder) { return; }
const verbs = folder.Items().Verbs;
WScript.Echo(verbs.Item(0).Name);
};
let folder = getWindowsFolder();
echoFirstVerbName(folder);
folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfCONTROLS);
echoFirstVerbName(folder);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774158(v=vs.85).aspx
(() => {
const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfCONTROLS);
if (folder) {
const verbs = folder.Self.Verbs();
WScript.Echo(verbs.Count);
}
})();
const getIELink = () => {
const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS);
const folderItem = folder ? folder.ParseName('Internet Explorer.lnk') : undefined;
return {
link: folderItem ? folderItem.GetLink : undefined,
folderItem
};
};
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773990(v=vs.85).aspx
(() => {
const { link, folderItem } = getIELink();
if (link && folderItem) {
WScript.Echo(link.GetIconLocation(folderItem.Path));
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773996(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
link.Resolve(Shell32.ShellLinkResolveFlags.NoUI);
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773998(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
link.Description = 'New Description';
link.Save();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774002(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
link.SetIconLocation(link.Path, 1);
link.Save();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773986(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
WScript.Echo(link.Arguments);
link.Arguments = '/s';
link.Save();
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773988(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
WScript.Echo(link.Description);
link.Description = 'Test';
link.Save();
}
})();
const parseHotkey = (hotkey: number) => {
// missing implementation
return {
shift: false,
ctrl: false,
alt: false,
extended: false,
hotkey
};
};
const buildHotkey = (hotkey: number, shift: boolean = false, ctrl: boolean = false, alt: boolean = false, extended: boolean = false) => {
// missing implementation
return 0;
};
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773992(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
const { hotkey } = parseHotkey(link.Hotkey);
WScript.Echo(hotkey);
link.Hotkey = buildHotkey(4);
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773994(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
WScript.Echo(link.Path);
link.Path = 'C:\\Program Files\\IE\\IEXPLORE.EXE';
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774006(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
WScript.Echo(link.ShowCommand);
link.ShowCommand = Shell32.LinkShowWindowState.Normal;
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774008(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
WScript.Echo(link.WorkingDirectory);
link.WorkingDirectory = '';
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774115(v=vs.85).aspx
(() => {
const { link } = getIELink();
if (link) {
const target = link.Target;
if (target) {
WScript.Echo(target.Size);
}
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774055(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItem = folder ? folder.ParseName('notepad.exe') : undefined;
if (folderItem) {
WScript.Echo(folderItem.ExtendedProperty('infotip'));
}
const wordDoc = shell.NameSpace('C:\\')!.ParseName('test.doc');
if (wordDoc) {
const FMTID_SummaryInfo = "{F29F85E0-4FF9-1068-AB91-08002B27B3D9}";
const PID_TITLE = "2";
const PID_AUTHOR = "4";
const SCID_TITLE = `${FMTID_SummaryInfo} ${PID_TITLE}`;
const SCID_AUTHOR = `${FMTID_SummaryInfo} ${PID_AUTHOR}`;
const docTitle = wordDoc.ExtendedProperty(SCID_TITLE);
const docAuthor = wordDoc.ExtendedProperty(SCID_AUTHOR);
}
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774057(v=vs.85).aspx
(() => {
const folder = getWindowsFolder();
const folderItem = folder ? folder.ParseName('notepad.exe') : undefined;
if (folderItem) {
folderItem.InvokeVerbEx("open", "c:\\autoexec.bat");
}
})();
const collectionToArray = <T>(col: any): T[] => { // tslint:disable-line no-unnecessary-generics
const results: T[] = [];
const enumerator = new Enumerator<T>(col);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
results.push(enumerator.item());
enumerator.moveNext();
}
return results;
};
interface String {
endsWith(searchString: string, length?: number): boolean;
}
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(search, this_len) {
if (this_len === undefined || this_len > this.length) {
this_len = this.length;
}
return this.substring(this_len - search.length, this_len) === search;
};
}
// shell.Windows() includes items other than Explorer windows, such as Internet Explorer tabs
const getExplorerWindows = () =>
collectionToArray<SHDocVw.InternetExplorer>(shell.Windows())
.filter(x => x.FullName.toLowerCase().endsWith('explorer.exe'));
const getFolderViews = () =>
getExplorerWindows()
.map(x => x.Document as Shell32.ShellFolderView);
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774045(v=vs.85).aspx
(() => {
getFolderViews().forEach(x =>
ActiveXObject.on(x, 'SelectionChanged', function(this: Shell32.ShellFolderView) {
WScript.Echo(`Selection change in ${this.Folder.Title} -- count: ${this.SelectedItems().Count}`);
})
);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773970(v=vs.85).aspx
WScript.Echo(shell.Windows().Item().Path);
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb773969(v=vs.85).aspx
WScript.Echo(shell.Windows().Count);
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774043(v=vs.85).aspx
(() => {
getFolderViews().forEach(x =>
WScript.Echo(`${x.Folder.Title} -- ${x.SelectedItems().Count} selected items`)
);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774047(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774022(v=vs.85).aspx
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774053(v=vs.85).aspx
(() => {
const folderView = getExplorerWindows()[0].Document as Shell32.ShellFolderView;
const folder = folderView.Folder;
if (folder) {
const folderItem = folder.Self;
folderView.SelectItem(folder.Self, Shell32.ShellFolderViewSelectItem.Focus);
}
WScript.Echo(folderView.ViewOptions);
})();
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb774020(v=vs.85).aspx
(() => {
const folderView = getExplorerWindows()[0].Document as Shell32.ShellFolderView;
const focusedItem = folderView.FocusedItem;
if (focusedItem) {
WScript.Echo(`Focused item in first Excplorer window -- ${focusedItem.Path}`);
}
})();
(() => {
const router = new ActiveXObject('Shell.FolderView');
const folder = getFolderViews()[0];
router.SetFolderView(folder);
ActiveXObject.on(router, 'EnumDone', () => WScript.Echo('Current folder view was finisehd enumerating'));
ActiveXObject.on(router, 'SelectionChanged', () => WScript.Echo('Selection changed in current folder view'));
// the folder view monitored by the ShellFolderViewOC object can be changed via SetFolderView without disconnecting and reconnecting the handlers
})();
+1016
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-shell-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}
+492 -66
View File
@@ -1,79 +1,505 @@
// Note -- running these tests under cscript requires some ES5 polyfills
const collectionToArray = <T>(col: { Item(key: any): T }): T[] => {
const results: T[] = [];
const enumerator = new Enumerator<T>(col);
enumerator.moveFirst();
while (!enumerator.atEnd()) {
results.push(enumerator.item());
enumerator.moveNext();
}
return results;
};
// source -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms630826(v=vs.85).aspx
{
const cd = new ActiveXObject('WIA.CommonDialog');
const dm = new ActiveXObject('WIA.DeviceManager');
// Convert a file
let commonDialog = new ActiveXObject('WIA.CommonDialog');
let img = commonDialog.ShowAcquireImage();
// Download new items as they are created
{
dm.RegisterEvent(WIA.EventID.wiaEventItemCreated, WIA.Miscellaneous.wiaAnyDeviceID);
ActiveXObject.on(dm, 'OnEvent', ['EventID', 'DeviceID', 'ItemID'], x => {
const dev = dm.DeviceInfos(x.DeviceID).Connect();
const itm = dev.GetItem(x.ItemID);
const img = cd.ShowTransfer(itm);
const v = img.FileData;
// Picture type not available in Javascript
});
}
// when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these:
let jpegFormatID = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}';
if (img.FormatID !== jpegFormatID) {
const ip = new ActiveXObject('WIA.ImageProcess');
ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID);
ip.Filters.Item(1).Properties.Item('FormatID').Value = jpegFormatID;
img = ip.Apply(img);
}
// with this:
/*if (img.FormatID !== WIA.FormatID.wiaFormatJPEG) {
let ip = new ActiveXObject('WIA.ImageProcess');
ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID);
ip.Filters.Item(1).Properties.Item('FormatID').Value = WIA.FormatID.wiaFormatJPEG;
img = ip.Apply(img);
}*/
// Take a picture
let dev = commonDialog.ShowSelectDevice();
if (dev.Type === WIA.WiaDeviceType.CameraDeviceType) {
// when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these:
const commandID = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}';
const itm = dev.ExecuteCommand(commandID);
// with this:
// let itm = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture);
}
// Display detailed property information
dev = commonDialog.ShowSelectDevice();
let e = new Enumerator<WIA.Property>(dev.Properties); // no foreach over ActiveX collections
e.moveFirst();
while (!e.atEnd()) {
const p = e.item();
let s = `${p.Name} (${p.PropertyID}) = `;
if (p.IsVector) {
s += '[vector of data]';
} else {
s += p.Value;
if (p.SubType !== WIA.WiaSubType.UnspecifiedSubType) {
if (p.Value !== p.SubTypeDefault) {
s += ` (Default = ${p.SubTypeDefault})`;
}
// Convert a file
{
let img = cd.ShowAcquireImage();
if (img && img.FormatID !== WIA.FormatID.wiaFormatJPEG) {
const ip = new ActiveXObject('WIA.ImageProcess');
ip.Filters.Add(ip.FilterInfos('Convert').FilterID);
ip.Filters(1).Properties('FormatID').Value = WIA.FormatID.wiaFormatJPEG;
img = ip.Apply(img);
}
}
if (p.IsReadOnly) {
s += ' [READ ONLY]';
} else {
switch (p.SubType) {
case WIA.WiaSubType.FlagSubType:
case WIA.WiaSubType.ListSubType:
if (p.SubType === WIA.WiaSubType.FlagSubType) {
s += ' [valid flags include: ';
// Take a picture
{
const dev = cd.ShowSelectDevice();
if (dev && dev.Type === WIA.WiaDeviceType.CameraDeviceType) {
const item = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture);
}
}
// Display detailed property information
{
const dev = cd.ShowSelectDevice();
if (dev) {
collectionToArray(dev.Properties).forEach(p => {
let s = `${p.Name} (${p.PropertyID}) = `;
if (p.IsVector) {
s += '[vector of data]';
} else {
s += ' [valid values include: ';
}
const count = p.SubTypeValues.Count;
for (let i = 1; i <= count; i++) {
s += p.SubTypeValues.Item(i);
if (i < count) {
s += ', ';
s += p.Value;
if (p.SubType !== WIA.WiaSubType.UnspecifiedSubType
&& p.Value !== p.SubTypeDefault) {
s += ` (Default = ${p.SubTypeDefault})`;
}
}
s += ']';
break;
case WIA.WiaSubType.RangeSubType:
s += ` [valid values in the range from ${p.SubTypeMin} to ${p.SubTypeMax} in increments of ${p.SubTypeStep}]`;
break;
if (p.IsReadOnly) {
s += ' [READ ONLY]';
} else {
switch (p.SubType) {
case WIA.WiaSubType.FlagSubType:
case WIA.WiaSubType.ListSubType:
const count = p.SubTypeValues.Count;
const items: string[] = [];
for (let i = 1; i <= count; i++) {
items.push(p.SubTypeValues(i));
}
const descr = p.SubType === WIA.WiaSubType.FlagSubType ? 'flags' : 'values';
s += ` [valid ${descr} include: ${items.join(',')}]`;
break;
case WIA.WiaSubType.RangeSubType:
s += ` [valid values in the range from ${p.SubTypeMin} to ${p.SubTypeMax} in increments of ${p.SubTypeStep}]`;
break;
}
}
WScript.Echo(s);
});
}
}
WScript.Echo(s);
// Determine whether the selected device is a camera
{
const dev = cd.ShowSelectDevice();
if (dev && dev.Type === WIA.WiaDeviceType.CameraDeviceType) {
WScript.Echo('Selectd device is a camera');
}
}
// Count root - level images for transfer
{
const dev = cd.ShowSelectDevice();
if (dev) {
const count = collectionToArray(dev.Items).filter(f => {
const imageFlag = WIA.WiaItemFlag.ImageItemFlag;
return (f.Properties('Item Flags').Value & imageFlag) === imageFlag;
}).length;
WScript.Echo(`Selected device has ${count} top-level images`);
}
}
// Display all imagefile properties
{
const img = cd.ShowAcquireImage();
if (img) {
collectionToArray(img.Properties).forEach(p => {
let contents = '';
if (p.IsVector) {
contents = '[vector data not emitted]';
} else if (p.Type === WIA.WiaImagePropertyType.RationalImagePropertyType) {
contents = `${p.Value.Nunerator}/${p.Value.Denominator}`;
} else if (p.Type === WIA.WiaImagePropertyType.StringImagePropertyType) {
contents = `"${p.Value}"`;
} else {
contents = p.Value;
}
WScript.Echo(`${p.Name} (${p.PropertyID}) = ${contents}`);
});
}
}
// Determine the event type
{
const dev = cd.ShowSelectDevice();
if (dev) {
const actionEvent = WIA.WiaEventFlag.ActionEvent;
collectionToArray(dev.Events).forEach(e => {
const msg = (e.Type & actionEvent) === actionEvent ?
`${e.Name} is an Action event` :
`${e.Name} is not an Action event`;
WScript.Echo(msg);
});
}
}
// Set rational numerator and denominator
{
const r = new ActiveXObject('WIA.Rational');
r.Numerator = 1;
r.Denominator = 3;
WScript.Echo(`1/3 = ${r.Value}`);
r.Numerator = 2;
r.Denominator = 6;
WScript.Echo(`2/6 = ${r.Value}`);
}
// Create and initialize a vector object
{
const v: WIA.Vector<number> = new ActiveXObject('WIA.Vector');
v.SetFromString('This is a test', true, false);
// when iterated using Enumerator / collectionToArray, each item comes back as an Automation Byte
// https://stackoverflow.com/questions/48757982/wia-vector-returns-something-which-is-not-a-number
// so the following falls, because fromCharCode is expecting a number
// collectionToArray(v).forEach(item => WScript.Echo(String.fromCharCode(item)));
// Instead, use the Vector's Item method, or the Vector's default property:
for (let i = 1; i <= v.Count; i++) {
WScript.Echo(String.fromCharCode(v(i)));
}
}
// Display detailed image information
{
const img = new ActiveXObject('WIA.ImageFile');
img.LoadFile('c:\\windows\\web\\Screen\\img102.jpg');
let s = `
Width = ${img.Width}
Height = ${img.Height}
Depth = ${img.PixelDepth}
Horizontal resolution = ${img.HorizontalResolution}
Vertical resolution = ${img.VerticalResolution}
Frame count = ${img.FrameCount}}
`.trim();
let arr: string[] = [];
if (img.IsIndexedPixelFormat) { arr.push('Pixel data contains palette indexes'); }
if (img.IsAlphaPixelFormat) { arr.push('Pixel data has alpha information'); }
if (img.IsExtendedPixelFormat) { arr.push('Pixel data has extended color information (16 bit/channel)'); }
if (img.IsAnimated) { arr.push('Image is animated'); }
const propertyTests = [40091, 40092, 40093, 40094, 40095]
.filter(n => img.Properties.Exists(n))
.map(n => {
const prp = img.Properties(n);
return `${prp.Name} = ${prp.Value.String}`;
});
arr = arr.concat(propertyTests);
if (arr.length) {
s += '\n' + arr.join('\n');
}
WScript.Echo(s);
}
// Create an imageprocess object and enumerate filters
{
const ip = new ActiveXObject('WIA.ImageProcess');
collectionToArray(ip.FilterInfos).forEach(fi => {
const s = [
fi.Name,
new Array(51).join('='),
fi.Description
].join('\n');
WScript.Echo(s);
});
}
// Create an imageprocess object and create one of each available filter
{
const ip = new ActiveXObject('WIA.ImageProcess');
const stringValue = (v: any) => {
if (typeof v === 'string') { return `"${v}"`; }
return v;
};
const listValues = (v: any) => collectionToArray(v).join(', ');
const listProperties = (filter: WIA.Filter) => {
let s = [
`${filter.Name} (${filter.FilterID})`,
new Array(51).join('='),
filter.Description,
new Array(51).join('=')
].map(line => line + '\n').join('');
s += collectionToArray(filter.Properties).map(p => {
let contents: string;
switch (typeof p.Value) {
// these case clauses replace the IsObject function in VB6/VBScript
case 'boolean':
case 'string':
case 'number':
contents = stringValue(p.Value);
default:
switch (p.SubType) {
case WIA.WiaSubType.FlagSubType:
contents = ` // [valid values formed by using the OR operator with the following bit flags: ${listValues(p.SubTypeValues)}]`;
break;
case WIA.WiaSubType.ListSubType:
contents = ` // [valid values from the following list: ${listValues(p.SubTypeValues)}]`;
break;
case WIA.WiaSubType.RangeSubType:
contents = ` // [valid values between ${p.SubTypeMin} and ${p.SubTypeMax}, with a step of ${p.SubTypeStep}]`;
break;
default:
contents = '';
break;
}
}
return `ip.Filters(1).Properties("${p.Name}") = ${contents}`;
}).join('\n');
WScript.Echo(s);
};
collectionToArray(ip.FilterInfos).forEach(fi => {
ip.Filters.Add(fi.FilterID);
listProperties(ip.Filters(1));
ip.Filters.Remove(1);
});
}
// List the supported transfer formats
{
const stringFormat = (fld: string) => {
switch (fld) {
case WIA.FormatID.wiaFormatBMP: return 'BMP';
case WIA.FormatID.wiaFormatPNG: return 'PNG';
case WIA.FormatID.wiaFormatGIF: return 'GIF';
case WIA.FormatID.wiaFormatJPEG: return 'JPEG';
case WIA.FormatID.wiaFormatTIFF: return 'TIFF';
default: return 'Unknown';
}
};
const dev = cd.ShowSelectDevice();
const items = dev && cd.ShowSelectItems(dev, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true);
if (items) {
WScript.Echo(collectionToArray(items(1).Formats).map(stringFormat).join(', '));
}
}
// Enumerate supported commands in commands collection
{
const dev = cd.ShowSelectDevice();
if (dev && collectionToArray(dev.Commands).some(dc => dc.CommandID === WIA.CommandID.wiaCommandTakePicture)) {
WScript.Echo('Selected device supports the TakePicture command');
}
}
// Enumerate root - level items and display their names
{
const dev = cd.ShowSelectDevice();
if (dev) {
collectionToArray(dev.Items).forEach(item => {
let s: string = item.Properties("Item Name").Value;
if (item.Properties.Exists("Item Time Stamp")) {
const v: WIA.Vector = item.Properties("Item Time Stamp").Value;
if (v.Count === 8) { s += ` (${v.Date})`; }
}
WScript.Echo(s);
});
}
}
// Determine the number of items returned by ShowSelectItems
{
const dev = cd.ShowSelectDevice();
const items = dev && cd.ShowSelectItems(dev, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true);
if (items) {
WScript.Echo(`You selected ${items.Count} items`);
}
}
// Enumerate all the supported events for the selected device
{
const dev = cd.ShowSelectDevice();
if (dev) {
const msg = collectionToArray(dev.Events)
.map(e => `\n${e.Name} (${e.EventID}): ${e.Description}`)
.join('');
WScript.Echo('The selected device supports the following events: ' + msg);
}
}
// List all available devices by name and deviceid
collectionToArray(dm.DeviceInfos).forEach(di => {
const name: string = di.Properties("Name").Value;
WScript.Echo(`${name} (${di.DeviceID})`);
});
// Display all the properties for the selected device
{
const dev = cd.ShowSelectDevice();
if (dev) {
collectionToArray(dev.Properties).forEach(p => {
const name = `${p.Name} (${p.PropertyID})`;
let contents: string;
if (p.IsVector) {
contents = '[vector of data]';
} else if (p.Type === WIA.WiaPropertyType.StringPropertyType) {
contents = `"${p.Value}"`;
} else {
contents = p.Value;
}
WScript.Echo(`${name} = ${contents}`);
});
}
}
// Enumerate the supported commands
{
const dev = cd.ShowSelectDevice();
const items = dev && cd.ShowSelectItems(dev, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true);
if (items) {
const msg = collectionToArray(items(1).Commands)
.map(c => `${c.Name}: ${c.Description}\n`)
.join('');
WScript.Echo(`The selected item supports the following commands:\n${msg}`);
}
}
// Create an imagefile object that contains a blank page
{
// This fails with the error: `The Vector's Type is not compatible with this operation`
/*const c = 0xFF0000FF;
const v: WIA.Vector<number> = new ActiveXObject('WIA.Vector');
for (let i = 0; i < 4; i++) {
v.Add(c);
}
const img = v.ImageFile(2, 2);
img.SaveFile('C:\\test.' + img.FileExtension);*/
}
interface WshArgumentsBase<TKey = number | string> {
Item(index: TKey): string;
(index: TKey): string;
length: number;
Count(): number;
}
interface WshArguments extends WshArgumentsBase { // not sure if WshArguments takes a string as well, or only a number
Named: WshArgumentsBase<string>;
Unnamed: WshArgumentsBase<number>;
ShowUsage(): void;
}
// Implement a windows script host script that runs automatically
{
const args = collectionToArray(WScript.Arguments as WshArguments)
.map(arg => arg.toLowerCase());
switch (args.length) {
case 1:
case 2:
const command = `${WScript.FullName} "${WScript.ScriptFullName}" connect`;
const name = 'QuickTransfer';
const title = 'Quick Scripting Transfer';
const icon = `${WScript.FullName}, 0`;
const eventID = WIA.EventID.wiaEventDeviceConnected;
const deviceID = args.length === 2 ? args[1] : WIA.Miscellaneous.wiaAnyDeviceID;
if (args[0] === 'register') {
WScript.Echo('Registering event handler');
dm.RegisterPersistentEvent(command, name, title, icon, eventID, deviceID);
WScript.Quit();
} else if (args[0] === 'unregister') {
WScript.Echo('Unregistering event handler');
dm.UnregisterPersistentEvent(command, name, title, icon, eventID, deviceID);
WScript.Quit();
}
break;
case 3:
if (args[0] === 'connect') {
const deviceID = args[1].substr(12);
const device = dm.DeviceInfos(deviceID).Connect();
collectionToArray(device.Items).forEach(item => {
const img = item.Transfer();
img.SaveFile(`C:\\${item.Properties('Item Name').Value}.${img.FileExtension}`);
// Uncomment the following lines to remove the picture from the camera after transfer
for (let i = 1; i < device.Items.Count; i++) {
const item2 = device.Items(i);
if (item2.ItemID !== item.ItemID) { continue; }
try {
// some cameras don't support deleting a picture
device.Items.Remove(i);
} catch (error) {
WScript.Echo(error);
}
}
});
WScript.Quit();
}
break;
}
const usage = `
Usage:
To register, type:
${WScript.ScriptName} register [<device id>]
To unregister, type:
${WScript.ScriptName} unregister [<device id>]
Available device ids:
${collectionToArray(dm.DeviceInfos)
.map(device => `${device.DeviceID} '${device.Properties("Name").Value}'`)
.join('\n')}
`.trim();
WScript.Echo(usage);
}
// Count the number of child items available for transfer
{
const device = cd.ShowSelectDevice();
const items = device && cd.ShowSelectItems(device, WIA.WiaImageIntent.UnspecifiedIntent, WIA.WiaImageBias.MaximizeQuality, true);
const item = items && items(1);
if (item) {
const count = collectionToArray(item.Items).filter(childItem => {
const flags = childItem.Properties('Item Flags').Value as number;
return (flags & WIA.WiaItemFlag.TransferItemFlag) === WIA.WiaItemFlag.TransferItemFlag;
}).length;
WScript.Echo(`Selected device has ${count} child items that can be transferred.`);
}
}
// Use a vector object
{
const v: WIA.Vector<number | string> = new ActiveXObject('WIA.Vector');
v.Add(1);
v.Add(42);
v.Add(3);
v.Remove(1);
v.Remove(2);
WScript.Echo(`v(1) = ${v(1)}`);
v.Clear();
v.Add('This');
v.Add('is');
v.Add('Cool');
v.Remove(1);
v.Remove(2);
WScript.Echo(`v(1) = ${v(1)}`);
}
}
+196 -148
View File
@@ -2,22 +2,20 @@
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms630368(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Typescript Version: 2.4
// TypeScript Version: 2.6
declare namespace WIA {
/** String versions of globally unique identifiers (GUIDs) that identify common Device and Item commands. */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum CommandID {
const enum CommandID {
wiaCommandChangeDocument = '{04E725B0-ACAE-11D2-A093-00C04F72DC3C}',
wiaCommandDeleteAllItems = '{E208C170-ACAD-11D2-A093-00C04F72DC3C}',
wiaCommandSynchronize = '{9B26B7B2-ACAD-11D2-A093-00C04F72DC3C}',
wiaCommandTakePicture = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}',
wiaCommandUnloadDocument = '{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}'
}*/
wiaCommandUnloadDocument = '{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}',
}
/** String versions of globally unique identifiers (GUIDs) that identify DeviceManager events. */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum EventID {
const enum EventID {
wiaEventDeviceConnected = '{A28BBADE-64B6-11D2-A231-00C04FA31809}',
wiaEventDeviceDisconnected = '{143E4E83-6497-11D2-A231-00C04FA31809}',
wiaEventItemCreated = '{4C8F4EF5-E14F-11D2-B326-00C04F68CE61}',
@@ -30,50 +28,48 @@ declare namespace WIA {
wiaEventScanImage3 = '{154E27BE-B617-4653-ACC5-0FD7BD4C65CE}',
wiaEventScanImage4 = '{A65B704A-7F3C-4447-A75D-8A26DFCA1FDF}',
wiaEventScanOCRImage = '{9D095B89-37D6-4877-AFED-62A297DC6DBE}',
wiaEventScanPrintImage = '{B441F425-8C6E-11D2-977A-0000F87A926F}'
}*/
wiaEventScanPrintImage = '{B441F425-8C6E-11D2-977A-0000F87A926F}',
}
/** String versions of globally unique identifiers (GUIDs) that indicate the file format of an image. */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum FormatID {
const enum FormatID {
wiaFormatBMP = '{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatGIF = '{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatJPEG = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatPNG = '{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}',
wiaFormatTIFF = '{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}'
}*/
wiaFormatTIFF = '{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}',
}
/** Miscellaneous string constants */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum Miscellaneous {
const enum Miscellaneous {
wiaAnyDeviceID = '*',
wiaIDUnknown = '{00000000-0000-0000-0000-000000000000}'
}*/
wiaIDUnknown = '{00000000-0000-0000-0000-000000000000}',
}
/**
* The WiaDeviceType enumeration specifies the type of device attached to a user's computer. Use the Type property on the DeviceInfo object or the Device
* object to obtain these values from the device.
* object to obtain these values from the device.
*/
const enum WiaDeviceType {
CameraDeviceType = 2,
ScannerDeviceType = 1,
UnspecifiedDeviceType = 0,
VideoDeviceType = 3
VideoDeviceType = 3,
}
/**
* A DeviceEvent's type is composed of bits from the WiaEventFlags enumeration. You can test a DeviceEvent's type by using the AND operation with DeviceEv
* ent.Type and a member from the WiaEventFlags enumeration.
* A DeviceEvent's type is composed of bits from the WiaEventFlags enumeration. You can test a DeviceEvent's type by using the AND operation with
* DeviceEvent.Type and a member from the WiaEventFlags enumeration.
*/
const enum WiaEventFlag {
ActionEvent = 2,
NotificationEvent = 1
NotificationEvent = 1,
}
/** The WiaImageBias enumeration helps specify what type of data the image is intended to represent. */
const enum WiaImageBias {
MaximizeQuality = 131072,
MinimizeSize = 65536
MinimizeSize = 65536,
}
/** The WiaImageIntent enumeration helps specify what type of data the image is intended to represent. */
@@ -81,12 +77,12 @@ declare namespace WIA {
ColorIntent = 1,
GrayscaleIntent = 2,
TextIntent = 4,
UnspecifiedIntent = 0
UnspecifiedIntent = 0,
}
/**
* The WiaImagePropertyType enumeration specifies the type of the value of an image property. Image properties can be found in the Properties collection o
* f an ImageFile object.
* The WiaImagePropertyType enumeration specifies the type of the value of an image property. Image properties can be found in the Properties collection
* of an ImageFile object.
*/
const enum WiaImagePropertyType {
ByteImagePropertyType = 1001,
@@ -103,12 +99,12 @@ declare namespace WIA {
VectorOfUndefinedImagePropertyType = 1100,
VectorOfUnsignedIntegersImagePropertyType = 1102,
VectorOfUnsignedLongsImagePropertyType = 1104,
VectorOfUnsignedRationalsImagePropertyType = 1106
VectorOfUnsignedRationalsImagePropertyType = 1106,
}
/**
* An Item's type is composed of bits from the WiaItemFlags enumeration. You can test an Item's type by using the AND operation with Item.Properties("Item
* Flags") and a member from the WiaItemFlags enumeration.
* An Item's type is composed of bits from the WiaItemFlags enumeration. You can test an Item's type by using the AND operation with
* Item.Properties("Item Flags") and a member from the WiaItemFlags enumeration.
*/
const enum WiaItemFlag {
AnalyzeItemFlag = 16,
@@ -129,12 +125,12 @@ declare namespace WIA {
StorageItemFlag = 4096,
TransferItemFlag = 8192,
VideoItemFlag = 65536,
VPanoramaItemFlag = 1024
VPanoramaItemFlag = 1024,
}
/**
* The WiaPropertyType enumeration specifies the type of the value of an item property. Item properties can be found in the Properties collection of a Dev
* ice or Item object.
* The WiaPropertyType enumeration specifies the type of the value of an item property. Item properties can be found in the Properties collection of a
* Device or Item object.
*/
const enum WiaPropertyType {
BooleanPropertyType = 1,
@@ -173,28 +169,31 @@ declare namespace WIA {
VectorOfUnsignedIntegersPropertyType = 104,
VectorOfUnsignedLargeIntegersPropertyType = 109,
VectorOfUnsignedLongsPropertyType = 106,
VectorOfVariantsPropertyType = 119
VectorOfVariantsPropertyType = 119,
}
/**
* The WiaSubType enumeration specifies more detail about the property value. Use the SubType property on the Property object to obtain these values for t
* he property.
* The WiaSubType enumeration specifies more detail about the property value. Use the SubType property on the Property object to obtain these values for
* the property.
*/
const enum WiaSubType {
FlagSubType = 3,
ListSubType = 2,
RangeSubType = 1,
UnspecifiedSubType = 0
UnspecifiedSubType = 0,
}
/**
* The CommonDialog control is an invisible-at-runtime control that contains all the methods that display a User Interface. A CommonDialog control can be
* created using "WIA.CommonDialog" in a call to CreateObject or by dropping a CommonDialog on a form.
* created using "WIA.CommonDialog" in a call to CreateObject or by dropping a CommonDialog on a form.
*/
interface CommonDialog {
class CommonDialog {
private constructor();
private 'WIA.CommonDialog_typekey': CommonDialog;
/**
* Displays one or more dialog boxes that enable the user to acquire an image from a hardware device for image acquisition and returns an ImageFile object
* on success, otherwise Nothing
* Displays one or more dialog boxes that enable the user to acquire an image from a hardware device for image acquisition and returns an ImageFile
* object on success, otherwise Nothing
* @param WIA.WiaDeviceType [DeviceType=0]
* @param WIA.WiaImageIntent [Intent=0]
* @param WIA.WiaImageBias [Bias=131072]
@@ -203,11 +202,11 @@ declare namespace WIA {
* @param boolean [UseCommonUI=true]
* @param boolean [CancelError=false]
*/
ShowAcquireImage(
DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean, CancelError?: boolean): ImageFile;
ShowAcquireImage(DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean,
CancelError?: boolean): ImageFile | null;
/** Launches the Windows Scanner and Camera Wizard and returns Nothing. Future versions may return a collection of ImageFile objects. */
ShowAcquisitionWizard(Device: Device): any;
ShowAcquisitionWizard(Device: Device): null;
/**
* Displays the properties dialog box for the specified Device
@@ -222,38 +221,41 @@ declare namespace WIA {
ShowItemProperties(Item: Item, CancelError?: boolean): void;
/** Launches the Photo Printing Wizard with the absolute path of a specific file or Vector of absolute paths to files */
ShowPhotoPrintingWizard(Files: any): void;
ShowPhotoPrintingWizard(Files: string | Vector<string>): void;
/**
* Displays a dialog box that enables the user to select a hardware device for image acquisition. Returns the selected Device object on success, otherwise
* Nothing
* Displays a dialog box that enables the user to select a hardware device for image acquisition. Returns the selected Device object on success,
* otherwise Nothing
* @param WIA.WiaDeviceType [DeviceType=0]
* @param boolean [AlwaysSelectDevice=false]
* @param boolean [CancelError=false]
*/
ShowSelectDevice(DeviceType?: WiaDeviceType, AlwaysSelectDevice?: boolean, CancelError?: boolean): Device;
ShowSelectDevice(DeviceType?: WiaDeviceType, AlwaysSelectDevice?: boolean, CancelError?: boolean): Device | null;
/**
* Displays a dialog box that enables the user to select an item for transfer from a hardware device for image acquisition. Returns the selection as an It
* ems collection on success, otherwise Nothing
* Displays a dialog box that enables the user to select an item for transfer from a hardware device for image acquisition. Returns the selection as an
* Items collection on success, otherwise Nothing
* @param WIA.WiaImageIntent [Intent=0]
* @param WIA.WiaImageBias [Bias=131072]
* @param boolean [SingleSelect=true]
* @param boolean [UseCommonUI=true]
* @param boolean [CancelError=false]
*/
ShowSelectItems(Device: Device, Intent?: WiaImageIntent, Bias?: WiaImageBias, SingleSelect?: boolean, UseCommonUI?: boolean, CancelError?: boolean): Items;
ShowSelectItems(Device: Device, Intent?: WiaImageIntent, Bias?: WiaImageBias, SingleSelect?: boolean, UseCommonUI?: boolean, CancelError?: boolean): Items | null;
/**
* Displays a progress dialog box while transferring the specified Item to the local machine. See Item.Transfer for additional information.
* @param string [FormatID='{00000000-0000-0000-0000-000000000000}']
* @param boolean [CancelError=false]
*/
ShowTransfer(Item: Item, FormatID?: string, CancelError?: boolean): any;
ShowTransfer(Item: Item, FormatID?: string, CancelError?: boolean): ImageFile;
}
/** The Device object represents an active connection to an imaging device. */
interface Device {
class Device {
private constructor();
private 'WIA.Device_typekey': Device;
/** A collection of all commands for this imaging device */
readonly Commands: DeviceCommands;
@@ -264,8 +266,8 @@ declare namespace WIA {
readonly Events: DeviceEvents;
/**
* Issues the command specified by CommandID to the imaging device. CommandIDs are device dependent. Valid CommandIDs for this Device are contained in the
* Commands collection.
* Issues the command specified by CommandID to the imaging device. CommandIDs are device dependent. Valid CommandIDs for this Device are contained in
* the Commands collection.
*/
ExecuteCommand(CommandID: string): Item;
@@ -280,13 +282,13 @@ declare namespace WIA {
/** Returns the Type of Device */
readonly Type: WiaDeviceType;
/** Returns the underlying IWiaItem interface for this Device object */
readonly WiaItem: any;
}
/** The DeviceCommand object describes a CommandID that can be used when calling ExecuteCommand on a Device or Item object. */
interface DeviceCommand {
class DeviceCommand {
private constructor();
private 'WIA.DeviceCommand_typekey': DeviceCommand;
/** Returns the commandID for this Command */
readonly CommandID: string;
@@ -298,8 +300,8 @@ declare namespace WIA {
}
/**
* The DeviceCommands object is a collection of all the supported DeviceCommands for an imaging device. See the Commands property of a Device or Item obje
* ct for more details on determining the collection of supported device commands.
* The DeviceCommands object is a collection of all the supported DeviceCommands for an imaging device. See the Commands property of a Device or Item
* object for more details on determining the collection of supported device commands.
*/
interface DeviceCommands {
/** Returns the number of members in the collection */
@@ -307,10 +309,16 @@ declare namespace WIA {
/** Returns the specified item in the collection by position */
Item(Index: number): DeviceCommand;
/** Returns the specified item in the collection by position */
(Index: number): DeviceCommand;
}
/** The DeviceEvent object describes an EventID that can be used when calling RegisterEvent or RegisterPersistentEvent on a DeviceManager object. */
interface DeviceEvent {
class DeviceEvent {
private constructor();
private 'WIA.DeviceEvent_typekey': DeviceEvent;
/** Returns the event Description */
readonly Description: string;
@@ -325,8 +333,8 @@ declare namespace WIA {
}
/**
* The DeviceEvents object is a collection of all the supported DeviceEvent for an imaging device. See the Events property of a Device object for more det
* ails on determining the collection of supported device events.
* The DeviceEvents object is a collection of all the supported DeviceEvent for an imaging device. See the Events property of a Device object for more
* details on determining the collection of supported device events.
*/
interface DeviceEvents {
/** Returns the number of members in the collection */
@@ -334,13 +342,19 @@ declare namespace WIA {
/** Returns the specified item in the collection by position */
Item(Index: number): DeviceEvent;
/** Returns the specified item in the collection by position */
(Index: number): DeviceEvent;
}
/**
* The DeviceInfo object is a container that describes the unchanging (static) properties of an imaging device that is currently connected to the computer
* .
* The DeviceInfo object is a container that describes the unchanging (static) properties of an imaging device that is currently connected to the
* computer.
*/
interface DeviceInfo {
class DeviceInfo {
private constructor();
private 'WIA.DeviceInfo_typekey': DeviceInfo;
/** Establish a connection with this device and return a Device object */
Connect(): Device;
@@ -355,59 +369,68 @@ declare namespace WIA {
}
/**
* The DeviceInfos object is a collection of all the imaging devices currently connected to the computer. See the DeviceInfos property on the DeviceManage
* r object for detail on accessing the DeviceInfos object.
* The DeviceInfos object is a collection of all the imaging devices currently connected to the computer. See the DeviceInfos property on the
* DeviceManager object for detail on accessing the DeviceInfos object.
*/
interface DeviceInfos {
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection either by position or Device ID */
Item(Index: any): DeviceInfo;
Item(Index: number | string): DeviceInfo;
/** Returns the specified item in the collection either by position or Device ID */
(Index: number | string): DeviceInfo;
}
/**
* The DeviceManager control is an invisible-at-runtime control that manages the imaging devices connected to the computer. A DeviceManager control can be
* created using "WIA.DeviceManager" in a call to CreateObject or by dropping a DeviceManager on a form.
* The DeviceManager control is an invisible-at-runtime control that manages the imaging devices connected to the computer. A DeviceManager control can
* be created using "WIA.DeviceManager" in a call to CreateObject or by dropping a DeviceManager on a form.
*/
interface DeviceManager {
class DeviceManager {
private constructor();
private 'WIA.DeviceManager_typekey': DeviceManager;
/** A collection of all imaging devices connected to this computer */
readonly DeviceInfos: DeviceInfos;
/**
* Registers the specified EventID for the specified DeviceID. If DeviceID is "*" then OnEvent will be called whenever the event specified occurs for any
* device. Otherwise, OnEvent will only be called if the event specified occurs on the device specified.
* device. Otherwise, OnEvent will only be called if the event specified occurs on the device specified.
* @param string [DeviceID='*']
*/
RegisterEvent(EventID: string, DeviceID?: string): void;
/**
* Registers the specified Command to launch when the specified EventID for the specified DeviceID occurs. Command can be either a ClassID or the full pat
* h name and the appropriate command-line arguments needed to invoke the application.
* Registers the specified Command to launch when the specified EventID for the specified DeviceID occurs. Command can be either a ClassID or the full
* path name and the appropriate command-line arguments needed to invoke the application.
* @param string [DeviceID='*']
*/
RegisterPersistentEvent(Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string): void;
/**
* Unregisters the specified EventID for the specified DeviceID. UnregisterEvent should only be called for EventID and DeviceID for which you called Regis
* terEvent.
* Unregisters the specified EventID for the specified DeviceID. UnregisterEvent should only be called for EventID and DeviceID for which you called
* RegisterEvent.
* @param string [DeviceID='*']
*/
UnregisterEvent(EventID: string, DeviceID?: string): void;
/**
* Unregisters the specified Command for the specified EventID for the specified DeviceID. UnregisterPersistentEvent should only be called for the Command
* , Name, Description, Icon, EventID and DeviceID for which you called RegisterPersistentEvent.
* Unregisters the specified Command for the specified EventID for the specified DeviceID. UnregisterPersistentEvent should only be called for the
* Command, Name, Description, Icon, EventID and DeviceID for which you called RegisterPersistentEvent.
* @param string [DeviceID='*']
*/
UnregisterPersistentEvent(Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string): void;
}
/**
* The Filter object represents a unit of modification on an ImageFile. To use a Filter, add it to the Filters collection, then set the filter's propertie
* s and finally use the Apply method of the ImageProcess object to filter an ImageFile.
* The Filter object represents a unit of modification on an ImageFile. To use a Filter, add it to the Filters collection, then set the filter's
* properties and finally use the Apply method of the ImageProcess object to filter an ImageFile.
*/
interface Filter {
class Filter {
private constructor();
private 'WIA.Filter_typekey': Filter;
/** Returns a Description of what the filter does */
readonly Description: string;
@@ -422,10 +445,13 @@ declare namespace WIA {
}
/**
* The FilterInfo object is a container that describes a Filter object without requiring a Filter to be Added to the process chain. See the FilterInfos pr
* operty on the ImageProcess object for details on accessing FilterInfo objects.
* The FilterInfo object is a container that describes a Filter object without requiring a Filter to be Added to the process chain. See the FilterInfos
* property on the ImageProcess object for details on accessing FilterInfo objects.
*/
interface FilterInfo {
class FilterInfo {
private constructor();
private 'WIA.FilterInfo_typekey': FilterInfo;
/** Returns a technical Description of what the filter does and how to use it in a filter chain */
readonly Description: string;
@@ -437,15 +463,18 @@ declare namespace WIA {
}
/**
* The FilterInfos object is a collection of all the available FilterInfo objects. See the FilterInfos property on the ImageProcess object for detail on a
* ccessing the FilterInfos object.
* The FilterInfos object is a collection of all the available FilterInfo objects. See the FilterInfos property on the ImageProcess object for detail on
* accessing the FilterInfos object.
*/
interface FilterInfos {
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection either by position or name */
Item(Index: any): FilterInfo;
Item(Index: number | string): FilterInfo;
/** Returns the specified item in the collection either by position or name */
(Index: number | string): FilterInfo;
}
/** The Filters object is a collection of the Filters that will be applied to an ImageFile when you call the Apply method on the ImageProcess object. */
@@ -464,11 +493,14 @@ declare namespace WIA {
/** Removes the designated filter */
Remove(Index: number): void;
/** Returns the specified item in the collection by position or FilterID */
(Index: number): Filter;
}
/**
* The Formats object is a collection of supported FormatIDs that you can use when calling Transfer on an Item object or ShowTransfer on a CommonDialog ob
* ject for this Item.
* The Formats object is a collection of supported FormatIDs that you can use when calling Transfer on an Item object or ShowTransfer on a CommonDialog
* object for this Item.
*/
interface Formats {
/** Returns the number of members in the collection */
@@ -476,13 +508,19 @@ declare namespace WIA {
/** Returns the specified item in the collection by position */
Item(Index: number): string;
/** Returns the specified item in the collection by position */
(Index: number): string;
}
/**
* The ImageFile object is a container for images transferred to your computer when you call Transfer or ShowTransfer. It also supports image files throug
* h LoadFile. An ImageFile object can be created using "WIA.ImageFile" in a call to CreateObject.
* The ImageFile object is a container for images transferred to your computer when you call Transfer or ShowTransfer. It also supports image files
* through LoadFile. An ImageFile object can be created using "WIA.ImageFile" in a call to CreateObject.
*/
interface ImageFile {
class ImageFile {
private constructor();
private 'WIA.ImageFile_typekey': ImageFile;
/** Returns/Sets the current frame in the image */
ActiveFrame: number;
@@ -539,7 +577,10 @@ declare namespace WIA {
}
/** The ImageProcess object manages the filter chain. An ImageProcess object can be created using "WIA.ImageProcess" in a call to CreateObject. */
interface ImageProcess {
class ImageProcess {
private constructor();
private 'WIA.ImageProcess_typekey': ImageProcess;
/** Takes the specified ImageFile and returns the new ImageFile with all the filters applied on success */
Apply(Source: ImageFile): ImageFile;
@@ -551,10 +592,13 @@ declare namespace WIA {
}
/**
* The Item object is a container for an item on an imaging device object. See the Items property on the Device or Item object for details on accessing It
* em objects.
* The Item object is a container for an item on an imaging device object. See the Items property on the Device or Item object for details on accessing
* Item objects.
*/
interface Item {
class Item {
private constructor();
private 'WIA.Item_typekey': Item;
/** A collection of all commands for this item */
readonly Commands: DeviceCommands;
@@ -574,17 +618,15 @@ declare namespace WIA {
readonly Properties: Properties;
/**
* Returns an ImageFile object, in this version, in the format specified in FormatID if supported, otherwise using the preferred format for this imaging d
* evice. Future versions may return a collection of ImageFile objects.
* Returns an ImageFile object, in this version, in the format specified in FormatID if supported, otherwise using the preferred format for this imaging
* device. Future versions may return a collection of ImageFile objects.
* @param string [FormatID='{00000000-0000-0000-0000-000000000000}']
*/
Transfer(FormatID?: string): any;
/** Returns the underlying IWiaItem interface for this Item object */
readonly WiaItem: any;
Transfer(FormatID?: string): ImageFile;
}
/** The Items object contains a collection of Item objects. See the Items property on the Device or Item object for details on accessing the Items object. */
// tslint:disable-next-line interface-name
interface Items {
/** Adds a new Item with the specified Name and Flags. The Flags value is created by using the OR operation with members of the WiaItemFlags enumeration. */
Add(Name: string, Flags: number): void;
@@ -597,28 +639,37 @@ declare namespace WIA {
/** Removes the designated Item */
Remove(Index: number): void;
/** Returns the specified item in the collection by position */
(Index: number): Item;
}
/**
* The Properties object is a collection of all the Property objects associated with a given Device, DeviceInfo, Filter, ImageFile or Item object. See the
* Properties property on any of these objects for detail on accessing the Properties object.
* The Properties object is a collection of all the Property objects associated with a given Device, DeviceInfo, Filter, ImageFile or Item object. See
* the Properties property on any of these objects for detail on accessing the Properties object.
*/
interface Properties {
/** Returns the number of members in the collection */
readonly Count: number;
/** Indicates whether the specified Property exists in the collection */
Exists(Index: any): boolean;
Exists(Index: number | string): boolean;
/** Returns the specified item in the collection either by position or name. */
Item(Index: any): Property;
Item(Index: number | string): Property;
/** Returns the specified item in the collection either by position or name. */
(Index: number | string): Property;
}
/**
* The Property object is a container for a property associated with a Device, DeviceInfo, Filter, ImageFile or Item object. See the Properties property o
* n any of these objects for details on accessing Property objects.
* The Property object is a container for a property associated with a Device, DeviceInfo, Filter, ImageFile or Item object. See the Properties property
* on any of these objects for details on accessing Property objects.
*/
interface Property {
class Property {
private constructor();
private 'WIA.Property_typekey': Property;
/** Indicates whether the Property Value is read only */
readonly IsReadOnly: boolean;
@@ -657,10 +708,13 @@ declare namespace WIA {
}
/**
* The Rational object is a container for the rational values found in Exif tags. It is a supported element type of the Vector object and may be created u
* sing "WIA.Rational" in a call to CreateObject.
* The Rational object is a container for the rational values found in Exif tags. It is a supported element type of the Vector object and may be created
* using "WIA.Rational" in a call to CreateObject.
*/
interface Rational {
class Rational {
private constructor();
private 'WIA.Rational_typekey': Rational;
/** Returns/Sets the Rational Value Denominator */
Denominator: number;
@@ -672,19 +726,19 @@ declare namespace WIA {
}
/**
* The Vector object is a collection of values of the same type. It is used throughout the library in many different ways. The Vector object may be create
* d using "WIA.Vector" in a call to CreateObject.
* The Vector object is a collection of values of the same type. It is used throughout the library in many different ways. The Vector object may be
* created using "WIA.Vector" in a call to CreateObject.
*/
interface Vector {
interface Vector<TItem = any> {
/**
* If Index is not zero, Inserts a new element into the Vector collection before the specified Index. If Index is zero, Appends a new element to the Vecto
* r collection.
* If Index is not zero, Inserts a new element into the Vector collection before the specified Index. If Index is zero, Appends a new element to the
* Vector collection.
* @param number [Index=0]
*/
Add(Value: any, Index?: number): void;
Add(Value: TItem, Index?: number): void;
/** Returns/Sets the Vector of Bytes as an array of bytes */
BinaryData: any;
BinaryData: SafeArray;
/** Removes all elements. */
Clear(): void;
@@ -696,30 +750,30 @@ declare namespace WIA {
Date: VarDate;
/**
* Used to get the Thumbnail property of an ImageFile which is an image file, The thumbnail property of an Item which is RGB data, or creating an ImageFil
* e from raw ARGB data. Returns an ImageFile object on success. See the Picture method for more details.
* Used to get the Thumbnail property of an ImageFile which is an image file, The thumbnail property of an Item which is RGB data, or creating an
* ImageFile from raw ARGB data. Returns an ImageFile object on success. See the Picture method for more details.
* @param number [Width=0]
* @param number [Height=0]
*/
ImageFile(Width?: number, Height?: number): ImageFile;
/** Returns/Sets the specified item in the vector by position */
Item(Index: number): any;
/** Returns the specified item in the vector by position */
Item(Index: number): TItem;
/**
* If the Vector of Bytes contains an image file, then Width and Height are ignored. Otherwise a Vector of Bytes must be RGB data and a Vector of Longs mu
* st be ARGB data. Returns a Picture object on success. See the ImageFile method for more details.
* If the Vector of Bytes contains an image file, then Width and Height are ignored. Otherwise a Vector of Bytes must be RGB data and a Vector of Longs
* must be ARGB data. Returns a Picture object on success. See the ImageFile method for more details.
* @param number [Width=0]
* @param number [Height=0]
*/
Picture(Width?: number, Height?: number): any;
/** Removes the designated element and returns it if successful */
Remove(Index: number): any;
Remove(Index: number): TItem | null;
/**
* Stores the string Value into the Vector of Bytes including the NULL terminator. Value may be truncated unless Resizable is True. The string will be sto
* red as an ANSI string unless Unicode is True, in which case it will be stored as a Unicode string.
* Stores the string Value into the Vector of Bytes including the NULL terminator. Value may be truncated unless Resizable is True. The string will be
* stored as an ANSI string unless Unicode is True, in which case it will be stored as a Unicode string.
* @param boolean [Resizable=true]
* @param boolean [Unicode=true]
*/
@@ -730,30 +784,24 @@ declare namespace WIA {
* @param boolean [Unicode=true]
*/
String(Unicode?: boolean): string;
/** Returns the specified item in the vector by position */
(Index: number): TItem;
}
}
interface ActiveXObject {
new<K extends keyof ActiveXObjectNameMap = any>(progid: K): ActiveXObjectNameMap[K];
on(obj: WIA.DeviceManager, event: 'OnEvent', argNames: ['EventID', 'DeviceID', 'ItemID'], handler: (
this: WIA.DeviceManager, parameter: {
EventID: string, DeviceID: string, ItemID: string}) => void): void;
set(obj: WIA.Vector, propertyName: 'Item', parameterTypes: [number], newValue: any): void;
new(progid: 'WIA.CommonDialog'): WIA.CommonDialog;
new(progid: 'WIA.DeviceManager'): WIA.DeviceManager;
new(progid: 'WIA.ImageFile'): WIA.ImageFile;
new(progid: 'WIA.ImageProcess'): WIA.ImageProcess;
new(progid: 'WIA.Rational'): WIA.Rational;
new(progid: 'WIA.Vector'): WIA.Vector;
this: WIA.DeviceManager, parameter: { readonly EventID: string, readonly DeviceID: string, readonly ItemID: string }) => void): void;
set<TItem>(obj: WIA.Vector<TItem>, propertyName: 'Item', parameterTypes: [number], newValue: TItem): void;
}
interface EnumeratorConstructor {
new(col: WIA.DeviceCommands): WIA.DeviceCommand;
new(col: WIA.DeviceEvents): WIA.DeviceEvent;
new(col: WIA.DeviceInfos): WIA.DeviceInfo;
new(col: WIA.FilterInfos): WIA.FilterInfo;
new(col: WIA.Filters): WIA.Filter;
new(col: WIA.Formats): string;
new(col: WIA.Items): WIA.Item;
new(col: WIA.Properties): WIA.Property;
new(col: WIA.Vector): any;
interface ActiveXObjectNameMap {
'WIA.CommonDialog': WIA.CommonDialog;
'WIA.DeviceManager': WIA.DeviceManager;
'WIA.ImageFile': WIA.ImageFile;
'WIA.ImageProcess': WIA.ImageProcess;
'WIA.Rational': WIA.Rational;
'WIA.Vector': WIA.Vector;
}
+6 -1
View File
@@ -1 +1,6 @@
{ "extends": "dtslint/dt.json" }
{
"extends": "dtslint/dt.json",
"rules":{
"no-const-enum": false
}
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false]
"no-const-enum": false
}
}
}
+1 -1
View File
@@ -20,4 +20,4 @@
"index.d.ts",
"add-zero-tests.ts"
]
}
}
+14 -40
View File
@@ -7,16 +7,15 @@ declare namespace adone {
export function identity<T>(x: T): T;
export function truly(): true;
export function falsely(): false;
export const ok: "OK";
export const bad: "BAD";
export const exts: [".js", ".tjs", ".ajs"];
export const ok: "ok";
export const bad: "bad";
export function log(...args: any[]): void;
export function fatal(...args: any[]): void;
export function error(...args: any[]): void;
export function warn(...args: any[]): void;
export function info(...args: any[]): void;
export function debug(...args: any[]): void;
export function trace(...args: any[]): void;
export function logFatal(...args: any[]): void;
export function logError(...args: any[]): void;
export function logWarn(...args: any[]): void;
export function logInfo(...args: any[]): void;
export function logDebug(...args: any[]): void;
export function logTrace(...args: any[]): void;
export function o(...props: any[]): object;
export const Date: typeof global.Date;
export const hrtime: typeof global.process.hrtime;
@@ -76,40 +75,16 @@ declare namespace adone {
set(Class: object, tag: string): void;
has(obj: object, tag: string): boolean;
define(tag: string, predicate?: string): void;
SUBSYSTEM: symbol;
APPLICATION: symbol;
TRANSFORM: symbol;
CORE_STREAM: symbol;
LOGGER: symbol;
LONG: symbol;
BIGNUMBER: symbol;
EXBUFFER: symbol;
EXDATE: symbol;
CONFIGURATION: symbol;
GENESIS_NETRON: symbol;
GENESIS_PEER: symbol;
NETRON: symbol;
NETRON_PEER: symbol;
NETRON_ADAPTER: symbol;
NETRON_DEFINITION: symbol;
NETRON_DEFINITIONS: symbol;
NETRON_REFERENCE: symbol;
NETRON_INTERFACE: symbol;
NETRON_STUB: symbol;
NETRON_REMOTESTUB: symbol;
NETRON_STREAM: symbol;
FAST_STREAM: symbol;
FAST_FS_STREAM: symbol;
FAST_FS_MAP_STREAM: symbol;
}
}
export const tag: I.Tag;
export function bind(libName: string): object;
export function getAssetAbsolutePath(relPath: string): string;
export function loadAsset(relPath: string): string | Buffer;
export function require(path: string): object;
export const package: object;
export function sprintf(format: string, ...args: any[]): string;
namespace I {
interface Runtime {
term: object; // TODO
@@ -120,11 +95,10 @@ declare namespace adone {
export const runtime: I.Runtime;
export const homePath: string;
export const rootPath: string;
export const etcPath: string;
export const config: object;
export const emptyBuffer: Buffer;
export const ROOT_PATH: string;
export const ETC_PATH: string;
export const configuration: object;
export const EMPTY_BUFFER: Buffer;
export const assert: assertion.I.AssertFunction;
export const expect: assertion.I.ExpectFunction;
+271 -1
View File
@@ -1,5 +1,275 @@
declare namespace adone {
namespace application {
function run(app: object, ignoreArgs?: boolean): Promise<void>;
namespace I {
type ArgumentType = ((x: string, index: number) => any) | RegExp;
interface ArgumentInfo {
name: string | string[];
action?: "store"
| "store_const"
| "store_true"
| "store_false"
| "append"
| "count"
| "set";
nargs?: number | "+" | "*" | "?"
type?: ArgumentType | ArgumentType[];
verify?: (args: any, opts: any) => boolean; // TODO
required?: boolean;
description?: string;
help?: string;
holder?: string | string[];
appendDefaultMessage?: boolean;
appendChoicesHelpMessage?: boolean;
default?: any;
enabled?: boolean;
}
interface Group {
name: string;
description?: string;
}
interface MainCommandInfo {
arguments?: Array<ArgumentInfo | string>;
options?: Array<ArgumentInfo | string>;
description?: string;
optionsGroups?: Group[];
blindMode?: boolean;
match?: (name: string) => boolean;
handler?: (args: object, opts: object) => void;
}
interface CommandInfo extends MainCommandInfo {
name?: string | string[];
group?: string;
}
interface ApplicationInfo {
name?: string;
description?: string;
subsystems?: SubsystemInfo[];
commandsGroups?: Group[]
}
interface SubsystemInfo {
name: string;
description?: string;
subsystem: string;
transpile?: boolean;
group?: string;
}
}
function DSubsystem(info?: I.ApplicationInfo): (...args: any[]) => void;
function DApplication(info?: I.ApplicationInfo): (...args: any[]) => void;
function DCliCommand(info?: I.CommandInfo): (...args: any[]) => void;
function DMainCliCommand(info?: I.MainCommandInfo): (...args: any[]) => void;
namespace I {
interface LoadSubsystemOptions {
name?: string,
description?: string,
group?: string,
transpile?: boolean
}
interface CommonAddSubsystemInfo {
name?: string,
useFilename?: boolean
description?: string,
group?: string,
configureArgs?: any[]
transpile?: boolean,
bind?: boolean | string
}
interface AddSubsystemInfo extends CommonAddSubsystemInfo {
subsystem: Subsystem | string,
}
interface SysInfo {
name: string;
description: string;
group: string;
configureArgs: any[];
instance: Subsystem;
path: string | null;
}
interface SysInfoWithPath extends SysInfo {
path: string;
}
interface SysInfoNoPath extends SysInfo {
path: null;
}
interface AddSubsystemsFromOptions extends CommonAddSubsystemInfo {
filter?: string[] | ((file: string) => boolean | Promise<boolean>)
}
}
class Subsystem extends event.AsyncEmitter {
constructor(options?: { name?: string });
readonly name?: string;
readonly root?: Subsystem;
setRoot(root: Subsystem): void;
readonly parent?: Subsystem;
readonly state: number;
readonly isOwned: boolean;
setState(state: number): void;
waitForState(expectedState: number, timeout?: number): Promise<void>;
configure(): void;
initialize(): void;
uninitialize(): void;
configureSubsystems(): Promise<void>;
uninitializeSubsystems(): Promise<void>;
reinitializeSubsystems(): Promise<void>;
configureSubsystem(name: string): Promise<void>;
loadSubsystem(subsystem: string | Subsystem, options?: I.LoadSubsystemOptions): Promise<void>;
unloadSubsystem(name: string): Promise<void>;
initializeSubsystem(name: string): Promise<void>;
uninitializeSubsystem(name: string): Promise<void>;
reinitializeSubsystem(name: string): Promise<void>;
getSubsystem(name: string): Subsystem;
hasSubsystem(name: string): boolean;
hasSubsystems(): boolean;
addSubsystem(info: I.AddSubsystemInfo & { subsystem: Subsystem }): I.SysInfoNoPath;
addSubsystem(info: I.AddSubsystemInfo & { subsystem: string }): I.SysInfoWithPath;
addSubsystemsFrom(path: string, options?: I.AddSubsystemsFromOptions): I.SysInfoWithPath;
instantiateSubsystem(subsystem: string | Subsystem, options?: {
transpile?: boolean
}): Subsystem;
deleteSubsystem(name: string, force?: boolean): void;
getSubsystemInfo(name: string): I.SysInfo;
getSubsystems(): I.SysInfo[];
}
namespace I {
interface ReportOptions {
events?: string;
signal?: string;
filename?: string;
directory?: string;
}
}
class Application extends Subsystem {
readonly isMain: boolean;
main(): void;
enableReport(opts?: I.ReportOptions): void;
reportEnabled(): boolean;
run(): Promise<void>;
exit(code?: number): Promise<void>;
exitOnSignal(...names: string[]): void;
removeProcesshandlers(): void;
_uncaughtException(err: any): void;
_unhandledRejection(reson: any, p: Promise<any>): void;
_rejectionHandled(p: Promise<any>): void;
_signalExit(sigName: string): void;
}
namespace I {
interface Command {
// ?
}
interface Argument {
// ?
}
interface PositionalArgument extends Argument {
// ?
}
interface OptionalArgument extends Argument {
// ?
}
interface DefineCommandFromSubsystemOptions {
name?: string;
description?: string;
group?: string;
subsystem: string | Subsystem;
configureArgs?: any[];
lazily?: boolean;
transpile?: boolean;
}
}
class CliApplication extends Application {
run(options?: { ignoreArgs?: boolean }): Promise<void>;
getVersion(): Promise<string | undefined>;
exposeCliInterface(ctxId?: string): void;
readonly mainCommand: I.Command;
defineMainCommand(schema: I.MainCommandInfo): this;
defineArguments(schema: I.MainCommandInfo): this;
defineCommand(schema: I.CommandInfo): I.Command;
defineCommandFromSubsystem(options?: I.DefineCommandFromSubsystemOptions): void;
defineOption(schema: I.ArgumentInfo): void;
defineOptionsGroup(schema: I.Group): void;
defineCommandsGroup(schema: I.Group): void;
option(path: string, options?: { value?: boolean }): any;
}
function run(app: Application, ignoreArgs?: boolean): Promise<void>;
function runCli(app: CliApplication, ignoreArgs?: boolean): Promise<void>;
}
}
+1 -1
View File
@@ -448,7 +448,7 @@ declare namespace adone {
isCompressed(): boolean;
}
interface ZipFile<StringType> extends event.EventEmitter {
interface ZipFile<StringType> extends event.Emitter {
/**
* true until close() is called; then it's false
*/
+47 -87
View File
@@ -38,7 +38,7 @@ declare namespace adone {
proxyExcludedKeys: string[];
}
type PossibleTypes = util.I.PossibleTypes | "array";
type PossibleTypes = meta.I.PossibleTypes | "array";
type UseFunction = (fn: () => void) => assertion;
@@ -53,18 +53,10 @@ declare namespace adone {
* Throws an AssertionError, like node.js
*/
fail(actual?: any, expected?: any, message?: string, operator?: any): void;
/**
* Asserts that value is truthy
*/
isOk(value: any, message?: string): void;
/**
* Asserts that value is truthy
*/
ok(value: any, message?: string): void;
/**
* Asserts that value is falsy
*/
isNotOk(value: any, message?: string): void;
/**
* Asserts that value is falsy
*/
@@ -104,51 +96,51 @@ declare namespace adone {
/**
* Asserts that value > above
*/
isAbove(value: any, above: any, message?: string): void;
above(value: any, above: any, message?: string): void;
/**
* Asserts that value >= atLeast
*/
isAtLeast(value: any, atLeast: any, message?: string): void;
atLeast(value: any, atLeast: any, message?: string): void;
/**
* Asserts that value < below
*/
isBelow(value: any, below: any, message?: string): void;
below(value: any, below: any, message?: string): void;
/**
* Asserts that value <= atMost
*/
isAtMost(value: any, atMost: any, message?: string): void;
atMost(value: any, atMost: any, message?: string): void;
/**
* Asserts that value is true
*/
isTrue(value: any, message?: string): void;
true(value: any, message?: string): void;
/**
* Asserts that value is not true
*/
isNotTrue(value: any, message?: string): void;
notTrue(value: any, message?: string): void;
/**
* Asserts that value is false
*/
isFalse(value: any, message?: string): void;
false(value: any, message?: string): void;
/**
* Asserts that value is not false
*/
isNotFalse(value: any, message?: string): void;
notFalse(value: any, message?: string): void;
/**
* Asserts that value is null
*/
isNull(value: any, message?: string): void;
null(value: any, message?: string): void;
/**
* Asserts that valus is not null
*/
isNotNull(value: any, message?: string): void;
notNull(value: any, message?: string): void;
/**
* Asserts that value is NaN
*/
isNaN(value: any, message?: string): void;
NaN(value: any, message?: string): void;
/**
* Asserts that value is not NaN
*/
isNotNaN(value: any, message?: string): void;
NotNaN(value: any, message?: string): void;
/**
* Asserts that value is neither null nor undefined
*/
@@ -160,63 +152,63 @@ declare namespace adone {
/**
* Asserts that value is undefined
*/
isUndefined(value: any, message?: string): void;
undefined(value: any, message?: string): void;
/**
* Asserts that value is not undefined
*/
isDefined(value: any, message?: string): void;
defined(value: any, message?: string): void;
/**
* Asserts that value is a function
*/
isFunction(value: any, message?: string): void;
function(value: any, message?: string): void;
/**
* Asserts that value is not a function
*/
isNotFunction(value: any, message?: string): void;
notFunction(value: any, message?: string): void;
/**
* Asserts that value is an object of type Object
*/
isObject(value: any, message?: string): void;
object(value: any, message?: string): void;
/**
* Asserts that value is not an object of type Object
*/
isNotObject(value: any, message?: string): void;
notObject(value: any, message?: string): void;
/**
* Asserts that value is an array
*/
isArray(value: any, message?: string): void;
array(value: any, message?: string): void;
/**
* Asserts that value is not an array
*/
isNotArray(value: any, message?: string): void;
notArray(value: any, message?: string): void;
/**
* Asserts that value is a string
*/
isString(value: any, message?: string): void;
string(value: any, message?: string): void;
/**
* Asserts that value is not a string
*/
isNotString(value: any, message?: string): void;
notString(value: any, message?: string): void;
/**
* Asserts that value is a number
*/
isNumber(value: any, message?: string): void;
number(value: any, message?: string): void;
/**
* Asserts that value is not a number
*/
isNotNumber(value: any, message?: string): void;
notNumber(value: any, message?: string): void;
/**
* Asserts that value is a finite number
*/
isFinite(value: any, message?: string): void;
finite(value: any, message?: string): void;
/**
* Asserts that value is a boolean
*/
isBoolean(value: any, message?: string): void;
boolean(value: any, message?: string): void;
/**
* Asserts that value is not a boolean
*/
isNotBoolean(value: any, message?: string): void;
notBoolean(value: any, message?: string): void;
/**
* Asserts that value's type is `type`
*/
@@ -562,66 +554,34 @@ declare namespace adone {
* Throws an error if value is truthy
*/
ifError(value: any): void;
/**
* Asserts that object is extensible
*/
isExtensible(object: object, message?: string): void;
/**
* Asserts that object is extensible
*/
extensible(object: object, message?: string): void;
/**
* Asserts that object is not extensible
*/
isNotExtensible(object: object, message?: string): void;
/**
* Asserts that object is not extensible
*/
notExtensible(object: object, message?: string): void;
/**
* Asserts that object is sealed
*/
isSealed(object: object, message?: string): void;
/**
* Asserts that object is sealed
*/
sealed(object: object, message?: string): void;
/**
* Asserts that object is not sealed
*/
isNotSealed(object: object, message?: string): void;
/**
* Asserts that object is not sealed
*/
notSealed(object: object, message?: string): void;
/**
* Asserts that object is frozen
*/
isFrozen(object: object, message?: string): void;
/**
* Asserts that object is frozen
*/
frozen(object: object, message?: string): void;
/**
* Asserts that object is not frozen
*/
isNotFrozen(object: object, message?: string): void;
/**
* Asserts that object is not frozen
*/
notFrozen(object: object, message?: string): void;
/**
* Asserts that value is empty
*/
isEmpty(value: any, message?: string): void;
/**
* Asserts that value is empty
*/
empty(value: any, message?: string): void;
/**
* Asserts that value is not empty
*/
isNotEmpty(value: any, message?: string): void;
/**
* Asserts that value is not empty
*/
@@ -710,43 +670,43 @@ declare namespace adone {
/**
* Asserts that the target is non-strictly equal to true
*/
ok: this;
ok(): this;
/**
* Asserts that the target is true
*/
true: this;
true(): this;
/**
* Asserts that the target is false
*/
false: this;
false(): this;
/**
* Asserts that the target is null
*/
null: this;
null(): this;
/**
* Asserts that the target is undefined
*/
undefined: this;
undefined(): this;
/**
* Asserts that the target is NaN
*/
NaN: this;
NaN(): this;
/**
* Asserts that the target is neither null nor undefined
*/
exist: this;
exist(): this;
/**
* Asserts that the target is empty
*/
empty: this;
empty(): this;
/**
* Asserts that the target is an arguments object
*/
arguments: this;
arguments(): this;
/**
* Asserts that the target is an arguments object
*/
Arguments: this;
Arguments(): this;
/**
* Asserts that the target is strictly equal to value(===)
*/
@@ -976,26 +936,26 @@ declare namespace adone {
/**
* Asserts that the target is extensible
*/
extensible: this;
extensible(): this;
/**
* Asserts that the target is sealed
*/
sealed: this;
sealed(): this;
/**
* Asserts that the target is frozen
*/
frozen: this;
frozen(): this;
/**
* Asserts that the target is a finite number
*/
finite: this;
finite(): this;
}
interface MockAssertions extends Assertion {
/**
* Asserts that the spy has been called
*/
called: this;
called(): this;
/**
* Asserts that the spy has been called n times
*/
@@ -1003,15 +963,15 @@ declare namespace adone {
/**
* Asserts that the spy has been called once
*/
calledOnce: this;
calledOnce(): this;
/**
* Asserts that the spy has been called twice
*/
calledTwice: this;
calledTwice(): this;
/**
* Asserts that the spy has been been called with `new`
*/
calledThrice: this;
calledThrice(): this;
/**
* Asserts that the spy has been called before anotherSpy
*/
@@ -1059,7 +1019,7 @@ declare namespace adone {
}
}
class AssertionError extends x.Exception {
class AssertionError extends error.Exception {
constructor(message?: string, props?: object, ssf?: object)
}
File diff suppressed because it is too large Load Diff
+44
View File
@@ -0,0 +1,44 @@
declare namespace adone.collection {
/**
* Respresetns a data structure which is a combination of an array and a set.
* Adding a new member is O(1), testing for membership is O(1),
* and finding the index of an element is O(1).
*/
class ArraySet<T = any> {
/**
* The number of unique items in this ArraySet.
* If duplicates have been added, than those do not count towards the size.
*/
readonly length: number;
/**
* Adds the given value to this set.
*
* @param allowDuplicates Whether to allow duplicates in the set, false by default
*/
add(value: T, allowDuplicates?: boolean): this;
/**
* Checks whether the given value is a member of the set
*/
has(value: T): boolean;
/**
* Returns the index of the given element.
* If the value is not present it will return -1
*/
indexOf(value: T): number;
/**
* Converts the set to an array
*/
toArray(): T[];
/**
* Creates an ArraySet from the given iterable object
*
* @param allowDuplicates Whether to allow duplicates in the set, false by default
*/
static from<T>(iterable: Iterable<T>, allowDuplicates?: boolean): ArraySet<T>;
}
}
+12
View File
@@ -0,0 +1,12 @@
declare namespace adone.collection {
/**
* Represents an asynchronous queue, each pop is a promise
* that is resolved with an existing element or an element that will be pushed in the future
*/
class AsyncQueue<T = any> extends Queue<T, Promise<T>> {
/**
* Returns a promise that will be resolved with an existing element or an element that will be pushed in the future
*/
pop(): Promise<T>;
}
}
+48
View File
@@ -0,0 +1,48 @@
declare namespace adone.collection {
/**
* Represents an AVL tree, a self-balancing binary search tree
*/
class AVLTree<K = any, V = any> {
constructor(options?: I.BinarySearchTree.ConstructorOptions<K, V, AVLTree<K, V>>);
/**
* Checks whether the tree is an avl tree
*/
checkIsAVLT(): void;
/**
* Inserts a new key/value
*/
insert(key: K, value: V): void;
/**
* Deletes the given key/value from the tree
*/
delete(key: K, value?: V): void;
/**
* Returns the of keys in the tree
*/
getNumberOFKeys(): number;
/**
* Searches the given key in the tree
*/
search(key: K): V[];
/**
* Returns all the values from the given key bounds
*/
betweenBounds(query: I.BinarySearchTree.Query<K>): V[];
/**
* Executed the given callback for each node from left to right
*/
executeOnEveryNode(fn: (tree: AVLTree<K, V>) => void): void;
/**
* Prints the tree
*/
prettyPrint(printDate?: boolean, spacing?: string): void;
}
}
+110
View File
@@ -0,0 +1,110 @@
declare namespace adone.collection {
namespace I.BinarySearchTree {
interface ConstructorOptions<K, V, Tree> {
/**
* The parent tree
*/
parent?: Tree;
/**
* Value to keep in this node
*/
value?: V;
/**
* WHether the values must be unique, false by default.
* If false you can store many values for same keys, otherwise only one
*/
unique?: boolean;
/**
* Custom keys comparator, by default if a > b => -1, a < b -1, a === b => 0
*/
compareKeys?(a: K, b: K): number;
/**
* Function that defines whether 2 values are the same, by default a === b
*/
checkValueEquality?(a: V, b: V): boolean;
}
interface Query<K> {
$lt?: K;
$lte?: K;
$gt?: K;
$gte?: K;
}
}
/**
* Represents a binary search tree
*/
class BinarySearchTree<K = any, V = any> {
constructor(options?: I.BinarySearchTree.ConstructorOptions<K, V, BinarySearchTree<K, V>>);
/**
* Returns the max descendant tree
*/
getMaxKeyDescendant(): BinarySearchTree<K, V>;
/**
* Returns the maximum key
*/
getMaxKey(): K;
/**
* Returns the min descendant tree
*/
getMinKeyDescendant(): BinarySearchTree<K, V>;
/**
* Returns the minumum key
*/
getMinKey(): K;
/**
* Traverses the tree and calls the given function for each node
*/
checkAllNodesFullfillCondition(test: (key: K, value: V) => void): void;
/**
* Checks whether the tree is a binary search tree
*/
checkIsBST(): void;
/**
* Returns the of keys in the tree
*/
getNumberOfKeys(): number;
/**
* Inserts a new key/value
*/
insert(key: K, value: V): void;
/**
* Searches the given key in the tree
*/
search(key: K): V[];
/**
* Returns all the values from the given key bounds
*/
betweenBounds(query: I.BinarySearchTree.Query<K>): V[];
/**
* Deletes the given key/value from the tree
*/
delete(key: K, value?: V): void;
/**
* Executed the given callback for each node from left to right
*/
executeOnEveryNode(fn: (tree: BinarySearchTree<K, V>) => void): void;
/**
* Prints the tree
*/
prettyPrint(printData?: boolean, spacing?: string): void;
}
}
+92
View File
@@ -0,0 +1,92 @@
declare namespace adone.collection {
namespace I.BufferList {
type Appendable = Buffer | BufferList | string | number | Array<Buffer | BufferList | string | number>;
}
/**
* Represents a Node.js Buffer list collector, reader and streamer with callback/promise interface support
*/
class BufferList extends std.stream.Duplex implements PromiseLike<Buffer> {
/**
* Creates a new buffer list
*/
constructor();
/**
* Creates a new buffer list and initiates with the given value
*/
constructor(buffer: I.BufferList.Appendable);
/**
* Creates a new buffer list and subscribes the given callback on the end/error event
*/
constructor(callback: (err: any, data: Buffer) => void);
/**
* Adds an additional buffer or BufferList to the internal list
*/
append(buf: I.BufferList.Appendable): this;
/**
* Ends the stream
*/
end(chunk?: Buffer): void;
end(chunk?: () => void): void;
/**
* Returns the byte at the specified index
*/
get(idx: number): number;
/**
* Returns a new Buffer object containing the bytes within the range specified.
*/
slice(start?: number, end?: number): Buffer;
/**
* Copies the content of the list in the dest buffer
* starting from destStart and containing the bytes within the range specified with srcStart to srcEnd
*
* @param dstStart writes from this position
* @param srcStart reads bytes from this position
* @param srcEnd read bytes to this position
*/
copy<T extends Buffer = Buffer>(dst: T, dstStart?: number, srcStart?: number, srcEnd?: number): T;
/**
* Returns a new BufferList object containing the bytes within the range specified.
* No copies will be performed. All buffers in the result share memory with the original list.
*
* @param start slice from
* @param end slice to
*/
shallowSlice(start?: number, end?: number): BufferList;
/**
* Return a string representation of the buffer
*/
toString(encoding?: fs.I.Encoding, start?: number, end?: number): string;
/**
* Shifts bytes off the start of the list
*/
consume(bytes: number): this;
/**
* Performs a shallow-copy of the list.
*/
duplicate(): BufferList;
/**
* Destroys the stream
*/
destroy(): void;
then<T1 = Buffer, T2 = never>(
onfulfilled?: ((value: Buffer) => T1 | PromiseLike<T1>) | null,
onrejected?: ((reason: any) => T2 | PromiseLike<T2>) | null
): PromiseLike<T1 | T2>;
catch<T>(onrejected?: ((reason: any) => T | PromiseLike<T>) | null): PromiseLike<T | Buffer>;
}
}
+892
View File
@@ -0,0 +1,892 @@
declare namespace adone.collection {
namespace I {
type Long = math.Long;
type Longable = math.I.Longable;
namespace ByteArray {
interface Varint32 {
value: number;
length: number;
}
interface Varint64 {
value: Long;
length: number;
}
interface String {
string: string;
length: number;
}
type Wrappable = string | ByteArray | Buffer | Uint8Array | ArrayBuffer;
type Metrics = "b" | "c";
}
}
/**
* Represents an array of bytes, enhanced Node.js Buffer
*/
class ByteArray {
readonly woffset: number;
readonly roffset: number;
readonly buffer: Buffer;
readonly noAssert: boolean;
/**
* Constructs a new ByteArray
*
* @param capacity Initial capacity. Defaults to ByteArray.DEFAULT_CAPACITY(64)
* @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false)
*/
constructor(capacity?: number, noAssert?: boolean);
/**
* Reads a BitSet as an array of booleans.
*
* @param offset Offset to read from. Will use and increase offset by length if omitted.
*/
readBitSet(offset?: number): boolean[];
/**
* Reads the specified number of bytes.
*
* @param length Number of bytes to read
* @param offset Offset to read from. Will use and increase offset by length if omitted.
*/
read(length: number, offset?: number): ByteArray;
/**
* Reads an 8bit signed integer
*
* @param offset Offset to read from
*/
readInt8(offset?: number): number;
/**
* Reads an 8bit unsigned integer
*
* @param offset Offset to read from
*/
readUInt8(offset?: number): number;
/**
* Reads a 16bit signed le integer
*
* @param offset Offset to read from
*/
readInt16LE(offset?: number): number;
/**
* Reads a 16bit unsigned le integer
*
* @param offset Offset to read from
*/
readUInt16LE(offset?: number): number;
/**
* Reads a 16bit signed be integer
*
* @param offset Offset to read from
*/
readInt16BE(offset?: number): number;
/**
* Reads a 16bit unsigned be integer
*
* @param offset Offset to read from
*/
readUInt16BE(offset?: number): number;
/**
* Reads a 32bit signed le integer
*
* @param offset Offset to read from
*/
readInt32LE(offset?: number): number;
/**
* Reads a 32bit unsigned le integer
*
* @param offset Offset to read from
*/
readUInt32LE(offset?: number): number;
/**
* Reads a 32bit signed be integer
*
* @param offset Offset to read from
*/
readInt32BE(offset?: number): number;
/**
* Reads a 32bit unsigned be integer
*
* @param offset Offset to read from
*/
readUInt32BE(offset?: number): number;
/**
* Reads a 64bit signed le integer as math.Long
*
* @param offset Offset to read from
*/
readInt64LE(offset?: number): math.Long;
/**
* Reads a 64bit unsigned le integer as math.Long
*
* @param offset Offset to read from
*/
readUInt64LE(offset?: number): math.Long;
/**
* Reads a 64bit signed be integer as math.Long
*
* @param offset Offset to read from
*/
readInt64BE(offset?: number): math.Long;
/**
* Reads a 64bit unsigned be integer as math.Long
*
* @param offset Offset to read from
*/
readUInt64BE(offset?: number): math.Long;
/**
* Reads a 32bit le float
*
* @param offset Offset to read from
*/
readFloatLE(offset?: number): number;
/**
* Reads a 32bit be float
*
* @param offset Offset to read from
*/
readFloatBE(offset?: number): number;
/**
* Reads a 64bit le float
*
* @param offset Offset to read from
*/
readDoubleLE(offset?: number): number;
/**
* Reads a 64bit be float
*
* @param offset Offset to read from
*/
readDoubleBE(offset?: number): number;
/**
* Appends some data to this ByteArray.
* This will overwrite any contents behind the specified offset up to the appended data's length.
*
* @param source The source write from
* @param offset Offset to write at
* @param length length to read from the source
* @param encoding encoding to use for wrapping the source in bytearray
*/
write(source: I.ByteArray.Wrappable, offset?: number, length?: number, encoding?: string): this;
/**
* Writes the array as a bitset.
* @param value Array of booleans to write
*/
writeBitSet(value: number[]): this;
/**
* Writes the array as a bitset.
* @param value Array of booleans to write
* @param offset Offset to write at
*/
writeBitSet(value: number[], offset: number): number;
/**
* Writes a buffer at the given offset
* @param buf Buffer to write
* @param offset Offset to write at
*/
writeBuffer(buf: Buffer, offset?: number): this;
/**
* Writes an 8bit signed integer
*
* @param offset Offset to write at
*/
writeInt8(value: number, offset?: number): this;
/**
* Writes an 8bit unsigned integer
*
* @param offset Offset to write at
*/
writeUInt8(value: number, offset?: number): this;
/**
* Writes a 16bit signed le integer
*
* @param offset Offset to write at
*/
writeInt16LE(value: number, offset?: number): this;
/**
* Writes a 16bit signed be integer
*
* @param offset Offset to write at
*/
writeInt16BE(value: number, offset?: number): this;
/**
* Writes a 16bit unsigned le integer
*
* @param offset Offset to write at
*/
writeUInt16LE(value: number, offset?: number): this;
/**
* Writes a 16bit unsigned be integer
*
* @param offset Offset to write at
*/
writeUInt16BE(value: number, offset?: number): this;
/**
* Writes a 32bit signed le integer
*
* @param offset Offset to write at
*/
writeInt32LE(value: number, offset?: number): this;
/**
* Writes a 32bit signed be integer
*
* @param offset Offset to write at
*/
writeInt32BE(value: number, offset?: number): this;
/**
* Writes a 32bit unsigned le integer
*
* @param offset Offset to write at
*/
writeUInt32LE(value: number, offset?: number): this;
/**
* Writes a 32bit unsigned be integer
*
* @param offset Offset to write at
*/
writeUInt32BE(value: number, offset?: number): this;
/**
* Writes a 64bit signed le long integer
*
* @param offset Offset to write at
*/
writeInt64LE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 64bit signed be long integer
*
* @param offset Offset to write at
*/
writeInt64BE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 64bit unsigned le long integer
*
* @param offset Offset to write at
*/
writeUInt64LE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 64bit unsigned be long integer
*
* @param offset Offset to write at
*/
writeUInt64BE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 32bit le float
*
* @param offset Offset to write at
*/
writeFloatLE(value: number, offset?: number): this;
/**
* Writes a 32bit be float
*
* @param offset Offset to write at
*/
writeFloatBE(value: number, offset?: number): this;
/**
* Writes a 64bit le float
*
* @param offset Offset to write at
*/
writeDoubleLE(value: number, offset?: number): this;
/**
* Writes a 64bit be float
*
* @param offset Offset to write at
*/
writeDoubleBE(value: number, offset?: number): this;
/**
* Writes a 32bit base 128 variable-length integer
*/
writeVarint32(value: number): this;
/**
* Writes a 32bit base 128 variable-length integer
*
* @param offset Offset to write at
*/
writeVarint32(value: number, offset: number): number;
/**
* Writes a zig-zag encoded 32bit base 128 variable-length integer
*/
writeVarint32ZigZag(value: number): this;
/**
* Writes a zig-zag encoded 32bit base 128 variable-length integer
*
* @param offset Offset to write at
*/
writeVarint32ZigZag(value: number, offset: number): number;
/**
* Reads a 32bit base 128 variable-length integer
*/
readVarint32(): number;
/**
* Reads a 32bit base 128 variable-length integer
*
* @param offset Offset to read from
*/
readVarint32(offset: number): I.ByteArray.Varint32;
/**
* Reads a zig-zag encoded 32bit base 128 variable-length integer
*/
readVarint32ZigZag(): number;
/**
* Reads a zig-zag encoded 32bit base 128 variable-length integer
*
* @param offset Offset to read from
*/
readVarint32ZigZag(offset: number): I.ByteArray.Varint32;
/**
* Writes a 64bit base 128 variable-length integer
*/
writeVarint64(value: math.Long | string | number): this;
/**
* Writes a 64bit base 128 variable-length integer
*
* @param offset Offset to write at
*/
writeVarint64(value: math.Long | string | number, offset: number): number;
/**
* Writes a zig-zag encoded 64bit base 128 variable-length integer
*/
writeVarint64ZigZag(value: math.Long | string | number): this;
/**
* Writes a zig-zag encoded 64bit base 128 variable-length integer
*
* @param offset Offset to write at
*/
writeVarint64ZigZag(value: math.Long | string | number, offset: number): number;
/**
* Reads a 64bit base 128 variable-length integer
*/
readVarint64(): I.Long;
/**
* Reads a 64bit base 128 variable-length integer
*
* @param offset Offset to read from
*/
readVarint64(offset: number): I.ByteArray.Varint64;
/**
* Reads a zig-zag encoded 64bit base 128 variable-length integer
*/
readVarint64ZigZag(): math.Long;
/**
* Reads a zig-zag encoded 64bit base 128 variable-length integer
*
* @param offset Offset to read from
*/
readVarint64ZigZag(offset: number): I.ByteArray.Varint64;
/**
* Writes a NULL-terminated UTF8 encoded string.
* For this to work the specified string must not contain any NULL characters itself
*/
writeCString(str: string): this;
/**
* Writes a NULL-terminated UTF8 encoded string.
* For this to work the specified string must not contain any NULL characters itself
*
* @param offset Offset to write at
*/
writeCString(str: string, offset: number): number;
/**
* Reads a NULL-terminated UTF8 encoded string.
* For this to work the string read must not contain any NULL characters itself
*/
readCString(): string;
/**
* Reads a NULL-terminated UTF8 encoded string.
* For this to work the string read must not contain any NULL characters itself
*
* @param offset Offset to read from
*/
readCString(offset: number): I.ByteArray.String;
/**
* Writes an UTF8 encoded string
*/
writeString(str: string): this;
/**
* Writes an UTF8 encoded string
*
* @param offset Offset to write at
*/
writeString(str: string, offset: number): number;
/**
* Reads an UTF8 encoded string
*
* @param length Number of characters or bytes to read
* @param metrics Metrics specifying what n is meant to count. Defaults to ByteArray.METRICS_CHARS("c")
*/
readString(length: number, metrics?: I.ByteArray.Metrics): string;
/**
* Reads an UTF8 encoded string
*
* @param length Number of characters or bytes to read
* @param metrics Metrics specifying what n is meant to count. Defaults to ByteArray.METRICS_CHARS("c")
* @param offset Offset to read from
*/
readString(length: number, metrics: I.ByteArray.Metrics, offset: number): I.ByteArray.String;
/**
* Reads an UTF8 encoded string
*
* @param length Number of characters or bytes to read
* @param offset Offset to read from
*/
readString(length: number, offset: number): I.ByteArray.String;
/**
* Writes a length as varint32 prefixed UTF8 encoded string
*/
writeVString(str: string): this;
/**
* Writes a length as varint32 prefixed UTF8 encoded string
*
* @param offset Offset to read from
*/
writeVString(str: string, offset: number): number;
/**
* Reads a length as varint32 prefixed UTF8 encoded string
*/
readVString(): string;
/**
* Reads a length as varint32 prefixed UTF8 encoded string
*
* @param offset Offset to read from
*/
readVString(offset: number): I.ByteArray.String;
/**
* Appends this ByteArray's contents to another ByteArray.
* This will overwrite any contents behind the specified offset up to the length of this ByteArray's data
*
* @param offset Offset to append to
*/
appendTo(target: ByteArray, offset?: number): this;
/**
* Enables or disables assertions of argument types and offsets.
* Assertions are enabled by default but you can opt to disable them if your code already makes sure that everything is valid
*/
assert(assert?: boolean): this;
/**
* Gets the capacity of this ByteArray's backing buffer
*/
capacity(): number;
/**
* Clears this ByteArray's offsets by setting offset to 0 and limit to the backing buffer's capacity
*/
clear(): this;
/**
* Creates a cloned instance of this ByteArray,
* preset with this ByteArray's values for offset, markedOffset and limit
*
* @param copy Whether to copy the backing buffer or to return another view on the same, false by default
*/
clone(copy?: boolean): ByteArray;
/**
* Compacts this ByteArray to be backed by a buffer of its contents' length.
* Will set offset = 0 and limit = capacity and adapt markedOffset to the same relative position if set
*
* @param begin Offset to start at, buffer offset by default
* @param end Offset to end at, buffer limit by default
*/
compact(begin?: number, end?: number): this;
/**
* Creates a copy of this ByteArray's contents.
*
* @param begin Begin offset, buffer offset by default
* @param end End offset, buffer limit by default
*/
copy(begin?: number, end?: number): ByteArray;
/**
* Copies this ByteArray's contents to another ByteArray.
*
* @param targetOffset Offset to copy to. Will use and increase the target's offset by the number of bytes copied if omitted
* @param sourceOffset Offset to start copying from. Will use and increase offset by the number of bytes copied if omitted
* @param sourceLimit Offset to end copying from, defaults to the buffer limit
*/
copyTo(target: ByteArray, targetOffset?: number, souceOffset?: number, sourceLimit?: number): this | ByteArray;
/**
* Makes sure that this ByteArray is backed by a ByteArray#buffer of at least the specified capacity.
* If the current capacity is exceeded, it will be doubled.
* If double the current capacity is less than the required capacity, the required capacity will be used instead
*/
ensureCapacity(capacity: number): this;
/**
* Overwrites this ByteArray's contents with the specified value.
*
* @param value Byte value to fill with. If given as a string, the first character is used
* @param begin Begin offset. Will use and increase offset by the number of bytes written if omitted. defaults to offset
* @param end End offset, defaults to limit.
*/
fill(value: string | number, begin?: number, end?: number): this;
/**
* Makes this ByteArray ready for a new sequence of write or relative read operations.
* Sets limit = offset and offset = 0.
* Make sure always to flip a ByteArray when all relative read or write operations are complete
*/
flip(): this;
/**
* Marks an offset on this ByteArray to be used later
*
* @param offset Offset to mark. Defaults to offset.
*/
mark(offset?: number): this;
/**
* Prepends some data to this ByteArray.
* This will overwrite any contents before the specified offset up to the prepended data's length.
* If there is not enough space available before the specified offset,
* the backing buffer will be resized and its contents moved accordingly
*
* @param source Data to prepend
* @param offset Offset to prepend at. Will use and decrease offset by the number of bytes prepended if omitted.
*/
prepend(source: I.ByteArray.Wrappable, offset: number): this;
/**
* Prepends some data to this ByteArray.
* This will overwrite any contents before the specified offset up to the prepended data's length.
* If there is not enough space available before the specified offset,
* the backing buffer will be resized and its contents moved accordingly
*
* @param source Data to prepend
* @param encoding Encoding if data is a string
* @param offset Offset to prepend at. Will use and decrease offset by the number of bytes prepended if omitted.
*/
prepend(source: I.ByteArray.Wrappable, encoding?: string, offset?: number): this;
/**
* Prepends this ByteArray to another ByteArray.
* This will overwrite any contents before the specified offset up to the prepended data's length.
* If there is not enough space available before the specified offset,
* the backing buffer will be resized and its contents moved accordingly
*
* @param offset Offset to prepend at
*/
prependTo(target: ByteArray, offset?: number): this;
/**
* Gets the number of remaining readable bytes
*/
remaining(): number;
/**
* Resets this ByteArray's offset.
* If an offset has been marked through mark before, offset will be set to markedOffset, which will then be discarded.
* If no offset has been marked, sets offset = 0
*/
reset(): this;
/**
* Resizes this ByteArray to be backed by a buffer of at least the given capacity.
* Will do nothing if already that large or larger.
*
* @param capacity Capacity required
*/
resize(capacity: number): this;
/**
* Reverses this ByteArray's contents.
*
* @param begin Offset to start at, defaults to offset
* @param end Offset to end at, defaults to limit
*/
reverse(begin?: number, end?: number): this;
/**
* Skips the next length bytes. This will just advance
*/
skip(length: number): this;
/**
* Slices this ByteArray by creating a cloned instance with offset = begin and limit = end
*
* @param begin Begin offset, defaults to offset
* @param end End offset, defaults to limit
*/
slice(begin?: number, end?: number): ByteArray;
/**
* Returns a copy of the backing buffer that contains this ByteArray's contents.
*
* @param forceCopy If true returns a copy, otherwise returns a view referencing the same memory if possible, false by default
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toBuffer(forceCopy?: boolean, begin?: number, end?: number): Buffer;
/**
* Returns a raw buffer compacted to contain this ByteArray's contents
*/
toArrayBuffer(): ArrayBuffer;
/**
* Converts the ByteArray's contents to a string
*
* @param encoding Output encoding
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toString(encoding?: string, begin?: number, end?: number): string;
/**
* Encodes this ByteArray's contents to a base64 encoded string
*
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toBase64(begin?: number, end?: number): string;
/**
* Encodes this ByteArray to a binary encoded string, that is using only characters 0x00-0xFF as bytes
*
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toBinary(begin?: number, end?: number): string;
/**
* Encodes this ByteArray to a hex encoded string with marked offsets
*
* @param columns If true returns two columns hex + ascii, defaults to false
*/
toDebug(columns?: boolean): string;
/**
* Encodes this ByteArray's contents to a hex encoded string
*
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toHex(begin?: number, end?: number): string;
/**
* Encodes this ByteArray's contents to an UTF8 encoded string
*
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toUTF8(begin?: number, end?: number): string;
static accessor(): typeof Buffer;
/**
* Allocates a new ByteArray backed by a buffer of the specified capacity.
*
* @param capacity Initial capacity. Defaults to ByteArray.DEFAULT_CAPACITY(64)
* @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false)
*/
static allocate(capacity?: number, noAssert?: boolean): ByteArray;
/**
* Concatenates multiple ByteArrays into one
*
* @param encoding Encoding for strings
* @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false)
*/
static concat(buffers: I.ByteArray.Wrappable[], encoding?: string, noAssert?: boolean): ByteArray;
static type(): typeof Buffer;
/**
* Wraps a buffer or a string.
* Sets the allocated ByteArray's offset to 0 and its limit to the length of the wrapped data
*
* @param encoding Encoding for strings
* @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false)
*/
static wrap(buffer: I.ByteArray.Wrappable, encoding?: string, noAssert?: boolean): ByteArray;
/**
* Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer
*/
static calculateVarint32(value: number): number;
/**
* Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding
*/
static zigZagEncode32(n: number): number;
/**
* Decodes a zigzag encoded signed 32bit integer
*/
static zigZagDecode32(n: number): number;
/**
* Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer
*/
static calculateVarint64(value: number | string): number;
/**
* Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding
*/
static zigZagEncode64(value: number | string | I.Long): I.Long;
/**
* Decodes a zigzag encoded signed 64bit integer.
*/
static zigZagDecode64(value: number | string | I.Long): I.Long;
/**
* Calculates the number of UTF8 characters of a string.
* JavaScript itself uses UTF-16,
* so that a string's length property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF
*/
static calculateUTF8Chars(str: string): number;
/**
* Calculates the number of UTF8 bytes of a string.
*/
static calculateString(str: string): number;
/**
* Decodes a base64 encoded string to a ByteArray
*/
static fromBase64(str: string): ByteArray;
/**
* Encodes a binary string to base64 like window.btoa does
*/
static btoa(str: string): string;
/**
* Decodes a base64 encoded string to binary like window.atob does
*/
static atob(b64: string): string;
/**
* Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteArray
*/
static fromBinary(str: string): ByteArray;
/**
* Decodes a hex encoded string with marked offsets to a ByteArray
*/
static fromDebug(str: string, noAssert?: boolean): ByteArray;
/**
* Decodes a hex encoded string to a ByteArray
*/
static fromHex(str: string, noAssert?: boolean): ByteArray;
/**
* Decodes an UTF8 encoded string to a ByteArray
*/
static fromUTF8(str: string, noAssert?: boolean): ByteArray;
/**
* Default initial capacity
*/
static DEFAULT_CAPACITY: number;
/**
* Default no assertions flag
*/
static DEFAULT_NOASSERT: boolean;
/**
* Maximum number of bytes required to store a 32bit base 128 variable-length integer
*/
static MAX_VARINT32_BYTES: number;
/**
* Maximum number of bytes required to store a 64bit base 128 variable-length integer
*/
static MAX_VARINT64_BYTES: number;
/**
* Metrics representing number of UTF8 characters. Evaluates to `c`.
*/
static METRICS_CHARS: string;
/**
* Metrics representing number of bytes. Evaluates to `b`.
*/
static METRICS_BYTES: string;
}
}
+9
View File
@@ -0,0 +1,9 @@
declare namespace adone.collection {
/**
* Represents a Map that has a default values factory object or function.
* Each get of non-existent key goes through the factory
*/
class DefaultMap<K = string, V = any> extends Map<K, V> {
constructor(factory?: ((key: K) => V) | { [key: string]: V }, iterable?: Iterable<[K, V]>);
}
}
+61
View File
@@ -0,0 +1,61 @@
declare namespace adone.collection {
/**
* Represents a faster LRU cache but with less functionality
*/
class FastLRU<K = any, V = any> {
/**
* @param size Cache size, unlimited by default
*/
constructor(size?: number, options?: {
/**
* Function that is called when a value is deleted
*/
dispose?(key: K, value: V): void
});
/**
* The actual size of the cache
*/
readonly size: number;
/**
* Gets the value by the given key
*/
get(key: K): V | undefined;
/**
* Sets a new value for the given key
*/
set(key: K, value: V): void;
/**
* Deletes the given key from the cache
*/
delete(key: K): boolean;
/**
* Checks whether the cache has an element with the given key
*/
has(key: K): boolean;
/**
* Returns the keys iterator
*/
keys(): IterableIterator<K>;
/**
* Returns the values iterator
*/
values(): IterableIterator<V>;
/**
* Returns the entries iterator
*/
entries(): IterableIterator<[K, V]>;
/**
* Clears the cache
*/
clear(): void;
}
}
+28
View File
@@ -0,0 +1,28 @@
/// <reference path="./array_set.d.ts" />
/// <reference path="./async_queue.d.ts" />
/// <reference path="./avl_tree.d.ts" />
/// <reference path="./binary_search_tree.d.ts" />
/// <reference path="./buffer_list.d.ts" />
/// <reference path="./byte_array.d.ts" />
/// <reference path="./default_map.d.ts" />
/// <reference path="./fast_lru.d.ts" />
/// <reference path="./linked_list.d.ts" />
/// <reference path="./lru.d.ts" />
/// <reference path="./map_cache.d.ts" />
/// <reference path="./ns_cache.d.ts" />
/// <reference path="./priority_queue.d.ts" />
/// <reference path="./queue.d.ts" />
/// <reference path="./rb_tree.d.ts" />
/// <reference path="./refcounted_cache.d.ts" />
/// <reference path="./set.d.ts" />
/// <reference path="./stack.d.ts" />
/// <reference path="./timedout_map.d.ts" />
declare namespace adone {
/**
* Data structures
*/
namespace collection {
//
}
}
+150
View File
@@ -0,0 +1,150 @@
declare namespace adone.collection {
namespace I.LinkedList {
/**
* Represents the node of a linked list
*/
interface Node<T> {
/**
* The next node
*/
next?: Node<T>;
/**
* The previous node
*/
prev?: Node<T>;
/**
* The value this node contains
*/
value: T;
}
}
/**
* Represents a linked list
*/
class LinkedList<T = any> {
/**
* The maximum length of the list
*/
readonly maxLength: number;
/**
* Current length of the list
*/
readonly length: number;
/**
* Whether the list is autoresizable
*/
readonly autoresize: boolean;
/**
* @param maxLength Maximum length of the linked list
*/
constructor(maxLength?: number);
/**
* Whether the list is full
*/
readonly full: boolean;
/**
* Whether the list is empty
*/
readonly empty: boolean;
/**
* Resizes the list
*/
resize(newLength: number): this;
/**
* Adds a new node to the end
*
* @returns Added node
*/
push(value: T): I.LinkedList.Node<T>;
/**
* Removes the last node, returns undefined if the list is empty
*/
pop(): T | undefined;
/**
* Removes the first node, returns undefined if the list is empty
*/
shift(): T | undefined;
/**
* Inserts a new node at the beginning of the list
*
* @returns Added node
*/
unshift(value: T): I.LinkedList.Node<T>;
/**
* Moves the given node to the end of the list
*/
pushNode(node: I.LinkedList.Node<T>): void;
/**
* Moved the given node to the beginning of the list
*/
unshiftNode(node: I.LinkedList.Node<T>): void;
/**
* Removes the given node from the list
*/
removeNode(node: I.LinkedList.Node<T>): void;
/**
* Clears the list
*
* @param strong Whether to reset all the node's values
*/
clear(strong?: boolean): void;
/**
* Convers the list to an array
*/
toArray(): T[];
/**
* The first element of the list
*/
readonly front: T;
/**
* The last element of the list
*/
readonly back: T;
/**
* Returns an iterator over the list elements
*/
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns the next node for the given node
*/
nextNode(node: I.LinkedList.Node<T>): I.LinkedList.Node<T>;
/**
* Maps this linked list to a new one using the given function
*/
map<R>(fn: (value: T, index: number) => R): LinkedList<R>;
/**
* Invokes the given callback for each value from the beginning to the end (much faster than for-of).
* If the given function returns false it stops iterating.
*/
forEach(callback: (value: T, index: number) => void | boolean): void;
/**
* Default length of a new created linked list
*/
static DEFAULT_LENGTH: number;
}
}
+213
View File
@@ -0,0 +1,213 @@
declare namespace adone.collection {
namespace I.LRU {
type LengthCalculator<K, V> = (value: V, key: K) => number;
interface ConstructorOptions<K, V> {
/**
* The maximum size of the cache, checked by applying the length function to all values in the cache.
* Default is Infinity
*/
max?: number;
/**
* Maximum age in ms. Items are not pro-actively pruned out as they age,
* but if you try to get an item that is too old,
* it'll drop it and return undefined instead of giving it to you
*/
maxAge?: number;
/**
* Function that is used to calculate the length of stored items
*/
length?: LengthCalculator<K, V>;
/**
* Function that is called on items when they are dropped from the cache
*/
dispose?(key: K, value: V): void;
/**
* Whether to return the stale value before deleting it
*/
stale?: boolean;
/**
* Dispose will only be called when a key falls out of the cache, not when it is overwritten
*/
noDisposeOnSet?: boolean;
}
interface SerializedEntry<K, V> {
/**
* key
*/
key: K;
/**
* value
*/
value: V;
/**
* when it becomes expired
*/
e: number;
}
interface Entry<K, V> {
/**
* key
*/
key: K;
/**
* value
*/
value: V;
/**
* entry length
*/
length: number;
/**
* Timestamp when the entry was created
*/
now: number;
/**
* Maximum live time
*/
maxAge: number;
}
}
/**
* Represent an LRU cache
*/
class LRU<K = any, V = any> {
/**
* Creates an LRU cache of the given size
*/
constructor(max: number);
/**
* Creates an LRU cache with the given options
*/
constructor(options?: I.LRU.ConstructorOptions<K, V>);
/**
* The length of the cache, setter resizes the cache
*/
max: number;
/**
* stale setting
*/
allowStale: boolean;
/**
* maxAge setting
*/
maxAge: number;
/**
* length setting
*/
lengthCalculator: I.LRU.LengthCalculator<K, V>;
/**
* Total length of objects in cache taking into account length options function
*/
readonly length: number;
/**
* Total quantity of objects currently in cache.
* Note, that stale items are returned as part of this item count.
*/
readonly itemCount: number;
/**
* Iterates over all the keys in the cache, in reverse recent-ness order. (ie, less recently used items are iterated over first.)
*/
rforEach<T = any>(fn: (this: T, value: V, key: K, cache: LRU<K, V>) => void, thisp?: T): void;
/**
* Iterates over all the keys in the cache, in order of recent-ness
*/
forEach<T = any>(fn: (this: T, value: V, key: K, cache: LRU<K, V>) => void, thisp?: T): void;
/**
* Returns an array of the keys in the cache
*/
keys(): K[];
/**
* Returns an array of the values in the cache
*/
values(): V[];
/**
* Clears the cache entirely, throwing away all values
*/
reset(): void;
/**
* Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)`
*/
dump(): Array<I.LRU.SerializedEntry<K, V>>;
/**
* Returns an internal lru list of entries
*/
dumpLru(): LinkedList<I.LRU.Entry<K, V>>;
/**
* @param opts std.util.inspect options
*/
inspect(opts?: object): string;
/**
* Sets a new value for the given key. Updates the "recently used"-ness of the key
*
* @param maxAge maxAge option specific for this key
* @returns Whether the key was set
*/
set(key: K, value: V, maxAge?: number): boolean;
/**
* Check if a key is in the cache, without updating the recent-ness or deleting it for being stale
*/
has(key: K): boolean;
/**
* Gets the value of the given key. Updates the "recently used"-ness of the key
*/
get(key: K): V | undefined;
/**
* Returns the key value without updating the "recently used"-ness of the key
*/
peek(key: K): V | undefined;
/**
* Deletes the less recently used element
*/
pop(): I.LRU.Entry<K, V>;
/**
* Deletes a key out of the cache
*/
del(key: K): void;
/**
* Loads another cache entries array, obtained with sourceCache.dump(), into the cache.
* The destination cache is reset before loading new entries
*/
load(arr: Array<I.LRU.SerializedEntry<K, V>>): void;
/**
* Manually iterates over the entire cache proactively pruning old entries
*/
prune(): void;
}
}
+13
View File
@@ -0,0 +1,13 @@
declare namespace adone.collection {
class MapCache<T = any> {
has(key: string): boolean;
get(key: string): T;
set(key: string, value: T): void;
delete(key: string): void;
clear(): void;
}
}
+17
View File
@@ -0,0 +1,17 @@
declare namespace adone.collection {
class NSCache<T = any> {
constructor(size: number, namespaces: string[]);
resize(newSize: number): void;
set(ns: string, key: string, value: T): void;
get(ns: string, key: string): T;
has(ns: string, key: string): boolean;
delete(ns: string, key: string): void;
clear(): void;
}
}
+78
View File
@@ -0,0 +1,78 @@
declare namespace adone.collection {
namespace I.PriorityQueue {
interface ConstructorOptions<T> {
/**
* Function that compares objects.
*
* Must return a positive value if a > b, a negative if a < b, and zero for equal objects
*/
compare?(a: T, b: T): number;
/**
* Function that evaluates the priority value by the given objects,
* if the returned value > 0, then the first argument has higher priority,
* = 0 same priority, < 0 lower priority.
* By default the top element is an element that has the highest priority,
* the default priority function is equal to the compare function
*/
priority?(a: T, b: T): number;
}
}
/**
* Represents a priority queue
*/
class PriorityQueue<T = any> {
/**
* Whether the queue is empty
*/
readonly empty: boolean;
/**
* The length of the queue
*/
readonly length: number;
constructor(options?: I.PriorityQueue.ConstructorOptions<T>);
/**
* Clones the queue
*/
clone(): PriorityQueue<T>;
/**
* Inserts a new element
*/
push(x: T): this;
/**
* Removes the top element (that has the highest priority)
*/
pop(): T | undefined;
/**
* Deletes the given element from the queue
*/
delete(x: T): this;
/**
* Replaces the top element (pop + push)
*/
replace(x: T): T;
/**
* Faster push + pop
*/
pushpop(x: T): T;
/**
* Converts the queue to an array, it works with a clone of the queue, so the original queue is untouched
*/
toArray(): T[];
/**
* Creates a queue object from the given iterable
*/
static from<T>(iterable: Iterable<T>, options?: I.PriorityQueue.ConstructorOptions<T>): PriorityQueue<T>;
}
}
+33
View File
@@ -0,0 +1,33 @@
declare namespace adone.collection {
/**
* Represents a queue
*/
class Queue<S = any, T = S> {
/**
* Whether the queue is full
*/
readonly full: boolean;
/**
* The length of the queue
*/
readonly length: number;
/**
* Whether the queue is empty
*/
readonly empty: boolean;
/**
* Inserts a new element at the end
*/
push(x: S): this;
/**
* Removes and returns an element from the beginning
*/
pop(): T | undefined;
static from<T>(iterable: Iterable<T>, length?: number): Queue<T>;
}
}
+184
View File
@@ -0,0 +1,184 @@
declare namespace adone.collection {
namespace I.RedBlackTree {
interface Node<K, V> {
/**
* The key associated to the node
*/
key: K;
/**
* The value associated to the node
*/
value: V;
/**
* The left subtree of the node
*/
left?: Node<K, V>;
/**
* The right subtree of the node
*/
right?: Node<K, V>;
}
interface Iterator<K, V> {
/**
* Checks if the iterator is valid
*/
readonly valid: boolean;
/**
* The value of the node at the iterator's current position, null if invalid
*/
readonly node: Node<K, V> | null;
/**
* The key of the item referenced by the iterator, undefined if invalid
*/
readonly key?: K;
/**
* The value of the item referenced by the iterator, undefined if invalid
*/
readonly value?: V;
/**
* Returns the position of this iterator in the sequence
*/
readonly index: number;
/**
* If true, then the iterator is not at the end of the sequence
*/
readonly hasNext: boolean;
/**
* If true, then the iterator is not at the beginning of the sequence
*/
readonly hasPrev: boolean;
/**
* The tree associated to the iterator
*/
tree: RedBlackTree<K, V>;
/**
* Makes a copy of the iterator
*/
clone(): Iterator<K, V>;
/**
* Removes the item at the position of the iterator and returns a new rb-tree
*/
remove(): RedBlackTree<K, V>;
/**
* Advances the iterator to the next position
*/
next(): void;
/**
* Updates the value of the node in the tree at this iterator and returns a new rb-tree
*/
update(value: V): RedBlackTree<K, V>;
/**
* Moves the iterator backward one element
*/
prev(): void;
}
}
/**
* Represents a fully persistent red-black tree
*/
class RedBlackTree<K = any, V = any> {
/**
* The root node of the tree
*/
root: I.RedBlackTree.Node<K, V>;
constructor(compare?: (a: K, b: K) => number, root?: RedBlackTree<K, V>);
/**
* A sorted array of all the keys in the tree
*/
readonly keys: K[];
/**
* An array of all the values in the tree
*/
readonly values: V[];
/**
* The number of items in the tree
*/
readonly length: number;
/**
* An iterator pointing to the first element in the tree
*/
readonly begin: I.RedBlackTree.Iterator<K, V>;
/**
* An iterator pointing to the last element in the tree
*/
readonly end: I.RedBlackTree.Iterator<K, V>;
/**
* Creates a new tree with the new pair inserted
*/
insert(key: K, value: V): RedBlackTree<K, V>;
/**
* Walks a visitor function over the nodes of the tree in order
*
* @param visit A callback that gets executed on each node.
* If a truthy value is returned from the visitor, then iteration is stopped.
* @param lo An optional start of the range to visit (inclusive)
* @param hi An optional end of the range to visit (non-inclusive)
*/
forEach<T>(visit: (key: K, value: V) => T, lo?: K, hi?: K): T;
/**
* Finds an iterator starting at the given element
*/
at(idx: number): I.RedBlackTree.Iterator<K, V>;
/**
* Finds the first item in the tree whose key is >= key
*/
ge(key: K): I.RedBlackTree.Iterator<K, V>;
/**
* Finds the first item in the tree whose key is > key
*/
gt(key: K): I.RedBlackTree.Iterator<K, V>;
/**
* Finds the first item in the tree whose key is < key
*/
lt(key: K): I.RedBlackTree.Iterator<K, V>;
/**
* Finds the first item in the tree whose key is <= key
*/
le(key: K): I.RedBlackTree.Iterator<K, V>;
/**
* Returns an iterator pointing to the first item in the tree with key, otherwise null
*/
find(key: K): I.RedBlackTree.Iterator<K, V> | null;
/**
* Removes the first item with key in the tree
*/
remove(key: K): RedBlackTree<K, V>;
/**
* Retrieves the value associated to the given key
*/
get(key: K): V | undefined;
}
}
+9
View File
@@ -0,0 +1,9 @@
declare namespace adone.collection {
class RefcountedCache<T = any> extends MapCache<T> {
ref(key: string): void;
unref(key: string): void;
references(key: string): number;
}
}
+17
View File
@@ -0,0 +1,17 @@
declare namespace adone.collection {
class Set<T = any> {
constructor(key?: (x: T) => any);
has(value: T): boolean;
add(value: T): void;
delete(value: T): void;
get(value: T): T; // ???
readonly size: number;
only(): T;
}
}
+36
View File
@@ -0,0 +1,36 @@
declare namespace adone.collection {
/**
* Represents a stack
*/
class Stack<T = any> {
/**
* Whether the stack is empty
*/
readonly empty: boolean;
/**
* The top element of the stack
*/
readonly top: T;
/**
* Inserts a new element
*/
push(x: T): this;
/**
* Removes the top element
*/
pop(): T | undefined;
/**
* Returns an iterator over the values
*/
[Symbol.iterator](): IterableIterator<T>;
/**
* Creates a stack and pushed all the values from the given iterable object
*/
static from<T>(iterable: Iterable<T>): Stack<T>;
}
}
+32
View File
@@ -0,0 +1,32 @@
declare namespace adone.collection {
/**
* Represents a Map that keeps keys only for a specified interval of time
*/
class TimedoutMap<K = any, V = any> extends Map<K, V> {
/**
* @param timeout maximum age of the keys, 1000 by default
* @param callback callback that is called with each key when the timeout is passed
*/
constructor(timeout?: number, callback?: (key: K) => void);
/**
* Gets the timeout
*/
getTimeout(): number;
/**
* Sets the timeout
*/
setTimeout(ms: number): void;
/**
* Iterates over the map and calls the callback for each element
*/
forEach<T = any>(callback: (this: T, value: V, key: K, cache: this) => void, thisArg?: T): this;
/**
* Deletes the given key
*/
delete(key: K): boolean;
}
}
+597
View File
@@ -0,0 +1,597 @@
declare namespace adone.crypto {
namespace asn1 {
namespace I {
interface LocalBaseBlockParams {
blockLength?: number;
error?: string;
warnings?: string[];
valueBeforeDecode?: ArrayBuffer;
}
interface JsonLocalBaseBlock {
blockName: string;
blockLength: number;
error: string;
warnings: string[];
valueBeforeDecode: ArrayBuffer;
}
class LocalBaseBlock {
blockLength: number;
error: string;
warnings: string[];
valueBeforeDecode: ArrayBuffer;
constructor(params?: LocalBaseBlockParams);
/**
* Aux function, need to get a block name. Need to have it here for inhiritence
*/
static blockName(): string;
/**
* Convertion for the block to JSON object
*/
toJSON(): JsonLocalBaseBlock;
}
interface LocalHexBlockParams extends LocalBaseBlockParams {
isHexOnly?: boolean;
valueHex?: ArrayBuffer;
}
class LocalHexBlock {
isHexOnly: boolean;
valueHex: ArrayBuffer;
constructor(params: any);
/**
* Aux function, need to get a block name. Need to have it here for inhiritence
*/
static blockName(): string;
/**
* Base function for converting block from BER encoded array of bytes
*
* @param inputBuffer ASN.1 BER encoded array
* @param inputOffset Offset in ASN.1 BER encoded array where decoding should be started
* @param inputLength Maximum length of array of bytes which can be using in this function
*/
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number;
/**
* Encoding of current ASN.1 block into ASN.1 encoded array (BER rules)
*
* @param sizeOnly Flag that we need only a size of encoding, not a real array of bytes
*/
toBER(sizeOnly?: boolean): ArrayBuffer;
/**
* Convertion for the block to JSON object
*/
toJSON(): any;
}
interface LocalIdentificationBlockParams {
idBlock?: LocalHexBlockParams & {
isConstructed?: boolean;
tagClass?: number;
tagNumber?: number;
};
}
class LocalIdentificationBlock extends LocalBaseBlock {
isConstructed: boolean;
tagClass: number;
tagNumber: number;
constructor(params?: LocalIdentificationBlockParams);
// ILocalHexBlock implementation
isHexOnly: boolean;
valueHex: ArrayBuffer;
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number;
toBER(sizeOnly?: boolean): ArrayBuffer;
}
interface LocalLengthBlockParams {
lenBlock?: {
isIndefiniteForm?: boolean;
longFormUsed?: boolean;
length: number;
};
}
class LocalLengthBlock extends LocalBaseBlock {
isIndefiniteForm: boolean;
longFormUsed: boolean;
length: number;
constructor(params?: LocalLengthBlockParams);
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): void;
toBER(sizeOnly?: boolean): ArrayBuffer;
}
class LocalValueBlock extends LocalBaseBlock {
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): void;
toBER(sizeOnly?: boolean): ArrayBuffer;
}
interface BaseBlockParams extends LocalBaseBlockParams {
name?: string;
optional?: boolean;
primitiveSchema?: object;
}
interface LocalPrimitiveValueBlockParams extends LocalBaseBlockParams {
valueHex?: ArrayBuffer;
isHexOnly?: boolean;
}
class LocalPrimitiveValueBlock extends LocalValueBlock {
valueHex: ArrayBuffer;
isHexOnly: boolean;
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number;
toBER(sizeOnly?: boolean): ArrayBuffer;
}
interface LocalConstructedValueBlockParams extends LocalBaseBlockParams {
value?: LocalValueBlock;
isIndefiniteForm?: boolean;
}
class LocalConstructedValueBlock extends LocalValueBlock {
value: LocalValueBlock[];
isIndefiniteForm: boolean;
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number;
toBER(sizeOnly?: boolean): ArrayBuffer;
}
class LocalEndOfContentValueBlock extends LocalValueBlock {
constructor(params?: LocalBaseBlockParams);
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number;
toBER(sizeOnly?: boolean): ArrayBuffer;
}
interface LocalBooleanValueBlockParams extends LocalBaseBlockParams {
value?: boolean;
isHexOnly?: boolean;
valueHex?: ArrayBuffer;
}
class LocalBooleanValueBlock extends LocalValueBlock {
value: boolean;
isHexOnly: boolean;
valueHex: ArrayBuffer;
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number;
toBER(sizeOnly?: boolean): ArrayBuffer;
}
interface LocalOctetStringValueBlockParams extends LocalConstructedValueBlockParams, LocalHexBlockParams {
isConstructed?: boolean;
}
class LocalOctetStringValueBlock extends LocalConstructedValueBlock {
isConstructed: boolean;
isHexOnly: boolean;
valueHex: ArrayBuffer;
constructor(params?: LocalOctetStringValueBlockParams);
}
interface LocalBitStringValueBlockParams extends LocalConstructedValueBlockParams, LocalHexBlockParams {
unusedBits?: number;
isConstructed?: boolean;
blockLength?: number;
}
class LocalBitStringValueBlock extends LocalConstructedValueBlock implements LocalHexBlock {
unusedBits: number;
isConstructed: boolean;
blockLength: number;
isHexOnly: boolean;
valueHex: ArrayBuffer;
constructor(params?: LocalBitStringValueBlockParams);
}
interface LocalIntegerValueBlockParams extends LocalBaseBlockParams, LocalHexBlockParams {
}
class LocalIntegerValueBlock extends LocalValueBlock implements LocalHexBlock {
valueDec: number;
isHexOnly: boolean;
valueHex: ArrayBuffer;
constructor(params?: LocalIntegerValueBlockParams);
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number;
toBER(sizeOnly?: boolean): ArrayBuffer;
/**
* Base function for converting block from DER encoded array of bytes
*
* @param inputBuffer ASN.1 DER encoded array
* @param inputOffset Offset in ASN.1 DER encoded array where decoding should be started
* @param inputLength Maximum length of array of bytes which can be using in this function
* @param expectedLength Expected length of converted "valueHex" buffer
*/
fromDER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number, expectedLength?: number): number;
/**
* Encoding of current ASN.1 block into ASN.1 encoded array (DER rules)
*
* @param sizeOnly Flag that we need only a size of encoding, not a real array of bytes
*/
toDER(sizeOnly?: boolean): ArrayBuffer;
}
interface IntegerParams {
value?: number;
}
interface LocalSidValueBlockParams extends LocalBaseBlockParams, LocalHexBlockParams {
valueDec?: number;
isFirstSid?: boolean;
}
class LocalSidValueBlock extends LocalBaseBlock implements LocalHexBlock {
valueDec: number;
isFirstSid: boolean;
isHexOnly: boolean;
valueHex: ArrayBuffer;
constructor(params?: LocalSidValueBlockParams);
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number;
toBER(sizeOnly?: boolean): ArrayBuffer;
toString(): string;
}
interface LocalObjectIdentifierValueBlockParams extends LocalBaseBlockParams {
value?: string;
}
class LocalObjectIdentifierValueBlock extends LocalValueBlock {
constructor(params?: LocalObjectIdentifierValueBlockParams);
/**
* Create "LocalObjectIdentifierValueBlock" class from string
*
* @param string Input string to convert from
*/
fromString(data: string): boolean;
/**
* Converts "LocalObjectIdentifierValueBlock" class to string
*/
toString(): string;
}
interface LocalUtf8StringValueBlockParams extends LocalBaseBlockParams, LocalHexBlock {
}
class LocalUtf8StringValueBlock extends LocalBaseBlock implements LocalHexBlock {
isHexOnly: boolean;
valueHex: ArrayBuffer;
constructor(params?: LocalSidValueBlockParams);
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number;
toBER(sizeOnly?: boolean): ArrayBuffer;
toString(): string;
}
interface Utf8StringParams {
value?: string;
}
interface LocalBmpStringValueBlockParams extends LocalHexBlockParams, LocalBaseBlockParams {
}
class LocalBmpStringValueBlock extends LocalBaseBlock implements LocalHexBlock {
value: string;
isHexOnly: boolean;
valueHex: ArrayBuffer;
constructor(params?: LocalBmpStringValueBlockParams);
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number;
toBER(sizeOnly?: boolean): ArrayBuffer;
}
interface LocalUniversalStringValueParams extends LocalHexBlockParams, LocalBaseBlockParams {
}
class LocalUniversalStringValueBlock extends LocalBaseBlock implements LocalHexBlock {
value: string;
isHexOnly: boolean;
valueHex: ArrayBuffer;
constructor(params?: LocalUniversalStringValueParams);
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number;
toBER(sizeOnly?: boolean): ArrayBuffer;
}
interface LocalSimpleLocalSimpleStringValueBlockParams extends LocalHexBlockParams, LocalBaseBlockParams {
}
class LocalSimpleLocalSimpleStringValueBlock extends LocalBaseBlock implements LocalHexBlock {
value: string;
isHexOnly: boolean;
valueHex: ArrayBuffer;
constructor(params?: LocalSimpleLocalSimpleStringValueBlockParams);
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number;
toBER(sizeOnly?: boolean): ArrayBuffer;
}
interface LocalSimpleStringBlockParams {
value?: string;
}
class LocalSimpleStringBlock extends BaseBlock<LocalSimpleLocalSimpleStringValueBlock> {
constructor(params?: LocalSimpleStringBlockParams);
/**
* Function converting ArrayBuffer into ASN.1 internal string
*
* @param inputBuffer ASN.1 BER encoded array
*/
fromBuffer(inputBuffer: ArrayBuffer): void;
/**
* Function converting JavaScript string into ASN.1 internal class
*
* @param inputString ASN.1 BER encoded array
*/
fromString(inputString: string): void;
}
interface BmpStringParams {
value?: string;
}
interface UniversalStringParams {
value?: string;
}
interface UTCTimeParams extends LocalSimpleLocalSimpleStringValueBlockParams {
value?: string;
valueDate?: Date;
}
interface ChoiceParams {
value?: LocalValueBlock[];
optional?: boolean;
}
interface AnyParams {
name?: string;
optional?: boolean;
}
interface RepeatedParams {
name?: string;
optional?: boolean;
value?: Any;
local?: boolean;
}
interface RawDataParams {
data?: ArrayBuffer;
}
}
class BaseBlock<T extends I.LocalValueBlock> extends I.LocalBaseBlock {
constructor(parameters?: I.BaseBlockParams, valueBlockType?: typeof I.LocalValueBlock);
idBlock: I.LocalIdentificationBlock;
lenBlock: I.LocalLengthBlock;
valueBlock: T;
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number;
toBER(sizeOnly?: boolean): ArrayBuffer;
}
class Primitive extends BaseBlock<I.LocalPrimitiveValueBlock> {
}
class Constructed extends BaseBlock<I.LocalConstructedValueBlock> { }
class EndOfContent extends BaseBlock<I.LocalEndOfContentValueBlock> { }
class Boolean extends BaseBlock<I.LocalBooleanValueBlock> { }
class Sequence extends Constructed { }
class Set extends Constructed { }
class Null extends BaseBlock<I.LocalValueBlock> { }
class OctetString extends BaseBlock<I.LocalOctetStringValueBlock> {
constructor(params?: I.LocalOctetStringValueBlockParams);
/**
* Checking that two OCTETSTRINGs are equal
*/
isEqual(octetString: OctetString): boolean;
}
class BitString extends BaseBlock<I.LocalBitStringValueBlock> {
constructor(params?: I.LocalBitStringValueBlockParams);
/**
* Checking that two BITSTRINGs are equal
* @param bitString
*/
isEqual(bitString: BitString): boolean;
}
class Integer extends BaseBlock<I.LocalIntegerValueBlock> {
constructor(params?: I.IntegerParams)
/**
* Compare two Integer object, or Integer and ArrayBuffer objects
*/
isEqual(otherValue: Integer | ArrayBuffer): boolean;
/**
* Convert current Integer value from BER into DER format
*/
convertToDER(): Integer;
/**
* Convert current Integer value from DER to BER format
*/
convertFromDER(): Integer;
}
class Enumerated extends Integer { }
class ObjectIdentifier extends BaseBlock<I.LocalObjectIdentifierValueBlock> {
constructor(params?: I.LocalObjectIdentifierValueBlockParams);
}
class Utf8String extends BaseBlock<I.LocalUtf8StringValueBlock> {
constructor(params?: I.Utf8StringParams);
/**
* Function converting ArrayBuffer into ASN.1 internal string
*
* @param inputBuffer ASN.1 BER encoded array
*/
fromBuffer(inputBuffer: ArrayBuffer): void;
/**
* Function converting JavaScript string into ASN.1 internal class
*
* @param inputString ASN.1 BER encoded array
*/
fromString(inputString: string): void;
}
class BmpString extends BaseBlock<I.LocalBmpStringValueBlock> {
constructor(params?: I.BmpStringParams);
/**
* Function converting ArrayBuffer into ASN.1 internal string
*
* @param inputBuffer ASN.1 BER encoded array
*/
fromBuffer(inputBuffer: ArrayBuffer): void;
/**
* Function converting JavaScript string into ASN.1 internal class
*
* @param inputString ASN.1 BER encoded array
*/
fromString(inputString: string): void;
}
class UniversalString extends BaseBlock<I.LocalUniversalStringValueBlock> {
constructor(params?: I.UniversalStringParams);
/**
* Function converting ArrayBuffer into ASN.1 internal string
*
* @param inputBuffer ASN.1 BER encoded array
*/
fromBuffer(inputBuffer: ArrayBuffer): void;
/**
* Function converting JavaScript string into ASN.1 internal class
*
* @param inputString ASN.1 BER encoded array
*/
fromString(inputString: string): void;
}
class NumericString extends I.LocalSimpleStringBlock { }
class PrintableString extends I.LocalSimpleStringBlock { }
class TeletexString extends I.LocalSimpleStringBlock { }
class VideotexString extends I.LocalSimpleStringBlock { }
class IA5String extends I.LocalSimpleStringBlock { }
class GraphicString extends I.LocalSimpleStringBlock { }
class VisibleString extends I.LocalSimpleStringBlock { }
class GeneralString extends I.LocalSimpleStringBlock { }
class CharacterString extends I.LocalSimpleStringBlock { }
class UTCTime extends VisibleString {
year: number;
month: number;
day: number;
hour: number;
minute: number;
second: number;
constructor(params?: I.UTCTimeParams);
/**
* Function converting ASN.1 internal string into ArrayBuffer
*/
toBuffer(): ArrayBuffer;
/**
* Function converting "Date" object into ASN.1 internal string
*
* @param inputDate JavaScript "Date" object
*/
fromDate(inputDate: Date): void;
/**
* Function converting ASN.1 internal string into "Date" object
*/
toDate(): Date;
}
class GeneralizedTime extends UTCTime {
millisecond: number;
}
class DATE extends Utf8String { }
class TimeOfDay extends Utf8String { }
class DateTime extends Utf8String { }
class Duration extends Utf8String { }
class TIME extends Utf8String { }
class Choice {
value: I.LocalValueBlock[];
optional: boolean;
constructor(params?: I.ChoiceParams);
}
class Any {
name: string;
optional: boolean;
constructor(params?: I.AnyParams);
}
class Repeated {
name: string;
optional: boolean;
value: Any;
local: boolean;
constructor(params?: I.RepeatedParams);
}
class RawData {
data: ArrayBuffer;
constructor(params?: I.RawDataParams);
fromBER(inputBuffer: ArrayBuffer, inputOffset: number, inputLength: number): number;
toBER(sizeOnly?: boolean): ArrayBuffer;
}
/**
* Major function for decoding ASN.1 BER array into internal library structuries
*
* @param inputBuffer ASN.1 BER encoded array of bytes
*/
function fromBER(inputBuffer: ArrayBuffer): { offset: number; result: I.LocalBaseBlock };
/**
* Compare of two ASN.1 object trees
*
* @param root Root of input ASN.1 object tree
* @param inputData Input ASN.1 object tree
* @param inputSchema Input ASN.1 schema to compare with
*/
function compareSchema(root: any, inputData: any, inputSchema: any): { verified: boolean, result?: any };
/**
* ASN.1 schema verification for ArrayBuffer data
*
* @param inputBuffer Input BER-encoded ASN.1 data
* @param inputSchema Input ASN.1 schema to verify against to
*/
function verifySchema(inputBuffer: ArrayBuffer, inputSchema: any): { verified: boolean, result?: any };
}
}
+20
View File
@@ -0,0 +1,20 @@
declare namespace adone.crypto {
namespace ed25519 {
const publicKeyLength: number;
const privateKeyLength: number;
namespace I {
interface KeyPair {
publicKey: Buffer;
privateKey: Buffer;
}
}
function generateKeyPair(seed: Buffer): I.KeyPair;
function sign(message: Buffer, seed: Buffer | I.KeyPair): Buffer;
function verify(message: Buffer, signature: Buffer, publicKey: Buffer): boolean;
}
}
+9
View File
@@ -0,0 +1,9 @@
/// <reference path="./asn1.d.ts" />
/// <reference path="./ed25519.d.ts" />
/// <reference path="./secp256k1.d.ts" />
declare namespace adone {
namespace crypto {
//
}
}
+127
View File
@@ -0,0 +1,127 @@
declare namespace adone.crypto {
namespace secp256k1 {
/**
* Verifies an ECDSA privateKey
*/
function privateKeyVerify(privateKey: Buffer): boolean;
/**
* Exports a privateKey in DER format
*/
function privateKeyExport(privateKey: Buffer, compressed?: boolean): Buffer;
/**
* Imports a privateKey in DER format
*/
function privateKeyImport(privateKey: Buffer): Buffer;
/**
* Negates a privateKey by subtracting it from the order of the curve's base point
*/
function privateKeyNegate(privateKey: Buffer): Buffer;
/**
* Computes the inverse of a privateKey (modulo the order of the curve's base point)
*/
function privateKeyModInverse(privateKey: Buffer): Buffer;
/**
* Tweaks a privateKey by adding tweak to it
*/
function privateKeyTweakAdd(privateKey: Buffer, tweak: Buffer): Buffer;
/**
* Tweaks a privateKey by multiplying it by a tweak
*/
function privateKeyTweakMul(privateKey: Buffer, tweak: Buffer): Buffer;
/**
* Computes the public key for a privateKey
*/
function publicKeyCreate(privateKey: Buffer, compressed?: boolean): Buffer;
/**
* Converts a publicKey to compressed or uncompressed form
*/
function publicKeyConvert(publicKey: Buffer, compressed?: boolean): Buffer;
/**
* Verifies an ECDSA publicKey
*/
function publicKeyVerify(publicKey: Buffer): boolean;
/**
* Tweaks a publicKey by adding tweak times the generator to it
*/
function publicKeyTweakAdd(publicKey: Buffer, tweak: Buffer, compressed?: boolean): Buffer;
/**
* Tweaks a publicKey by multiplying it by a tweak value
*/
function publicKeyTweakMul(publicKey: Buffer, tweak: Buffer, compressed?: boolean): Buffer;
/**
* Adds a given publicKeys together
*/
function publicKeyCombine(publicKeys: Buffer[], compressed?: boolean): Buffer;
/**
* Converts a signature to a normalized lower-S form
*/
function signatureNormalize(signature: Buffer): Buffer;
/**
* Serializes an ECDSA signature in DER format
*/
function signatureExport(signature: Buffer): Buffer;
/**
* Parse a DER ECDSA signature (follow by BIP66)
*/
function signatureImport(signature: Buffer): Buffer;
/**
* Same as signatureImport but not follow by BIP66
*/
function signatureImportLax(signature: Buffer): Buffer;
namespace I {
interface SignOptions {
noncefn?: (message: Buffer, privateKey: Buffer, algo: Buffer, data: Buffer, attempt: number) => Buffer;
data?: Buffer | null;
}
interface SignResult {
signature: Buffer;
recovery: number;
}
}
/**
* Creates an ECDSA signature. Always return low-S signature.
*/
function sign(message: Buffer, privateKey: Buffer, options?: I.SignOptions): I.SignResult;
/**
* Verifies an ECDSA signature
*
* Note: return false for high signatures!
*/
function verify(message: Buffer, signature: Buffer, publicKey: Buffer): boolean;
/**
* Recovers an ECDSA public key from a signature
*/
function recover(message: Buffer, signature: Buffer, recovery: number, compressed?: boolean): Buffer;
/**
* Computes an EC Diffie-Hellman secret and applied sha256 to compressed public key
*/
function ecdh(publicKey: Buffer, privateKey: Buffer): Buffer;
/**
* Computes an EC Diffie-Hellman secret and return public key as result
*/
function ecdhUnsafe(publicKey: Buffer, privateKey: Buffer, compressed?: boolean): Buffer;
}
}
+206 -6
View File
@@ -30,7 +30,12 @@ declare namespace adone {
* or an array of String and Number objects that serve as a whitelist
* for selecting/filtering the properties of the value object to be included in the JSON string
*/
replacer?: I.Replacer
replacer?: I.Replacer,
/**
* Wheter to append a newline
*/
newline?: boolean
}): Buffer;
/**
@@ -84,6 +89,8 @@ declare namespace adone {
*/
function decode(buf: collection.I.ByteArray.Wrappable): any;
function tryDecode(buf: collection.ByteArray): any;
namespace I {
type Type = string | number; // ?
type DecodeFunction = (buf: collection.ByteArray) => any;
@@ -153,6 +160,8 @@ declare namespace adone {
* Represents a MessagePack serializer
*/
class Serializer {
constructor(initialCapacity?: number);
/**
* Encoder instance
*/
@@ -211,6 +220,8 @@ declare namespace adone {
* x.Exception, Error, Date, Map, Set, math.Long
*/
const serializer: Serializer;
function registerCommonTypesFor(s: Serializer): void;
}
/**
@@ -244,21 +255,32 @@ declare namespace adone {
* Base64 encoder
*/
namespace base64 {
namespace I {
interface DecodeOptions {
buffer?: boolean;
encoding?: string;
}
interface EncodeOptions {
buffer?: boolean;
}
}
/**
* Encodes a string/Buffer to base64
*/
function encode(str: string | Buffer, options: { buffer: false }): string;
function encode(str: string | Buffer, options?: { buffer?: true }): Buffer;
function encode(str: string | Buffer, options: I.EncodeOptions & { buffer: false }): string;
function encode(str: string | Buffer, options?: I.EncodeOptions): Buffer;
/**
* Decodes base64 string/buffer into a buffer
*/
function decode(str: string | Buffer, options: { buffer: true }): Buffer;
function decode(str: string | Buffer, options: I.DecodeOptions & { buffer: true }): Buffer;
/**
* Decodes base64 string/buffer into a string
*/
function decode(str: string | Buffer, options?: { buffer?: false }): string;
function decode(str: string | Buffer, options?: I.DecodeOptions): string;
function encodeVLQ(value: number): string;
@@ -560,7 +582,7 @@ declare namespace adone {
/**
* Represents a YAML exception
*/
class Exception extends adone.x.Exception {
class Exception extends adone.error.Exception {
reason: string;
mark: Mark;
@@ -1028,5 +1050,183 @@ declare namespace adone {
*/
function decode(buf: Buffer, options?: I.DeserializeOptions): any;
}
namespace protobuf {
namespace schema {
namespace I {
interface Field {
name: string | null;
type: string | null;
tag: number;
map: {
from: string;
to: string;
} | null;
oneof: string | null;
required: boolean;
repeated: boolean;
options: object;
}
interface Enum {
name: string;
values: object;
options: object;
}
interface Extend {
name: string;
message: Message;
}
interface Message {
name: string;
enums: Enum[];
extends: Extend[];
messages: Message[];
fields: Field[];
extensions: {
from: number,
to: number
} | null;
}
interface RPCMethod {
name: string;
input_type: string | null;
output_type: string | null;
client_streaming: boolean;
server_streaming: boolean;
options: object;
}
interface Service {
name: string;
methods: RPCMethod[];
options: object;
}
interface Schema {
syntax: any; // ??
package: string | null;
imports: string[];
enums: Enum[];
messages: Message[];
options: object;
extends: Extend[];
services?: Service[];
}
}
function parse(buf: Buffer | string): I.Schema;
function stringify(schema: object): string;
}
function create(proto: Buffer | string | object, opts?: object): object;
}
namespace base32 {
function charmap<T = object>(alphabet: string, mappings?: T): T;
namespace I {
interface Spec {
alphabet: string;
charmap: {
[c: string]: number;
};
}
}
const rfc4648: I.Spec;
const crockford: I.Spec;
const base32hex: I.Spec;
namespace I {
interface DecoderOptions {
type: "rfc4648" | "crockford" | "base32hex";
charmap?: object;
}
interface EncoderOptions {
type: "rfc4648" | "crockford" | "base32hex";
alphabet?: string;
}
}
class Decoder {
constructor(options?: I.DecoderOptions);
write(str: string): this;
finalize(str?: string): Buffer;
}
class Encoder {
constructor(options?: I.EncoderOptions);
write(buf: Buffer): this;
finalize(buf?: Buffer): string;
}
function encode(buf: Buffer, options?: I.EncoderOptions): string;
function decode(str: string, options?: I.DecoderOptions): Buffer;
}
namespace I {
interface BaseX {
encode(buf: Buffer): string;
decode(str: string): Buffer;
decodeUnsafe(str: string): Buffer;
}
}
function basex(alphabet: string): I.BaseX;
const base58: I.BaseX;
namespace base64url {
function unescape(str: string): string;
function escape(str: string): string;
namespace I {
interface EncodeOptions {
encoding?: string;
}
interface DecodeOptions {
encoding?: string;
buffer?: boolean;
}
}
function encode(str: Buffer | string, options?: I.EncodeOptions): string;
function decode(str: string, options: I.DecodeOptions & { buffer: true }): Buffer;
function decode(str: string, options?: I.DecodeOptions): string;
}
namespace varint {
function encode<T = any>(num: number, out?: T[], offset?: number): T[];
function decode(buf: Buffer, offset?: number): number;
function encodingLength(value: number): number;
}
namespace varintSigned {
function encode<T = any>(num: number, out?: T[], offset?: number): T[];
function decode(buf: Buffer, offset?: number): number;
function encodingLength(value: number): number;
}
}
}
@@ -1,5 +1,5 @@
declare namespace adone {
namespace x {
namespace error {
class Exception extends Error {
constructor(message?: string | Error, captureStackTrace?: boolean);
}
+26 -3
View File
@@ -1,25 +1,48 @@
declare namespace adone {
namespace event {
class EventEmitter {
static listenerCount(emitter: EventEmitter, event: string | symbol): number;
namespace I {
interface PropagateEventsEnder {
end(): void;
}
}
class Emitter {
static listenerCount(emitter: Emitter, event: string | symbol): number;
static defaultMaxListeners: number;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
removeAllListeners(event?: string | symbol): this;
setMaxListeners(n: number): this;
getMaxListeners(): number;
listeners(event: string | symbol): Array<(...args: any[]) => any>;
emit(event: string | symbol, ...args: any[]): boolean;
eventNames(): Array<string | symbol>;
listenerCount(type: string | symbol): number;
propagateEvents(dest: Emitter, events: string[]): I.PropagateEventsEnder;
static propagateEvents(source: Emitter, dest: Emitter, events: string[]): I.PropagateEventsEnder;
}
class AsyncEmitter extends EventEmitter {
class AsyncEmitter extends Emitter {
constructor(concurrency?: number);
setConcurrency(max?: number): this;
+337
View File
@@ -0,0 +1,337 @@
declare namespace adone {
namespace fake {
namespace I {
interface Card {
name: string;
username: string;
email: string;
address: FullAddress;
phone: string;
website: string;
company: Company;
posts: Post[];
accountHistory: string[];
}
interface FullAddress {
streetA: string;
streetB: string;
streetC: string;
streetD: string;
city: string;
state: string;
county: string;
zipcode: string;
geo: Geo;
}
interface Geo {
lat: string;
lng: string;
}
interface Company {
name: string;
catchPhrase: string;
bs: string;
}
interface Post {
words: string;
sentence: string;
sentences: string;
paragraph: string;
}
interface ContextualCard {
name: string;
username: string;
email: string;
dob: Date;
phone: string;
address: Address;
website: string;
company: Company;
}
interface Address {
street: string;
suite: string;
city: string;
state: string;
zipcode: string;
geo: Geo;
}
interface UserCard {
name: string;
username: string;
email: string;
address: Address;
phone: string;
website: string;
company: Company;
}
interface Transaction {
amount: string;
date: Date;
business: string;
name: string;
type: string;
account: string;
}
}
namespace address {
function zipCode(format?: string): string;
function city(format?: number): string;
function cityPrefix(): string;
function citySuffix(): string;
function streetName(): string;
function streetAddress(useFullAddress?: boolean): string;
function streetSuffix(): string;
function streetPrefix(): string;
function secondaryAddress(): string;
function county(): string;
function country(): string;
function countryCode(): string;
function state(useAbbr?: boolean): string;
function stateAbbr(): string;
function latitude(): string;
function longitude(): string;
}
namespace commerce {
function color(): string;
function department(): string;
function productName(): string;
function price(min?: number, max?: number, dec?: number, symbol?: string): string;
function productAdjective(): string;
function productMaterial(): string;
function product(): string;
}
namespace company {
function suffixes(): string[];
function companyName(format?: number): string;
function companySuffix(): string;
function catchPhrase(): string;
function bs(): string;
function catchPhraseAdjective(): string;
function catchPhraseDescriptor(): string;
function catchPhraseNoun(): string;
function bsAdjective(): string;
function bsBuzz(): string;
function bsNoun(): string;
}
namespace database {
function column(): string;
function type(): string;
function collation(): string;
function engine(): string;
}
namespace date {
function past(years?: number, refDate?: string|Date): Date;
function future(years?: number, refDate?: string|Date): Date;
function between(from: string|number|Date, to: string|Date): Date;
function recent(days?: number): Date;
function soon(days?: number): Date;
function month(options?: { abbr?: boolean, context?: boolean }): string;
function weekday(options?: { abbr?: boolean, context?: boolean }): string;
}
function fake(str: string): string;
namespace finance {
function account(length?: number): string;
function accountName(): string;
function mask(length?: number, parens?: boolean, elipsis?: boolean): string;
function amount(min?: number, max?: number, dec?: number, symbol?: string): string;
function transactionType(): string;
function currencyCode(): string;
function currencyName(): string;
function currencySymbol(): string;
function bitcoinAddress(): string;
function ethereumAddress(): string;
function iban(formatted?: boolean): string;
function bic(): string;
}
namespace hacker {
function abbreviation(): string;
function adjective(): string;
function noun(): string;
function verb(): string;
function ingverb(): string;
function phrase(): string;
}
namespace helpers {
function randomize<T>(array: T[]): T;
function randomize(): string;
function slugify(string?: string): string;
function replaceSymbolWithNumber(string?: string, symbol?: string): string;
function replaceSymbols(string?: string): string;
function shuffle<T>(o: T[]): T[];
function shuffle(): string[];
function mustache(str: string, data: { [key: string]: string|((substring: string, ...args: any[]) => string) }): string;
function createCard(): I.Card;
function contextualCard(): I.ContextualCard;
function userCard(): I.UserCard;
function createTransaction(): I.Transaction;
}
namespace image {
function image(): string;
function avatar(): string;
function imageUrl(width?: number, height?: number, category?: string): string;
function abstract(width?: number, height?: number): string;
function animals(width?: number, height?: number): string;
function business(width?: number, height?: number): string;
function cats(width?: number, height?: number): string;
function city(width?: number, height?: number): string;
function food(width?: number, height?: number): string;
function nightlife(width?: number, height?: number): string;
function fashion(width?: number, height?: number): string;
function people(width?: number, height?: number): string;
function nature(width?: number, height?: number): string;
function sports(width?: number, height?: number): string;
function technics(width?: number, height?: number): string;
function transport(width?: number, height?: number): string;
function dataUri(width?: number, height?: number): string;
}
namespace internet {
function avatar(): string;
function email(firstName?: string, lastName?: string, provider?: string): string;
function exampleEmail(firstName?: string, lastName?: string): string;
function userName(firstName?: string, lastName?: string): string;
function protocol(): string;
function url(): string;
function domainName(): string;
function domainSuffix(): string;
function domainWord(): string;
function ip(): string;
function ipv6(): string;
function userAgent(): string;
function color(baseRed255?: number, baseGreen255?: number, baseBlue255?: number): string;
function mac(): string;
function password(len?: number, memorable?: boolean, pattern?: string|RegExp, prefix?: string): string;
}
namespace lorem {
function word(): string;
function words(num?: number): string;
function sentence(wordCount?: number, range?: number): string;
function slug(wordCount?: number): string;
function sentences(sentenceCount?: number): string;
function paragraph(sentenceCount?: number): string;
function paragraphs(paragraphCount?: number, separator?: string): string;
function text(times?: number): string;
function lines(lineCount?: number): string;
}
namespace name {
function firstName(gender?: number): string;
function lastName(gender?: number): string;
function findName(firstName?: string, lastName?: string, gender?: number): string;
function jobTitle(): string;
function prefix(): string;
function suffix(): string;
function title(): string;
function jobDescriptor(): string;
function jobArea(): string;
function jobType(): string;
}
namespace phone {
function phoneNumber(format?: string): string;
function phoneNumberFormat(phoneFormatsArrayIndex?: number): string;
function phoneFormats(): string;
}
namespace random {
function number(max: number): number;
function number(options?: { min?: number, max?: number, precision?: number }): number;
function arrayElement(): string;
function arrayElement<T>(array: T[]): T;
function objectElement(object?: { [key: string]: any }, field?: "key"): string;
function objectElement<T>(object?: { [key: string]: T }, field?: any): T;
function uuid(): string;
function boolean(): boolean;
function word(type?: string): string;
function words(count?: number): string;
function image(): string;
function locale(): string;
function alphaNumeric(count?: number): string;
function hexaDecimal(count?: number): string;
}
namespace system {
function fileName(ext: string, type: string): string;
function commonFileName(ext: string, type: string): string;
function mimeType(): string;
function commonFileType(): string;
function commonFileExt(): string;
function fileType(): string;
function fileExt(mimeType: string): string;
function directoryPath(): string;
function filePath(): string;
function semver(): string;
}
function seed(value: number): void;
namespace I {
type Locale =
| "az"
| "cz"
| "de"
| "de_AT"
| "de_CH"
| "el"
| "en"
| "en_AU"
| "en_BORK"
| "en_CA"
| "en_GB"
| "en_IE"
| "en_IND"
| "en_US"
| "en_au_ocker"
| "es"
| "es_MX"
| "fa"
| "fr"
| "fr_CA"
| "ge"
| "id_ID"
| "it"
| "ja"
| "ko"
| "lv"
| "nb_NO"
| "nep"
| "nl"
| "nl_BE"
| "pl"
| "pt_BR"
| "ro"
| "ru"
| "sk"
| "sv"
| "tr"
| "uk"
| "vi"
| "zh_CN"
| "zh_TW";
}
function getLocale(): I.Locale;
function setLocale(locale: I.Locale): void;
}
}
+3 -3
View File
@@ -152,7 +152,7 @@ declare namespace adone {
type SymbolicFile = File;
/* tslint:disable-next-line:no-empty-interface */
interface Stream<S, T = File> extends stream.CoreStream<S, T> {
interface Stream<S, T = File> extends stream.core.Stream<S, T> {
//
}
}
@@ -160,7 +160,7 @@ declare namespace adone {
export const File: I.FileConstructor;
namespace I {
type CoreStreamSource = stream.I.CoreStream.Source<any, File>;
type CoreStreamSource = stream.core.I.Source<any, File>;
interface LocalStreamConstructorOptions {
/**
@@ -586,7 +586,7 @@ declare namespace adone {
/**
* Read JSON manifests written out by revisionHash
*/
manifest?: File[] | stream.CoreStream<any, File>,
manifest?: File[] | stream.core.Stream<any, File>,
/**
* Modify the name of the unreved files before using them
+382 -186
View File
@@ -22,6 +22,14 @@ declare namespace adone {
function readlink(path: string | Buffer | I.URL, options: { encoding: null }): Promise<Buffer>;
function readlink(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): Promise<string>;
/**
* Reads the value of a symbolic link
*/
function readlinkSync(path: string | Buffer | I.URL, encoding: null): Buffer;
function readlinkSync(path: string | Buffer | I.URL, encoding: I.Encoding): string;
function readlinkSync(path: string | Buffer | I.URL, options: { encoding: null }): Buffer;
function readlinkSync(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): string;
/**
* Deletes a name and possibly the file it refers to
*/
@@ -32,6 +40,21 @@ declare namespace adone {
*/
function unlinkSync(path: string | Buffer | I.URL): void;
/**
* Changes the file system timestamps of the object referenced by path
*/
function utimes(path: string | Buffer | I.URL, atime: number | string | Date, mtime: number | string | Date): Promise<void>;
/**
* Changes the file system timestamps of the object referenced by path
*/
function utimesSync(path: string | Buffer | I.URL, atime: number | string | Date, mtime: number | string | Date): void;
/**
* Changes the file system timestamps of the object referenced by path
*/
function utimesMillis(path: string | Buffer | I.URL, atime: number, mtime: number): Promise<void>;
/**
* Changes permissions of a file
*/
@@ -42,6 +65,11 @@ declare namespace adone {
*/
function chown(path: string | Buffer | I.URL, uid: number, gid: number): Promise<void>;
/**
* Changes ownership recursively for a given path
*/
function chownr(path: string | Buffer | I.URL, uid: number, gid: number): Promise<void>;
/**
* Deletes a directory
*/
@@ -63,6 +91,87 @@ declare namespace adone {
function readdirSync(path: string | Buffer | I.URL, options: { encoding: null }): Buffer[];
function readdirSync(path: string | Buffer | I.URL, options?: { encoding?: I.Encoding }): string[];
namespace I {
interface ReaddirpEntry {
/**
* filename
*/
name: string;
/**
* full path to a file
*/
fullPath: string;
/**
* relative path to a file
*/
path: string;
/**
* relative path to the parent dir
*/
parentDir: string;
/**
* full path to the parent dir
*/
fullParentDir: string;
/**
* file stats
*/
stat: fs.I.Stats;
}
type ReaddirpFilter = string | ((entry: ReaddirpEntry) => boolean);
interface ReaddirpOptions {
/**
* filter for files
*/
fileFilter?: ReaddirpFilter | ReaddirpFilter[];
/**
* filter for directories
*/
directoryFilter?: ReaddirpFilter | ReaddirpFilter[];
/**
* maximum recursion depth
*
* Infinity by default
*/
depth?: number;
/**
* whether to emit files
*
* true by default
*/
files?: boolean;
/**
* whether to emit directories
*
* true by default
*/
directories?: boolean;
/**
* whether to use lstat for stating
*
* false by default
*/
lstat?: boolean;
}
}
/**
* Traverses the given path
*/
function readdirp(root: string | Buffer | I.URL, options?: I.ReaddirpOptions): stream.core.Stream<never, I.ReaddirpEntry>;
/**
* Gets file status, identical to stat, except that if pathname is a symbolic link,
* then it returns information about the link itself, not the file that it refers to
@@ -117,6 +226,15 @@ declare namespace adone {
flag?: I.Flag
}): Promise<void>;
/**
* Appends data to a file, creating the file if it does not yet exist
*/
function appendFileSync(file: string | Buffer | number, data: string | Buffer, options?: {
encoding?: I.Encoding,
mode?: number,
flag?: I.Flag
}): void;
/**
* Tests a user's permissions for the file or directory specified by path
*/
@@ -154,6 +272,14 @@ declare namespace adone {
cwd?: string
}): Promise<void>;
/**
* Recursively deletes empty directiries inside the given directory
*/
function rmEmpty(path: string, options?: {
cwd?: string;
filter?: (filename: string) => boolean
}): Promise<void>;
namespace I {
interface Access {
read: boolean;
@@ -460,12 +586,12 @@ declare namespace adone {
/**
* Copies this from this directory to the given path
*/
copyTo(destPath: string, options?: I.CopyOptions): Promise<void>;
copyTo(destPath: string, options?: I.CopyToOptions): Promise<void>;
/**
* Copies files from the given path to this directory
*/
copyFrom(srcPath: string, options?: I.CopyOptions): Promise<void>;
copyFrom(srcPath: string, options?: I.CopyToOptions): Promise<void>;
/**
* Creates a new directory with the given path
@@ -560,7 +686,7 @@ declare namespace adone {
/**
* Represents a file that supports random access
*/
class RandomAccessFile extends event.EventEmitter {
class RandomAccessFile extends event.Emitter {
constructor(filename: string, options?: I.RandomAccessFile.ConstructorOptions);
/**
@@ -602,7 +728,7 @@ declare namespace adone {
/**
* Represents an abstract random access reader
*/
class AbstractRandomAccessReader extends event.EventEmitter {
class AbstractRandomAccessReader extends event.Emitter {
/**
* Increments the reference counter
*/
@@ -826,7 +952,7 @@ declare namespace adone {
}>;
}
type Stream<T> = stream.CoreStream<never, T>;
type Stream<T> = stream.core.Stream<never, T>;
interface EmitterConstructor {
new(pattern: string, optons: Options, callback?: (error: any, matches: string[]) => void): Emitter;
@@ -835,7 +961,7 @@ declare namespace adone {
prototype: Emitter;
}
interface Emitter extends event.EventEmitter {
interface Emitter extends event.Emitter {
isIgnored(path: string): boolean;
/**
@@ -999,7 +1125,7 @@ declare namespace adone {
/**
* Represents a file watcher
*/
class Watcher extends event.EventEmitter {
class Watcher extends event.Emitter {
constructor(options?: I.Watcher.ConstructorOptions);
/**
@@ -1128,214 +1254,209 @@ declare namespace adone {
function whichSync(cmd: string, options?: I.Which.Options): string;
/**
* Functions to work with files using file descriptors
* Opens and possibly creates a file
*/
namespace fd {
/**
* Opens and possibly create a file
*/
function open(path: string | Buffer | I.URL, flags: I.Flag | number, mode?: number): Promise<I.FD>;
function open(path: string | Buffer | I.URL, flags: I.Flag | number, mode?: number): Promise<I.FD>;
/**
* Opens and possibly create a file
*/
function openSync(path: string | Buffer | I.URL, flags: I.Flag | number, mode?: number): I.FD;
/**
* Opens and possibly creates a file
*/
function openSync(path: string | Buffer | I.URL, flags: I.Flag | number, mode?: number): I.FD;
/**
* Closes a file descriptor
*/
function close(fd: I.FD): Promise<void>;
/**
* Closes a file descriptor
*/
function close(fd: I.FD): Promise<void>;
/**
* Closes a file descriptor
*/
function closeSync(fd: I.FD): void;
/**
* Closes a file descriptor
*/
function closeSync(fd: I.FD): void;
/**
* Changes the file timestamps of a file referenced by the supplied file descriptor
*/
function utimes(fd: I.FD, atime: number, mtime: number): Promise<void>;
/**
* Changes the file timestamps of a file referenced by the supplied file descriptor
*/
function futimes(fd: I.FD, atime: number, mtime: number): Promise<void>;
/**
* Changes the file timestamps of a file referenced by the supplied file descriptor
*/
function utimesSync(fd: I.FD, atime: number, mtime: number): void;
/**
* Changes the file timestamps of a file referenced by the supplied file descriptor
*/
function futimesSync(fd: I.FD, atime: number, mtime: number): void;
/**
* Gets file status
*/
function stat(fd: I.FD): Promise<I.Stats>;
/**
* Gets file status
*/
function fstat(fd: I.FD): Promise<I.Stats>;
/**
* Gets file status
*/
function statSync(fd: I.FD): I.Stats;
/**
* Gets file status
*/
function fstatSync(fd: I.FD): I.Stats;
/**
* Truncates a file to a specified length
*/
function truncate(fd: I.FD, length?: number): Promise<void>;
/**
* Truncates a file to a specified length
*/
function ftruncate(fd: I.FD, length?: number): Promise<void>;
/**
* Truncates a file to a specified length
*/
function truncateSync(fd: I.FD, length?: number): void;
/**
* Truncates a file to a specified length
*/
function ftruncateSync(fd: I.FD, length?: number): void;
/**
* Read data from the file specified by fd
*/
function read(
fd: I.FD,
/**
* Read data from the file specified by fd
* The buffer that the data will be written to
*/
function read(
fd: I.FD,
/**
* The buffer that the data will be written to
*/
buffer: Buffer | Uint8Array,
/**
* The offset in the buffer to start writing at
*/
offset: number,
/**
* An integer specifying the number of bytes to read
*/
length: number,
/**
* An argument specifying where to begin reading from in the file
*/
position: number
): Promise<number>;
function readSync(
fd: I.FD,
/**
* The buffer that the data will be written to
*/
buffer: Buffer | Uint8Array,
/**
* The offset in the buffer to start writing at
*/
offset: number,
/**
* An integer specifying the number of bytes to read
*/
length: number,
/**
* An argument specifying where to begin reading from in the file
*/
position: number
): number;
buffer: Buffer | Uint8Array,
/**
* Writes buffer to the file specified by fd
* The offset in the buffer to start writing at
*/
function write(
fd: I.FD,
buffer: Buffer | Uint8Array,
/**
* Determines the part of the buffer to be written
*/
offset?: number,
/**
* An integer specifying the number of bytes to write
*/
length?: number,
/**
* The offset from the beginning of the file where this data should be written
*/
position?: number
): Promise<number>;
offset: number,
/**
* Writes string to the file specified by fd
* An integer specifying the number of bytes to read
*/
function write(
fd: I.FD,
string: string,
/**
* The offset from the beginning of the file where this data should be written
*/
position?: number,
/**
* The expected string encoding
*/
encoding?: I.Encoding
): Promise<number>;
length: number,
/**
* Writes buffer to the file specified by fd
* An argument specifying where to begin reading from in the file
*/
function writeSync(
fd: I.FD,
buffer: Buffer | Uint8Array,
/**
* Determines the part of the buffer to be written
*/
offset?: number,
/**
* An integer specifying the number of bytes to write
*/
length?: number,
/**
* The offset from the beginning of the file where this data should be written
*/
position?: number
): number;
position: number
): Promise<number>;
function readSync(
fd: I.FD,
/**
* Writes string to the file specified by fd
* The buffer that the data will be written to
*/
function writeSync(
fd: I.FD,
string: string,
/**
* The offset from the beginning of the file where this data should be written
*/
position?: number,
/**
* The expected string encoding
*/
encoding?: I.Encoding
): number;
buffer: Buffer | Uint8Array,
/**
* The offset in the buffer to start writing at
*/
offset: number,
/**
* An integer specifying the number of bytes to read
*/
length: number,
/**
* An argument specifying where to begin reading from in the file
*/
position: number
): number;
/**
* Writes buffer to the file specified by fd
*/
function write(
fd: I.FD,
buffer: Buffer | Uint8Array,
/**
* Synchronizes a file's in-core state with storage
* Determines the part of the buffer to be written
*/
function sync(fd: I.FD): Promise<void>;
offset?: number,
/**
* An integer specifying the number of bytes to write
*/
length?: number,
/**
* The offset from the beginning of the file where this data should be written
*/
position?: number
): Promise<number>;
/**
* Writes string to the file specified by fd
*/
function write(
fd: I.FD,
string: string,
/**
* Synchronizes a file's in-core state with storage
* The offset from the beginning of the file where this data should be written
*/
function syncSync(fd: I.FD): void;
position?: number,
/**
* The expected string encoding
*/
encoding?: I.Encoding
): Promise<number>;
/**
* Writes buffer to the file specified by fd
*/
function writeSync(
fd: I.FD,
buffer: Buffer | Uint8Array,
/**
* Changes ownership of a file
* Determines the part of the buffer to be written
*/
function chown(fd: I.FD, uid: number, gid: number): Promise<void>;
offset?: number,
/**
* An integer specifying the number of bytes to write
*/
length?: number,
/**
* The offset from the beginning of the file where this data should be written
*/
position?: number
): number;
/**
* Writes string to the file specified by fd
*/
function writeSync(
fd: I.FD,
string: string,
/**
* Changes ownership of a file
* The offset from the beginning of the file where this data should be written
*/
function chownSync(fd: I.FD, uid: number, gid: number): void;
position?: number,
/**
* The expected string encoding
*/
encoding?: I.Encoding
): number;
/**
* Changes permissions of a file
*/
function chmod(fd: I.FD, mode: number): Promise<void>;
/**
* Synchronizes a file's in-core state with storage
*/
function fsync(fd: I.FD): Promise<void>;
/**
* Changes permissions of a file
*/
function chmodSync(fd: I.FD, mode: number): void;
/**
* Synchronizes a file's in-core state with storage
*/
function fsyncSync(fd: I.FD): void;
/**
* Repositions read/write file offset
*/
function seek(fd: I.FD, offset: number, whence: number): Promise<number>;
/**
* Changes ownership of a file
*/
function fchown(fd: I.FD, uid: number, gid: number): Promise<void>;
/**
* Applies or removes an advisory lock on an open file
*/
function lock(fd: I.FD, flags: "sh" | "ex" | "shnb" | "exnb" | "un" | number): Promise<void>;
}
/**
* Changes ownership of a file
*/
function fchownSync(fd: I.FD, uid: number, gid: number): void;
/**
* Changes permissions of a file
*/
function fchmod(fd: I.FD, mode: number): Promise<void>;
/**
* Changes permissions of a file
*/
function fchmodSync(fd: I.FD, mode: number): void;
/**
* Repositions read/write file offset
*/
function seek(fd: I.FD, offset: number, whence: number): Promise<number>;
/**
* Applies or removes an advisory lock on an open file
*/
function flock(fd: I.FD, flags: "sh" | "ex" | "shnb" | "exnb" | "un" | number): Promise<void>;
namespace constants {
const F_OK: number;
@@ -1475,12 +1596,63 @@ declare namespace adone {
function existsSync(path: string | Buffer | I.URL): boolean;
/**
* Creates a new directory and any necessary subdirectories
* Creates a new directory
*/
function mkdir(path: string, mode?: number): Promise<void>;
/**
* Creates a new directory
*/
function mkdirSync(path: string, mode?: number): Promise<void>;
/**
* Creates a new directory and any necessary subdirectories
*/
function mkdirp(path: string, mode?: number): Promise<void>;
/**
* Creates a new directory and any necessary subdirectories
*/
function mkdirpSync(path: string, mode?: number): Promise<void>;
namespace I {
interface CopyOptions {
/**
* regexp or function against which each filename is tested whether to copy it or not
*/
filter?: RegExp | ((src: string, dst: string) => boolean);
/**
* transform function which applies when files are streamed
*/
transform?(
readStream: NodeJS.ReadableStream,
writeStream: NodeJS.WritableStream,
file: {
name: string,
mode: number,
mtime: Date,
atime: Date,
stats: adone.fs.I.Stats
}
): void;
/**
* Whether to overwrite destination files if they exist.
*
* true by default
*/
clobber?: boolean; // ???
/**
* Whether to overwrite destination files if they exist.
*
* true by default
*/
overwrite?: boolean;
}
interface CopyToOptions {
/**
* Do not replace existing files
*/
@@ -1494,10 +1666,15 @@ declare namespace adone {
}
/**
* Copies all files from src to dst
* Recursively copies all the files from src to dst
*/
function copy(src: string, dst: string, options?: I.CopyOptions): Promise<void>;
/**
* Copies all files from src to dst
*/
function copyTo(src: string, dst: string, options?: I.CopyToOptions): Promise<void>;
/**
* Renames a file
*/
@@ -1514,8 +1691,32 @@ declare namespace adone {
/**
* Returns the last lines of a file
*
* @param path path to a file
* @param n number of lines to return
*/
function tail(path: string, n: number, options?: { separator?: string, chunkLength?: number }): Promise<Buffer[]>;
function tail(path: string, n: number, options?: {
/**
* Line separator
*
* By default "\r\n" for windows and "\n" for others
*/
separator?: string,
/**
* The number of bytes to read at once
*
* By default 4096
*/
chunkLength?: number
/**
* Position from which to start reading (from the end)
*
* By default stats.size of the file
*/
pos?: number
}): Promise<Buffer[]>;
namespace I {
interface StatVFS {
@@ -1667,11 +1868,6 @@ declare namespace adone {
*/
function lookup(path: string): Promise<string>;
/**
* Recursively changes ownership of files
*/
function chownr(path: string, uid: number, gid: number): Promise<void>;
namespace I.TailWatcher {
interface ConstructorOptions {
/**
@@ -1709,7 +1905,7 @@ declare namespace adone {
* Represents an event emitter that watches for a file growing,
* emits "line" event for each new line in a file
*/
class TailWatcher extends event.EventEmitter {
class TailWatcher extends event.Emitter {
constructor(filename: string, options?: I.TailWatcher.ConstructorOptions);
/**
+179 -52
View File
@@ -6,13 +6,13 @@ declare namespace adone {
/**
* Checks whether the given object is `null`
*/
function _null(obj: any): boolean;
function _null(obj: any): obj is null;
export { _null as null };
/**
* Checks whether the given object is `undefined`
*/
export function undefined(obj: any): boolean;
export function undefined(obj: any): obj is undefined;
/**
* Checks whether the given object is nither `undefined` nor `null`
@@ -22,52 +22,54 @@ declare namespace adone {
/**
* Checks whether the given object is either `undefined` or `null`
*/
export function nil(obj: any): boolean;
export function nil(obj: any): obj is undefined | null;
/**
* Checks whether the given object is a number
*/
export function number(obj: any): boolean;
export function number(obj: any): obj is number;
/**
* Checks whether the given object is a finite number or a string represents a finite number
*/
export function numeral(obj: any): boolean;
export function numeral(obj: number): obj is number;
export function numeral(obj: string): obj is string;
export function numeral(obj: any): obj is number | string;
/**
* Checks whether the given object is either +Infinity or -Inginity
*/
export function infinite(obj: any): boolean;
export function infinite(obj: any): obj is number;
/**
* Checks whether the given object is an odd number
*/
export function odd(obj: any): boolean;
export function odd(obj: any): obj is number;
/**
* Checks whether the given object is an even number
*/
export function even(obj: any): boolean;
export function even(obj: any): obj is number;
/**
* Checks whether the given object is a float
*/
export function float(obj: any): boolean;
export function float(obj: any): obj is number;
/**
* Checks whether the given object is -0
*/
export function negativeZero(obj: any): boolean;
export function negativeZero(obj: any): obj is number;
/**
* Checks whether the given object is a string
*/
export function string(obj: any): boolean;
export function string(obj: any): obj is string;
/**
* Checks whether the given object is an empty string
* Checks whether the given object is an empty string, i.e. a string with only whitespace characters
*/
export function emptyString(obj: any): boolean;
export function emptyString(obj: any): obj is string;
/**
* Checks whether the first string is a substring of the second string from the given offset
@@ -87,7 +89,7 @@ declare namespace adone {
/**
* Checks whether the given object is a boolean
*/
export function boolean(obj: any): boolean;
export function boolean(obj: any): obj is boolean;
/**
* Checks whether the given object is a string with ".json" extension or an object
@@ -97,12 +99,12 @@ declare namespace adone {
/**
* Checks whether the given object is not a primitive, i.e. neither `undefined` nor `null` nor number nor string nor boolean nor symbol)
*/
export function object(obj: any): boolean;
export function object(obj: any): obj is object;
/**
* Checks whether the given object is a plain object, i.e. created by Object
*/
export function plainObject(obj: any): boolean;
export function plainObject(obj: any): obj is object;
/**
* Checks whether the given object is an adone namespace
@@ -118,7 +120,7 @@ declare namespace adone {
/**
* Checks whether the given object is empty, i.e. it is an object(not a primitive), and Object.keys returns an empty array
*/
export function emptyObject(obj: any): boolean;
export function emptyObject(obj: any): obj is object;
/**
* Checks whether the given object has the given owned property
@@ -138,7 +140,7 @@ declare namespace adone {
/**
* Checks whether the given object is like an array, i.e. it is not a primitive, not a function and has length
*/
export function arrayLikeObject(obj: any): boolean;
export function arrayLikeObject(obj: any): obj is ArrayLike<any>;
/**
* Checks whether the given array has the given value
@@ -215,7 +217,7 @@ declare namespace adone {
/**
* Checks whether the given string is a glob
*/
export function glob(str: string): boolean;
export function glob(str: any): str is string;
/**
* Checks whether the given path is not a dot-file path (.secret)
@@ -225,18 +227,18 @@ declare namespace adone {
/**
* Checks whether the given object is a function
*/
function _function(obj: any): boolean;
function _function(obj: any): obj is (...args: any[]) => any;
export { _function as function };
/**
* Checks whether the given object is an async function
*/
export function asyncFunction(obj: any): boolean;
export function asyncFunction(obj: any): obj is (...args: any[]) => Promise<any>;
/**
* Checks whether the given object is a promise
*/
export function promise(obj: any): boolean;
export function promise(obj: any): obj is PromiseLike<any>;
/**
* Checks whether the given string is a valid date-string
@@ -246,7 +248,7 @@ declare namespace adone {
/**
* Checks whether the given object is a buffer
*/
export function buffer(obj: any): boolean;
export function buffer(obj: any): obj is Buffer;
/**
* Checks whether the given object is a callback function, i.e. it has a common function name
@@ -256,7 +258,7 @@ declare namespace adone {
/**
* Checks whether the given object is a generator function
*/
export function generator(obj: any): boolean;
export function generator(obj: any): obj is GeneratorFunction;
/**
* Checks whether the given object is NaN
@@ -266,27 +268,27 @@ declare namespace adone {
/**
* Checks whether the given object is a finite number
*/
export function finite(obj: any): boolean;
export function finite(obj: any): obj is number;
/**
* Checks whether the given object is an integer
*/
export function integer(obj: any): boolean;
export function integer(obj: any): obj is number;
/**
* Checks whether the given object is a safe integer
*/
export function safeInteger(obj: any): boolean;
export function safeInteger(obj: any): obj is number;
/**
* Checks whether the given object is an array
*/
export function array(obj: any): boolean;
export function array(obj: any): obj is any[];
/**
* Checks whether the given object is a Uint8 array
*/
export function uint8Array(obj: any): boolean;
export function uint8Array(obj: any): obj is Uint8Array;
/**
* Checks whether the given object is an adone configuration
@@ -296,34 +298,34 @@ declare namespace adone {
/**
* Checks whether the given object is an instance of adone.math.Long
*/
export function long(obj: any): boolean;
export function long(obj: any): obj is adone.math.Long;
/**
* Checks whether the given object is an instance of adone.math.BigNumber
*/
export function bigNumber(obj: any): boolean;
export function bigNumber(obj: any): obj is adone.math.BigNumber;
/**
* Checks whether the given object is an instance of adone.collection.ByteArray
*/
export function byteArray(obj: any): boolean;
export function byteArray(obj: any): obj is adone.collection.ByteArray;
/**
* Checks whether the given object is an instance of adone.datetime
*/
export function datetime(obj: any): boolean;
export function datetime(obj: any): obj is adone.I.datetime.Datetime;
export function transform(obj: any): boolean;
/**
* Checks whether the given object is an adone subsystem
*/
export function subsystem(obj: any): boolean;
export function subsystem(obj: any): obj is adone.application.Subsystem;
/**
* Checks whether the given object is an adone application
*/
export function application(obj: any): boolean;
export function application(obj: any): obj is adone.application.Application;
/**
* Checks whether the given object is an adone logger
@@ -333,22 +335,22 @@ declare namespace adone {
/**
* Checks whether the given object is a core stream
*/
export function coreStream(obj: any): boolean;
export function coreStream(obj: any): obj is adone.stream.core.Stream;
/**
* Checks whether the given object is a fast local map stream
*/
export function fastLocalMapStream(obj: any): boolean;
export function fastLocalMapStream(obj: any): obj is adone.fast.I.LocalMapStream<any>;
/**
* Checks whether the given object is a fast local stream
*/
export function fastLocalStream(obj: any): boolean;
export function fastLocalStream(obj: any): obj is adone.fast.I.LocalStream<any>;
/**
* Checks whether the given object is a fast stream
*/
export function fastStream(obj: any): boolean;
export function fastStream(obj: any): obj is adone.fast.I.Stream<any>;
/**
* Checks whether the given object is a genesis netron
@@ -428,7 +430,7 @@ declare namespace adone {
/**
* Checks whether the given object is iterable, has defined Symbol.iterator property
*/
export function iterable(obj: any): boolean;
export function iterable(obj: any): obj is Iterable<any>;
/**
* true if the OS is Windows
@@ -498,17 +500,17 @@ declare namespace adone {
/**
* Checks whether the given object is an array buffer
*/
export function arrayBuffer(obj: any): boolean;
export function arrayBuffer(obj: any): obj is ArrayBuffer;
/**
* Checks whether the given object is an array buffer view
*/
export function arrayBufferView(obj: any): boolean;
export function arrayBufferView(obj: any): obj is ArrayBufferView;
/**
* Checks whether the given object is a date
*/
export function date(obj: any): boolean;
export function date(obj: any): obj is Date;
/**
* Checks whether the given object is an error, instance of Error
@@ -518,27 +520,22 @@ declare namespace adone {
/**
* Checks whether the given object is a map
*/
export function map(obj: any): boolean;
export function map(obj: any): obj is Map<any, any>;
/**
* Checks whether the given object is a regexp
*/
export function regexp(obj: any): boolean;
export function regexp(obj: any): obj is RegExp;
/**
* Checks whether the given object is a set
*/
export function set(obj: any): boolean;
export function set(obj: any): obj is Set<any>;
/**
* Checks whether the given object is a symbol
*/
export function symbol(obj: any): boolean;
/**
* Checks whether the given buffer a valid UTF-8 encoded text
*/
export function validUTF8(obj: Buffer): boolean;
export function symbol(obj: any): obj is symbol;
/**
* Checks whether the given object is a vault valuable
@@ -549,5 +546,135 @@ declare namespace adone {
* Checks whether the given object is an adone task
*/
export function task(obj: any): boolean;
namespace I {
interface FQDNOptions {
/**
* Whether to require top-level domain, default `true`
*/
requireTld?: boolean;
/**
* Whether to allow underscores("_"), default `false`
*/
allowUnderscores?: boolean;
/**
* Whether to allow trailing dot, default `false`
*/
allowTrailingDot?: boolean;
}
}
/**
* Checks whether the given object(string) is a fully qualified domain name (e.g. domain.com).
*/
export function fqdn(obj: any, options?: I.FQDNOptions): obj is string;
/**
* Checks whether the given object(string) is a url
*/
export function url(obj: any, options?: I.FQDNOptions & {
/**
* List of valid protocols.
* Used when requireValidProtocol is `true`.
* Default ["http", "https", "ftp"]
*/
protocols?: string[],
/**
* Whether to require protocol, default `true`
*/
requireProtocol?: boolean,
/**
* Whether to require host, default `true`
*/
requireHost?: boolean,
/**
* Whether to require valid protocol defined in `protocols` options, default `true`
*/
requireValidProtocol?: boolean,
/**
* Whether to allow urls like "//example.com", default `false`
*/
allowProtocolRelativeUrls?: boolean
}): obj is string;
/**
* Checks whether the given object(string) is a valid email address
*/
export function email(obj: any, options?: {
/**
* Whether to allow email addresses with display names ("Name <local@domain>"")
*/
allowDisplayName?: boolean,
/**
* Whether to require display name
*/
requireDisplayName?: boolean,
/**
* Whether to allow UTF8 characters in the local part
*/
allowUtf8LocalPart?: boolean,
/**
* Whether to require top-level domain, default `true`
*/
requireTld?: boolean
}): obj is string;
/**
* Checks whether the given object is a valid IPv4 address
*/
export function ip(obj: any, version: 4): boolean;
/**
* Checks whether the given object is a valid IPv6 address
*/
export function ip(obj: any, version: 6): boolean;
/**
* Checks whether the given object in a valid IPv4 or IPv6 address
*/
export function ip(obj: any): boolean;
/**
* Checks whether the given object is a valid UUIDv1 identifier
*/
export function uuid(obj: any, version: 1): obj is string;
/**
* Checks whether the given object is a valid UUIDv2 identifier
*/
export function uuid(obj: any, version: 2): obj is string;
/**
* Checks whether the given object is a valid UUIDv3 identifier
*/
export function uuid(obj: any, version: 3): obj is string;
/**
* Checks whether the given object is a valid UUIDv4 identifier
*/
export function uuid(obj: any, version: 4): obj is string;
/**
* Checks whether the given object is a valid UUIDv5 identifier
*/
export function uuid(obj: any, version: 5): obj is string;
/**
* Checks whether the given object is a valid UUID identifier (v1, v2, v3, v4 or v5)
*/
export function uuid(obj: any, version?: "all"): obj is string;
export function emitter(obj: any): obj is event.Emitter;
export function asyncEmitter(obj: any): obj is event.AsyncEmitter;
}
}
+13
View File
@@ -0,0 +1,13 @@
declare namespace adone {
namespace meta {
namespace I {
type PossibleTypes = "object" | "class" | "null" | "global" | "Array" | "RegExp" | "Date"
| "Promise" | "Set" | "Map" | "WeakSet" | "DataView" | "Map Iterator" | "Set Iterator"
| "Array Iterator" | "String Iterator" | "Object" | "function" | "boolean" | "number"
| "undefined" | "string" | "symbol";
}
function typeOf(obj: any): I.PossibleTypes;
function typeOf(obj: any): string;
}
}
+275
View File
@@ -0,0 +1,275 @@
declare namespace adone.net.http {
namespace client {
namespace I {
interface RequestHeaders {
"Accept"?: string;
"Accept-Charset"?: string;
"Accept-Encoding"?: string;
"Accept-Language"?: string;
"Accept-Datetime"?: string;
"Access-Control-Request-Method"?: string;
"Access-Control-Request-Headers"?: string;
"Authorization"?: string;
"Cache-Control"?: string;
"Connection"?: string;
"Cookie"?: string;
"Content-Length"?: string;
"Content-MD5"?: string;
"Content-Type"?: string;
"Date"?: string;
"Expect"?: string;
"Forwarded"?: string;
"From"?: string;
"Host"?: string;
"If-Match"?: string;
"If-Modified-Since"?: string;
"If-None-Match"?: string;
"If-Range"?: string;
"If-Unmodified-Since"?: string;
"Max-Forwards"?: string;
"Origin"?: string;
"Pragma"?: string;
"Proxy-Authorization"?: string;
"Range"?: string;
"Referer"?: string;
"TE"?: string;
"User-Agent"?: string;
"Upgrade"?: string;
"Via"?: string;
"Warning"?: string;
"X-Requested-With"?: string;
"DNT"?: string;
"X-Forwarded-For"?: string;
"X-Forwarded-Host"?: string;
"X-Forwarded-Proto"?: string;
"Front-End-Https"?: string;
"X-Http-Method-Override"?: string;
"X-ATT-DeviceId"?: string;
"X-Wap-Profile"?: string;
"Proxy-Connection"?: string;
"X-UIDH"?: string;
"X-Csrf-Token"?: string;
"X-Request-ID"?: string;
"X-Correlation-ID"?: string;
[name: string]: string | undefined;
}
interface ResponseHeaders {
"accept-patch": string | undefined;
"accept-ranges": string | undefined;
"access-control-allow-credentials": string | undefined;
"access-control-allow-headers": string | undefined;
"access-control-allow-methods": string | undefined;
"access-control-allow-origin": string | undefined;
"access-control-expose-headers": string | undefined;
"access-control-max-age": string | undefined;
"age": string | undefined;
"allow": string | undefined;
"alt-svc": string | undefined;
"cache-control": string | undefined;
"connection": string| undefined;
"content-disposition": string | undefined;
"content-encoding": string| undefined;
"content-language": string | undefined;
"content-length": string| undefined;
"content-location": string| undefined;
"content-md5": string| undefined;
"content-range": string| undefined;
"content-security-policy": string | undefined;
"content-type": string| undefined;
"date": string| undefined;
"etag": string| undefined;
"expires": string| undefined;
"keep-alive": string | undefined;
"last-modified": string | undefined;
"link": string| undefined;
"location": string| undefined;
"p3p": string| undefined;
"pragma": string| undefined;
"proxy-authenticate": string | undefined;
"public-key-pins": string| undefined;
"referer-policy": string | undefined;
"refresh": string | undefined;
"retry-after": string | undefined;
"server": string | undefined;
"set-cookie": string | undefined;
"status": string | undefined;
"strict-transport-security": string| undefined;
"timing-allow-origin": string | undefined;
"tk": string| undefined;
"transfer-encoding": string | undefined;
"upgrade-insecure-requests": string | undefined;
"upgrade": string| undefined;
"vary": string | undefined;
"via": string| undefined;
"warning": string| undefined;
"www-authenticate": string | undefined;
"x-content-duration": string | undefined;
"x-content-security-policy": string | undefined;
"x-content-type-options": string | undefined;
"x-correlation-id": string | undefined;
"x-frame-options": string| undefined;
"x-powered-by": string | undefined;
"x-request-id": string | undefined;
"x-ua-compatible": string | undefined;
"x-webkit-csp": string | undefined;
"x-xss-protection": string | undefined;
[header: string]: string | undefined;
}
interface Response<T> {
status: number;
statusText: string;
headers: ResponseHeaders;
data: T;
}
type Transformer = (data: Data, headers: object, config: I.Options) => Data;
interface FormValueOptions {
header?: string | { [key: string]: string };
knownLength?: number;
filename?: string;
filepath?: string;
contentType?: string;
}
type FormValue = string | Buffer | nodestd.stream.Readable | {
value: string | Buffer | nodestd.stream.Readable;
options: FormValueOptions
};
interface UploadProgressEvent {
lengthComputable: boolean;
loaded: number;
total: number;
}
interface ProxyObject {
protocol?: string;
host?: string;
port?: number;
auth?: {
username?: string;
password?: string;
};
}
interface Config {
adapter<T>(config: I.Config): Promise<Response<T>>;
transformRequest: Transformer[];
transformResponse: Transformer[];
timeout: number;
xsrfCookieName: string;
xsrfHeaderName: string;
maxContentLength: number;
validateStatus: (status: number) => boolean;
responseType: "buffer" | "string" | "stream" | "json";
responseEncoding: adone.util.iconv.I.SupportedEncoding;
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS";
headers: RequestHeaders;
data: Data;
formData: {
[formKey: string]: FormValue | FormValue[];
};
auth: {
username?: string;
password?: string;
};
httpsAgent: object;
httpAgent: object;
params: object;
rejectUnauthorized: boolean;
proxy: string | ProxyObject | false;
transport: object;
maxRedirects: number;
cancelToken: CancelToken;
onUploadProgress(event: UploadProgressEvent): void;
baseURL: string;
paramsSerializer(params: object): string;
}
type Options = Partial<Config>;
type Data = string | Buffer | ArrayBuffer | nodestd.stream.Readable | ArrayBufferView | object | undefined;
interface Request extends Client {
(config: I.Options, ...args: any[]): Promise<object>;
}
}
class Client {
constructor(options?: I.Options);
request(config: I.Options & { responseType: "json" }, ...args: any[]): Promise<I.Response<object | string>>;
request(config: I.Options & { responseType: "string" }, ...args: any[]): Promise<I.Response<string>>;
request(config: I.Options & { responseType: "buffer" }, ...args: any[]): Promise<I.Response<Buffer>>;
request(config: I.Options & { responseType: "stream" }, ...args: any[]): Promise<I.Response<nodestd.stream.Readable>>;
request(config: I.Options, ...args: any[]): Promise<I.Response<object | string>>;
get(url: string, options: I.Options & { responseType: "string" }): Promise<I.Response<string>>;
get(url: string, options: I.Options & { responseType: "buffer" }): Promise<I.Response<Buffer>>;
get(url: string, options: I.Options & { responseType: "stream" }): Promise<I.Response<nodestd.stream.Readable>>;
get(url: string, options?: I.Options): Promise<I.Response<object | string>>;
post(url: string, data: I.Data, options: I.Options & { responseType: "string" }): Promise<I.Response<string>>;
post(url: string, data: I.Data, options: I.Options & { responseType: "buffer" }): Promise<I.Response<Buffer>>;
post(url: string, data: I.Data, options: I.Options & { responseType: "stream" }): Promise<I.Response<nodestd.stream.Readable>>;
post(url: string, data?: I.Data, options?: I.Options): Promise<I.Response<object | string>>;
put(url: string, data: I.Data, options: I.Options & { responseType: "string" }): Promise<I.Response<string>>;
put(url: string, data: I.Data, options: I.Options & { responseType: "buffer" }): Promise<I.Response<Buffer>>;
put(url: string, data: I.Data, options: I.Options & { responseType: "stream" }): Promise<I.Response<nodestd.stream.Readable>>;
put(url: string, data?: I.Data, options?: I.Options): Promise<I.Response<object | string>>;
patch(url: string, data: I.Data, options: I.Options & { responseType: "string" }): Promise<I.Response<string>>;
patch(url: string, data: I.Data, options: I.Options & { responseType: "buffer" }): Promise<I.Response<Buffer>>;
patch(url: string, data: I.Data, options: I.Options & { responseType: "stream" }): Promise<I.Response<nodestd.stream.Readable>>;
patch(url: string, data?: I.Data, options?: I.Options): Promise<I.Response<object | string>>;
delete(url: string, options: I.Options & { responseType: "string" }): Promise<I.Response<string>>;
delete(url: string, options: I.Options & { responseType: "buffer" }): Promise<I.Response<Buffer>>;
delete(url: string, options: I.Options & { responseType: "stream" }): Promise<I.Response<nodestd.stream.Readable>>;
delete(url: string, options?: I.Options): Promise<I.Response<object | string>>;
options(url: string, options: I.Options & { responseType: "string" }): Promise<I.Response<string>>;
options(url: string, options: I.Options & { responseType: "buffer" }): Promise<I.Response<Buffer>>;
options(url: string, options: I.Options & { responseType: "stream" }): Promise<I.Response<nodestd.stream.Readable>>;
options(url: string, options?: I.Options): Promise<I.Response<object | string>>;
}
class Cancel {
message: string;
constructor(message: string);
}
namespace I {
type Canceller = (message?: string) => void;
interface CancelTokenSource {
token: CancelToken;
cancel: Canceller;
}
}
class CancelToken {
promise: Promise<Cancel>;
reason?: Cancel;
constructor(executor: I.Canceller);
throwIfRequested(): void;
static source(): I.CancelTokenSource;
}
const request: I.Request;
function create(options?: I.Options): I.Request;
function isCancel(obj: any): obj is Cancel;
}
}

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