Merge remote-tracking branch 'DefinitelyTyped/master'

This commit is contained in:
Louis Orleans
2017-09-19 12:09:06 -07:00
12275 changed files with 784182 additions and 506488 deletions
+1 -1
View File
@@ -1,9 +1,9 @@
root = true
[*]
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
[{*.json,*.yml}]
indent_style = space
indent_size = 2
+3413
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -17,7 +17,7 @@ If adding a new definition:
If changing an existing definition:
- [ ] Provide a URL to documentation or source code which provides context for the suggested changes: <<url here>>
- [ ] Increase the version number in the header if appropriate.
- [ ] If you are making substantial changes, consider adding a `tslint.json` containing `{ "extends": "../tslint.json" }`.
- [ ] If you are making substantial changes, consider adding a `tslint.json` containing `{ "extends": "dtslint/dt.json" }`.
If removing a declaration:
- [ ] If a package was never on DefinitelyTyped, you don't need to do anything. (If you wrote a package and provided types, you don't need to register it with us.)
+10 -2
View File
@@ -12,7 +12,6 @@
*.map
*.swp
.DS_Store
npm-debug.log
_Resharper.DefinitelyTyped
bin
@@ -25,19 +24,28 @@ Properties
# test folder
_infrastructure/tests/build
# IntelliJ based IDEs
.idea
*.iml
*.js.map
!*.js/
!scripts/new-package.js
!scripts/not-needed.js
!scripts/lint.js
# npm
node_modules
package-lock.json
npm-debug.log
# Sublime
.sublimets
.settings/launch.json
# Visual Studio Code
.settings/launch.json
.vs
.vscode
# yarn
yarn.lock
+59 -14
View File
@@ -1,4 +1,4 @@
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.png?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
# 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)
@@ -71,7 +71,9 @@ Add to your `tsconfig.json`:
Create `types/foo/index.d.ts` containing declarations for the module "foo".
You should now be able import from `"foo"` in your code and it will route to the new type definition.
Then build *and* run the code to make sure your type definition actually corresponds to what happens at runtime.
Once you've tested your definitions with real code, make a PR contributing the definition by copying `types/foo` to `DefinitelyTyped/foo` and adding a `tsconfig.json` and `foo-tests.ts`.
Once you've tested your definitions with real code, make a [PR](#make-a-pull-request)
then follow the instructions to [edit an existing package](#edit-an-existing-package) or
[create a new package](#create-a-new-package).
### Make a pull request
@@ -83,11 +85,19 @@ First, [fork](https://guides.github.com/activities/forking/) this repository, in
#### Edit an existing package
* `cd my-package-to-edit`
* `cd types/my-package-to-edit`
* Make changes. Remember to edit tests.
* You may also want to add yourself to "Definitions by" section of the package header.
- This will cause you to be notified (via your GitHub username) whenever someone makes a pull request or issue about the package.
- Do this by adding your name to the end of the line, as in `// Definitions by: Alice <https://github.com/alice>, Bob <https://github.com/bob>`.
* `npm install -g typescript@2.0` and run `tsc`.
- Or if there are more people, it can be multiline
```typescript
// Definitions by: Alice <https://github.com/alice>
// Bob <https://github.com/bob>
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* If there is a `tslint.json`, run `npm run lint package-name`. Otherwise, run `tsc` in the package directory.
When you make a PR to edit an existing package, `dt-bot` should @-mention previous authors.
If it doesn't, you can do so yourself in the comment associated with the PR.
@@ -124,6 +134,7 @@ For a good example package, see [base64-js](https://github.com/DefinitelyTyped/D
* First, follow advice from the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
* Formatting: Either use all tabs, or always use 4 spaces.
* `function sum(nums: number[]): number`: Use `ReadonlyArray` if a function does not write to its parameters.
* `interface Foo { new(): Foo; }`:
This defines a type of objects that are new-able. You probably want `declare class Foo { constructor(); }`.
* `const Class: { new(): IClass; }`:
@@ -134,6 +145,10 @@ For a good example package, see [base64-js](https://github.com/DefinitelyTyped/D
Example where a type parameter is acceptable: `function id<T>(value: T): T;`.
Example where it is not acceptable: `function parseJson<T>(json: string): T;`.
Exception: `new Map<string, number>()` is OK.
* Using the types `Function` and `Object` is almost never a good idea. In 99% of cases it's possible to specify a more specific type. Examples are `(x: number) => number` for [functions](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) and `{ x: number, y: number }` for objects. If there is no certainty at all about the type, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) is the right choice, not `Object`. If the only known fact about the type is that it's some object, use the type [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), not `Object` or `{ [key: string]: any }`.
* `var foo: string | any`:
When `any` is used in a union type, the resulting type is still `any`. So while the `string` portion of this type annotation may _look_ useful, it in fact offers no additional typechecking over simply using `any`.
Depending on the intention, acceptable alternatives could be `any`, `string`, or `string | object`.
#### Removing a package
@@ -153,21 +168,33 @@ If a package was never on DefinitelyTyped, it does not need to be added to `notN
#### Lint
To lint a package, just add a `tslint.json` to that package containing `{ "extends": "../tslint.json" }`. All new packages must be linted.
To lint a package, just add a `tslint.json` to that package containing `{ "extends": "dtslint/dt.json" }`. All new packages must be linted.
If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. For example:
```js
{
"extends": "../tslint.json",
"extends": "dtslint/dt.json",
"rules": {
// This package uses the Function type, and it will take effort to fix.
"forbidden-types": false
"ban-types": false
}
}
```
(To indicate that a lint rule truly does not apply, use `// tslint:disable rule-name` or better, `//tslint:disable-next-line rule-name`.)
To assert that an expression is of a given type, use `$ExpectType`. To assert that an expression causes a compile error, use `$ExpectError`.
```js
// $ExpectType void
f(1);
// $ExpectError
f("one");
```
For more details, see [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme.
Test by running `npm run lint package-name` where `package-name` is the name of your package.
This script uses [dtslint](https://github.com/Microsoft/dtslint).
@@ -177,18 +204,20 @@ This script uses [dtslint](https://github.com/Microsoft/dtslint).
#### What exactly is the relationship between this repository and the `@types` packages on NPM?
The `master` branch is automatically published to the `@types` scope on NPM thanks to [types-publisher](https://github.com/Microsoft/types-publisher).
This usually happens within an hour of changes being merged.
#### I've submitted a pull request. How long until it is merged?
It depends, but most pull requests will be merged within a week. PRs that have been approved by an author listed in the definition's header are usually merged more quickly; PRs for new definitions will take more time as they require more review from maintainers. Each PR is reviewed by a TypeScript or DefinitelyTyped team member before being merged, so please be patient as human factors may cause delays. Check the [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) to see progress as maintainers work through the open PRs.
#### My PR is merged; when will the `@types` NPM package be updated?
NPM packages should update within a few hours. If it's been more than 24 hours, ping @RyanCavanaugh and @andy-ms on the PR to investigate.
#### I'm writing a definition that depends on another definition. Should I use `<reference types="" />` or an import?
If the module you're referencing is an external module (uses `export`), use an import.
If the module you're referencing is an ambient module (uses `declare module`, or just declares globals), use `<reference types="" />`.
#### What do I do about older versions of typings?
Currently we don't support this, though it is [planned](https://github.com/Microsoft/types-publisher/issues/3).
If you're adding a new major version of a library, you can copy `index.d.ts` to `foo-v2.3.d.ts` and edit `index.d.ts` to be the new version.
#### I notice some packages having a `package.json` here.
Usually you won't need this. When publishing a package we will normally automatically create a `package.json` for it.
@@ -214,7 +243,7 @@ If default imports work in your environment, consider turning on the [`--allowSy
Do not change the type definition if it is accurate.
For an NPM package, `export =` is accurate if `node -p 'require("foo")'` is the export, and `export default` is accurate if `node -p 'require("foo").default'` is the export.
#### I want to use features from TypeScript 2.1.
#### I want to use features from TypeScript 2.1 or above.
Then you will have to add a comment to the last line of your definition header (after `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`.
@@ -256,6 +285,22 @@ transitively `react-router-bootstrap` (which depends on `react-router`) also add
Also, `/// <reference types=".." />` will not work with path mapping, so dependencies must use `import`.
#### What about scoped packages?
Types for a scoped package `@foo/bar` should go in `types/foo__bar`. Note the double underscore.
When `dts-gen` is used to scaffold a scoped package, the `paths` property has to be manually adapted in the generated
`tsconfig.json` to correctly reference the scoped package:
```json
{
"paths":{
"@foo/bar": ["foo__bar"]
}
}
```
#### The file history in GitHub looks incomplete.
GitHub doesn't [support](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) file history for renamed files. Use [`git log --follow`](https://www.git-scm.com/docs/git-log) instead.
-1380
View File
File diff suppressed because it is too large Load Diff
-388
View File
@@ -1,388 +0,0 @@
/*
* Test file for node-jose. At this time these tests were taken verbatim
* from the documentation on the NPM page at
* https://www.npmjs.com/package/node-jose
* This file definitely needs to be cleaned up and more tests added to
* test the entirety of the definition file.
*/
import * as jose from 'node-jose';
let keystore = jose.JWK.createKeyStore();
let buf = new Buffer('a');
jose.JWK.asKeyStore("{key: somekey}").
then(function (result) {
// {result} is a jose.JWK.KeyStore
keystore = result;
});
let output = keystore.toJSON();
output = keystore.toJSON(true);
// by 'kid'
let kid: string = "someID";
let key = keystore.get(kid);
// ... and by 'kty'
key = keystore.get(kid, { kty: 'RSA' });
// ... and by 'use'
key = keystore.get(kid, { use: 'enc' });
// ... and by 'alg'
key = keystore.get(kid, { use: 'RSA-OAEP' });
// ... and by 'kty' and 'use'
key = keystore.get(kid, { kty: 'RSA', use: 'enc' });
// same as above, but with a single {props} argument
key = keystore.get({ kid: kid, kty: 'RSA', use: 'enc' });
// searching for keys
let everything = keystore.all();
// filter by 'kid'
everything = keystore.all({ kid: kid });
// filter by 'kty'
everything = keystore.all({ kty: 'RSA' });
// filter by 'use'
everything = keystore.all({ use: 'enc' });
// filter by 'alg'
everything = keystore.all({ alg: 'RSA-OAEP' });
// filter by 'kid' + 'kty' + 'alg'
everything = keystore.all({ kid: kid, kty: 'RSA', alg: 'RSA-OAEP' });
// input is either a:
// * jose.JWK.Key to copy from; or
// * JSON object representing a JWK; or
keystore.add({}).
then(function (result) {
// {result} is a jose.JWK.Key
key = result;
});
// input is either a:
// * String serialization of a JSON JWK/(base64-encoded) PEM/(binary-encoded) DER
// * Buffer of a JSON JWK/(base64-encoded) PEM/(binary-encoded) DER
// form is either a:
// * "json" for a JSON stringified JWK
// * "private" for a DER encoded 'raw' private key
// * "pkcs8" for a DER encoded (unencrypted!) PKCS8 private key
// * "public" for a DER encoded SPKI public key (alternate to 'spki')
// * "spki" for a DER encoded SPKI public key
// * "pkix" for a DER encoded PKIX X.509 certificate
// * "x509" for a DER encoded PKIX X.509 certificate
// * "pem" for a PEM encoded of PKCS8 / SPKI / PKIX
keystore.add(buf, "json").
then(function (result) {
// {result} is a jose.JWK.Key
key = result;
});
// first argument is the key type (kty)
// second is the key size (in bits) or named curve ('crv') for "EC"
keystore.generate("oct", 256).
then(function (result) {
// {result} is a jose.JWK.Key
key = result;
});
// ... with properties
var props = {
kid: 'gBdaS-G8RLax2qgObTD94w',
alg: 'A256GCM',
use: 'enc'
};
keystore.generate("oct", 256, props).
then(function (result) {
// {result} is a jose.JWK.Key
key = result;
});
keystore.remove(key);
// NOTE: key.keystore does not change!!
// where input is either a:
// * jose.JWK.Key instance
// * JSON Object representation of a JWK
jose.JWK.asKey({}).
then(function (result) {
// {result} is a jose.JWK.Key
// {result.keystore} is a unique jose.JWK.KeyStore
key = result;
});
// where input is either a:
// * String serialization of a JSON JWK/(base64-encoded) PEM/(binary-encoded) DER
// * Buffer of a JSON JWK/(base64-encoded) PEM/(binary-encoded) DER
// form is either a:
// * "json" for a JSON stringified JWK
// * "pkcs8" for a DER encoded (unencrypted!) PKCS8 private key
// * "spki" for a DER encoded SPKI public key
// * "pkix" for a DER encoded PKIX X.509 certificate
// * "x509" for a DER encoded PKIX X.509 certificate
// * "pem" for a PEM encoded of PKCS8 / SPKI / PKIX
jose.JWK.asKey({}, 'json').
then(function (result) {
// {result} is a jose.JWK.Key
// {result.keystore} is a unique jose.JWK.KeyStore
key = result;
});
output = key.toJSON();
output = key.toJSON(true);
// where hash is a supported algorithm, currently one of:
// * SHA-1
// * SHA-256
// * SHA-384
// * SHA-512
key.thumbprint('SHA-1').
then(function (print) {
// {print} is a Buffer containing the thumbprint binary value
});
// {input} is a Buffer
jose.JWS.createSign(key).
update(buf).
final().
then(function (result) {
// {result} is a JSON object -- JWS using the JSON General Serialization
});
jose.JWS.createSign({ format: 'flattened' }, key).
update(buf).
final().
then(function (result) {
// {result} is a JSON object -- JWS using the JSON Flattened Serialization
});
jose.JWS.createSign({ format: 'compact' }, key).
update(buf).
final().
then(function (result) {
// {result} is a String -- JWS using the Compact Serialization
});
jose.JWS.createSign({ alg: 'PS256' }, key).
update(buf).
final().
then(function (result) {
// ....
});
jose.JWS.createSign({ fields: { cty: 'jwk+json' } }, key).
update(buf).
final().
then(function (result) {
// ....
});
jose.JWS.createSign(key).
update(buf, "utf8").
final().
then(function (result) {
// ....
});
// {keys} is an Array of jose.JWK.Key instances
jose.JWS.createSign([key, key]).
update(buf).
final().
then(function (result) {
// ....
});
jose.JWS.createVerify(keystore).
verify("some.jws.object").
then(function (result) {
// {result} is a Object with:
// * header: the combined 'protected' and 'unprotected' header members
// * payload: Buffer of the signed content
// * signature: Buffer of the verified signature
// * key: The key used to verify the signature
});
// {key} can be:
// * jose.JWK.Key
// * JSON object representing a JWK
jose.JWS.createVerify(key).
verify('some.jws.object').
then(function (result) {
// ...
});
jose.JWS.createVerify().
verify('some.jws.key').
then(function (result) {
// ...
});
var opts = {
handlers: {
"exp": true
}
};
jose.JWS.createVerify(key, opts).
verify('some.jws.key').
then(function (result) {
// ...
});
var opts2 = {
handlers: {
"exp": function (jws: any) {
// {jws} is the JWS verify output, pre-verification
jws.header.exp = new Date(jws.header.exp);
}
}
};
jose.JWS.createVerify(key, opts2).
verify('some.jws.key').
then(function (result) {
// ...
});
var opts3 = {
handlers: {
"exp": {
complete: function (jws: any) {
// {jws} is the JWS verify output, post-verification
jws.header.exp = new Date(jws.header.exp);
}
}
}
};
jose.JWS.createVerify(key, opts3).
verify('some.jws.key').
then(function (result) {
// ...
});
//Encryption
// {input} is a Buffer
jose.JWE.createEncrypt(key).
update(buf).
final().
then(function (result) {
// {result} is a JSON Object -- JWE using the JSON General Serialization
});
jose.JWE.createEncrypt({ format: 'compact' }, key).
update(buf).
final().
then(function (result) {
// {result} is a String -- JWE using the Compact Serialization
});
jose.JWE.createEncrypt({ format: 'flattened' }, key).
update(buf).
final().
then(function (result) {
// {result} is a JSON Object -- JWE using the JSON Flattened Serialization
});
jose.JWE.createEncrypt({ zip: true }, key).
update(buf).
final().
then(function (result) {
// ....
});
jose.JWE.createEncrypt({ fields: { cty: 'jwk+json' } }, key).
update(buf).
final().
then(function (result) {
// ....
});
// {keys} is an Array of jose.JWK.Key instances
jose.JWE.createEncrypt([key, key]).
update(buf).
final().
then(function (result) {
// ....
});
jose.JWE.createDecrypt(keystore).
decrypt('some.jwe').
then(function (result) {
// {result} is a Object with:
// * header: the combined 'protected' and 'unprotected' header members
// * protected: an array of the member names from the "protected" member
// * key: Key used to decrypt
// * payload: Buffer of the decrypted content
// * plaintext: Buffer of the decrypted content (alternate)
});
jose.JWE.createDecrypt(key).
decrypt('some.jwe').
then(function (result) {
// ....
});
var opts4 = {
handlers: {
"exp": true
}
};
jose.JWE.createDecrypt(key, opts4).
decrypt('some.jwe').
then(function (result) {
// ...
});
//To perform additional (pre-decrypt) processing on a crit header member:
var opts5 = {
handlers: {
"exp": function (jwe: any) {
// {jwe} is the JWE decrypt output, pre-decryption
jwe.header.exp = new Date(jwe.header.exp);
}
}
};
jose.JWE.createDecrypt(key, opts5).
decrypt('some.jwe').
then(function (result) {
// ...
});
//To perform additional (post-decrypt) processing on a crit header member:
var opts6 = {
handlers: {
"exp": {
complete: function (jwe: any) {
// {jwe} is the JWE decrypt output, post-decryption
jwe.header.exp = new Date(jwe.header.exp);
}
}
}
};
jose.JWE.createDecrypt(key, opts6).
decrypt('some.jwe').
then(function (result) {
// ...
});
var buff = jose.util.asBuffer('input');
var output2 = jose.util.base64url.encode(buf);
// explicit encoding
output2 = jose.util.base64url.encode(buf, "utf8");
// implied "utf8" encoding
output2 = jose.util.base64url.encode(buf);
var output3 = jose.util.base64url.decode('input');
// argument is size (in bytes)
var rnd = jose.util.randomBytes(32);
-22
View File
@@ -1,22 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"node-jose-tests.ts"
]
}
+324
View File
@@ -1,29 +1,101 @@
{
"packages": [
{
"libraryName": "3d-bin-packing",
"typingsPackageName": "3d-bin-packing",
"sourceRepoURL": "https://github.com/betterwaysystems/packer",
"asOfVersion": "1.1.3"
},
{
"libraryName": "ag-grid",
"typingsPackageName": "ag-grid",
"sourceRepoURL": "https://github.com/ceolter/ag-grid",
"asOfVersion": "3.2.0"
},
{
"libraryName": "ajv",
"typingsPackageName": "ajv",
"sourceRepoURL": "https://github.com/epoberezkin/ajv",
"asOfVersion": "1.0.0"
},
{
"libraryName": "angular-ui-router-default",
"typingsPackageName": "angular-ui-router-default",
"sourceRepoURL": "https://github.com/nonplus/angular-ui-router-default",
"asOfVersion": "0.0.5"
},
{
"libraryName": "angular-ui-router-uib-modal",
"typingsPackageName": "angular-ui-router-uib-modal",
"sourceRepoURL": "https://github.com/nonplus/angular-ui-router-uib-modal",
"asOfVersion": "0.0.11"
},
{
"libraryName": "antd",
"typingsPackageName": "antd",
"sourceRepoURL": "https://github.com/ant-design/ant-design",
"asOfVersion": "1.0.0"
},
{
"libraryName": "anydb-sql",
"typingsPackageName": "anydb-sql",
"sourceRepoURL": "https://github.com/doxout/anydb-sql",
"asOfVersion": "0.6.46"
},
{
"libraryName": "apn",
"typingsPackageName": "apn",
"sourceRepoURL": "https://github.com/node-apn/node-apn",
"asOfVersion": "2.1.2"
},
{
"libraryName": "Argon2",
"typingsPackageName": "argon2",
"sourceRepoURL": "https://github.com/ranisalt/node-argon2",
"asOfVersion": "0.15.0"
},
{
"libraryName": "aws-sdk",
"typingsPackageName": "aws-sdk",
"sourceRepoURL": "https://github.com/aws/aws-sdk-js",
"asOfVersion": "2.7.0"
},
{
"libraryName": "axe-core",
"typingsPackageName": "axe-core",
"sourceRepoURL": "https://github.com/dequelabs/axe-core",
"asOfVersion": "2.0.7"
},
{
"libraryName": "axios",
"typingsPackageName": "axios",
"sourceRepoURL": "https://github.com/mzabriskie/axios",
"asOfVersion": "0.14.0"
},
{
"libraryName": "azure-mobile-apps",
"typingsPackageName": "azure-mobile-apps",
"sourceRepoURL": "https://github.com/Azure/azure-mobile-apps-node/",
"asOfVersion": "3.0.0"
},
{
"libraryName": "BabylonJS",
"typingsPackageName": "babylonjs",
"sourceRepoURL": "http://www.babylonjs.com/",
"asOfVersion": "2.4.1"
},
{
"libraryName": "base64url",
"typingsPackageName": "base64url",
"sourceRepoURL": "https://github.com/brianloveswords/base64url",
"asOfVersion": "2.0.0"
},
{
"libraryName": "BigInteger.js",
"typingsPackageName": "big-integer",
"sourceRepoURL": "https://github.com/peterolson/BigInteger.js",
"asOfVersion": "0.0.31"
},
{
"libraryName": "Bugsnag Browser",
"typingsPackageName": "bugsnag-js",
@@ -60,6 +132,12 @@
"sourceRepoURL": "https://github.com/date-fns/date-fns",
"asOfVersion": "2.6.0"
},
{
"libraryName": "DevExtreme",
"typingsPackageName": "devextreme",
"sourceRepoURL": "http://js.devexpress.com/",
"asOfVersion": "16.2.1"
},
{
"libraryName": "Dexie.js",
"typingsPackageName": "dexie",
@@ -84,6 +162,42 @@
"sourceRepoURL": "https://github.com/bterlson/ecmarkup",
"asOfVersion": "3.4.0"
},
{
"libraryName": "electron",
"typingsPackageName": "electron",
"sourceRepoURL": "https://github.com/electron/electron",
"asOfVersion": "1.6.10"
},
{
"libraryName": "electron-builder",
"typingsPackageName": "electron-builder",
"sourceRepoURL": "https://github.com/loopline-systems/electron-builder",
"asOfVersion": "2.8.0"
},
{
"libraryName": "eventemitter2",
"typingsPackageName": "eventemitter2",
"sourceRepoURL": "https://github.com/asyncly/EventEmitter2",
"asOfVersion": "4.1.0"
},
{
"libraryName": "EventEmitter3",
"typingsPackageName": "eventemitter3",
"sourceRepoURL": "https://github.com/primus/eventemitter3",
"asOfVersion": "2.0.2"
},
{
"libraryName": "express-validator",
"typingsPackageName": "express-validator",
"sourceRepoURL": "https://github.com/ctavan/express-validator",
"asOfVersion": "3.0.0"
},
{
"libraryName": "JSON-Patch",
"typingsPackageName": "fast-json-patch",
"sourceRepoURL": "https://github.com/Starcounter-Jack/JSON-Patch",
"asOfVersion": "1.1.5"
},
{
"libraryName": "FastSimplexNoise",
"typingsPackageName": "fast-simplex-noise",
@@ -108,6 +222,12 @@
"sourceRepoURL": "https://github.com/mikedeboer/node-github",
"asOfVersion": "7.1.0"
},
{
"libraryName": "gulp-typescript",
"typingsPackageName": "gulp-typescript",
"sourceRepoURL": "https://github.com/ivogabe/gulp-typescript",
"asOfVersion": "2.13.0"
},
{
"libraryName": "Facebook's Immutable",
"typingsPackageName": "immutable",
@@ -162,12 +282,42 @@
"sourceRepoURL": "https://github.com/blakeembrey/is-upper-case",
"asOfVersion": "1.1.2"
},
{
"libraryName": "jpush-react-native",
"typingsPackageName": "jpush-react-native",
"sourceRepoURL": "https://github.com/jpush/jpush-react-native",
"asOfVersion": "2.0.0"
},
{
"libraryName": "jquery.ajaxfile",
"typingsPackageName": "jquery.ajaxfile",
"sourceRepoURL": "https://github.com/fpellet/jquery.ajaxFile",
"asOfVersion": "0.2.29"
},
{
"libraryName": "JSNLog",
"typingsPackageName": "jsnlog",
"sourceRepoURL": "https://github.com/mperdeck/jsnlog.js",
"asOfVersion": "2.17.2"
},
{
"libraryName": "jsonschema",
"typingsPackageName": "jsonschema",
"sourceRepoURL": "https://github.com/tdegrunt/jsonschema",
"asOfVersion": "1.1.1"
},
{
"libraryName": "knockout-paging",
"typingsPackageName": "knockout-paging",
"sourceRepoURL": "https://github.com/ErikSchierboom/knockout-paging",
"asOfVersion": "0.3.1"
},
{
"libraryName": "knockout-pre-rendered",
"typingsPackageName": "knockout-pre-rendered",
"sourceRepoURL": "https://github.com/ErikSchierboom/knockout-pre-rendered",
"asOfVersion": "0.7.1"
},
{
"libraryName": "Linq.JS",
"typingsPackageName": "linq",
@@ -186,6 +336,12 @@
"sourceRepoURL": "https://github.com/localForage/localForage",
"asOfVersion": "0.0.34"
},
{
"libraryName": "lodash-decorators",
"typingsPackageName": "lodash-decorators",
"sourceRepoURL": "https://github.com/steelsojka/lodash-decorators",
"asOfVersion": "4.0.0"
},
{
"libraryName": "lower-case",
"typingsPackageName": "lower-case",
@@ -204,12 +360,24 @@
"sourceRepoURL": "http://maquettejs.org/",
"asOfVersion": "2.1.6"
},
{
"libraryName": "mendixmodelsdk",
"typingsPackageName": "mendixmodelsdk",
"sourceRepoURL": "http://www.mendix.com",
"asOfVersion": "0.8.1"
},
{
"libraryName": "mobservable",
"typingsPackageName": "mobservable",
"sourceRepoURL": "github.com/mweststrate/mobservable",
"asOfVersion": "1.2.5"
},
{
"libraryName": "mobservable-react",
"typingsPackageName": "mobservable-react",
"sourceRepoURL": "https://github.com/mweststrate/mobservable-react",
"asOfVersion": "1.0.0"
},
{
"libraryName": "Moment",
"typingsPackageName": "moment",
@@ -234,12 +402,24 @@
"sourceRepoURL": "https://github.com/foretagsplatsen/numbro/",
"asOfVersion": "1.9.3"
},
{
"libraryName": "Onsen UI",
"typingsPackageName": "onsenui",
"sourceRepoURL": "http://onsen.io",
"asOfVersion": "2.0.0"
},
{
"libraryName": "param-case",
"typingsPackageName": "param-case",
"sourceRepoURL": "https://github.com/blakeembrey/param-case",
"asOfVersion": "1.1.2"
},
{
"libraryName": "parse5",
"typingsPackageName": "parse5",
"sourceRepoURL": "https://github.com/inikulin/parse5",
"asOfVersion": "3.0.0"
},
{
"libraryName": "pascal-case",
"typingsPackageName": "pascal-case",
@@ -252,12 +432,30 @@
"sourceRepoURL": "https://github.com/blakeembrey/path-case",
"asOfVersion": "1.1.2"
},
{
"libraryName": "path-to-regexp",
"typingsPackageName": "path-to-regexp",
"sourceRepoURL": "https://github.com/pillarjs/path-to-regexp",
"asOfVersion": "1.7.0"
},
{
"libraryName": "pg-promise",
"typingsPackageName": "pg-promise",
"sourceRepoURL": "https://github.com/vitaly-t/pg-promise",
"asOfVersion": "5.4.3"
},
{
"libraryName": "pixi-spine",
"typingsPackageName": "pixi-spine",
"sourceRepoURL": "https://github.com/pixijs/pixi-spine",
"asOfVersion": "1.4.2"
},
{
"libraryName": "pkcs11js",
"typingsPackageName": "pkcs11js",
"sourceRepoURL": "https://github.com/PeculiarVentures/pkcs11js",
"asOfVersion": "1.0.4"
},
{
"libraryName": "poly2tri.js",
"typingsPackageName": "poly2tri",
@@ -276,18 +474,48 @@
"sourceRepoURL": "https://github.com/angular/protractor",
"asOfVersion": "4.0.0"
},
{
"libraryName": "qiniu",
"typingsPackageName": "qiniu",
"sourceRepoURL": "https://github.com/qiniu/nodejs-sdk",
"asOfVersion": "7.0.1"
},
{
"libraryName": "Raven JS",
"typingsPackageName": "raven-js",
"sourceRepoURL": "https://github.com/getsentry/raven-js",
"asOfVersion": "3.10.0"
},
{
"libraryName": "raw-body",
"typingsPackageName": "raw-body",
"sourceRepoURL": "https://github.com/stream-utils/raw-body",
"asOfVersion": "2.3.0"
},
{
"libraryName": "react-day-picker",
"typingsPackageName": "react-day-picker",
"sourceRepoURL": "https://github.com/gpbl/react-day-picker",
"asOfVersion": "5.3.0"
},
{
"libraryName": "Redux",
"typingsPackageName": "redux",
"sourceRepoURL": "https://github.com/reactjs/redux",
"asOfVersion": "3.6.0"
},
{
"libraryName": "redux-batched-actions",
"typingsPackageName": "redux-batched-actions",
"sourceRepoURL": "https://github.com/tshelburne/redux-batched-actions",
"asOfVersion": "0.1.5"
},
{
"libraryName": "redux-devtools-extension",
"typingsPackageName": "redux-devtools-extension",
"sourceRepoURL": "https://github.com/zalmoxisus/redux-devtools-extension",
"asOfVersion": "2.13.2"
},
{
"libraryName": "redux-persist",
"typingsPackageName": "redux-persist",
@@ -312,12 +540,60 @@
"sourceRepoURL": "https://github.com/gaearon/redux-thunk",
"asOfVersion": "2.1.0"
},
{
"libraryName": "reselect",
"typingsPackageName": "reselect",
"sourceRepoURL": "https://github.com/rackt/reselect",
"asOfVersion": "2.2.0"
},
{
"libraryName": "rest-io",
"typingsPackageName": "rest-io",
"sourceRepoURL": "https://github.com/EnoF/rest-io",
"asOfVersion": "4.1.0"
},
{
"libraryName": "route-recognizer",
"typingsPackageName": "route-recognizer",
"sourceRepoURL": "https://github.com/tildeio/route-recognizer",
"asOfVersion": "0.3.0"
},
{
"libraryName": "router5",
"typingsPackageName": "router5",
"sourceRepoURL": "https://github.com/router5/router5",
"asOfVersion": "5.0.0"
},
{
"libraryName": "samchon",
"typingsPackageName": "samchon",
"sourceRepoURL": "https://github.com/samchon/framework",
"asOfVersion": "2.0.22"
},
{
"libraryName": "samchon-framework",
"typingsPackageName": "samchon-framework",
"sourceRepoURL": "https://github.com/samchon/framework",
"asOfVersion": "2.0.21"
},
{
"libraryName": "samchon-library",
"typingsPackageName": "samchon-library",
"sourceRepoURL": "https://github.com/samchon/framework",
"asOfVersion": "0.1.0"
},
{
"libraryName": "node-scanf",
"typingsPackageName": "scanf",
"sourceRepoURL": "https://github.com/Lellansin/node-scanf",
"asOfVersion": "0.7.3"
},
{
"libraryName": "sendgrid",
"typingsPackageName": "sendgrid",
"sourceRepoURL": "https://github.com/sendgrid/sendgrid-nodejs",
"asOfVersion": "4.3.0"
},
{
"libraryName": "sentence-case",
"typingsPackageName": "sentence-case",
@@ -354,12 +630,30 @@
"sourceRepoURL": "https://github.com/andrewplummer/Sugar",
"asOfVersion": "2.0.2"
},
{
"libraryName": "svg.js",
"typingsPackageName": "svg.js",
"sourceRepoURL": "http://www.svgjs.com/",
"asOfVersion": "2.3.1"
},
{
"libraryName": "swap-case",
"typingsPackageName": "swap-case",
"sourceRepoURL": "https://github.com/blakeembrey/swap-case",
"asOfVersion": "1.1.2"
},
{
"libraryName": "Tabris.js",
"typingsPackageName": "tabris",
"sourceRepoURL": "http://tabrisjs.com",
"asOfVersion": "1.8.0"
},
{
"libraryName": "tcomb",
"typingsPackageName": "tcomb",
"sourceRepoURL": "http://gcanti.github.io/tcomb/guide/index.html",
"asOfVersion": "2.6.0"
},
{
"libraryName": "title-case",
"typingsPackageName": "title-case",
@@ -372,6 +666,12 @@
"sourceRepoURL": "https://github.com/cbowdon/TsMonad",
"asOfVersion": "0.5.0"
},
{
"libraryName": "tstl",
"typingsPackageName": "tstl",
"sourceRepoURL": "https://github.com/samchon/tstl",
"asOfVersion": "1.5.7"
},
{
"libraryName": "TypeScript",
"typingsPackageName": "typescript",
@@ -384,6 +684,12 @@
"sourceRepoURL": "https://github.com/Microsoft/TypeScript",
"asOfVersion": "2.0.0"
},
{
"libraryName": "uk.co.workingedge.phonegap.plugin.istablet",
"typingsPackageName": "uk.co.workingedge.phonegap.plugin.istablet",
"sourceRepoURL": "https://github.com/dpa99c/phonegap-istablet",
"asOfVersion": "1.1.3"
},
{
"libraryName": "upper-case",
"typingsPackageName": "upper-case",
@@ -396,6 +702,12 @@
"sourceRepoURL": "https://github.com/blakeembrey/upper-case-first",
"asOfVersion": "1.1.2"
},
{
"libraryName": "vso-node-api",
"typingsPackageName": "vso-node-api",
"sourceRepoURL": "https://github.com/Microsoft/vso-node-api",
"asOfVersion": "4.0.0"
},
{
"libraryName": "vuejs",
"typingsPackageName": "vue",
@@ -408,6 +720,12 @@
"sourceRepoURL": "https://github.com/vuejs/vue-router",
"asOfVersion": "2.0.0"
},
{
"libraryName": "webcola",
"typingsPackageName": "webcola",
"sourceRepoURL": "https://github.com/tgdwyer/WebCola",
"asOfVersion": "3.2.0"
},
{
"libraryName": "x2js",
"typingsPackageName": "x2js",
@@ -425,6 +743,12 @@
"typingsPackageName": "xmpp-jid",
"sourceRepoURL": "github.com/node-xmpp/node-xmpp/",
"asOfVersion": "1.2.0"
},
{
"libraryName": "Zone.js",
"typingsPackageName": "zone.js",
"sourceRepoURL": "https://github.com/angular/zone.js",
"asOfVersion": "0.5.12"
}
]
}
+3 -3
View File
@@ -17,11 +17,11 @@
"scripts": {
"compile-scripts": "tsc -p scripts",
"not-needed": "node scripts/not-needed.js",
"test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed --nProcesses 1",
"lint": "dtslint --dt types"
"test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed",
"lint": "dtslint types"
},
"devDependencies": {
"dtslint": "Microsoft/dtslint#production",
"dtslint": "github:Microsoft/dtslint#production",
"types-publisher": "Microsoft/types-publisher#production"
}
}
+11 -2
View File
@@ -31,7 +31,7 @@ function fixTslint(dir: string): void {
if (!fs.existsSync(target)) return;
let json = JSON.parse(fs.readFileSync(target, 'utf-8'));
json = fix(json);
const text = Object.keys(json).length === 1 ? '{ "extends": "../tslint.json" }' : JSON.stringify(json, undefined, 4);
const text = Object.keys(json).length === 1 ? '{ "extends": "dtslint/dt.json" }' : JSON.stringify(json, undefined, 4);
fs.writeFileSync(target, text + "\n", "utf-8");
}
@@ -39,7 +39,16 @@ function fix(config: any): any {
const out: any = {};
for (const key in config) {
let value = config[key];
out[key] = value;
out[key] = key === "rules" ? fixRules(value) : value;
}
return out;
}
function fixRules(rules: any): any {
const out: any = {};
for (const key in rules) {
out[key] = rules[key];
}
return out;
}
-4
View File
@@ -5,10 +5,6 @@
import * as fs from 'fs';
import * as path from 'path';
function repeat(s: string, count: number) {
return Array(count + 1).join(s);
}
const home = path.join(__dirname, '..');
for (const dirName of fs.readdirSync(home)) {
@@ -1,50 +0,0 @@
import packer = require("3d-bin-packing");
import samchon = require("samchon");
function main(): void
{
///////////////////////////
// CONSTRUCT OBJECTS
///////////////////////////
let wrapperArray: bws.packer.WrapperArray = new packer.WrapperArray();
let instanceArray: bws.packer.InstanceArray = new packer.InstanceArray();
// Wrappers
wrapperArray.push
(
new packer.Wrapper("Large", 1000, 40, 40, 15, 0),
new packer.Wrapper("Medium", 700, 20, 20, 10, 0),
new packer.Wrapper("Small", 500, 15, 15, 8, 0)
);
///////
// Each Instance is repeated #15
///////
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Eraser", 1, 2, 5));
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Book", 15, 30, 3));
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Drink", 3, 3, 10));
instanceArray.insert(instanceArray.end(), 15, new packer.Product("Umbrella", 5, 5, 20));
// Wrappers also can be packed into another Wrapper.
instanceArray.insert(instanceArray.end(), 15, new packer.Wrapper("Notebook-Box", 2000, 30, 40, 4, 2));
instanceArray.insert(instanceArray.end(), 15, new packer.Wrapper("Tablet-Box", 2500, 20, 28, 2, 0));
///////////////////////////
// BEGINS PACKING
///////////////////////////
// CONSTRUCT PACKER
let my_packer: bws.packer.Packer = new packer.Packer(wrapperArray, instanceArray);
///////
// PACK (OPTIMIZE)
let result: bws.packer.WrapperArray = my_packer.optimize();
///////
///////////////////////////
// TRACE PACKING RESULT
///////////////////////////
let xml: samchon.library.XML = result.toXML();
console.log(xml.toString());
}
main();
-1383
View File
File diff suppressed because it is too large Load Diff
-23
View File
@@ -1,23 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"3d-bin-packing-tests.ts"
]
}
+13
View File
@@ -0,0 +1,13 @@
import abbrev = require('abbrev');
let abbrs: { [abbreviation: string]: string; };
abbrs = abbrev();
abbrs = abbrev('foo', 'fool', 'folding', 'flop');
abbrs = abbrev(['foo', 'fool', 'folding', 'flop']);
abbrev.monkeyPatch();
abbrs = [].abbrev();
const roArr: ReadonlyArray<string> = [];
abbrs = roArr.abbrev();
abbrs = ({}).abbrev();
+27
View File
@@ -0,0 +1,27 @@
// Type definitions for abbrev 1.1
// Project: https://github.com/isaacs/abbrev-js#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = abbrev;
declare function abbrev(words: string[]): {[abbreviation: string]: string};
declare function abbrev(...words: string[]): {[abbreviation: string]: string};
declare namespace abbrev {
function monkeyPatch(): void;
}
declare global {
interface Array<T> {
abbrev(): {[abbreviation: string]: string};
}
interface ReadonlyArray<T> {
abbrev(): {[abbreviation: string]: string};
}
interface Object {
abbrev(): {[abbreviation: string]: string};
}
}
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"abbrev-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+3 -3
View File
@@ -1,6 +1,6 @@
// Type definitions for Ably Realtime and Rest client library 0.9
// Project: https://www.ably.io/
// Definitions by: Ably <https://github.com/ably/>
// Definitions by: Ably <https://github.com/ably>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export namespace ablyLib {
@@ -287,7 +287,7 @@ export namespace ablyLib {
}
// Common Listeners
type paginatedResultCallback<T> = (error: ErrorInfo, results: PaginatedResult<T> ) => void;
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;
@@ -410,7 +410,7 @@ export namespace ablyLib {
state: ConnectionState;
close: () => void;
connect: () => void;
ping: (callback?: (error: ErrorInfo, responseTime: number ) => void ) => void;
ping: (callback?: (error: ErrorInfo, responseTime: number) => void) => void;
}
class Stats {
+6 -1
View File
@@ -1 +1,6 @@
{ "extends": "../tslint.json" }
{
"extends": "dtslint/dt.json",
"rules": {
"no-any-union": false
}
}
+1 -1
View File
@@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "dtslint/dt.json" }
+2 -1
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/sathomas/acc-wizard
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
interface AccWizardOptions {
/**
@@ -110,4 +111,4 @@ interface AccWizardOptions {
*/
interface JQuery {
accwizard(options?: AccWizardOptions): void;
}
}
+5 -7
View File
@@ -44,16 +44,14 @@ declare namespace accepts {
/**
* 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.
* If no types are supplied, return the entire set of acceptable types.
*
* The `types` array can contain full MIME types or file extensions. Any value that is not a full MIME types is passed to `require('mime-types').lookup`.
*/
type(types: string[]): string | false;
type(...types: string[]): string | false;
/**
* Return the types that the request accepts, in the order of the client's preference (most preferred first).
*/
types(): string[];
type(types: string[]): string[] | string | false;
type(...types: string[]): string[] | string | false;
types(types: string[]): string[] | string | false;
types(...types: string[]): string[] | string | false;
}
}
+1 -1
View File
@@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "dtslint/dt.json" }
+3
View File
@@ -3,6 +3,9 @@
// Default usage:
accounting.formatMoney(12345678); // $12,345,678.00
// Stringified usage:
accounting.formatMoney('$4394958309392.9401'); // $4,394,958,309,392.94
// European formatting (custom symbol and separators), could also use options object as second param:
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
+7 -6
View File
@@ -1,6 +1,7 @@
// Type definitions for accounting.js 0.3
// Project: http://josscrowcroft.github.io/accounting.js/
// Definitions by: Sergey Gerasimov <https://github.com/gerich-home/>
// Type definitions for accounting.js 0.4
// Project: http://openexchangerates.github.io/accounting.js/
// Definitions by: Sergey Gerasimov <https://github.com/gerich-home>
// Christopher Eck <https://github.com/chrisleck>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace accounting {
@@ -30,9 +31,9 @@ declare namespace accounting {
}
interface Static {
// format any number into currency
formatMoney(number: number, symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string;
formatMoney(number: number, options: CurrencySettings<string> | CurrencySettings<CurrencyFormat>): string;
// format any number or stringified number into currency
formatMoney(number: number | string, symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string;
formatMoney(number: number | string, options: CurrencySettings<string> | CurrencySettings<CurrencyFormat>): string;
formatMoney(numbers: number[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[];
formatMoney(numbers: number[], options: CurrencySettings<string> | CurrencySettings<CurrencyFormat>): string[];
+1 -1
View File
@@ -1 +1 @@
{ "extends": "../tslint.json" }
{ "extends": "dtslint/dt.json" }
+20 -2
View File
@@ -474,7 +474,9 @@ declare namespace AceAjax {
removeFold(arg: any): void;
expandFold(arg: any): void;
foldAll(startRow?: number, endRow?: number, depth?: number): void
unfold(arg1: any, arg2: boolean): void;
screenToDocumentColumn(row: number, column: number): void;
@@ -1039,6 +1041,12 @@ declare namespace AceAjax {
addEventListener(ev: 'change', callback: (ev: EditorChangeEvent) => any): void;
addEventListener(ev: string, callback: Function): void;
off(ev: string, callback: Function): void;
removeListener(ev: string, callback: Function): void;
removeEventListener(ev: string, callback: Function): void;
inMultiSelectMode: boolean;
selectMoreLines(n: number): void;
@@ -2164,8 +2172,16 @@ declare namespace AceAjax {
**/
export interface Selection {
on(ev: string, callback: Function): void;
addEventListener(ev: string, callback: Function): void;
off(ev: string, callback: Function): void;
removeListener(ev: string, callback: Function): void;
removeEventListener(ev: string, callback: Function): void;
moveCursorWordLeft(): void;
moveCursorWordRight(): void;
@@ -2643,7 +2659,9 @@ declare namespace AceAjax {
characterWidth: number;
lineHeight: number;
setScrollMargin(top:number, bottom:number, left: number, right: number): void;
screenToTextCoordinates(left: number, top: number): void;
/**
+1
View File
@@ -15,6 +15,7 @@ const aceVirtualRendererTests = {
var renderer = new AceAjax.VirtualRenderer(el);
renderer.setPadding(0);
renderer.setScrollMargin(0,0,0,0)
renderer.setSession(new AceAjax.EditSession("1234"));
var r = renderer.scroller.getBoundingClientRect();
+5 -1
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/optimalbits/node_acl
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="bluebird" />
/// <reference types="node"/>
@@ -49,7 +50,10 @@ interface Acl {
allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise<void>;
isAllowed: (userId: Value, resources: strings, permissions: strings, cb?: AllowedCallback) => Promise<boolean>;
areAnyRolesAllowed: (roles: strings, resource: strings, permissions: strings, cb?: AllowedCallback) => Promise<any>;
whatResources: (roles: strings, permissions: strings, cb?: AnyCallback) => Promise<any>;
whatResources: {
(roles: strings, cb?: AnyCallback): Promise<any>;
(roles: strings, permissions: strings, cb?: AnyCallback): Promise<any>;
}
permittedResources: (roles: strings, permissions: strings, cb?: Function) => Promise<void>;
middleware: (numPathComponents?: number, userId?: Value | GetUserId, actions?: strings) => express.RequestHandler;
}
+12
View File
@@ -66,6 +66,18 @@ acl.isAllowed('joed', 'blogs', 'view', (err, res) => {
}
});
acl.whatResources('foo', (err, res) => {
if (res) {
console.log(res);
}
});
acl.whatResources('foo', 'view', (err, res) => {
if (res) {
console.log(res);
}
});
acl.isAllowed('jsmith', 'blogs', ['edit','view','delete'])
.then((result) => {
console.dir('jsmith is allowed blogs ' + result);
@@ -0,0 +1,28 @@
let obj0 = new ActiveXObject('ADODB.Command');
let obj1 = new ActiveXObject('ADODB.Connection');
let obj2 = new ActiveXObject('ADODB.Parameter');
let obj3 = new ActiveXObject('ADODB.Record');
let obj4 = new ActiveXObject('ADODB.Recordset');
let obj5 = new ActiveXObject('ADODB.Stream');
// open connection to an Excel file
let pathToExcelFile = 'C:\\path\\to\\excel\\file.xlsx';
let conn = new ActiveXObject('ADODB.Connection');
conn.Provider = 'Microsoft.ACE.OLEDB.12.0';
conn.ConnectionString = `Data Source="${pathToExcelFile}";Extended Properties="Excel 12.0;HDR=Yes"`;
conn.Open();
// create a Command to access the data
let cmd = new ActiveXObject('ADODB.Command');
cmd.CommandText = 'SELECT DISTINCT LastName, CityName FROM [Sheet1$]';
// get a Recordset
let rs = cmd.Execute();
// build a string from the Recordset
let s = rs.GetString(ADODB.StringFormatEnum.adClipString, -1, '\t', '\n', '(NULL)');
rs.Close();
WScript.Echo(s);
+1007
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-adodb-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
@@ -1,18 +0,0 @@
//open connection to an Excel file
var pathToExcelFile = 'C:\\path\\to\\excel\\file.xlsx';
var conn = new ActiveXObject('ADODB.Connection');
conn.Provider = 'Microsoft.ACE.OLEDB.12.0';
conn.ConnectionString =
'Data Source="' + pathToExcelFile + '";' +
'Extended Properties="Excel 12.0;HDR=Yes"';
conn.Open();
//create a Command to access the data
var cmd = new ActiveXObject('ADODB.Command');
cmd.CommandText = 'SELECT DISTINCT LastName, CityName FROM [Sheet1$]';
//get a Recordset
var rs = cmd.Execute();
//build a string from the Recordset
var s = rs.GetString(ADODB.StringFormatEnum.adClipString, -1, '\t', '\n', '(NULL)');
rs.Close();
WScript.Echo(s);
-834
View File
@@ -1,834 +0,0 @@
// Type definitions for Microsoft ActiveX Data Objects
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms675532(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace ADODB {
//Enums
const enum ADCPROP_ASYNCTHREADPRIORITY_ENUM {
adPriorityAboveNormal = 4,
adPriorityBelowNormal = 2,
adPriorityHighest = 5,
adPriorityLowest = 1,
adPriorityNormal = 3
}
const enum ADCPROP_AUTORECALC_ENUM {
adRecalcAlways = 1,
adRecalcUpFront = 0
}
const enum ADCPROP_UPDATECRITERIA_ENUM {
adCriteriaAllCols = 1,
adCriteriaKey = 0,
adCriteriaTimeStamp = 3,
adCriteriaUpdCols = 2
}
const enum ADCPROP_UPDATERESYNC_ENUM {
adResyncAll = 15,
adResyncAutoIncrement = 1,
adResyncConflicts = 2,
adResyncInserts = 8,
adResyncNone = 0,
adResyncUpdates = 4
}
const enum AffectEnum {
adAffectAll = 3,
adAffectAllChapters = 4,
adAffectCurrent = 1,
adAffectGroup = 2
}
const enum BookmarkEnum {
adBookmarkCurrent = 0,
adBookmarkFirst = 1,
adBookmarkLast = 2
}
const enum CommandTypeEnum {
adCmdFile = 256,
adCmdStoredProc = 4,
adCmdTable = 2,
adCmdTableDirect = 512,
adCmdText = 1,
adCmdUnknown = 8,
adCmdUnspecified = -1
}
const enum CompareEnum {
adCompareEqual = 1,
adCompareGreaterThan = 2,
adCompareLessThan = 0,
adCompareNotComparable = 4,
adCompareNotEqual = 3
}
const enum ConnectModeEnum {
adModeRead = 1,
adModeReadWrite = 3,
adModeRecursive = 4194304,
adModeShareDenyNone = 16,
adModeShareDenyRead = 4,
adModeShareDenyWrite = 8,
adModeShareExclusive = 12,
adModeUnknown = 0,
adModeWrite = 2
}
const enum ConnectOptionEnum {
adAsyncConnect = 16,
adConnectUnspecified = -1
}
const enum ConnectPromptEnum {
adPromptAlways = 1,
adPromptComplete = 2,
adPromptCompleteRequired = 3,
adPromptNever = 4
}
const enum CopyRecordOptionsEnum {
adCopyAllowEmulation = 4,
adCopyNonRecursive = 2,
adCopyOverWrite = 1,
adCopyUnspecified = -1
}
const enum CursorLocationEnum {
adUseClient = 3,
adUseClientBatch = 3,
adUseNone = 1,
adUseServer = 2
}
const enum CursorOptionEnum {
adAddNew = 16778240,
adApproxPosition = 16384,
adBookmark = 8192,
adDelete = 16779264,
adFind = 524288,
adHoldRecords = 256,
adIndex = 8388608,
adMovePrevious = 512,
adNotify = 262144,
adResync = 131072,
adSeek = 4194304,
adUpdate = 16809984,
adUpdateBatch = 65536
}
const enum CursorTypeEnum {
adOpenDynamic = 2,
adOpenForwardOnly = 0,
adOpenKeyset = 1,
adOpenStatic = 3,
adOpenUnspecified = -1
}
const enum DataTypeEnum {
adArray = 8192,
adBigInt = 20,
adBinary = 128,
adBoolean = 11,
adBSTR = 8,
adChapter = 136,
adChar = 129,
adCurrency = 6,
adDate = 7,
adDBDate = 133,
adDBTime = 134,
adDBTimeStamp = 135,
adDecimal = 14,
adDouble = 5,
adEmpty = 0,
adError = 10,
adFileTime = 64,
adGUID = 72,
adIDispatch = 9,
adInteger = 3,
adIUnknown = 13,
adLongVarBinary = 205,
adLongVarChar = 201,
adLongVarWChar = 203,
adNumeric = 131,
adPropVariant = 138,
adSingle = 4,
adSmallInt = 2,
adTinyInt = 16,
adUnsignedBigInt = 21,
adUnsignedInt = 19,
adUnsignedSmallInt = 18,
adUnsignedTinyInt = 17,
adUserDefined = 132,
adVarBinary = 204,
adVarChar = 200,
adVariant = 12,
adVarNumeric = 139,
adVarWChar = 202,
adWChar = 130
}
const enum EditModeEnum {
adEditAdd = 2,
adEditDelete = 4,
adEditInProgress = 1,
adEditNone = 0
}
const enum ErrorValueEnum {
adErrBoundToCommand = 3707,
adErrCannotComplete = 3732,
adErrCantChangeConnection = 3748,
adErrCantChangeProvider = 3220,
adErrCantConvertvalue = 3724,
adErrCantCreate = 3725,
adErrCatalogNotSet = 3747,
adErrColumnNotOnThisRow = 3726,
adErrConnectionStringTooLong = 3754,
adErrDataConversion = 3421,
adErrDataOverflow = 3721,
adErrDelResOutOfScope = 3738,
adErrDenyNotSupported = 3750,
adErrDenyTypeNotSupported = 3751,
adErrFeatureNotAvailable = 3251,
adErrFieldsUpdateFailed = 3749,
adErrIllegalOperation = 3219,
adErrIntegrityViolation = 3719,
adErrInTransaction = 3246,
adErrInvalidArgument = 3001,
adErrInvalidConnection = 3709,
adErrInvalidParamInfo = 3708,
adErrInvalidTransaction = 3714,
adErrInvalidURL = 3729,
adErrItemNotFound = 3265,
adErrNoCurrentRecord = 3021,
adErrNotExecuting = 3715,
adErrNotReentrant = 3710,
adErrObjectClosed = 3704,
adErrObjectInCollection = 3367,
adErrObjectNotSet = 3420,
adErrObjectOpen = 3705,
adErrOpeningFile = 3002,
adErrOperationCancelled = 3712,
adErrOutOfSpace = 3734,
adErrPermissionDenied = 3720,
adErrPropConflicting = 3742,
adErrPropInvalidColumn = 3739,
adErrPropInvalidOption = 3740,
adErrPropInvalidValue = 3741,
adErrPropNotAllSettable = 3743,
adErrPropNotSet = 3744,
adErrPropNotSettable = 3745,
adErrPropNotSupported = 3746,
adErrProviderFailed = 3000,
adErrProviderNotFound = 3706,
adErrProviderNotSpecified = 3753,
adErrReadFile = 3003,
adErrResourceExists = 3731,
adErrResourceLocked = 3730,
adErrResourceOutOfScope = 3735,
adErrSchemaViolation = 3722,
adErrSignMismatch = 3723,
adErrStillConnecting = 3713,
adErrStillExecuting = 3711,
adErrTreePermissionDenied = 3728,
adErrUnavailable = 3736,
adErrUnsafeOperation = 3716,
adErrURLDoesNotExist = 3727,
adErrURLNamedRowDoesNotExist = 3737,
adErrVolumeNotFound = 3733,
adErrWriteFile = 3004,
adwrnSecurityDialog = 3717,
adwrnSecurityDialogHeader = 3718
}
const enum EventReasonEnum {
adRsnAddNew = 1,
adRsnClose = 9,
adRsnDelete = 2,
adRsnFirstChange = 11,
adRsnMove = 10,
adRsnMoveFirst = 12,
adRsnMoveLast = 15,
adRsnMoveNext = 13,
adRsnMovePrevious = 14,
adRsnRequery = 7,
adRsnResynch = 8,
adRsnUndoAddNew = 5,
adRsnUndoDelete = 6,
adRsnUndoUpdate = 4,
adRsnUpdate = 3
}
const enum EventStatusEnum {
adStatusCancel = 4,
adStatusCantDeny = 3,
adStatusErrorsOccurred = 2,
adStatusOK = 1,
adStatusUnwantedEvent = 5
}
const enum ExecuteOptionEnum {
adAsyncExecute = 16,
adAsyncFetch = 32,
adAsyncFetchNonBlocking = 64,
adExecuteNoRecords = 128,
adExecuteRecord = 2048,
adExecuteStream = 1024,
adOptionUnspecified = -1
}
const enum FieldAttributeEnum {
adFldCacheDeferred = 4096,
adFldFixed = 16,
adFldIsChapter = 8192,
adFldIsCollection = 262144,
adFldIsDefaultStream = 131072,
adFldIsNullable = 32,
adFldIsRowURL = 65536,
adFldKeyColumn = 32768,
adFldLong = 128,
adFldMayBeNull = 64,
adFldMayDefer = 2,
adFldNegativeScale = 16384,
adFldRowID = 256,
adFldRowVersion = 512,
adFldUnknownUpdatable = 8,
adFldUnspecified = -1,
adFldUpdatable = 4
}
const enum FieldEnum {
adDefaultStream = -1,
adRecordURL = -2
}
const enum FieldStatusEnum {
adFieldAlreadyExists = 26,
adFieldBadStatus = 12,
adFieldCannotComplete = 20,
adFieldCannotDeleteSource = 23,
adFieldCantConvertValue = 2,
adFieldCantCreate = 7,
adFieldDataOverflow = 6,
adFieldDefault = 13,
adFieldDoesNotExist = 16,
adFieldIgnore = 15,
adFieldIntegrityViolation = 10,
adFieldInvalidURL = 17,
adFieldIsNull = 3,
adFieldOK = 0,
adFieldOutOfSpace = 22,
adFieldPendingChange = 262144,
adFieldPendingDelete = 131072,
adFieldPendingInsert = 65536,
adFieldPendingUnknown = 524288,
adFieldPendingUnknownDelete = 1048576,
adFieldPermissionDenied = 9,
adFieldReadOnly = 24,
adFieldResourceExists = 19,
adFieldResourceLocked = 18,
adFieldResourceOutOfScope = 25,
adFieldSchemaViolation = 11,
adFieldSignMismatch = 5,
adFieldTruncated = 4,
adFieldUnavailable = 8,
adFieldVolumeNotFound = 21
}
const enum FilterGroupEnum {
adFilterAffectedRecords = 2,
adFilterConflictingRecords = 5,
adFilterFetchedRecords = 3,
adFilterNone = 0,
adFilterPendingRecords = 1,
adFilterPredicate = 4
}
const enum GetRowsOptionEnum {
adGetRowsRest = -1
}
const enum IsolationLevelEnum {
adXactBrowse = 256,
adXactChaos = 16,
adXactCursorStability = 4096,
adXactIsolated = 1048576,
adXactReadCommitted = 4096,
adXactReadUncommitted = 256,
adXactRepeatableRead = 65536,
adXactSerializable = 1048576,
adXactUnspecified = -1
}
const enum LineSeparatorEnum {
adCR = 13,
adCRLF = -1,
adLF = 10
}
const enum LockTypeEnum {
adLockBatchOptimistic = 4,
adLockOptimistic = 3,
adLockPessimistic = 2,
adLockReadOnly = 1,
adLockUnspecified = -1
}
const enum MarshalOptionsEnum {
adMarshalAll = 0,
adMarshalModifiedOnly = 1
}
const enum MoveRecordOptionsEnum {
adMoveAllowEmulation = 4,
adMoveDontUpdateLinks = 2,
adMoveOverWrite = 1,
adMoveUnspecified = -1
}
const enum ObjectStateEnum {
adStateClosed = 0,
adStateConnecting = 2,
adStateExecuting = 4,
adStateFetching = 8,
adStateOpen = 1
}
const enum ParameterAttributesEnum {
adParamLong = 128,
adParamNullable = 64,
adParamSigned = 16
}
const enum ParameterDirectionEnum {
adParamInput = 1,
adParamInputOutput = 3,
adParamOutput = 2,
adParamReturnValue = 4,
adParamUnknown = 0
}
const enum PersistFormatEnum {
adPersistADTG = 0,
adPersistXML = 1
}
const enum PositionEnum {
adPosBOF = -2,
adPosEOF = -3,
adPosUnknown = -1
}
const enum PositionEnum_Param {
adPosBOF = -2,
adPosEOF = -3,
adPosUnknown = -1
}
const enum PropertyAttributesEnum {
adPropNotSupported = 0,
adPropOptional = 2,
adPropRead = 512,
adPropRequired = 1,
adPropWrite = 1024
}
const enum RecordCreateOptionsEnum {
adCreateCollection = 8192,
adCreateNonCollection = 0,
adCreateOverwrite = 67108864,
adCreateStructDoc = -2147483648,
adFailIfNotExists = -1,
adOpenIfExists = 33554432
}
const enum RecordOpenOptionsEnum {
adDelayFetchFields = 32768,
adDelayFetchStream = 16384,
adOpenAsync = 4096,
adOpenExecuteCommand = 65536,
adOpenOutput = 8388608,
adOpenRecordUnspecified = -1,
adOpenSource = 8388608
}
const enum RecordStatusEnum {
adRecCanceled = 256,
adRecCantRelease = 1024,
adRecConcurrencyViolation = 2048,
adRecDBDeleted = 262144,
adRecDeleted = 4,
adRecIntegrityViolation = 4096,
adRecInvalid = 16,
adRecMaxChangesExceeded = 8192,
adRecModified = 2,
adRecMultipleChanges = 64,
adRecNew = 1,
adRecObjectOpen = 16384,
adRecOK = 0,
adRecOutOfMemory = 32768,
adRecPendingChanges = 128,
adRecPermissionDenied = 65536,
adRecSchemaViolation = 131072,
adRecUnmodified = 8
}
const enum RecordTypeEnum {
adCollectionRecord = 1,
adSimpleRecord = 0,
adStructDoc = 2
}
const enum ResyncEnum {
adResyncAllValues = 2,
adResyncUnderlyingValues = 1
}
const enum SaveOptionsEnum {
adSaveCreateNotExist = 1,
adSaveCreateOverWrite = 2
}
const enum SchemaEnum {
adSchemaActions = 41,
adSchemaAsserts = 0,
adSchemaCatalogs = 1,
adSchemaCharacterSets = 2,
adSchemaCheckConstraints = 5,
adSchemaCollations = 3,
adSchemaColumnPrivileges = 13,
adSchemaColumns = 4,
adSchemaColumnsDomainUsage = 11,
adSchemaCommands = 42,
adSchemaConstraintColumnUsage = 6,
adSchemaConstraintTableUsage = 7,
adSchemaCubes = 32,
adSchemaDBInfoKeywords = 30,
adSchemaDBInfoLiterals = 31,
adSchemaDimensions = 33,
adSchemaForeignKeys = 27,
adSchemaFunctions = 40,
adSchemaHierarchies = 34,
adSchemaIndexes = 12,
adSchemaKeyColumnUsage = 8,
adSchemaLevels = 35,
adSchemaMeasures = 36,
adSchemaMembers = 38,
adSchemaPrimaryKeys = 28,
adSchemaProcedureColumns = 29,
adSchemaProcedureParameters = 26,
adSchemaProcedures = 16,
adSchemaProperties = 37,
adSchemaProviderSpecific = -1,
adSchemaProviderTypes = 22,
adSchemaReferentialConstraints = 9,
adSchemaReferentialContraints = 9,
adSchemaSchemata = 17,
adSchemaSets = 43,
adSchemaSQLLanguages = 18,
adSchemaStatistics = 19,
adSchemaTableConstraints = 10,
adSchemaTablePrivileges = 14,
adSchemaTables = 20,
adSchemaTranslations = 21,
adSchemaTrustees = 39,
adSchemaUsagePrivileges = 15,
adSchemaViewColumnUsage = 24,
adSchemaViews = 23,
adSchemaViewTableUsage = 25
}
const enum SearchDirection {
adSearchBackward = -1,
adSearchForward = 1
}
const enum SearchDirectionEnum {
adSearchBackward = -1,
adSearchForward = 1
}
const enum SeekEnum {
adSeekAfter = 8,
adSeekAfterEQ = 4,
adSeekBefore = 32,
adSeekBeforeEQ = 16,
adSeekFirstEQ = 1,
adSeekLastEQ = 2
}
const enum StreamOpenOptionsEnum {
adOpenStreamAsync = 1,
adOpenStreamFromRecord = 4,
adOpenStreamUnspecified = -1
}
const enum StreamReadEnum {
adReadAll = -1,
adReadLine = -2
}
const enum StreamTypeEnum {
adTypeBinary = 1,
adTypeText = 2
}
const enum StreamWriteEnum {
adWriteChar = 0,
adWriteLine = 1,
stWriteChar = 0,
stWriteLine = 1
}
const enum StringFormatEnum {
adClipString = 2
}
const enum XactAttributeEnum {
adXactAbortRetaining = 262144,
adXactAsyncPhaseOne = 524288,
adXactCommitRetaining = 131072,
adXactSyncPhaseOne = 1048576
}
//Interfaces
interface Command {
ActiveConnection: Connection;
Cancel: () => void;
CommandStream: any /*VT_UNKNOWN*/;
CommandText: string;
CommandTimeout: number;
CommandType: CommandTypeEnum;
CreateParameter: (Name?: string, Type?: DataTypeEnum, Direction?: ParameterDirectionEnum, Size?: number, Value?: any) => Parameter;
Dialect: string;
Execute: (RecordsAffected?: any, Parameters?: any, Options?: number) => Recordset;
Name: string;
NamedParameters: boolean;
Parameters: Parameters;
Prepared: boolean;
Properties: Properties;
State: number;
}
interface Connection {
Attributes: number;
BeginTrans: () => number;
Cancel: () => void;
Close: () => void;
CommandTimeout: number;
CommitTrans: () => void;
ConnectionString: string;
ConnectionTimeout: number;
CursorLocation: CursorLocationEnum;
DefaultDatabase: string;
Errors: Errors;
Execute: (CommandText: string, RecordsAffected: any, Options?: number) => Recordset;
IsolationLevel: IsolationLevelEnum;
Mode: ConnectModeEnum;
Open: (ConnectionString?: string, UserID?: string, Password?: string, Options?: number) => void;
OpenSchema: (Schema: SchemaEnum, Restrictions?: any, SchemaID?: any) => Recordset;
Properties: Properties;
Provider: string;
RollbackTrans: () => void;
State: number;
Version: string;
}
interface Error {
Description: string;
HelpContext: number;
HelpFile: string;
NativeError: number;
Number: number;
Source: string;
SQLState: string;
}
interface Errors {
Clear: () => void;
Count: number;
Item: (Index: any) => Error;
Refresh: () => void;
}
interface Field {
ActualSize: number;
AppendChunk: (Data: any) => void;
Attributes: number;
DataFormat: any /*VT_UNKNOWN*/;
DefinedSize: number;
GetChunk: (Length: number) => any;
Name: string;
NumericScale: number;
OriginalValue: any;
Precision: number;
Properties: Properties;
Status: number;
Type: DataTypeEnum;
UnderlyingValue: any;
Value: any;
}
interface Fields {
_Append: (Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum) => void;
Append: (Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum, FieldValue?: any) => void;
CancelUpdate: () => void;
Count: number;
Delete: (Index: any) => void;
Item: (Index: any) => Field;
Refresh: () => void;
Resync: (ResyncValues?: ResyncEnum) => void;
Update: () => void;
}
interface Parameter {
AppendChunk: (Val: any) => void;
Attributes: number;
Direction: ParameterDirectionEnum;
Name: string;
NumericScale: number;
Precision: number;
Properties: Properties;
Size: number;
Type: DataTypeEnum;
Value: any;
}
interface Parameters {
Append: (Object: any /*VT_DISPATCH*/) => void;
Count: number;
Delete: (Index: any) => void;
Item: (Index: any) => Parameter;
Refresh: () => void;
}
interface Properties {
Count: number;
Item: (Index: any) => Property;
Refresh: () => void;
}
interface Property {
Attributes: number;
Name: string;
Type: DataTypeEnum;
Value: any;
}
interface Record {
ActiveConnection: any;
Cancel: () => void;
Close: () => void;
CopyRecord: (Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: CopyRecordOptionsEnum, Async?: boolean) => string;
DeleteRecord: (Source?: string, Async?: boolean) => void;
Fields: Fields;
GetChildren: () => Recordset;
Mode: ConnectModeEnum;
MoveRecord: (Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: MoveRecordOptionsEnum, Async?: boolean) => string;
Open: (Source: any, ActiveConnection: any, Mode?: ConnectModeEnum, CreateOptions?: RecordCreateOptionsEnum, Options?: RecordOpenOptionsEnum, UserName?: string, Password?: string) => void;
ParentURL: string;
Properties: Properties;
RecordType: RecordTypeEnum;
Source: any;
State: ObjectStateEnum;
}
interface Recordset {
_xClone: () => Recordset;
_xResync: (AffectRecords?: AffectEnum) => void;
_xSave: (FileName?: string, PersistFormat?: PersistFormatEnum) => void;
AbsolutePage: PositionEnum;
AbsolutePosition: PositionEnum;
ActiveCommand: any /*VT_DISPATCH*/;
ActiveConnection: any /*VT_DISPATCH*/;
AddNew: (FieldList?: any, Values?: any) => void;
BOF: boolean;
Bookmark: any;
CacheSize: number;
Cancel: () => void;
CancelBatch: (AffectRecords?: AffectEnum) => void;
CancelUpdate: () => void;
Clone: (LockType?: LockTypeEnum) => Recordset;
Close: () => void;
Collect: (Index: any) => any; //Also has setter with parameters
CompareBookmarks: (Bookmark1: any, Bookmark2: any) => CompareEnum;
CursorLocation: CursorLocationEnum;
CursorType: CursorTypeEnum;
DataMember: string;
DataSource: any /*VT_UNKNOWN*/;
Delete: (AffectRecords?: AffectEnum) => void;
EditMode: EditModeEnum;
EOF: boolean;
Fields: Fields;
Filter: any;
Find: (Criteria: string, SkipRecords?: number, SearchDirection?: SearchDirectionEnum, Start?: any) => void;
GetRows: (Rows?: number, Start?: any, Fields?: any) => any;
GetString: (StringFormat?: StringFormatEnum, NumRows?: number, ColumnDelimeter?: string, RowDelimeter?: string, NullExpr?: string) => string;
Index: string;
LockType: LockTypeEnum;
MarshalOptions: MarshalOptionsEnum;
MaxRecords: number;
Move: (NumRecords: number, Start?: any) => void;
MoveFirst: () => void;
MoveLast: () => void;
MoveNext: () => void;
MovePrevious: () => void;
NextRecordset: (RecordsAffected?: any) => Recordset;
Open: (Source: any, ActiveConnection: any, CursorType?: CursorTypeEnum, LockType?: LockTypeEnum, Options?: number) => void;
PageCount: number;
PageSize: number;
Properties: Properties;
RecordCount: number;
Requery: (Options?: number) => void;
Resync: (AffectRecords?: AffectEnum, ResyncValues?: ResyncEnum) => void;
Save: (Destination: any, PersistFormat?: PersistFormatEnum) => void;
Seek: (KeyValues: any, SeekOption?: SeekEnum) => void;
Sort: string;
Source: any /*VT_DISPATCH*/;
State: number;
Status: number;
StayInSync: boolean;
Supports: (CursorOptions: CursorOptionEnum) => boolean;
Update: (Fields?: any, Values?: any) => void;
UpdateBatch: (AffectRecords?: AffectEnum) => void;
}
interface Stream {
Cancel: () => void;
Charset: string;
Close: () => void;
CopyTo: (DestStream: Stream, CharNumber?: number) => void;
EOS: boolean;
Flush: () => void;
LineSeparator: LineSeparatorEnum;
LoadFromFile: (FileName: string) => void;
Mode: ConnectModeEnum;
Open: (Source: any, Mode?: ConnectModeEnum, Options?: StreamOpenOptionsEnum, UserName?: string, Password?: string) => void;
Position: number;
Read: (NumBytes?: number) => any;
ReadText: (NumChars?: number) => string;
SaveToFile: (FileName: string, Options?: SaveOptionsEnum) => void;
SetEOS: () => void;
Size: number;
SkipLine: () => void;
State: ObjectStateEnum;
Type: StreamTypeEnum;
Write: (Buffer: any) => void;
WriteText: (Data: string, Options?: StreamWriteEnum) => void;
}
}
interface ActiveXObject {
new (progID: 'ADODB.Connection'): ADODB.Connection;
new (progID: 'ADODB.Record'): ADODB.Record;
new (progID: 'ADODB.Stream'): ADODB.Stream;
new (progID: 'ADODB.Command'): ADODB.Command;
new (progID: 'ADODB.Recordset'): ADODB.Recordset;
new (progID: 'ADODB.Parameter'): ADODB.Parameter;
}
-24
View File
@@ -1,24 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-data-objects-tests.ts"
]
}
@@ -0,0 +1,171 @@
(() => {
// https://wiki.openoffice.org/wiki/Documentation/DevGuide/ProUNO/Bridge/Automation_Bridge
// This is a JScript example
// The service manager is always the starting point
// If there is no office running then an office is started up
const serviceManager = new ActiveXObject('com.sun.star.ServiceManager');
// Create the CoreReflection service that is later used to create structs
const coreReflection = serviceManager.createInstance("com.sun.star.reflection.CoreReflection");
// Create the Desktop
const desktop = serviceManager.defaultContext.getByName('/singleton/com.sun.star.frame.theDesktop');
// Open a new empty writer document
const args: any[] = [];
const document = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, args); // as com.sun.star.text.TextDocument;
// Create a text object
const text = document.Text;
// Create a cursor object
const cursor = (text.createTextCursor() as any) as com.sun.star.text.TextCursor;
// Inserting some Text
text.insertString(cursor, "The first line in the newly created text document.\n", false);
// Inserting a second line
text.insertString(cursor, "Now we're in the second line", false);
// Create instance of a text table with 4 columns and 4 rows
const table = document.createInstance("com.sun.star.text.TextTable");
table.initialize(4, 4);
// Insert the table
text.insertTextContent(cursor, table, false);
// Get first row
const rows = table.Rows;
const row = rows.getByIndex(0) as com.sun.star.table.TableRow;
// Set the table background color
((table as any) as com.sun.star.beans.XPropertySet).setPropertyValue("BackTransparent", false);
((table as any) as com.sun.star.beans.XPropertySet).setPropertyValue("BackColor", 13421823);
// Set a different background color for the first row
row.setPropertyValue("BackTransparent", false);
row.setPropertyValue("BackColor", 6710932);
// Fill the first table row
insertIntoCell("A1", "FirstColumn", table); // insertIntoCell is a helper function, see below
insertIntoCell("B1", "SecondColumn", table);
insertIntoCell("C1", "ThirdColumn", table);
insertIntoCell("D1", "SUM", table);
table.getCellByName("A2").setValue(22.5);
table.getCellByName("B2").setValue(5615.3);
table.getCellByName("C2").setValue(-2315.7);
table.getCellByName("D2").setFormula("sum ");
table.getCellByName("A3").setValue(21.5);
table.getCellByName("B3").setValue(615.3);
table.getCellByName("C3").setValue(- 315.7);
table.getCellByName("D3").setFormula("sum ");
table.getCellByName("A4").setValue(121.5);
table.getCellByName("B4").setValue(-615.3);
table.getCellByName("C4").setValue(415.7);
table.getCellByName("D4").setFormula("sum ");
// Change the CharColor and add a Shadow
cursor.setPropertyValue("CharColor", 255);
cursor.setPropertyValue("CharShadowed", true);
// Create a paragraph break
// The second argument is a com::sun::star::text::ControlCharacter::PARAGRAPH_BREAK constant
text.insertControlCharacter(cursor, 0, false);
// Inserting colored Text.
text.insertString(cursor, " This is a colored Text - blue with shadow\n", false);
// Create a paragraph break ( ControlCharacter::PARAGRAPH_BREAK).
text.insertControlCharacter(cursor, 0, false);
// Create a TextFrame.
const textFrame = document.createInstance("com.sun.star.text.TextFrame");
// Create a Size struct.
const size = createStruct("com.sun.star.awt.Size"); // helper function, see below
size.Width = 15000;
size.Height = 400;
textFrame.setSize(size);
// TextContentAnchorType.AS_CHARACTER = 1
textFrame.setPropertyValue("AnchorType", com.sun.star.text.TextContentAnchorType.AS_CHARACTER);
// insert the frame
text.insertTextContent(cursor, textFrame, false);
// Get the text object of the frame
const objFrameText = textFrame.Text;
// Create a cursor object
const objFrameTextCursor = objFrameText.createTextCursor();
// Inserting some Text
objFrameText.insertString(objFrameTextCursor, "The first line in the newly created text frame.", false);
objFrameText.insertString(objFrameTextCursor, "\nWith this second line the height of the frame raises.", false);
// Create a paragraph break
// The second argument is a com::sun::star::text::ControlCharacter::PARAGRAPH_BREAK constant
objFrameText.insertControlCharacter(cursor, 0, false);
// Change the CharColor and add a Shadow
cursor.setPropertyValue("CharColor", 65536);
cursor.setPropertyValue("CharShadowed", false);
// Insert another string
text.insertString(cursor, " That's all for now !!", false);
function insertIntoCell(strCellName: string, strText: string, objTable: com.sun.star.text.TextTable) {
const objCellText = objTable.getCellByName(strCellName) as com.sun.star.table.Cell;
const objCellCursor = (objCellText.createTextCursor() as any) as com.sun.star.text.TextCursor;
objCellCursor.setPropertyValue("CharColor", 16777215);
objCellText.insertString(objCellCursor, strText, false);
}
function createStruct<K extends keyof LibreOffice.StructNameMap>(strTypeName: K): LibreOffice.StructNameMap[K] {
const classSize = coreReflection.forName(strTypeName);
const aStruct: [LibreOffice.StructNameMap[K]] = [] as any;
classSize.createObject(aStruct);
return aStruct[0];
}
})();
(() => {
// This shows some specific features of the Automation bridge
const serviceManager = new ActiveXObject('com.sun.star.ServiceManager');
// singleton access
const desktop = serviceManager.defaultContext.getByName('/singleton/com.sun.star.frame.theDesktop');
// defaultContext property implements XNameAccess
// sequence is returned as a safearray
const elementNames = new VBArray(serviceManager.defaultContext.getElementNames()).toArray().join('\n');
WScript.Echo(elementNames);
// get/set methods exposed as properties -- getText => Text, getViewData/setViewData => ViewData
const document = desktop.loadComponentFromURL("private:factory/swriter", "_blank", 0, []);
const viewData = document.ViewData;
WScript.Echo(viewData.Count);
const text = document.Text;
WScript.Echo(text);
})();
(() => {
// Forces use of tuple type for out parameters
// Instantiating via reflection
const serviceManager = new ActiveXObject('com.sun.star.ServiceManager');
const coreReflection = serviceManager.defaultContext.getByName('/singleton/com.sun.star.reflection.theCoreReflection');
const classInfo = coreReflection.forName('com.sun.star.accessibility.Accessible');
const accessible: [com.sun.star.accessibility.XAccessible] = [] as any;
classInfo.createObject(accessible);
accessible[0].acquire();
// Get a struct via Bridge_GetStruct
const size = serviceManager.Bridge_GetStruct('com.sun.star.awt.Size');
size.Height = 110;
size.Width = 120;
})();
+105882
View File
File diff suppressed because it is too large Load Diff
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-libreoffice-tests.ts"
]
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "dtslint/dt.json",
"rules": {
"interface-name": [false],
"ban-types": false,
"no-unnecessary-qualifier": false
}
}
@@ -1,64 +0,0 @@
//source -- https://msdn.microsoft.com/en-us/library/ebkhfaaz.aspx
//Generates a string describing the drive type of a given Drive object.
var 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';
}
};
//Generates a string describing the attributes of a file or folder.
var showFileAttributes = (file: Scripting.File) => {
var attr = file.Attributes;
if (attr === 0) {
return 'Normal';
}
var 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
var showFreeSpace = (drvPath: string) => {
var fso = new ActiveXObject('Scripting.FileSystemObject');
var d = fso.GetDrive(fso.GetDriveName(drvPath));
var 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
var getALine = (filespec: string) => {
var fso = new ActiveXObject('Scripting.FileSystemObject');
var file = fso.OpenTextFile(filespec, Scripting.IOMode.ForReading, false);
var s = '';
while (!file.AtEndOfLine) {
s += file.Read(1);
}
file.Close();
return (s);
};
-205
View File
@@ -1,205 +0,0 @@
// Type definitions for Microsoft Scripting Runtime
// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Scripting {
//Enums
const enum CompareMethod {
BinaryCompare = 0,
DatabaseCompare = 2,
TextCompare = 1
}
const enum DriveTypeConst {
CDRom = 4,
Fixed = 2,
RamDisk = 5,
Remote = 3,
Removable = 1,
UnknownType = 0
}
const enum FileAttribute {
Alias = 1024,
Archive = 32,
Compressed = 2048,
Directory = 16,
Hidden = 2,
Normal = 0,
ReadOnly = 1,
System = 4,
Volume = 8
}
const enum IOMode {
ForAppending = 8,
ForReading = 1,
ForWriting = 2
}
const enum SpecialFolderConst {
SystemFolder = 1,
TemporaryFolder = 2,
WindowsFolder = 0
}
const enum StandardStreamTypes {
StdErr = 2,
StdIn = 0,
StdOut = 1
}
const enum Tristate {
TristateFalse = 0,
TristateMixed = -2,
TristateTrue = -1,
TristateUseDefault = -2
}
//Interfaces
interface Dictionary {
Add: (Key: any, Item: any) => void;
CompareMode: CompareMethod;
Count: number;
Exists: (Key: any) => boolean;
HashVal: (Key: any) => any;
Item: (Key: any) => any; //Also has setter with parameters
Items: () => any;
Key: (Key: any) => any;
Keys: () => any;
Remove: (Key: any) => void;
RemoveAll: () => void;
}
interface Drive {
AvailableSpace: any;
DriveLetter: string;
DriveType: DriveTypeConst;
FileSystem: string;
FreeSpace: any;
IsReady: boolean;
Path: string;
RootFolder: Folder;
SerialNumber: number;
ShareName: string;
TotalSize: any;
VolumeName: string;
}
interface Drives {
Count: number;
Item: (Key: any) => Drive;
}
interface Encoder {
EncodeScriptFile: (szExt: string, bstrStreamIn: string, cFlags: number, bstrDefaultLang: string) => string;
}
interface File {
Attributes: FileAttribute;
Copy: (Destination: string, OverWriteFiles?: boolean) => void;
DateCreated: VarDate;
DateLastAccessed: VarDate;
DateLastModified: VarDate;
Delete: (Force?: boolean) => void;
Drive: Drive;
Move: (Destination: string) => void;
Name: string;
OpenAsTextStream: (IOMode?: IOMode, Format?: Tristate) => TextStream;
ParentFolder: Folder;
Path: string;
ShortName: string;
ShortPath: string;
Size: any;
Type: string;
}
interface Files {
Count: number;
Item: (Key: any) => File;
}
interface FileSystemObject {
BuildPath: (Path: string, Name: string) => string;
CopyFile: (Source: string, Destination: string, OverWriteFiles?: boolean) => void;
CopyFolder: (Source: string, Destination: string, OverWriteFiles?: boolean) => void;
CreateFolder: (Path: string) => Folder;
CreateTextFile: (FileName: string, Overwrite?: boolean, Unicode?: boolean) => TextStream;
DeleteFile: (FileSpec: string, Force?: boolean) => void;
DeleteFolder: (FolderSpec: string, Force?: boolean) => void;
DriveExists: (DriveSpec: string) => boolean;
Drives: Drives;
FileExists: (FileSpec: string) => boolean;
FolderExists: (FolderSpec: string) => boolean;
GetAbsolutePathName: (Path: string) => string;
GetBaseName: (Path: string) => string;
GetDrive: (DriveSpec: string) => Drive;
GetDriveName: (Path: string) => string;
GetExtensionName: (Path: string) => string;
GetFile: (FilePath: string) => File;
GetFileName: (Path: string) => string;
GetFileVersion: (FileName: string) => string;
GetFolder: (FolderPath: string) => Folder;
GetParentFolderName: (Path: string) => string;
GetSpecialFolder: (SpecialFolder: SpecialFolderConst) => Folder;
GetStandardStream: (StandardStreamType: StandardStreamTypes, Unicode?: boolean) => TextStream;
GetTempName: () => string;
MoveFile: (Source: string, Destination: string) => void;
MoveFolder: (Source: string, Destination: string) => void;
OpenTextFile: (FileName: string, IOMode?: IOMode, Create?: boolean, Format?: Tristate) => TextStream;
}
interface Folder {
Attributes: FileAttribute;
Copy: (Destination: string, OverWriteFiles?: boolean) => void;
CreateTextFile: (FileName: string, Overwrite?: boolean, Unicode?: boolean) => TextStream;
DateCreated: VarDate;
DateLastAccessed: VarDate;
DateLastModified: VarDate;
Delete: (Force?: boolean) => void;
Drive: Drive;
Files: Files;
IsRootFolder: boolean;
Move: (Destination: string) => void;
Name: string;
ParentFolder: Folder;
Path: string;
ShortName: string;
ShortPath: string;
Size: any;
SubFolders: Folders;
Type: string;
}
interface Folders {
Add: (Name: string) => Folder;
Count: number;
Item: (Key: any) => Folder;
}
interface TextStream {
AtEndOfLine: boolean;
AtEndOfStream: boolean;
Close: () => void;
Column: number;
Line: number;
Read: (Characters: number) => string;
ReadAll: () => string;
ReadLine: () => string;
Skip: (Characters: number) => void;
SkipLine: () => void;
Write: (Text: string) => void;
WriteBlankLines: (Lines: number) => void;
WriteLine: (Text?: string) => void;
}
}
interface ActiveXObject {
new (progID: 'Scripting.Dictionary'): Scripting.Dictionary;
new (progID: 'Scripting.FileSystemObject'): Scripting.FileSystemObject;
new (progID: 'Scripting.Encoder'): Scripting.Encoder;
}
@@ -1,24 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-scripting-runtime-tests.ts"
]
}
@@ -0,0 +1,60 @@
// source -- https://msdn.microsoft.com/en-us/library/ebkhfaaz.aspx
// 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';
}
}
// 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 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);
}
// 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);
let s = '';
while (!file.AtEndOfLine) {
s += file.Read(1);
}
file.Close();
return (s);
}
+465
View File
@@ -0,0 +1,465 @@
// Type definitions for Microsoft Scripting Runtime 1.0
// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Scripting {
const enum CompareMethod {
BinaryCompare = 0,
DatabaseCompare = 2,
TextCompare = 1
}
const enum DriveTypeConst {
CDRom = 4,
Fixed = 2,
RamDisk = 5,
Remote = 3,
Removable = 1,
UnknownType = 0
}
const enum FileAttribute {
Alias = 1024,
Archive = 32,
Compressed = 2048,
Directory = 16,
Hidden = 2,
Normal = 0,
ReadOnly = 1,
System = 4,
Volume = 8
}
const enum IOMode {
ForAppending = 8,
ForReading = 1,
ForWriting = 2
}
const enum SpecialFolderConst {
SystemFolder = 1,
TemporaryFolder = 2,
WindowsFolder = 0
}
const enum StandardStreamTypes {
StdErr = 2,
StdIn = 0,
StdOut = 1
}
const enum Tristate {
TristateFalse = 0,
TristateMixed = -2,
TristateTrue = -1,
TristateUseDefault = -2
}
/** Scripting.Dictionary */
interface Dictionary {
/** Add a new key and item to the dictionary. */
Add(Key: any, Item: any): void;
/** Set or get the string comparison method. */
CompareMode: CompareMethod;
/** Get the number of items in the dictionary. */
readonly Count: number;
/** Determine if a given key is in the dictionary. */
Exists(Key: any): boolean;
HashVal(Key: any): any;
/** Set or get the item for a given key */
Item(Key: any): any;
/** Get an array containing all items in the dictionary. */
Items(): any;
/** Change a key to a different key. */
Key(Key: any): any;
/** Get an array containing all keys in the dictionary. */
Keys(): any;
/** Remove a given key from the dictionary. */
Remove(Key: any): void;
/** Remove all information from the dictionary. */
RemoveAll(): void;
}
/** Drive Object */
interface Drive {
/** Get available space */
readonly AvailableSpace: any;
/** Drive letter */
readonly DriveLetter: string;
/** Drive type */
readonly DriveType: DriveTypeConst;
/** Filesystem type */
readonly FileSystem: string;
/** Get drive free space */
readonly FreeSpace: any;
/** Check if disk is available */
readonly IsReady: boolean;
/** Path */
readonly Path: string;
/** Root folder */
readonly RootFolder: Folder;
/** Serial number */
readonly SerialNumber: number;
/** Share name */
readonly ShareName: string;
/** Get total drive size */
readonly TotalSize: any;
/** Name of volume */
VolumeName: string;
}
/** Collection of drives associated with drive letters */
interface Drives {
/** Number of drives */
readonly Count: number;
/** Get drive */
Item(Key: any): 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;
}
/** File object */
interface File {
/** File attributes */
Attributes: FileAttribute;
/**
* Copy this file
* @param boolean [OverWriteFiles=true]
*/
Copy(Destination: string, OverWriteFiles?: boolean): void;
/** Date file was created */
readonly DateCreated: VarDate;
/** Date file was last accessed */
readonly DateLastAccessed: VarDate;
/** Date file was last modified */
readonly DateLastModified: VarDate;
/**
* Delete this file
* @param boolean [Force=false]
*/
Delete(Force?: boolean): void;
/** Get drive that contains file */
readonly Drive: Drive;
/** Move this file */
Move(Destination: string): void;
/** Get name of file */
Name: string;
/**
* Open a file as a TextStream
* @param Scripting.IOMode [IOMode=1]
* @param Scripting.Tristate [Format=0]
*/
OpenAsTextStream(IOMode?: IOMode, Format?: Tristate): TextStream;
/** Get folder that contains file */
readonly ParentFolder: Folder;
/** Path to the file */
readonly Path: string;
/** Short name */
readonly ShortName: string;
/** Short path */
readonly ShortPath: string;
/** File size */
readonly Size: any;
/** Type description */
readonly Type: string;
}
/** Collection of files in a folder */
interface Files {
/** Number of folders */
readonly Count: number;
/** Get file */
Item(Key: any): File;
}
/** FileSystem Object */
interface FileSystemObject {
/** Generate a path from an existing path and a name */
BuildPath(Path: string, Name: string): string;
/**
* Copy a file
* @param boolean [OverWriteFiles=true]
*/
CopyFile(Source: string, Destination: string, OverWriteFiles?: boolean): void;
/**
* Copy a folder
* @param boolean [OverWriteFiles=true]
*/
CopyFolder(Source: string, Destination: string, OverWriteFiles?: boolean): void;
/** Create a folder */
CreateFolder(Path: string): Folder;
/**
* Create a file as a TextStream
* @param boolean [Overwrite=true]
* @param boolean [Unicode=false]
*/
CreateTextFile(FileName: string, Overwrite?: boolean, Unicode?: boolean): TextStream;
/**
* Delete a file
* @param boolean [Force=false]
*/
DeleteFile(FileSpec: string, Force?: boolean): void;
/**
* Delete a folder
* @param boolean [Force=false]
*/
DeleteFolder(FolderSpec: string, Force?: boolean): void;
/** Check if a drive or a share exists */
DriveExists(DriveSpec: string): boolean;
/** Get drives collection */
readonly Drives: Drives;
/** Check if a file exists */
FileExists(FileSpec: string): boolean;
/** Check if a path exists */
FolderExists(FolderSpec: string): boolean;
/** Return the canonical representation of the path */
GetAbsolutePathName(Path: string): string;
/** Return base name from a path */
GetBaseName(Path: string): string;
/** Get drive or UNC share */
GetDrive(DriveSpec: string): Drive;
/** Return drive from a path */
GetDriveName(Path: string): string;
/** Return extension from path */
GetExtensionName(Path: string): string;
/** Get file */
GetFile(FilePath: string): File;
/** Return the file name from a path */
GetFileName(Path: string): string;
/** Retrieve the file version of the specified file into a string */
GetFileVersion(FileName: string): string;
/** Get folder */
GetFolder(FolderPath: string): Folder;
/** Return path to the parent folder */
GetParentFolderName(Path: string): string;
/** Get location of various system folders */
GetSpecialFolder(SpecialFolder: SpecialFolderConst): Folder;
/**
* Retrieve the standard input, output or error stream
* @param boolean [Unicode=false]
*/
GetStandardStream(StandardStreamType: StandardStreamTypes, Unicode?: boolean): TextStream;
/** Generate name that can be used to name a temporary file */
GetTempName(): string;
/** Move a file */
MoveFile(Source: string, Destination: string): void;
/** Move a folder */
MoveFolder(Source: string, Destination: string): void;
/**
* Open a file as a TextStream
* @param Scripting.IOMode [IOMode=1]
* @param boolean [Create=false]
* @param Scripting.Tristate [Format=0]
*/
OpenTextFile(FileName: string, IOMode?: IOMode, Create?: boolean, Format?: Tristate): TextStream;
}
/** Folder object */
interface Folder {
/** Folder attributes */
Attributes: FileAttribute;
/**
* Copy this folder
* @param boolean [OverWriteFiles=true]
*/
Copy(Destination: string, OverWriteFiles?: boolean): void;
/**
* Create a file as a TextStream
* @param boolean [Overwrite=true]
* @param boolean [Unicode=false]
*/
CreateTextFile(FileName: string, Overwrite?: boolean, Unicode?: boolean): TextStream;
/** Date folder was created */
readonly DateCreated: VarDate;
/** Date folder was last accessed */
readonly DateLastAccessed: VarDate;
/** Date folder was last modified */
readonly DateLastModified: VarDate;
/**
* Delete this folder
* @param boolean [Force=false]
*/
Delete(Force?: boolean): void;
/** Get drive that contains folder */
readonly Drive: Drive;
/** Get files collection */
readonly Files: Files;
/** True if folder is root */
readonly IsRootFolder: boolean;
/** Move this folder */
Move(Destination: string): void;
/** Get name of folder */
Name: string;
/** Get parent folder */
readonly ParentFolder: Folder;
/** Path to folder */
readonly Path: string;
/** Short name */
readonly ShortName: string;
/** Short path */
readonly ShortPath: string;
/** Sum of files and subfolders */
readonly Size: any;
/** Get folders collection */
readonly SubFolders: Folders;
/** Type description */
readonly Type: string;
}
/** Collection of subfolders in a folder */
interface Folders {
/** Create a new folder */
Add(Name: string): Folder;
/** Number of folders */
readonly Count: number;
/** Get folder */
Item(Key: any): Folder;
}
/** TextStream object */
interface TextStream {
/** Is the current position at the end of a line? */
readonly AtEndOfLine: boolean;
/** Is the current position at the end of the stream? */
readonly AtEndOfStream: boolean;
/** Close a text stream */
Close(): void;
/** Current column number */
readonly Column: number;
/** Current line number */
readonly Line: number;
/** Read a specific number of characters into a string */
Read(Characters: number): string;
/** Read the entire stream into a string */
ReadAll(): string;
/** Read an entire line into a string */
ReadLine(): string;
/** Skip a specific number of characters */
Skip(Characters: number): void;
/** Skip a line */
SkipLine(): void;
/** Write a string to the stream */
Write(Text: string): void;
/** Write a number of blank lines to the stream */
WriteBlankLines(Lines: number): void;
/**
* Write a string and an end of line to the stream
* @param string [Text='']
*/
WriteLine(Text?: string): void;
}
}
interface ActiveXObject {
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;
}
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-scripting-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+79
View File
@@ -0,0 +1,79 @@
// source -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms630826(v=vs.85).aspx
// Convert a file
let commonDialog = new ActiveXObject('WIA.CommonDialog');
let img = commonDialog.ShowAcquireImage();
// 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})`;
}
}
}
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: ';
} 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 += ']';
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);
}
+759
View File
@@ -0,0 +1,759 @@
// Type definitions for Windows Image Acquisition 2.0
// 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
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 {
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}'
}*/
/** 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 {
wiaEventDeviceConnected = '{A28BBADE-64B6-11D2-A231-00C04FA31809}',
wiaEventDeviceDisconnected = '{143E4E83-6497-11D2-A231-00C04FA31809}',
wiaEventItemCreated = '{4C8F4EF5-E14F-11D2-B326-00C04F68CE61}',
wiaEventItemDeleted = '{1D22A559-E14F-11D2-B326-00C04F68CE61}',
wiaEventScanEmailImage = '{C686DCEE-54F2-419E-9A27-2FC7F2E98F9E}',
wiaEventScanFaxImage = '{C00EB793-8C6E-11D2-977A-0000F87A926F}',
wiaEventScanFilmImage = '{9B2B662C-6185-438C-B68B-E39EE25E71CB}',
wiaEventScanImage = '{A6C5A715-8C6E-11D2-977A-0000F87A926F}',
wiaEventScanImage2 = '{FC4767C1-C8B3-48A2-9CFA-2E90CB3D3590}',
wiaEventScanImage3 = '{154E27BE-B617-4653-ACC5-0FD7BD4C65CE}',
wiaEventScanImage4 = '{A65B704A-7F3C-4447-A75D-8A26DFCA1FDF}',
wiaEventScanOCRImage = '{9D095B89-37D6-4877-AFED-62A297DC6DBE}',
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 {
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}'
}*/
/** Miscellaneous string constants */
// uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017)
/*const enum Miscellaneous {
wiaAnyDeviceID = '*',
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.
*/
const enum WiaDeviceType {
CameraDeviceType = 2,
ScannerDeviceType = 1,
UnspecifiedDeviceType = 0,
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.
*/
const enum WiaEventFlag {
ActionEvent = 2,
NotificationEvent = 1
}
/** The WiaImageBias enumeration helps specify what type of data the image is intended to represent. */
const enum WiaImageBias {
MaximizeQuality = 131072,
MinimizeSize = 65536
}
/** The WiaImageIntent enumeration helps specify what type of data the image is intended to represent. */
const enum WiaImageIntent {
ColorIntent = 1,
GrayscaleIntent = 2,
TextIntent = 4,
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.
*/
const enum WiaImagePropertyType {
ByteImagePropertyType = 1001,
LongImagePropertyType = 1004,
RationalImagePropertyType = 1006,
StringImagePropertyType = 1002,
UndefinedImagePropertyType = 1000,
UnsignedIntegerImagePropertyType = 1003,
UnsignedLongImagePropertyType = 1005,
UnsignedRationalImagePropertyType = 1007,
VectorOfBytesImagePropertyType = 1101,
VectorOfLongsImagePropertyType = 1103,
VectorOfRationalsImagePropertyType = 1105,
VectorOfUndefinedImagePropertyType = 1100,
VectorOfUnsignedIntegersImagePropertyType = 1102,
VectorOfUnsignedLongsImagePropertyType = 1104,
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.
*/
const enum WiaItemFlag {
AnalyzeItemFlag = 16,
AudioItemFlag = 32,
BurstItemFlag = 2048,
DeletedItemFlag = 128,
DeviceItemFlag = 64,
DisconnectedItemFlag = 256,
FileItemFlag = 2,
FolderItemFlag = 4,
FreeItemFlag = 0,
GeneratedItemFlag = 16384,
HasAttachmentsItemFlag = 32768,
HPanoramaItemFlag = 512,
ImageItemFlag = 1,
RemovedItemFlag = -2147483648,
RootItemFlag = 8,
StorageItemFlag = 4096,
TransferItemFlag = 8192,
VideoItemFlag = 65536,
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.
*/
const enum WiaPropertyType {
BooleanPropertyType = 1,
BytePropertyType = 2,
ClassIDPropertyType = 15,
CurrencyPropertyType = 12,
DatePropertyType = 13,
DoublePropertyType = 11,
ErrorCodePropertyType = 7,
FileTimePropertyType = 14,
HandlePropertyType = 18,
IntegerPropertyType = 3,
LargeIntegerPropertyType = 8,
LongPropertyType = 5,
ObjectPropertyType = 17,
SinglePropertyType = 10,
StringPropertyType = 16,
UnsignedIntegerPropertyType = 4,
UnsignedLargeIntegerPropertyType = 9,
UnsignedLongPropertyType = 6,
UnsupportedPropertyType = 0,
VariantPropertyType = 19,
VectorOfBooleansPropertyType = 101,
VectorOfBytesPropertyType = 102,
VectorOfClassIDsPropertyType = 115,
VectorOfCurrenciesPropertyType = 112,
VectorOfDatesPropertyType = 113,
VectorOfDoublesPropertyType = 111,
VectorOfErrorCodesPropertyType = 107,
VectorOfFileTimesPropertyType = 114,
VectorOfIntegersPropertyType = 103,
VectorOfLargeIntegersPropertyType = 108,
VectorOfLongsPropertyType = 105,
VectorOfSinglesPropertyType = 110,
VectorOfStringsPropertyType = 116,
VectorOfUnsignedIntegersPropertyType = 104,
VectorOfUnsignedLargeIntegersPropertyType = 109,
VectorOfUnsignedLongsPropertyType = 106,
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.
*/
const enum WiaSubType {
FlagSubType = 3,
ListSubType = 2,
RangeSubType = 1,
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.
*/
interface 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
* @param WIA.WiaDeviceType [DeviceType=0]
* @param WIA.WiaImageIntent [Intent=0]
* @param WIA.WiaImageBias [Bias=131072]
* @param string [FormatID='{00000000-0000-0000-0000-000000000000}']
* @param boolean [AlwaysSelectDevice=false]
* @param boolean [UseCommonUI=true]
* @param boolean [CancelError=false]
*/
ShowAcquireImage(
DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean, CancelError?: boolean): ImageFile;
/** Launches the Windows Scanner and Camera Wizard and returns Nothing. Future versions may return a collection of ImageFile objects. */
ShowAcquisitionWizard(Device: Device): any;
/**
* Displays the properties dialog box for the specified Device
* @param boolean [CancelError=false]
*/
ShowDeviceProperties(Device: Device, CancelError?: boolean): void;
/**
* Displays the properties dialog box for the specified Item
* @param boolean [CancelError=false]
*/
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;
/**
* 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;
/**
* 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
* @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;
/**
* 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;
}
/** The Device object represents an active connection to an imaging device. */
interface Device {
/** A collection of all commands for this imaging device */
readonly Commands: DeviceCommands;
/** Returns the DeviceID for this Device */
readonly DeviceID: string;
/** A collection of all events for this imaging device */
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.
*/
ExecuteCommand(CommandID: string): Item;
/** Returns the Item object specified by ItemID if it exists */
GetItem(ItemID: string): Item;
/** A collection of all items for this imaging device */
readonly Items: Items;
/** A collection of all properties for this imaging device */
readonly Properties: Properties;
/** 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 {
/** Returns the commandID for this Command */
readonly CommandID: string;
/** Returns the command Description */
readonly Description: string;
/** Returns the command Name */
readonly Name: string;
}
/**
* 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.
*/
interface DeviceCommands {
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection by position */
Item(Index: number): DeviceCommand;
}
/** The DeviceEvent object describes an EventID that can be used when calling RegisterEvent or RegisterPersistentEvent on a DeviceManager object. */
interface DeviceEvent {
/** Returns the event Description */
readonly Description: string;
/** Returns the EventID for this Event */
readonly EventID: string;
/** Returns the event Name */
readonly Name: string;
/** Returns the Type of this Event */
readonly Type: WiaEventFlag;
}
/**
* 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.
*/
interface DeviceEvents {
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection by position */
Item(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
* .
*/
interface DeviceInfo {
/** Establish a connection with this device and return a Device object */
Connect(): Device;
/** Returns the DeviceID for this Device */
readonly DeviceID: string;
/** A collection of all properties for this imaging device that are applicable when the device is not connected */
readonly Properties: Properties;
/** Returns the Type of Device */
readonly Type: WiaDeviceType;
}
/**
* 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.
*/
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;
}
/**
* 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 {
/** 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.
* @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.
* @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.
* @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.
* @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.
*/
interface Filter {
/** Returns a Description of what the filter does */
readonly Description: string;
/** Returns the FilterID for this Filter */
readonly FilterID: string;
/** Returns the Filter Name */
readonly Name: string;
/** A collection of all properties for this filter */
readonly Properties: Properties;
}
/**
* 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.
*/
interface FilterInfo {
/** Returns a technical Description of what the filter does and how to use it in a filter chain */
readonly Description: string;
/** Returns the FilterID for this filter */
readonly FilterID: string;
/** Returns the FilterInfo Name */
readonly Name: string;
}
/**
* 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.
*/
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;
}
/** 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. */
interface Filters {
/**
* Appends/Inserts a new Filter of the specified FilterID into a Filter collection
* @param number [Index=0]
*/
Add(FilterID: string, Index?: number): void;
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection by position or FilterID */
Item(Index: number): Filter;
/** Removes the designated filter */
Remove(Index: number): void;
}
/**
* 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.
*/
interface Formats {
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection by position */
Item(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.
*/
interface ImageFile {
/** Returns/Sets the current frame in the image */
ActiveFrame: number;
/** Returns the raw image bits as a Vector of Long values */
readonly ARGBData: Vector;
/** Returns the raw image file as a Vector of Bytes */
readonly FileData: Vector;
/** Returns the file extension for this image file type */
readonly FileExtension: string;
/** Returns the FormatID for this file type */
readonly FormatID: string;
/** Returns the number of frames in the image */
readonly FrameCount: number;
/** Returns the Height of the image in pixels */
readonly Height: number;
/** Returns the Horizontal pixels per inch of the image */
readonly HorizontalResolution: number;
/** Indicates if the pixel format has an alpha component */
readonly IsAlphaPixelFormat: boolean;
/** Indicates whether the image is animated */
readonly IsAnimated: boolean;
/** Indicates if the pixel format is extended (16 bits/channel) */
readonly IsExtendedPixelFormat: boolean;
/** Indicates if the pixel data is an index into a palette or the actual color data */
readonly IsIndexedPixelFormat: boolean;
/** Loads the ImageFile object with the specified File */
LoadFile(Filename: string): void;
/** Returns the depth of the pixels of the image in bits per pixel */
readonly PixelDepth: number;
/** A collection of all properties for this image */
readonly Properties: Properties;
/** Save the ImageFile object to the specified File */
SaveFile(Filename: string): void;
/** Returns the Vertical pixels per inch of the image */
readonly VerticalResolution: number;
/** Returns the Width of the image in pixels */
readonly Width: number;
}
/** The ImageProcess object manages the filter chain. An ImageProcess object can be created using "WIA.ImageProcess" in a call to CreateObject. */
interface ImageProcess {
/** Takes the specified ImageFile and returns the new ImageFile with all the filters applied on success */
Apply(Source: ImageFile): ImageFile;
/** A collection of all available filters */
readonly FilterInfos: FilterInfos;
/** A collection of the filters to be applied in this process */
readonly Filters: Filters;
}
/**
* 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.
*/
interface Item {
/** A collection of all commands for this item */
readonly Commands: DeviceCommands;
/** Issues the command specified by CommandID. CommandIDs are device dependent. Valid CommandIDs for this Item are contained in the Commands collection. */
ExecuteCommand(CommandID: string): Item;
/** A collection of all supported format types for this item */
readonly Formats: Formats;
/** Returns the ItemID for this Item */
readonly ItemID: string;
/** A collection of all child items for this item */
readonly Items: Items;
/** A collection of all properties for this item */
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.
* @param string [FormatID='{00000000-0000-0000-0000-000000000000}']
*/
Transfer(FormatID?: string): any;
/** Returns the underlying IWiaItem interface for this Item object */
readonly WiaItem: any;
}
/** 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. */
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;
/** Returns the number of members in the collection */
readonly Count: number;
/** Returns the specified item in the collection by position */
Item(Index: number): Item;
/** Removes the designated Item */
Remove(Index: number): void;
}
/**
* 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;
/** Returns the specified item in the collection either by position or name. */
Item(Index: any): 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.
*/
interface Property {
/** Indicates whether the Property Value is read only */
readonly IsReadOnly: boolean;
/** Indicates whether the Property Value is a vector */
readonly IsVector: boolean;
/** Returns the Property Name */
readonly Name: string;
/** Returns the PropertyID of this Property */
readonly PropertyID: number;
/** Returns the SubType of the Property, if any */
readonly SubType: WiaSubType;
/** Returns the default Property Value if the SubType is not UnspecifiedSubType */
readonly SubTypeDefault: any;
/** Returns the maximum valid Property Value if the SubType is RangeSubType */
readonly SubTypeMax: number;
/** Returns the minimum valid Property Value if the SubType is RangeSubType */
readonly SubTypeMin: number;
/** Returns the step increment of Property Values if the SubType is RangeSubType */
readonly SubTypeStep: number;
/** Returns a Vector of valid Property Values if the SubType is ListSubType or valid flag Values that can be ored together if the SubType is FlagSubType */
readonly SubTypeValues: Vector;
/** Returns either a WiaPropertyType or a WiaImagePropertyType */
readonly Type: number;
/** Returns/Sets the Property Value */
Value: any;
}
/**
* 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.
*/
interface Rational {
/** Returns/Sets the Rational Value Denominator */
Denominator: number;
/** Returns/Sets the Rational Value Numerator */
Numerator: number;
/** Returns the Rational Value as a Double */
readonly Value: number;
}
/**
* 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.
*/
interface Vector {
/**
* 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.
* @param number [Index=0]
*/
Add(Value: any, Index?: number): void;
/** Returns/Sets the Vector of Bytes as an array of bytes */
BinaryData: any;
/** Removes all elements. */
Clear(): void;
/** Returns the number of members in the vector */
readonly Count: number;
/** Returns/Sets the Vector of Integers from a Date */
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.
* @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;
/**
* 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.
* @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;
/**
* 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.
* @param boolean [Resizable=true]
* @param boolean [Unicode=true]
*/
SetFromString(Value: string, Resizable?: boolean, Unicode?: boolean): void;
/**
* Returns a Vector of Bytes as a String
* @param boolean [Unicode=true]
*/
String(Unicode?: boolean): string;
}
}
interface ActiveXObject {
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;
}
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;
}
+6
View File
@@ -0,0 +1,6 @@
{
"private": true,
"dependencies": {
"activex-helpers": "*"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es5", "scripthost"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-wia-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
@@ -1,71 +0,0 @@
//source -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms630826(v=vs.85).aspx
//Convert a file
var commonDialog = new ActiveXObject('WIA.CommonDialog');
var img = commonDialog.ShowAcquireImage();
if (img.FormatID !== WIA.FormatID.wiaFormatJPEG) {
var 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
var dev = commonDialog.ShowSelectDevice();
if (dev.Type === WIA.WiaDeviceType.CameraDeviceType) {
var itm = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture);
}
//Display detailed property information
dev = commonDialog.ShowSelectDevice();
var e = new Enumerator<WIA.Property>(dev.Properties); //no foreach over ActiveX collections
e.moveFirst();
while (!e.atEnd()) {
var p = e.item();
var 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 + ')';
}
}
}
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: ';
} else {
s += ' [valid values include: ';
}
var count = p.SubTypeValues.Count;
for (var i = 1; i <= count; i++) {
s += p.SubTypeValues.Item(i);
if (i < count) {
s += ', ';
}
}
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 (WScript) {
WScript.Echo(s);
} else if (window) {
window.alert(s);
}
}
-379
View File
@@ -1,379 +0,0 @@
// Type definitions for Microsoft Windows Image Acquisition Library v2.0
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms630827(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace WIA {
//Enums
type CommandID =
"'{04E725B0-ACAE-11D2-A093-00C04F72DC3C}'" //wiaCommandChangeDocument
| "'{E208C170-ACAD-11D2-A093-00C04F72DC3C}'" //wiaCommandDeleteAllItems
| "'{9B26B7B2-ACAD-11D2-A093-00C04F72DC3C}'" //wiaCommandSynchronize
| "'{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}'" //wiaCommandTakePicture
| "'{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}'"; //wiaCommandUnloadDocument
const CommandID: {
wiaCommandChangeDocument: CommandID,
wiaCommandDeleteAllItems: CommandID,
wiaCommandSynchronize: CommandID,
wiaCommandTakePicture: CommandID,
wiaCommandUnloadDocument: CommandID
};
type EventID =
"'{A28BBADE-64B6-11D2-A231-00C04FA31809}'" //wiaEventDeviceConnected
| "'{143E4E83-6497-11D2-A231-00C04FA31809}'" //wiaEventDeviceDisconnected
| "'{4C8F4EF5-E14F-11D2-B326-00C04F68CE61}'" //wiaEventItemCreated
| "'{1D22A559-E14F-11D2-B326-00C04F68CE61}'" //wiaEventItemDeleted
| "'{C686DCEE-54F2-419E-9A27-2FC7F2E98F9E}'" //wiaEventScanEmailImage
| "'{C00EB793-8C6E-11D2-977A-0000F87A926F}'" //wiaEventScanFaxImage
| "'{9B2B662C-6185-438C-B68B-E39EE25E71CB}'" //wiaEventScanFilmImage
| "'{A6C5A715-8C6E-11D2-977A-0000F87A926F}'" //wiaEventScanImage
| "'{FC4767C1-C8B3-48A2-9CFA-2E90CB3D3590}'" //wiaEventScanImage2
| "'{154E27BE-B617-4653-ACC5-0FD7BD4C65CE}'" //wiaEventScanImage3
| "'{A65B704A-7F3C-4447-A75D-8A26DFCA1FDF}'" //wiaEventScanImage4
| "'{9D095B89-37D6-4877-AFED-62A297DC6DBE}'" //wiaEventScanOCRImage
| "'{B441F425-8C6E-11D2-977A-0000F87A926F}'"; //wiaEventScanPrintImage
const EventID: {
wiaEventDeviceConnected: EventID,
wiaEventDeviceDisconnected: EventID,
wiaEventItemCreated: EventID,
wiaEventItemDeleted: EventID,
wiaEventScanEmailImage: EventID,
wiaEventScanFaxImage: EventID,
wiaEventScanFilmImage: EventID,
wiaEventScanImage: EventID,
wiaEventScanImage2: EventID,
wiaEventScanImage3: EventID,
wiaEventScanImage4: EventID,
wiaEventScanOCRImage: EventID,
wiaEventScanPrintImage: EventID
};
type FormatID =
"'{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatBMP
| "'{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatGIF
| "'{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatJPEG
| "'{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatPNG
| "'{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}'"; //wiaFormatTIFF
const FormatID: {
wiaFormatBMP: FormatID,
wiaFormatGIF: FormatID,
wiaFormatJPEG: FormatID,
wiaFormatPNG: FormatID,
wiaFormatTIFF: FormatID
};
type Miscellaneous =
"'*'" //wiaAnyDeviceID
| "'{00000000-0000-0000-0000-000000000000}'"; //wiaIDUnknown
const Miscellaneous: {
wiaAnyDeviceID: Miscellaneous,
wiaIDUnknown: Miscellaneous
};
const enum WiaDeviceType {
CameraDeviceType = 2,
ScannerDeviceType = 1,
UnspecifiedDeviceType = 0,
VideoDeviceType = 3
}
const enum WiaEventFlag {
ActionEvent = 2,
NotificationEvent = 1
}
const enum WiaImageBias {
MaximizeQuality = 131072,
MinimizeSize = 65536
}
const enum WiaImageIntent {
ColorIntent = 1,
GrayscaleIntent = 2,
TextIntent = 4,
UnspecifiedIntent = 0
}
const enum WiaImagePropertyType {
ByteImagePropertyType = 1001,
LongImagePropertyType = 1004,
RationalImagePropertyType = 1006,
StringImagePropertyType = 1002,
UndefinedImagePropertyType = 1000,
UnsignedIntegerImagePropertyType = 1003,
UnsignedLongImagePropertyType = 1005,
UnsignedRationalImagePropertyType = 1007,
VectorOfBytesImagePropertyType = 1101,
VectorOfLongsImagePropertyType = 1103,
VectorOfRationalsImagePropertyType = 1105,
VectorOfUndefinedImagePropertyType = 1100,
VectorOfUnsignedIntegersImagePropertyType = 1102,
VectorOfUnsignedLongsImagePropertyType = 1104,
VectorOfUnsignedRationalsImagePropertyType = 1106
}
const enum WiaItemFlag {
AnalyzeItemFlag = 16,
AudioItemFlag = 32,
BurstItemFlag = 2048,
DeletedItemFlag = 128,
DeviceItemFlag = 64,
DisconnectedItemFlag = 256,
FileItemFlag = 2,
FolderItemFlag = 4,
FreeItemFlag = 0,
GeneratedItemFlag = 16384,
HasAttachmentsItemFlag = 32768,
HPanoramaItemFlag = 512,
ImageItemFlag = 1,
RemovedItemFlag = -2147483648,
RootItemFlag = 8,
StorageItemFlag = 4096,
TransferItemFlag = 8192,
VideoItemFlag = 65536,
VPanoramaItemFlag = 1024
}
const enum WiaPropertyType {
BooleanPropertyType = 1,
BytePropertyType = 2,
ClassIDPropertyType = 15,
CurrencyPropertyType = 12,
DatePropertyType = 13,
DoublePropertyType = 11,
ErrorCodePropertyType = 7,
FileTimePropertyType = 14,
HandlePropertyType = 18,
IntegerPropertyType = 3,
LargeIntegerPropertyType = 8,
LongPropertyType = 5,
ObjectPropertyType = 17,
SinglePropertyType = 10,
StringPropertyType = 16,
UnsignedIntegerPropertyType = 4,
UnsignedLargeIntegerPropertyType = 9,
UnsignedLongPropertyType = 6,
UnsupportedPropertyType = 0,
VariantPropertyType = 19,
VectorOfBooleansPropertyType = 101,
VectorOfBytesPropertyType = 102,
VectorOfClassIDsPropertyType = 115,
VectorOfCurrenciesPropertyType = 112,
VectorOfDatesPropertyType = 113,
VectorOfDoublesPropertyType = 111,
VectorOfErrorCodesPropertyType = 107,
VectorOfFileTimesPropertyType = 114,
VectorOfIntegersPropertyType = 103,
VectorOfLargeIntegersPropertyType = 108,
VectorOfLongsPropertyType = 105,
VectorOfSinglesPropertyType = 110,
VectorOfStringsPropertyType = 116,
VectorOfUnsignedIntegersPropertyType = 104,
VectorOfUnsignedLargeIntegersPropertyType = 109,
VectorOfUnsignedLongsPropertyType = 106,
VectorOfVariantsPropertyType = 119
}
const enum WiaSubType {
FlagSubType = 3,
ListSubType = 2,
RangeSubType = 1,
UnspecifiedSubType = 0
}
//Interfaces
interface CommonDialog {
ShowAcquireImage: (DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean, CancelError?: boolean) => ImageFile;
ShowAcquisitionWizard: (Device: Device) => any;
ShowDeviceProperties: (Device: Device, CancelError?: boolean) => void;
ShowItemProperties: (Item: Item, CancelError?: boolean) => void;
ShowPhotoPrintingWizard: (Files: any) => void;
ShowSelectDevice: (DeviceType?: WiaDeviceType, AlwaysSelectDevice?: boolean, CancelError?: boolean) => Device;
ShowSelectItems: (Device: Device, Intent?: WiaImageIntent, Bias?: WiaImageBias, SingleSelect?: boolean, UseCommonUI?: boolean, CancelError?: boolean) => Items;
ShowTransfer: (Item: Item, FormatID?: string, CancelError?: boolean) => any;
}
interface Device {
Commands: DeviceCommands;
DeviceID: string;
Events: DeviceEvents;
ExecuteCommand: (CommandID: string) => Item;
GetItem: (ItemID: string) => Item;
Items: Items;
Properties: Properties;
Type: WiaDeviceType;
WiaItem: any /*VT_UNKNOWN*/;
}
interface DeviceCommand {
CommandID: string;
Description: string;
Name: string;
}
interface DeviceCommands {
Count: number;
Item: (Index: number) => DeviceCommand;
}
interface DeviceEvent {
Description: string;
EventID: string;
Name: string;
Type: WiaEventFlag;
}
interface DeviceEvents {
Count: number;
Item: (Index: number) => DeviceEvent;
}
interface DeviceInfo {
Connect: () => Device;
DeviceID: string;
Properties: Properties;
Type: WiaDeviceType;
}
interface DeviceInfos {
Count: number;
Item: (Index: any) => DeviceInfo;
}
interface DeviceManager {
DeviceInfos: DeviceInfos;
RegisterEvent: (EventID: string, DeviceID?: string) => void;
RegisterPersistentEvent: (Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string) => void;
UnregisterEvent: (EventID: string, DeviceID?: string) => void;
UnregisterPersistentEvent: (Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string) => void;
}
interface Filter {
Description: string;
FilterID: string;
Name: string;
Properties: Properties;
}
interface FilterInfo {
Description: string;
FilterID: string;
Name: string;
}
interface FilterInfos {
Count: number;
Item: (Index: any) => FilterInfo;
}
interface Filters {
Add: (FilterID: string, Index?: number) => void;
Count: number;
Item: (Index: number) => Filter;
Remove: (Index: number) => void;
}
interface Formats {
Count: number;
Item: (Index: number) => string;
}
interface ImageFile {
ActiveFrame: number;
ARGBData: Vector;
FileData: Vector;
FileExtension: string;
FormatID: string;
FrameCount: number;
Height: number;
HorizontalResolution: number;
IsAlphaPixelFormat: boolean;
IsAnimated: boolean;
IsExtendedPixelFormat: boolean;
IsIndexedPixelFormat: boolean;
LoadFile: (Filename: string) => void;
PixelDepth: number;
Properties: Properties;
SaveFile: (Filename: string) => void;
VerticalResolution: number;
Width: number;
}
interface ImageProcess {
Apply: (Source: ImageFile) => ImageFile;
FilterInfos: FilterInfos;
Filters: Filters;
}
interface Item {
Commands: DeviceCommands;
ExecuteCommand: (CommandID: string) => Item;
Formats: Formats;
ItemID: string;
Items: Items;
Properties: Properties;
Transfer: (FormatID?: string) => any;
WiaItem: any /*VT_UNKNOWN*/;
}
interface Items {
Add: (Name: string, Flags: number) => void;
Count: number;
Item: (Index: number) => Item;
Remove: (Index: number) => void;
}
interface Properties {
Count: number;
Exists: (Index: any) => boolean;
Item: (Index: any) => Property;
}
interface Property {
IsReadOnly: boolean;
IsVector: boolean;
Name: string;
PropertyID: number;
SubType: WiaSubType;
SubTypeDefault: any;
SubTypeMax: number;
SubTypeMin: number;
SubTypeStep: number;
SubTypeValues: Vector;
Type: number;
Value: any;
}
interface Rational {
Denominator: number;
Numerator: number;
Value: number;
}
interface Vector {
Add: (Value: any, Index?: number) => void;
BinaryData: any;
Clear: () => void;
Count: number;
Date: VarDate;
ImageFile: (Width?: number, Height?: number) => ImageFile;
Item: (Index: number) => any; //Also has setter with parameters
Picture: (Width?: number, Height?: number) => any;
Remove: (Index: number) => any;
SetFromString: (Value: string, Resizable?: boolean, Unicode?: boolean) => void;
String: (Unicode?: boolean) => string;
}
}
interface ActiveXObject {
new (progID: 'WIA.Rational'): WIA.Rational;
new (progID: 'WIA.Vector'): WIA.Vector;
new (progID: 'WIA.ImageFile'): WIA.ImageFile;
new (progID: 'WIA.ImageProcess'): WIA.ImageProcess;
new (progID: 'WIA.CommonDialog'): WIA.CommonDialog;
new (progID: 'WIA.DeviceManager'): WIA.DeviceManager;
}
@@ -1,24 +0,0 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom",
"scripthost"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"activex-windows-image-acquisition-tests.ts"
]
}
+10 -6
View File
@@ -2,12 +2,14 @@
// Project: https://github.com/AzureAD/azure-activedirectory-library-for-js
// Definitions by: mmaitre314 <https://github.com/mmaitre314>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
declare var AuthenticationContext: adal.AuthenticationContextStatic;
declare var Logging: adal.Logging;
declare module 'adal' {
export = { AuthenticationContext, Logging };
export const AuthenticationContext: adal.AuthenticationContextStatic;
export const Logging: adal.Logging;
}
declare namespace adal {
@@ -30,6 +32,8 @@ declare namespace adal {
resource?: string;
extraQueryParameter?: string;
navigateToLoginRequestUrl?: boolean;
logOutUri?: string;
isAngular?: boolean;
}
interface User {
@@ -44,15 +48,15 @@ declare namespace adal {
stateResponse: string;
requestType: string;
}
interface Logging {
log: (message: string) => void;
level: LoggingLevel;
}
enum LoggingLevel {
ERROR = 0,
WARNING = 1,
WARNING = 1,
INFO = 2,
VERBOSE = 3
}
@@ -64,7 +68,7 @@ declare namespace adal {
interface AuthenticationContext {
instance: string;
config: Config;
config: Config;
/**
* Gets initial Idtoken for the app backend
@@ -159,7 +163,7 @@ declare namespace adal {
getResourceForEndpoint(endpoint: string): string;
/**
* Handles redirection after login operation.
* Handles redirection after login operation.
* Gets access token from url and saves token to the (local/session) storage
* or saves error in case unsuccessful login.
*/
+3
View File
@@ -0,0 +1,3 @@
// Actual tests inside ./test/
const a: string = adone.ok;
+85
View File
@@ -0,0 +1,85 @@
/// <reference types="node" />
declare const _null: symbol;
export { _null as null };
export function noop(): void;
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 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 o(...props: any[]): object;
export const Date: typeof global.Date;
export const hrtime: typeof global.process.hrtime;
export const setTimeout: typeof global.setTimeout;
export const setInterval: typeof global.setInterval;
export const setImmediate: typeof global.setImmediate;
export const clearTimeout: typeof global.clearTimeout;
export const clearInterval: typeof global.clearInterval;
export const clearImmediate: typeof global.clearImmediate;
interface LazifyOptions {
configurable: boolean;
}
export function lazify(modules: object, obj?: object, require?: (path: string) => any, options?: LazifyOptions): object;
interface Tag {
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: Tag;
export function run(App: object, ignoreArgs?: boolean): Promise<void>;
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;
import * as std from "./glosses/std";
export { std };
export * from "./glosses/common";
export * from "./glosses/math";
export * from "./glosses/utils";
export * from "./glosses/assertion";
export * from "./glosses/promise";
export * from "./glosses/shani";
import "./glosses/shani-global";
export const assert: adone.assertion.I.AssertFunction;
export const expect: adone.assertion.I.ExpectFunction;
export as namespace adone;
+1074
View File
File diff suppressed because it is too large Load Diff
+465
View File
@@ -0,0 +1,465 @@
/**
* predicates
*/
export namespace is {
function _null(obj: any): boolean;
export { _null as null };
export function undefined(obj: any): boolean;
export function exist(obj: any): boolean;
export function nil(obj: any): boolean;
export function number(obj: any): boolean;
export function numeral(obj: any): boolean;
export function infinite(obj: any): boolean;
export function odd(obj: any): boolean;
export function even(obj: any): boolean;
export function float(obj: any): boolean;
export function negativeZero(obj: any): boolean;
export function string(obj: any): boolean;
export function emptyString(obj: any): boolean;
export function substring(substring: string, string: string, offset?: number): boolean;
export function prefix(prefix: string, string: string): boolean;
export function suffix(suffix: string, string: string): boolean;
export function boolean(obj: any): boolean;
export function json(obj: any): boolean;
export function object(obj: any): boolean;
export function plainObject(obj: any): boolean;
function _class(obj: any): boolean;
export { _class as class };
export function emptyObject(obj: any): boolean;
export function propertyOwned(obj: any, field: string): boolean;
export function propertyDefined(obj: any, field: string): boolean;
export function conforms(obj: object, schema: object, strict?: boolean): boolean;
export function arrayLikeObject(obj: any): boolean;
export function inArray<T>(value: T, array: any[], offset?: number, comparator?: (a: T, b: T) => boolean): boolean;
export function sameType(value: any, other: any): boolean;
export function primitive(obj: any): boolean;
export function equalArrays(left: any[], right: any[]): boolean;
export function deepEqual(left: any, right: any): boolean;
export function shallowEqual(left: any, right: any): boolean;
export function stream(obj: any): boolean;
export function writableStream(obj: any): boolean;
export function readableStream(obj: any): boolean;
export function duplexStream(obj: any): boolean;
export function transformStream(obj: any): boolean;
export function utf8(obj: Buffer): boolean;
export function win32PathAbsolute(path: string): boolean;
export function posixPathAbsolute(path: string): boolean;
export function pathAbsolute(path: string): boolean;
export function glob(str: string): boolean;
export function dotfile(str: string): boolean;
function _function(obj: any): boolean;
export { _function as function };
export function asyncFunction(obj: any): boolean;
export function promise(obj: any): boolean;
export function validDate(str: string): boolean;
export function buffer(obj: any): boolean;
export function callback(obj: any): boolean;
export function generator(obj: any): boolean;
export function nan(obj: any): boolean;
export function finite(obj: any): boolean;
export function integer(obj: any): boolean;
export function safeInteger(obj: any): boolean;
export function array(obj: any): boolean;
export function uint8Array(obj: any): boolean;
export function configuration(obj: any): boolean;
export function long(obj: any): boolean;
export function bigNumber(obj: any): boolean;
export function exbuffer(obj: any): boolean;
export function exdate(obj: any): boolean;
export function transform(obj: any): boolean;
export function subsystem(obj: any): boolean;
export function application(obj: any): boolean;
export function logger(obj: any): boolean;
export function coreStream(obj: any): boolean;
export function fastStream(obj: any): boolean;
export function fastFSStream(obj: any): boolean;
export function fastFSMapStream(obj: any): boolean;
export function genesisNetron(obj: any): boolean;
export function genesisPeer(obj: any): boolean;
export function netronAdapter(obj: any): boolean;
export function netron(obj: any): boolean;
export function netronPeer(obj: any): boolean;
export function netronDefinition(obj: any): boolean;
export function netronDefinitions(obj: any): boolean;
export function netronReference(obj: any): boolean;
export function netronInterface(obj: any): boolean;
export function netronContext(obj: any): boolean;
export function netronIMethod(netronInterface: object, name: string): boolean;
export function netronIProperty(netronInterface: any, name: string): boolean;
export function netronStub(obj: any): boolean;
export function netronRemoteStub(obj: any): boolean;
export function netronStream(obj: any): boolean;
export function iterable(obj: any): boolean;
export const windows: boolean;
export const linux: boolean;
export const freebsd: boolean;
export const darwin: boolean;
export const sunos: boolean;
export function uppercase(str: string): boolean;
export function lowercase(str: string): boolean;
export function digits(str: string): boolean;
export function identifier(str: string): boolean;
export function binaryExtension(str: string): boolean;
export function binaryPath(str: string): boolean;
export function ip4(str: string): boolean;
export function ip6(str: string): boolean;
export function arrayBuffer(obj: any): boolean;
export function arrayBufferView(obj: any): boolean;
export function date(obj: any): boolean;
export function error(obj: any): boolean;
export function map(obj: any): boolean;
export function regexp(obj: any): boolean;
export function set(obj: any): boolean;
export function symbol(obj: any): boolean;
export function validUTF8(obj: any): boolean;
}
export namespace x {
class Exception extends Error {
constructor(message?: string | Error, captureStackTrace?: boolean);
}
class Runtime extends Exception { }
class IncompleteBufferError extends Exception { }
class NotImplemented extends Exception { }
class IllegalState extends Exception { }
class NotValid extends Exception { }
class Unknown extends Exception { }
class NotExists extends Exception { }
class Exists extends Exception { }
class Empty extends Exception { }
class InvalidAccess extends Exception { }
class NotSupported extends Exception { }
class InvalidArgument extends Exception { }
class InvalidNumberOfArguments extends Exception { }
class NotFound extends Exception { }
class Timeout extends Exception { }
class Incorrect extends Exception { }
class NotAllowed extends Exception { }
class LimitExceeded extends Exception { }
class Encoding extends Exception { }
class Network extends Exception { }
class Bind extends Exception { }
class Connect extends Exception { }
class Database extends Exception { }
class DatabaseInitialization extends Exception { }
class DatabaseOpen extends Exception { }
class DatabaseRead extends Exception { }
class DatabaseWrite extends Exception { }
class NetronIllegalState extends Exception { }
class NetronPeerDisconnected extends Exception { }
class NetronTimeout extends Exception { }
}
export class EventEmitter {
static listenerCount(emitter: EventEmitter, 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;
}
export class AsyncEmitter extends EventEmitter {
constructor(concurrency?: number);
setConcurrency(max?: number): this;
emitParallel(event: string, ...args: any[]): Promise<any[]>;
emitSerial(event: string, ...args: any[]): Promise<any[]>;
emitReduce(event: string, ...args: any[]): Promise<any>;
emitReduceRight(event: string, ...args: any[]): Promise<any>;
subscribe(event: string, listener: (...args: any[]) => void, once?: boolean): () => void;
}
declare namespace I {
type Long = adone.math.Long;
type Longable = adone.math.I.Longable;
namespace ExBuffer {
interface Varint32 {
value: number;
length: number;
}
interface Varint64 {
value: Long;
length: number;
}
interface String {
string: string;
length: number;
}
type Wrappable = string | ExBuffer | Buffer | Uint8Array | ArrayBuffer;
type METRICS = "b" | "c";
}
}
export class ExBuffer {
constructor(capacity?: number, noAssert?: boolean);
readBitSet(offset?: number): number[];
read(length: number, offset?: number): ExBuffer;
readInt8(offset?: number): number;
readUInt8(offset?: number): number;
readInt16LE(offset?: number): number;
readUInt16LE(offset?: number): number;
readInt16BE(offset?: number): number;
readUInt16BE(offset?: number): number;
readInt32LE(offset?: number): number;
readUInt32LE(offset?: number): number;
readInt32BE(offset?: number): number;
readUInt32BE(offset?: number): number;
readInt64LE(offset?: number): adone.math.Long;
readUInt64LE(offset?: number): adone.math.Long;
readInt64BE(offset?: number): adone.math.Long;
readUInt64BE(offset?: number): adone.math.Long;
readFloatLE(offset?: number): number;
readFloatBE(offset?: number): number;
readDoubleLE(offset?: number): number;
readDoubleBE(offset?: number): number;
write(source: I.ExBuffer.Wrappable, offset?: number, length?: number, encoding?: string): this;
writeBitSet(value: number[]): this;
writeBitSet(value: number[], offset: number): number;
writeInt8(value: number, offset?: number): this;
writeUInt8(value: number, offset?: number): this;
writeInt16LE(value: number, offset?: number): this;
writeInt16BE(value: number, offset?: number): this;
writeUInt16LE(value: number, offset?: number): this;
writeUInt16BE(value: number, offset?: number): this;
writeInt32LE(value: number, offset?: number): this;
writeInt32BE(value: number, offset?: number): this;
writeUInt32LE(value: number, offset?: number): this;
writeUInt32BE(value: number, offset?: number): this;
writeInt64LE(value: I.Longable, offset?: number): this;
writeInt64BE(value: I.Longable, offset?: number): this;
writeUInt64LE(value: I.Longable, offset?: number): this;
writeUInt64BE(value: I.Longable, offset?: number): this;
writeFloatLE(value: number, offset?: number): this;
writeFloatBE(value: number, offset?: number): this;
writeDoubleLE(value: number, offset?: number): this;
writeDoubleBE(value: number, offset?: number): this;
writeVarint32(value: number): this;
writeVarint32(value: number, offset: number): number;
writeVarint32ZigZag(value: number): this;
writeVarint32ZigZag(value: number, offset: number): number;
readVarint32(): number;
readVarint32(offset: number): I.ExBuffer.Varint32;
readVarint32ZigZag(): number;
readVarint32ZigZag(offset: number): I.ExBuffer.Varint32;
writeVarint64(value: I.Longable): this;
writeVarint64(value: I.Longable, offset: number): number;
writeVarint64ZigZag(value: I.Longable): this;
writeVarint64ZigZag(value: I.Longable, offset: number): number;
readVarint64(): I.Long;
readVarint64(offset: number): I.ExBuffer.Varint64;
readVarint64ZigZag(): adone.math.Long;
readVarint64ZigZag(offset: number): I.ExBuffer.Varint64;
writeCString(str: string): this;
writeCString(str: string, offset: number): number;
readCString(): string;
readCString(offset: number): I.ExBuffer.String;
writeString(str: string): this;
writeString(str: string, offset: number): number;
readString(length: number, metrics?: I.ExBuffer.METRICS): string;
readString(length: number, metrics: I.ExBuffer.METRICS, offset: number): I.ExBuffer.String;
readString(length: number, offset: number): I.ExBuffer.String;
writeVString(str: string): this;
writeVString(str: string, offset: number): number;
readVString(): string;
readVString(offset: number): I.ExBuffer.String;
appendTo(target: ExBuffer, offset?: number): this;
assert(assert?: boolean): this;
capacity(): number;
clear(): this;
compact(begin?: number, end?: number): this;
copy(begin?: number, end?: number): ExBuffer;
copyTo(target: ExBuffer, targetOffset?: number, souceOffset?: number, sourceLimit?: number): this | ExBuffer;
ensureCapacity(capacity: number): this;
fill(value: string | number, begin?: number, end?: number): this;
flip(): this;
mark(offset?: number): this;
prepend(source: I.ExBuffer.Wrappable, encoding?: string, offset?: number): this;
prepend(source: I.ExBuffer.Wrappable, offset: number): this;
prependTo(target: ExBuffer, offset?: number): this;
remaining(): number;
reset(): this;
resize(capacity: number): this;
reverse(begin?: number, end?: number): this;
skip(length: number): this;
slice(begin?: number, end?: number): ExBuffer;
toBuffer(forceCopy?: boolean, begin?: number, end?: number): Buffer;
toArrayBuffer(): ArrayBuffer;
toString(encoding?: string, begin?: number, end?: number): string;
toBase64(begin?: number, end?: number): string;
toBinary(begin?: number, end?: number): string;
toDebug(columns?: boolean): string;
toHex(begin?: number, end?: number): string;
toUTF8(begin?: number, end?: number): string;
static accessor(): typeof Buffer;
static allocate(capacity?: number, noAssert?: boolean): ExBuffer;
static concat(buffers: I.ExBuffer.Wrappable[], encoding?: string, noAssert?: boolean): ExBuffer;
static type(): typeof Buffer;
static wrap(buffer: I.ExBuffer.Wrappable, encoding?: string, noAssert?: boolean): ExBuffer;
static calculateVarint32(value: number): number;
static zigZagEncode32(n: number): number;
static zigZagDecode32(n: number): number;
static calculateVarint64(value: number | string): number;
static zigZagEncode64(value: number | string | I.Long): I.Long;
static zigZagDecode64(value: number | string | I.Long): I.Long;
static calculateUTF8Chars(str: string): number;
static calculateString(str: string): number;
static fromBase64(str: string): ExBuffer;
static btoa(str: string): string;
static atob(b64: string): string;
static fromBinary(str: string): ExBuffer;
static fromDebug(str: string, noAssert?: boolean): ExBuffer;
static fromHex(str: string, noAssert?: boolean): ExBuffer;
static fromUTF8(str: string, noAssert?: boolean): ExBuffer;
static DEFAULT_CAPACITY: number;
static DEFAULT_NOASSERT: boolean;
static MAX_VARINT32_BYTES: number;
static MAX_VARINT64_BYTES: number;
static METRICS_CHARS: string;
static METRICS_BYTES: string;
}
+118
View File
@@ -0,0 +1,118 @@
/**
* math related things
*/
export namespace math {
namespace I {
interface LowHighBits {
low: number;
high: number;
}
type Longable = math.Long | number | string | LowHighBits;
}
export class Long {
constructor(low?: number, high?: number, unsigned?: boolean);
toInt(): number;
toNumber(): number;
toString(radix?: number): string;
getHighBits(): number;
getHighBitsUnsigned(): number;
getLowBits(): number;
getLowBitsUnsigned(): number;
getNumBitsAbs(): number;
isZero(): boolean;
isNegative(): boolean;
isPositive(): boolean;
isOdd(): boolean;
isEven(): boolean;
equals(other: I.Longable): boolean;
lessThan(other: I.Longable): boolean;
lessThanOrEqual(other: I.Longable): boolean;
greaterThan(other: I.Longable): boolean;
greaterThanOrEqual(other: I.Longable): boolean;
compare(other: I.Longable): number;
negate(): Long;
add(addend: I.Longable): Long;
sub(subtrahend: I.Longable): Long;
mul(multiplier: I.Longable): Long;
div(divisor: I.Longable): Long;
mod(divisor: I.Longable): Long;
not(): Long;
and(other: I.Longable): Long;
or(other: I.Longable): Long;
xor(other: I.Longable): Long;
shl(numBits: number | Long): Long;
shr(numBits: number | Long): Long;
shru(numBits: number | Long): Long;
toSigned(): Long;
toUnsigned(): Long;
toBytes(le?: boolean): number[];
toBytesLE(): number[];
toBytesBE(): number[];
static fromInt(value: number, unsigned?: boolean): Long;
static fromNumber(value?: number, unsigned?: boolean): Long;
static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long;
static fromString(str: string, unsigned?: boolean, radix?: number): Long;
static fromString(str: string, radix?: number): Long;
static fromValue(val: I.Longable): Long;
static MIN_VALUE: Long;
static MAX_VALUE: Long;
static MAX_UNSIGNED_VALUE: Long;
static ZERO: Long;
static UZERO: Long;
static ONE: Long;
static UONE: Long;
static NEG_ONE: Long;
}
}
+114
View File
@@ -0,0 +1,114 @@
/**
* promise helpers
*/
export namespace promise {
namespace I {
interface Deferred<T> {
/**
* Resolves the promise
*/
resolve(value?: T): void;
/**
* Rejects the promise
*/
reject(value?: any): void;
promise: Promise<T>;
}
}
/**
* Creates a promise and returns an interface to control the state
*/
export function defer<T>(): I.Deferred<T>;
/**
* Creates a promise that will be resolved after given milliseconds
*
* @param ms delay in milliseconds
* @param value resolving value
*/
export function delay<T>(ms: number, value?: T): Promise<T>;
/**
* Creates a promise that will be rejected after given milliseconds if the given promise is not fulfilled
*
* @param ms timeout in milliseconds
*/
export function timeout<T>(promise: Promise<T>, ms: number): Promise<T>;
/**
* Converts a promise to node.js style callback
*/
export function nodeify<T>(promise: Promise<T>, callback: (err?: any, value?: T) => void): Promise<T>;
namespace I {
interface PromisifyOptions {
/**
* Context to bind to new function
*/
context?: object;
}
}
/**
* Converts a callback function to a promise-based function
*/
export function promisify<R>(fn: (callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): () => Promise<R>;
export function promisify<T, R>(fn: (a: T, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T) => Promise<R>;
export function promisify<T>(fn: (a: T, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T) => Promise<void>;
export function promisify<T1, T2, R>(fn: (a: T1, b: T2, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2) => Promise<R>;
export function promisify<T1, T2>(fn: (a: T1, b: T2, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2) => Promise<void>;
export function promisify<T1, T2, T3, R>(fn: (a: T1, b: T2, c: T3, callback: (err?: any, result?: R) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2, c: T3) => Promise<R>;
export function promisify<T1, T2, T3>(fn: (a: T1, b: T2, c: T3, callback: (err?: any) => void) => void, options?: I.PromisifyOptions): (a: T1, b: T2, c: T3) => Promise<void>;
export function promisify<T1, T2, T3, T4, R>(
fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any, result?: R) => void) => void,
options?: I.PromisifyOptions
): (a: T1, b: T2, c: T3, d: T4) => Promise<R>;
export function promisify<T1, T2, T3, T4>(
fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any) => void) => void,
options?: I.PromisifyOptions
): (a: T1, b: T2, c: T3, d: T4) => Promise<void>;
export function promisify<T1, T2, T3, T4, T5, R>(
fn: (a: T1, b: T2, c: T3, d: T4, e: T5, callback: (err?: any, result?: R) => void) => void,
options?: I.PromisifyOptions
): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise<R>;
export function promisify<T1, T2, T3, T4, T5>(
fn: (a: T1, b: T2, c: T3, d: T4, callback: (err?: any) => void) => void,
options?: I.PromisifyOptions
): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise<void>;
export function promisify(fn: (...args: any[]) => void, options?: I.PromisifyOptions): (...args: any[]) => Promise<any>;
namespace I {
interface PromisifyAllOptions {
/**
* Suffix to use for keys
*/
suffix?: string;
/**
* Function to filter keys
*/
filter?(key: string): boolean;
/**
* Context to bind to new functions
*/
context?: object;
}
}
/**
* Promisifies entire object
*/
export function promisifyAll(source: object, options?: I.PromisifyAllOptions): object;
/**
* Executes a function after promise fulfillment
*
* @returns the original promise
*/
function _finally<T>(promise: Promise<T>, onFinally?: (...args: any[]) => void): Promise<T>;
export { _finally as finally };
}
+79
View File
@@ -0,0 +1,79 @@
/**
* Defines a tests block
*/
declare const describe: adone.shani.I.DescribeFunction;
/**
* Defines a tests block
*/
declare const context: adone.shani.I.DescribeFunction;
/**
* Defines a test
*/
declare const it: adone.shani.I.TestFunction;
/**
* Defines a test
*/
declare const specify: adone.shani.I.TestFunction;
/**
* Defines a hook that will be called only once before the block's tests
*/
declare const before: adone.shani.I.HookFunction;
/**
* Defines a hook that will be called only once after the block's tests
*/
declare const after: adone.shani.I.HookFunction;
/**
* Defines a hook that will be called before each test
*/
declare const beforeEach: adone.shani.I.HookFunction;
/**
* Defines a hook that will be called after each test
*/
declare const afterEach: adone.shani.I.HookFunction;
/**
* assertion functions
*/
declare const assert: adone.assertion.I.AssertFunction;
/**
* bdd-style assertion functons
*/
declare const expect: adone.assertion.I.ExpectFunction;
/**
* tools for installing controllable timer functions
*/
declare const fakeClock: adone.util.I.fakeClock.FakeClock;
/**
* defines a spy function
*/
declare const spy: typeof adone.shani.util.spy;
/**
* defines a stub function
*/
declare const stub: typeof adone.shani.util.stub;
/**
* defines a mock function
*/
declare const mock: typeof adone.shani.util.mock;
/**
* defines a matcher for spies/stubs/mocks
*/
declare const match: typeof adone.shani.util.match;
/**
* assertion tool for http server responses
*/
declare const request: typeof adone.shani.util.request;
+1655
View File
File diff suppressed because it is too large Load Diff
+65
View File
@@ -0,0 +1,65 @@
import * as assert from "assert";
import * as fs from "fs";
import * as path from "path";
import * as util from "util";
import * as events from "events";
import * as stream from "stream";
import * as url from "url";
import * as net from "net";
import * as http from "http";
import * as https from "https";
import * as child_process from "child_process";
import * as os from "os";
import * as cluster from "cluster";
import * as repl from "repl";
import * as punycode from "punycode";
import * as readline from "readline";
import * as string_decoder from "string_decoder";
import * as querystring from "querystring";
import * as crypto from "crypto";
import * as vm from "vm";
import * as v8 from "v8";
import * as domain from "domain";
import * as tty from "tty";
import * as buffer from "buffer";
import * as constants from "constants";
import * as zlib from "zlib";
import * as tls from "tls";
import * as console from "console";
import * as dns from "dns";
import * as timers from "timers";
import * as dgram from "dgram";
export {
assert,
fs,
path,
util,
events,
stream,
url,
net,
http,
https,
child_process,
os,
cluster,
repl,
punycode,
readline,
string_decoder,
querystring,
crypto,
vm,
v8,
domain,
tty,
buffer,
constants,
zlib,
tls,
console,
dns,
timers,
dgram,
};
+473
View File
@@ -0,0 +1,473 @@
/**
* various utility functions
*/
export namespace util {
function arrify<T>(val: T[]): T[];
function arrify<T>(val: T): [T];
function slice<T>(args: T[], sliceStart?: number, sliceEnd?: number): T[];
function spliceOne(list: any[], index: number): void;
function normalizePath(str: string, stripTrailing?: boolean): string;
function unixifyPath(filePath: string, unescape?: boolean): string;
function functionName(fn: (...args: any[]) => any): string;
function mapArguments(argmap: (...args: any[]) => any | any[]): (...args: any[]) => any;
function mapArguments(argmap: number): <T>(...args: T[]) => T[];
function mapArguments(...args: any[]): <T>(x: T) => T;
namespace I {
interface ParseMsResult {
days: number;
hours: number;
minutes: number;
seconds: number;
milliseconds: number;
}
}
function parseMs(ms: number): I.ParseMsResult;
function pluralizeWord(str: string, plural?: string, count?: number): string;
function functionParams(func: (...args: any[]) => any): string[];
function randomChoice<T>(arrayLike: ArrayLike<T>, from?: number, to?: number): T;
function shuffleArray<T>(array: T[]): T[];
function enumerate<T>(iterable: Iterable<T>, start?: number): IterableIterator<[number, T]>;
function zip<T1, T2>(a: Iterable<T1>, b: Iterable<T2>): IterableIterator<[T1, T2]>;
function zip<T1, T2, T3>(a: Iterable<T1>, b: Iterable<T2>, c: Iterable<T3>): IterableIterator<[T1, T2, T3]>;
function zip<T1, T2, T3, T4>(a: Iterable<T1>, b: Iterable<T2>, c: Iterable<T3>, d: Iterable<T4>): IterableIterator<[T1, T2, T3, T4]>;
function zip(...iterables: Array<Iterable<any>>): IterableIterator<any[]>;
namespace I {
interface KeysOptions {
onlyEnumerable?: boolean;
followProto?: boolean;
all?: boolean;
}
}
function keys(object: object, options?: I.KeysOptions): string[];
function values(object: object, options?: I.KeysOptions): any[];
function entries(object: object, options?: I.KeysOptions): Array<string | any>;
function toDotNotation(object: object): object;
namespace I {
interface FlattenOptions {
depth?: number;
}
}
function flatten(array: any[], options?: I.FlattenOptions): any[];
function globParent(str: string): string;
namespace I {
interface ByResult<S, T, R> {
(a: S, b: S): R;
compare(a: T, b: T): R;
by(a: S): T;
}
}
function by<S, T, R>(by: (a: S) => T, compare?: (a: T, b: T) => R): I.ByResult<S, T, R>;
function toFastProperties(object: object): object;
function stripBom(x: string): string;
namespace I {
interface SortKeysOptions {
deep?: boolean;
compare?(a: any, b: any): number;
}
}
function sortKeys(object: object, options?: I.SortKeysOptions): object;
namespace I {
interface GlobizeOptions {
exts?: string;
recursively?: boolean;
}
}
function globize(path: string, options?: I.GlobizeOptions): string;
function unique<T>(array: T[], projection?: (a: T) => any): T[];
function invertObject(source: object, options?: I.KeysOptions): object;
namespace I {
interface HumanizeTimeOptions {
msDecimalDigits?: number;
secDecimalDigits?: number;
verbose?: boolean;
compact?: boolean;
}
}
function humanizeTime(ms: number, options?: I.HumanizeTimeOptions): string;
function humanizeSize(num: number, space?: string): string;
function parseSize(str: string | number): number | null;
namespace I {
interface CloneOptions {
deep?: boolean;
}
}
function clone(object: object, options?: I.CloneOptions): object;
function toUTF8Array(str: string): number[];
function asyncIter<T>(array: T[], iter: (elem: T, index: number, cb: () => void) => any, cb: () => void): void;
function asyncFor<T>(obj: { [key: string]: T }, iter: (key: string, value: T, index: number, length: number, next: () => void) => void, cb: () => void): void;
namespace I {
interface OnceOptions {
silent: boolean;
}
}
function once<T>(fn: (...args: any[]) => T, options?: I.OnceOptions): (...args: any[]) => T;
namespace I {
type WaterFallTask = (...args: any[]) => void;
}
function asyncWaterfall<T>(tasks: I.WaterFallTask[], callback?: (err?: Error | null, ...args: any[]) => void): void;
function xrange(start?: number, stop?: number, step?: number): IterableIterator<number>;
function range(start?: number, stop?: number, step?: number): number[];
function reFindAll(regexp: RegExp, str: string): RegExpExecArray[];
function assignDeep<T>(target: T, ...sources: object[]): T;
namespace I {
interface MatchOptions {
index?: boolean;
start?: number;
end?: number;
dot?: boolean;
}
}
function match(criteria: any | any[], options?: I.MatchOptions): (value: any | any[], options?: I.MatchOptions) => number | boolean;
function match(criteria: any | any[], value: any | any[], options?: I.MatchOptions): number | boolean;
namespace I {
interface ToposortFunction {
<T>(edges: Array<[T, T]>): T[];
array<T>(nodes: T[], edges: Array<[T, T]>): T[];
}
}
const toposort: I.ToposortFunction;
namespace I {
interface JSEscOptions {
escapeEverything?: boolean;
minimal?: boolean;
isScriptContext?: boolean;
quotes?: string;
wrap?: boolean;
es6?: boolean;
json?: boolean;
compact?: boolean;
lowercaseHex?: boolean;
numbers?: string;
indent?: string;
indentLevel?: number;
__inline1__?: boolean;
__inline2__?: boolean;
}
}
function jsesc(argument: any, options?: I.JSEscOptions): string;
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;
namespace memcpy {
function utou(target: Buffer, targetOffset: number, source: Buffer, sourceStart: number, sourceEnd: number): number;
function atoa(target: ArrayBuffer, targetOffset: number, source: ArrayBuffer, sourceStart: number, sourceEnd: number): number;
function atou(target: Buffer, targetOffset: number, source: ArrayBuffer, sourceStart: number, sourceEnd: number): number;
function utoa(target: ArrayBuffer, targetOffset: number, source: Buffer, sourceStart: number, sourceEnd: number): number;
function copy(target: Buffer | ArrayBuffer, targetOffset: number, source: Buffer | ArrayBuffer, sourceStart: number, sourceEnd: number): number;
}
namespace uuid {
namespace I {
interface V1Options {
clockseq?: number;
msecs?: number;
nsecs?: number;
}
}
function v1(options?: I.V1Options): string;
function v1(options: I.V1Options, buf: any[], offset?: number): number[];
function v4(options?: any): string;
function v4(options: any, buf: any[], offset?: number): number[];
function v5(name: string | number[], namespace: string | number[]): string;
function v5(name: string | number[], namespace: string | number[], buf: any[], offset?: number): number[];
}
namespace I {
interface Delegator {
method(name: string): Delegator;
access(name: string): Delegator;
getter(name: string): Delegator;
setter(name: string): Delegator;
}
}
function delegate(object: object, property: string): I.Delegator;
namespace I {
interface GlobExpOptions {
nocomment?: boolean;
nonegate?: boolean;
nobrace?: boolean;
noglobstar?: boolean;
nocase?: boolean;
dot?: boolean;
noext?: boolean;
matchBase?: boolean;
flipNegate?: boolean;
}
}
class GlobExp {
constructor(pattern: string, options?: I.GlobExpOptions);
hasMagic(): boolean;
static hasMagic(pattern: string, options?: I.GlobExpOptions): boolean;
expandBraces(): string[];
static expandBraces(pattern: string, options?: I.GlobExpOptions): string[];
makeRe(): RegExp;
static makeRe(pattern: string, options?: I.GlobExpOptions): RegExp;
static test(p: string, pattern: string, options?: I.GlobExpOptions): boolean;
test(p: string): boolean;
}
namespace iconv {
// TODO: need to normalize source code
}
namespace sqlstring {
function escapeId(val: string | string[], forbidQualified?: boolean): string;
function dateToString(date: any, timeZone?: string): string;
function arrayToList(array: any[]): string;
function bufferToString(buffer: Buffer): string;
function objectToValues(object: object, timeZone?: string): string;
function escape(value: any, stringifyObjects?: boolean, timeZone?: string): string;
function format(sql: string, values?: any | any[], stringifyObjects?: boolean, timeZone?: string): string;
}
namespace I {
interface EditorOptions {
text?: string;
editor?: string;
path?: string;
ext?: string;
}
}
class Editor {
static DEFAULT: string;
constructor(options?: I.EditorOptions);
spawn(): Promise<adone.std.child_process.ChildProcess>;
run(): Promise<string>;
cleanup(): Promise<void>;
static edit(options?: I.EditorOptions): Promise<string>;
}
namespace I {
interface BinarySearchFunction {
<T>(aHaystack: T[], aNeedle: number, aLow?: number, aHigh?: number, aCompare?: (a: T, b: T) => number, aBias?: number): T;
GREATEST_LOWER_BOUND: number;
LEAST_UPPER_BOUND: number;
}
}
const binarySearch: I.BinarySearchFunction;
namespace buffer {
function concat(list: Buffer[], totalLength: number): Buffer;
function mask(buffer: Buffer, mask: Buffer, output: Buffer, offset: number, length: number): void;
function unmask(buffer: Buffer, mask: Buffer): void;
}
function shebang(str: string): string | null;
class ReInterval {
constructor(callback: (...args: any[]) => void, interval: number, args?: any[]);
reschedule(interval: number): void;
clear(): void;
destroy(): void;
}
class RateLimiter {
constructor(tokensPerInterval?: number, interval?: number, fireImmediately?: boolean);
removeTokens(count: number): Promise<number>;
tryRemoveTokens(count: number): boolean;
getTokensRemaining(): number;
}
namespace I {
interface ThrottleOptions {
max?: number;
interval?: number;
ordered?: boolean;
waitForReturn?: boolean;
}
}
function throttle<R>(fn: () => R, options?: I.ThrottleOptions): () => Promise<R>;
function throttle<T1, R>(fn: (a: T1) => R, options?: I.ThrottleOptions): (a: T1) => Promise<R>;
function throttle<T1, T2, R>(fn: (a: T1, b: T2) => R, options?: I.ThrottleOptions): (a: T1, b: T2) => Promise<R>;
function throttle<T1, T2, T3, R>(fn: (a: T1, b: T2, c: T3) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3) => Promise<R>;
function throttle<T1, T2, T3, T4, R>(fn: (a: T1, b: T2, c: T3, d: T4) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3, d: T4) => Promise<R>;
function throttle<T1, T2, T3, T4, T5, R>(fn: (a: T1, b: T2, c: T3, d: T4, e: T5) => R, options?: I.ThrottleOptions): (a: T1, b: T2, c: T3, d: T4, e: T5) => Promise<R>;
function throttle<R>(fn: (...args: any[]) => R, options?: I.ThrottleOptions): (...args: any[]) => Promise<R>;
namespace I.fakeClock {
interface Timer {
id: number;
ref(): void;
unref(): void;
}
interface Clock {
setTimeout(func: (...args: any[]) => void, timeout: number, ...args: any[]): Timer;
clearTimeout(timer: Timer): void;
nextTick(func: (...args: any[]) => void, ...args: any[]): void;
setInterval(func: (...args: any[]) => void, ...args: any[]): Timer;
clearInterval(timer: Timer): void;
setImmediate(func: (...args: any[]) => void, ...args: any[]): Timer;
clearImmediate(timer: Timer): void;
updateHrTime(newNow: number): void;
tick(ms: number): number;
next(): number;
runAll(): number;
runToLast(): number;
setSystemTime(systemTime: number): void;
hrtime(prev?: [number, number]): [number, number];
}
interface InstalledClock extends Clock {
uninstall(): void;
}
interface InstallOptions {
target?: object;
now?: number;
toFake?: string[];
loopLimit?: number;
shouldAdvanceTime?: boolean;
advanceTimeDelta?: number;
}
interface Timers {
setTimeout: typeof global.setTimeout;
clearTimeout: typeof global.clearTimeout;
setInterval: typeof global.setInterval;
clearInterval: typeof global.clearInterval;
setImmediate: typeof global.setImmediate;
clearImmediate: typeof global.clearImmediate;
Date: typeof global.Date;
hrtime: typeof global.process.hrtime;
nextTick: typeof global.process.nextTick;
}
interface FakeClock {
timers: Timers;
createClock(now?: number, loopLimit?: number): Clock;
install(now?: number | Date | InstallOptions): InstalledClock;
}
}
const fakeClock: I.fakeClock.FakeClock;
namespace ltgt {
namespace I {
interface Range<T> {
lt?: T;
lte?: T;
gt?: T;
gte?: T;
min?: T;
max?: T;
start?: T;
end?: T;
reverse?: boolean;
}
type Comparator<T> = (a: T, b: T) => number;
}
function contains<T>(range: I.Range<T>, key: T, compare?: I.Comparator<T>): boolean;
function filter<T>(range: I.Range<T>, compare?: I.Comparator<T>): (key: T) => boolean;
function toLtgt<T, R>(
range: I.Range<T>,
_range: object,
map?: (value: T, isUpperBound: boolean) => R,
lowerBound?: T,
upperBound?: T
): I.Range<R>;
function endInclusive<T>(range: I.Range<T>): boolean;
function startInclusive<T>(range: I.Range<T>): boolean;
function end<T>(range: I.Range<T>): T | undefined;
function end<T, R>(range: I.Range<T>, defaultValue: R): T | R;
function start<T>(range: I.Range<T>): T | undefined;
function start<T, R>(range: I.Range<T>, defaultValue?: R): T | R;
function upperBound<T>(range: I.Range<T>): T | undefined;
function upperBound<T, R>(range: I.Range<T>, defaultValue: R): T | R;
function upperBoundKey<T>(range: I.Range<T>): T | undefined;
function upperBoundExclusive<T>(range: I.Range<T>): boolean;
function lowerBoundExclusive<T>(range: I.Range<T>): boolean;
function upperBoundInclusive<T>(range: I.Range<T>): boolean;
function lowerBoundInclusive<T>(range: I.Range<T>): boolean;
function lowerBound<T>(range: I.Range<T>): T | undefined;
function lowerBound<T, R>(range: I.Range<T>, defaultValue: R): T | R;
function lowerBoundKey<T>(range: I.Range<T>): T | undefined;
}
}
+9
View File
@@ -0,0 +1,9 @@
// Type definitions for adone 0.6
// Project: https://github.com/ciferox/adone
// Definitions by: am <https://github.com/s0m3on3>, Maximus <https://github.com/maxveres>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import * as adone from "./adone";
export default adone;
+653
View File
@@ -0,0 +1,653 @@
namespace assertionTests {
const { assertion } = adone;
namespace assertionInterface {
namespace exception {
const a: adone.x.Exception = new assertion.AssertionError();
const b: adone.x.Exception = new assertion.AssertionError("hello");
const c: adone.x.Exception = new assertion.AssertionError("hello", { actual: 2, expected: 3 }, () => {});
}
namespace config {
assertion.config.includeStack = true;
assertion.config.proxyExcludedKeys = ["a"];
assertion.config.showDiff = false;
assertion.config.truncateThreshold = 20;
assertion.config.useProxy = false;
}
namespace loadInterfaces {
assertion.loadAssertInterface().config.includeStack = true;
assertion.loadExpectInterface().config.includeStack = true;
assertion.loadMockInterface().config.includeStack = true;
}
namespace use {
assertion.use(() => {}).use(() => {}).config.includeStack = true;
}
}
const { assert } = assertion;
namespace assertTests {
assert(1);
assert(1, "hello");
assert.fail();
assert.fail(1);
assert.fail(1, 2);
assert.fail(1, 2, "hello");
assert.fail(1, 2, "hello", "<");
assert.isOk(1);
assert.isOk(1, "hello");
assert.isNotOk(1);
assert.isNotOk(1, "hello");
assert.equal(1, 2);
assert.equal(1, 2, "hello");
assert.notEqual(1, 2);
assert.notEqual(1, 2, "hello");
assert.strictEqual(1, 2);
assert.strictEqual(1, 2, "hello");
assert.notStrictEqual(1, 2);
assert.notStrictEqual(1, 2, "hello");
assert.deepEqual(1, 2);
assert.deepEqual(1, 2, "hello");
assert.deepStrictEqual(1, 2);
assert.deepStrictEqual(1, 2, "hello");
assert.equalArrays([1, 2, 3], [4, 5, 6]);
assert.equalArrays([1, 2, 3], [4, 5, 6], "hello");
assert.notDeepEqual(1, 2);
assert.notDeepEqual(1, 2, "hello");
assert.isAbove(1, 2);
assert.isAbove(1, 2, "hello");
assert.isAtLeast(1, 2);
assert.isAtLeast(1, 2, "hello");
assert.isBelow(1, 2);
assert.isBelow(1, 2, "hello");
assert.isAtMost(1, 2);
assert.isAtMost(1, 2, "hello");
assert.isTrue(1);
assert.isTrue(1, "hello");
assert.isNotTrue(1);
assert.isNotTrue(1, "hello");
assert.isFalse(1);
assert.isFalse(1, "hello");
assert.isNotFalse(1);
assert.isNotFalse(1, "hello");
assert.isNull(1);
assert.isNull(1, "hello");
assert.isNaN(1);
assert.isNaN(1, "hello");
assert.isNotNaN(1);
assert.isNotNaN(1, "hello");
assert.exists(1);
assert.exists(1, "hello");
assert.notExists(1);
assert.notExists(1, "hello");
assert.isUndefined(1);
assert.isUndefined(1, "hello");
assert.isDefined(1);
assert.isDefined(1, "hello");
assert.isFunction(1);
assert.isFunction(1, "hello");
assert.isNotFunction(1);
assert.isNotFunction(1, "hello");
assert.isObject(1);
assert.isObject(1, "hello");
assert.isNotObject(1);
assert.isNotObject(1, "hello");
assert.isArray(1);
assert.isArray(1, "hello");
assert.isNotArray(1);
assert.isNotArray(1, "hello");
assert.isString(1, "hello");
assert.isNotString(1);
assert.isNotString(1, "hello");
assert.isNumber(1);
assert.isNumber(1, "hello");
assert.isNotNumber(1);
assert.isNotNumber(1, "hello");
assert.isFinite(1);
assert.isFinite(1, "hello");
assert.isBoolean(1);
assert.isBoolean(1, "hello");
assert.isNotBoolean(1);
assert.isNotBoolean(1, "hello");
assert.typeOf(1, "string");
assert.typeOf(1, "number", "hello");
assert.notTypeOf(1, "string");
assert.notTypeOf(1, "number", "hello");
assert.instanceOf(1, Date);
class A {}
assert.instanceOf("4", A, "hello");
assert.notInstanceOf(1, Date);
assert.notInstanceOf(Date, A, "hello");
assert.include([1, 2, 3], 4);
assert.include([1, 2, 3], 4, "hello");
assert.include("string", "string");
assert.include("string", "string", "string");
assert.notInclude([1, 2, 3], 4);
assert.notInclude([1, 2, 3], 4, "hello");
assert.notInclude("string", "string");
assert.notInclude("string", "string", "string");
assert.deepInclude([1, 2, 3], 4);
assert.deepInclude([1, 2, 3], 4, "hello");
assert.deepInclude("string", "string");
assert.deepInclude("string", "string", "string");
assert.notDeepInclude([1, 2, 3], 4);
assert.notDeepInclude([1, 2, 3], 4, "hello");
assert.notDeepInclude("string", "string");
assert.notDeepInclude("string", "string", "string");
assert.nestedInclude({ a: 1 }, {});
assert.nestedInclude({ a: 1 }, {}, "hello");
assert.notNestedInclude({ a: 1 }, {});
assert.notNestedInclude({ a: 1 }, {}, "hello");
assert.deepNestedInclude({ a: 1 }, {});
assert.deepNestedInclude({ a: 1 }, {}, "hello");
assert.notDeepNestedInclude({ a: 1 }, {});
assert.notDeepNestedInclude({ a: 1 }, {}, "hello");
assert.ownInclude({ a: 1 }, {});
assert.ownInclude({ a: 1 }, {}, "hello");
assert.notOwnInclude({ a: 1 }, {});
assert.notOwnInclude({ a: 1 }, {}, "hello");
assert.deepOwnInclude({ a: 1 }, {});
assert.deepOwnInclude({ a: 1 }, {}, "hello");
assert.notDeepOwnInclude({ a: 1 }, {});
assert.notDeepOwnInclude({ a: 1 }, {}, "hello");
assert.match("1", /\d+/);
assert.match("1", /\d+/, "hello");
assert.notMatch("1", /\d+/);
assert.notMatch("1", /\d+/, "hello");
assert.property({ a: 1 }, "a");
assert.property({ a: 1 }, "a", "hello");
assert.notProperty({ a: 1 }, "a");
assert.notProperty({ a: 1 }, "a", "hello");
assert.propertyVal({ a: 1 }, "a", 1);
assert.propertyVal({ a: 1 }, "a", 1, "hello");
assert.notPropertyVal({ a: 1 }, "a", 1);
assert.notPropertyVal({ a: 1 }, "a", 1, "hello");
assert.deepPropertyVal({ a: 1 }, "a", 1);
assert.deepPropertyVal({ a: 1 }, "a", 1, "hello");
assert.notDeepPropertyVal({ a: 1 }, "a", 1);
assert.notDeepPropertyVal({ a: 1 }, "a", 1, "hello");
assert.ownProperty({ a: 1 }, "a");
assert.ownProperty({ a: 1 }, "a", "hello");
assert.notOwnProperty({ a: 1 }, "a");
assert.notOwnProperty({ a: 1 }, "a", "hello");
assert.ownPropertyVal({ a: 1 }, "a", 1);
assert.ownPropertyVal({ a: 1 }, "a", 1, "hello");
assert.deepOwnPropertyVal({ a: 1 }, "a", 1);
assert.deepOwnPropertyVal({ a: 1 }, "a", 1, "hello");
assert.notDeepOwnPropertyVal({ a: 1 }, "a", 1);
assert.notDeepOwnPropertyVal({ a: 1 }, "a", 1, "hello");
assert.nestedProperty({ a: 1 }, "a");
assert.nestedProperty({ a: 1 }, "a", "hello");
assert.notNestedProperty({ a: 1 }, "a");
assert.notNestedProperty({ a: 1 }, "a", "hello");
assert.nestedPropertyVal({ a: 1 }, "a", 1);
assert.nestedPropertyVal({ a: 1 }, "a", 1, "hello");
assert.notNestedPropertyVal({ a: 1 }, "a", 1);
assert.notNestedPropertyVal({ a: 1 }, "a", 1, "hello");
assert.deepNestedPropertyVal({ a: 1 }, "a", 1);
assert.deepNestedPropertyVal({ a: 1 }, "a", 1, "hello");
assert.notDeepNestedPropertyVal({ a: 1 }, "a", 1);
assert.notDeepNestedPropertyVal({ a: 1 }, "a", 1, "hello");
assert.lengthOf([1, 2, 3], 3);
assert.lengthOf([1, 2, 3], 3, "hello");
assert.hasAnyKeys({ a: 1 }, "a");
assert.hasAnyKeys({ a: 1 }, ["a"]);
assert.hasAnyKeys({ a: 1 }, ["a"], "hello");
assert.hasAnyKeys({ a: 1 }, { a: 1 });
assert.hasAnyKeys({ a: 1 }, { a: 1 }, "hello");
assert.hasAllKeys({ a: 1 }, "a");
assert.hasAllKeys({ a: 1 }, ["a"]);
assert.hasAllKeys({ a: 1 }, ["a"], "hello");
assert.hasAllKeys({ a: 1 }, { a: 1 });
assert.hasAllKeys({ a: 1 }, { a: 1 }, "hello");
assert.containsAllKeys({ a: 1 }, "a");
assert.containsAllKeys({ a: 1 }, ["a"]);
assert.containsAllKeys({ a: 1 }, ["a"], "hello");
assert.containsAllKeys({ a: 1 }, { a: 1 });
assert.containsAllKeys({ a: 1 }, { a: 1 }, "hello");
assert.doesNotHaveAnyKeys({ a: 1 }, "a");
assert.doesNotHaveAnyKeys({ a: 1 }, ["a"]);
assert.doesNotHaveAnyKeys({ a: 1 }, ["a"], "hello");
assert.doesNotHaveAnyKeys({ a: 1 }, { a: 1 });
assert.doesNotHaveAnyKeys({ a: 1 }, { a: 1 }, "hello");
assert.doesNotHaveAllDeepKeys({ a: 1 }, "a");
assert.doesNotHaveAllDeepKeys({ a: 1 }, ["a"]);
assert.doesNotHaveAllDeepKeys({ a: 1 }, ["a"], "hello");
assert.doesNotHaveAllDeepKeys({ a: 1 }, { a: 1 });
assert.doesNotHaveAllDeepKeys({ a: 1 }, { a: 1 }, "hello");
assert.hasAnyDeepKeys({ a: 1 }, "a");
assert.hasAnyDeepKeys({ a: 1 }, ["a"]);
assert.hasAnyDeepKeys({ a: 1 }, ["a"], "hello");
assert.hasAnyDeepKeys({ a: 1 }, { a: 1 });
assert.hasAnyDeepKeys({ a: 1 }, { a: 1 }, "hello");
assert.hasAllDeepKeys({ a: 1 }, "a");
assert.hasAllDeepKeys({ a: 1 }, ["a"]);
assert.hasAllDeepKeys({ a: 1 }, ["a"], "hello");
assert.hasAllDeepKeys({ a: 1 }, { a: 1 });
assert.hasAllDeepKeys({ a: 1 }, { a: 1 }, "hello");
assert.containsAllDeepKeys({ a: 1 }, "a");
assert.containsAllDeepKeys({ a: 1 }, ["a"]);
assert.containsAllDeepKeys({ a: 1 }, ["a"], "hello");
assert.containsAllDeepKeys({ a: 1 }, { a: 1 });
assert.containsAllDeepKeys({ a: 1 }, { a: 1 }, "hello");
assert.doesNotHaveAnyDeepKeys({ a: 1 }, "a");
assert.doesNotHaveAnyDeepKeys({ a: 1 }, ["a"]);
assert.doesNotHaveAnyDeepKeys({ a: 1 }, ["a"], "hello");
assert.doesNotHaveAnyDeepKeys({ a: 1 }, { a: 1 });
assert.doesNotHaveAnyDeepKeys({ a: 1 }, { a: 1 }, "hello");
assert.doesNotHaveAllDeepKeys({ a: 1 }, "a");
assert.doesNotHaveAllDeepKeys({ a: 1 }, ["a"]);
assert.doesNotHaveAllDeepKeys({ a: 1 }, ["a"], "hello");
assert.doesNotHaveAllDeepKeys({ a: 1 }, { a: 1 });
assert.doesNotHaveAllDeepKeys({ a: 1 }, { a: 1 }, "hello");
assert.throws(() => {});
assert.throws(() => {}, Error);
assert.throws(() => {}, Error, /\d+/);
assert.throws(() => {}, Error, "string");
assert.throws(() => {}, Error, "string", "hello");
assert.throws(async () => {}).then(() => 42);
assert.throws(async () => {}, Error).then(() => 42);
assert.throws(async () => {}, Error, /\d+/).then(() => 42);
assert.throws(async () => {}, Error, "string").then(() => 42);
assert.throws(async () => {}, Error, "string", "hello").then(() => 42);
assert.doesNotThrow(() => {});
assert.doesNotThrow(() => {}, Error);
assert.doesNotThrow(() => {}, Error, /\d+/);
assert.doesNotThrow(() => {}, Error, "string");
assert.doesNotThrow(() => {}, Error, "string", "hello");
assert.doesNotThrow(async () => {}).then(() => 42);
assert.doesNotThrow(async () => {}, Error).then(() => 42);
assert.doesNotThrow(async () => {}, Error, /\d+/).then(() => 42);
assert.doesNotThrow(async () => {}, Error, "string").then(() => 42);
assert.doesNotThrow(async () => {}, Error, "string", "hello").then(() => 42);
assert.operator(1, "<", 2);
assert.operator(1, "<", 2, "hello");
assert.closeTo(1, 2, 1);
assert.closeTo(1, 2, 1, "hello");
assert.approximately(1, 2, 2);
assert.approximately(1, 2, 2, "hello");
assert.sameMembers([1, 2, 3], [4, 5, 6]);
assert.sameMembers([1, 2, 3], [4, 5, 6], "hello");
assert.notSameMembers([1, 2, 3], [4, 5, 6]);
assert.notSameMembers([1, 2, 3], [4, 5, 6], "hello");
assert.sameDeepMembers([1, 2, 3], [4, 5, 6]);
assert.sameDeepMembers([1, 2, 3], [4, 5, 6], "hello");
assert.notSameDeepMembers([1, 2, 3], [4, 5, 6]);
assert.notSameDeepMembers([1, 2, 3], [4, 5, 6], "hello");
assert.sameOrderedMembers([1, 2, 3], [4, 5, 6]);
assert.sameOrderedMembers([1, 2, 3], [4, 5, 6], "hello");
assert.notSameOrderedMembers([1, 2, 3], [4, 5, 6]);
assert.notSameOrderedMembers([1, 2, 3], [4, 5, 6], "hello");
assert.includeMembers([1, 2, 3], [3]);
assert.includeMembers([1, 2, 3], [3], "hello");
assert.notIncludeMembers([1, 2, 3], [3]);
assert.notIncludeMembers([1, 2, 3], [3], "hello");
assert.includeDeepMembers([1, 2, 3], [3]);
assert.includeDeepMembers([1, 2, 3], [3], "hello");
assert.notIncludeDeepMembers([1, 2, 3], [3]);
assert.notIncludeDeepMembers([1, 2, 3], [3], "hello");
assert.includeOrderedMembers([1, 2, 3], [3]);
assert.includeOrderedMembers([1, 2, 3], [3], "hello");
assert.notIncludeOrderedMembers([1, 2, 3], [3]);
assert.notIncludeOrderedMembers([1, 2, 3], [3], "hello");
assert.includeDeepOrderedMembers([1, 2, 3], [3]);
assert.includeDeepOrderedMembers([1, 2, 3], [3], "hello");
assert.notIncludeDeepOrderedMembers([1, 2, 3], [3]);
assert.notIncludeDeepOrderedMembers([1, 2, 3], [3], "hello");
assert.oneOf(1, [1, 2, 3]);
assert.oneOf(1, [1, 2, 3], "hello");
assert.changes(() => {}, {}, "a");
assert.changes(() => {}, {}, "a", "hello");
assert.changesBy(() => {}, {}, "a", 2);
assert.changesBy(() => {}, {}, "a", 2, "hello");
assert.doesNotChange(() => {}, {}, "a");
assert.doesNotChange(() => {}, {}, "a", "hello");
assert.changesButNotBy(() => {}, {}, "a", 20);
assert.changesButNotBy(() => {}, {}, "a", 20, "hello");
assert.increases(() => {}, {}, "a");
assert.increases(() => {}, {}, "a", "hello");
assert.increasesBy(() => {}, {}, "a", 20);
assert.increasesBy(() => {}, {}, "a", 20, "hello");
assert.doesNotIncrease(() => {}, {}, "a");
assert.doesNotIncrease(() => {}, {}, "a", "hello");
assert.increasesButNotBy(() => {}, {}, "a", 20);
assert.increasesButNotBy(() => {}, {}, "a", 20, "hello");
assert.decreases(() => {}, {}, "a");
assert.decreases(() => {}, {}, "a", "hello");
assert.decreasesBy(() => {}, {}, "a", 20);
assert.decreasesBy(() => {}, {}, "a", 20, "hello");
assert.doesNotDecrease(() => {}, {}, "a");
assert.doesNotDecrease(() => {}, {}, "a", "hello");
assert.doesNotDecreaseBy(() => {}, {}, "a", 20);
assert.doesNotDecreaseBy(() => {}, {}, "a", 20, "hello");
assert.decreasesButNotBy(() => {}, {}, "a", 20);
assert.decreasesButNotBy(() => {}, {}, "a", 20, "hello");
assert.ifError(1);
assert.isExtensible({});
assert.isExtensible({}, "hello");
assert.isNotExtensible({});
assert.isNotExtensible({}, "hello");
assert.isSealed({});
assert.isSealed({}, "hello");
assert.isNotSealed({});
assert.isNotSealed({}, "hello");
assert.isFrozen({});
assert.isFrozen({}, "hello");
assert.isNotFrozen({});
assert.isNotFrozen({}, "hello");
assert.isEmpty({});
assert.isEmpty({}, "hello");
}
const { expect } = assertion;
namespace expectTests {
expect(1);
expect(1, "hello");
expect.fail(1, 2);
expect.fail(1, 2, "hello");
expect.fail(1, 2, "hello", "+");
expect(1).to.be.been.is.and.has.have.with.that.which.at.of.same.but.does.not.deep.nested.own.ordered.any.all.a("number");
expect(1).to.be.a("number", "hello").and;
expect(1).to.be.an("array").and;
expect(1).to.be.an("array", "hello").and;
expect(1).to.include(1).and;
expect(1).to.include(1, "hello").and;
expect(1).but.includes(2).and;
expect(1).but.includes(2, "hello").and;
expect(1).to.contain(2).and;
expect(1).to.contain(2, "hello").and;
expect(1).but.contains(2).and;
expect(1).but.contains(2, "hello").and;
expect(1).to.ok.not.ok;
expect(1).to.be.true.but.false;
expect(1).to.be.false.but.true;
expect(1).to.be.null.and.null;
expect(1).to.be.undefined.and.true;
expect(1).to.be.NaN.and.null;
expect(1).to.exist.and.be.null;
expect(1).to.be.empty.and.true;
expect(1).to.be.arguments.and.a("number");
expect(1).to.be.Arguments.and.false;
expect(1).to.be.equal(2).and;
expect(1).to.be.equal(2, "hello").and;
expect(1).but.equals(2).and;
expect(1).but.equals(2, "hello").and;
expect(1).to.eq(2).and;
expect(1).to.eq(2, "hello").and;
expect(1).but.eqls(2).and;
expect(1).but.eqls(2, "hello").and;
expect(1).to.eqlArray([1, 2, 3]).and;
expect(1).to.eqlArray([1, 2, 3], "hello").and;
expect(1).to.be.above(2).and;
expect(1).to.be.above(2, "hello").and;
expect(1).to.be.gt(2).and;
expect(1).to.be.gt(2, "hello").and;
expect(1).to.be.greaterThan(2).and;
expect(1).to.be.greaterThan(2, "hello").and;
expect(1).to.be.at.least(10).and;
expect(1).to.be.at.least(10, "hello").and;
expect(1).to.be.gte(10).and;
expect(1).to.be.gte(10, "hello").and;
expect(1).to.be.below(100).and;
expect(1).to.be.below(100, "hello").and;
expect(1).to.be.lt(10).and;
expect(1).to.be.lt(10, "hello").and;
expect(1).to.be.lessThan(10, "hello").and;
expect(1).to.be.at.most(10).and;
expect(1).to.be.at.most(10, "hello").and;
expect(1).to.be.lte(10).and;
expect(1).to.be.lte(10, "hello").and;
expect(1).to.be.within(1, 10).and;
expect(1).to.be.within(1, 10, "hello").and;
expect(1).to.be.instanceof(Number).and;
expect(1).to.be.instanceof(Number, "hello").and;
expect(1).to.be.instanceOf(Number).and;
expect(1).to.be.instanceOf(Number, "hello").and;
expect(1).to.have.property("a").and;
expect(1).to.have.property("a", 1).and;
expect(1).to.have.property("a", 1, "hello").and;
expect(1).to.have.ownProperty("a").and;
expect(1).to.have.ownProperty("a", 1).and;
expect(1).to.have.ownProperty("a", 1, "hello").and;
expect(1).to.haveOwnProperty("a").and;
expect(1).to.haveOwnProperty("a", 1).and;
expect(1).to.haveOwnProperty("a", 1, "hello").and;
expect(1).to.have.ownPropertyDescriptor("a").and;
expect(1).to.have.ownPropertyDescriptor("a", {}).and;
expect(1).to.have.ownPropertyDescriptor("a", {}, "hello").and;
expect(1).to.haveOwnPropertyDescriptor("a").and;
expect(1).to.haveOwnPropertyDescriptor("a", {}).and;
expect(1).to.haveOwnPropertyDescriptor("a", {}, "hello").and;
expect("a").to.have.length(1).and;
expect("a").to.have.length(1, "hello").and;
expect("a").to.have.lengthOf(1).and;
expect("a").to.have.lengthOf(1, "hello").and;
expect(1).to.match(/\d+/).and;
expect(1).to.match(/\d+/, "hello").and;
expect(1).to.have.string("1230").and;
expect(1).to.have.string("1230", "hello").and;
expect(1).to.have.key("a").and;
expect(1).to.have.key("a", "b").and;
expect(1).to.have.key(["a", "b"]).and;
expect(1).to.have.key({ a: 1, b: 2 }).and;
expect(1).to.have.keys("a").and;
expect(1).to.have.keys("a", "b").and;
expect(1).to.have.keys(["a", "b"]).and;
expect(1).to.have.keys({ a: 1, b: 2 }).and;
expect(() => {}).to.throw().and;
expect(() => {}).to.throw(Error).and;
expect(() => {}).to.throw(Error, "string").and;
expect(() => {}).to.throw(Error, "string", "hello").and;
expect(() => {}).to.throw(Error, /\d+/).and;
expect(() => {}).to.throw(Error, /\d+/, "hello").and;
expect(() => {}).but.throws().and;
expect(() => {}).but.throws(Error).and;
expect(() => {}).but.throws(Error, "string").and;
expect(() => {}).but.throws(Error, "string", "hello").and;
expect(() => {}).but.throws(Error, /\d+/).and;
expect(() => {}).but.throws(Error, /\d+/, "hello").and;
expect(1).to.respondTo("a").and;
expect(1).to.respondTo("a", "hello").and;
expect(1).to.respondsTo("a").and;
expect(1).to.respondsTo("a", "hello").and;
expect(1).itself.to.respondsTo("a").and;
expect(1).to.satisfy(() => true).and;
expect(1).to.satisfy(() => true, "hello").and;
expect(1).but.satisfies(() => true).and;
expect(1).but.satisfies(() => true, "hello").and;
expect(1).to.be.closeTo(2, 1).and;
expect(1).to.be.closeTo(2, 1, "hello").and;
expect(1).to.be.approximately(1, 2).and;
expect(1).to.be.approximately(1, 2, "hello").and;
expect(1).to.have.members([1, 2, 3]).and;
expect(1).to.have.members([1, 2, 3], "hello").and;
expect(1).to.be.oneOf([1, 2, 3]).and;
expect(1).to.be.oneOf([1, 2, 3], "hello").and;
expect(() => {}).to.change(() => {}).and;
expect(() => {}).to.change({}, "a").and;
expect(() => {}).to.change({}, "a", "hello").and;
expect(() => {}).but.changes(() => {}).and;
expect(() => {}).but.changes({}, "a").and;
expect(() => {}).but.changes({}, "a", "hello").and;
expect(() => {}).to.increase({}).and;
expect(() => {}).to.increase({}, "a").and;
expect(() => {}).to.increase({}, "a", "hello").and;
expect(() => {}).but.increases({}).and;
expect(() => {}).but.increases({}, "a").and;
expect(() => {}).but.increases({}, "a", "hello").and;
expect(() => {}).to.decrease({}).and;
expect(() => {}).to.decrease({}, "a").and;
expect(() => {}).to.decrease({}, "a", "hello").and;
expect(() => {}).but.decreases({}).and;
expect(() => {}).but.decreases({}, "a").and;
expect(() => {}).but.decreases({}, "a", "hello").and;
expect(() => {}).to.decreases({}).by(2).and;
expect(() => {}).to.decreases({}).by(2, "hello").and;
expect({}).to.be.extensible.and;
expect({}).to.be.sealed.and;
expect({}).to.be.frozen.and;
expect({}).to.be.finite.and;
namespace mockTests {
const s1 = adone.shani.util.spy();
const s2 = adone.shani.util.spy();
expect(s1).to.have.been.called;
expect(s1).to.have.been.calledOnce;
expect(s1).to.have.been.calledTwice;
expect(s1).to.have.been.calledThrice;
expect(s1).to.have.callCount(100);
expect(s1).to.have.been.calledBefore(s2);
expect(s1).to.have.been.calledAfter(s2);
expect(s1).to.have.been.calledImmediatelyAfter(s2);
expect(s1).to.have.been.calledImmediatelyBefore(s2);
expect(s1).to.have.been.calledOn({});
expect(s1).to.have.been.calledOn({});
expect(s1).to.have.been.calledWith(1, 2, 3);
expect(s1).to.have.been.calledWithExactly(1, 2, 3);
expect(s1).to.have.returned(1);
expect(s1).to.have.thrown({});
}
}
}
+808
View File
@@ -0,0 +1,808 @@
namespace commonTests {
namespace is {
{ const a: boolean = adone.is.null({}); }
{ const a: boolean = adone.is.undefined({}); }
{ const a: boolean = adone.is.exist({}); }
{ const a: boolean = adone.is.nil({}); }
{ const a: boolean = adone.is.number({}); }
{ const a: boolean = adone.is.numeral({}); }
{ const a: boolean = adone.is.infinite({}); }
{ const a: boolean = adone.is.odd({}); }
{ const a: boolean = adone.is.even({}); }
{ const a: boolean = adone.is.float({}); }
{ const a: boolean = adone.is.negativeZero({}); }
{ const a: boolean = adone.is.string({}); }
{ const a: boolean = adone.is.emptyString({}); }
{ const a: boolean = adone.is.substring("abc", "abcdef"); }
{ const a: boolean = adone.is.substring("abc", "abcdef", 0); }
{ const a: boolean = adone.is.prefix("abc", "abcdef"); }
{ const a: boolean = adone.is.suffix("def", "abbdef"); }
{ const a: boolean = adone.is.boolean({}); }
{ const a: boolean = adone.is.json({}); }
{ const a: boolean = adone.is.object({}); }
{ const a: boolean = adone.is.plainObject({}); }
{ const a: boolean = adone.is.class({}); }
{ const a: boolean = adone.is.emptyObject({}); }
{ const a: boolean = adone.is.propertyOwned({}, "a"); }
{ const a: boolean = adone.is.propertyDefined({}, "a"); }
{ const a: boolean = adone.is.conforms({}, {}); }
{ const a: boolean = adone.is.conforms({}, {}, true); }
{ const a: boolean = adone.is.arrayLikeObject({}); }
{ const a: boolean = adone.is.inArray(1, [1, 2, 3]); }
{ const a: boolean = adone.is.inArray(1, [1, 2, 3], 0); }
{ const a: boolean = adone.is.inArray(1, [1, 2, 3], 0, (a, b) => a === b); }
{ const a: boolean = adone.is.sameType({}, {}); }
{ const a: boolean = adone.is.primitive({}); }
{ const a: boolean = adone.is.equalArrays([], []); }
{ const a: boolean = adone.is.deepEqual({}, {}); }
{ const a: boolean = adone.is.shallowEqual({}, {}); }
{ const a: boolean = adone.is.stream({}); }
{ const a: boolean = adone.is.writableStream({}); }
{ const a: boolean = adone.is.readableStream({}); }
{ const a: boolean = adone.is.duplexStream({}); }
{ const a: boolean = adone.is.transformStream({}); }
{ const a: boolean = adone.is.utf8(Buffer.alloc(10)); }
{ const a: boolean = adone.is.win32PathAbsolute("abc"); }
{ const a: boolean = adone.is.posixPathAbsolute("abc"); }
{ const a: boolean = adone.is.pathAbsolute("abc"); }
{ const a: boolean = adone.is.glob("abc"); }
{ const a: boolean = adone.is.dotfile("abc"); }
{ const a: boolean = adone.is.function(() => { }); }
{ const a: boolean = adone.is.asyncFunction(async () => { }); }
{ const a: boolean = adone.is.promise({}); }
{ const a: boolean = adone.is.validDate("07.08.2017"); }
{ const a: boolean = adone.is.buffer({}); }
{ const a: boolean = adone.is.callback({}); }
{ const a: boolean = adone.is.generator({}); }
{ const a: boolean = adone.is.nan({}); }
{ const a: boolean = adone.is.finite({}); }
{ const a: boolean = adone.is.integer({}); }
{ const a: boolean = adone.is.safeInteger({}); }
{ const a: boolean = adone.is.array({}); }
{ const a: boolean = adone.is.uint8Array({}); }
{ const a: boolean = adone.is.configuration({}); }
{ const a: boolean = adone.is.long({}); }
{ const a: boolean = adone.is.bigNumber({}); }
{ const a: boolean = adone.is.exbuffer({}); }
{ const a: boolean = adone.is.exdate({}); }
{ const a: boolean = adone.is.transform({}); }
{ const a: boolean = adone.is.subsystem({}); }
{ const a: boolean = adone.is.application({}); }
{ const a: boolean = adone.is.logger({}); }
{ const a: boolean = adone.is.coreStream({}); }
{ const a: boolean = adone.is.fastStream({}); }
{ const a: boolean = adone.is.fastFSStream({}); }
{ const a: boolean = adone.is.fastFSMapStream({}); }
{ const a: boolean = adone.is.genesisNetron({}); }
{ const a: boolean = adone.is.genesisPeer({}); }
{ const a: boolean = adone.is.netronAdapter({}); }
{ const a: boolean = adone.is.netron({}); }
{ const a: boolean = adone.is.netronPeer({}); }
{ const a: boolean = adone.is.netronDefinition({}); }
{ const a: boolean = adone.is.netronDefinitions({}); }
{ const a: boolean = adone.is.netronReference({}); }
{ const a: boolean = adone.is.netronInterface({}); }
{ const a: boolean = adone.is.netronContext({}); }
{ const a: boolean = adone.is.netronIMethod({}, "hello"); }
{ const a: boolean = adone.is.netronIProperty({}, "hello"); }
{ const a: boolean = adone.is.netronStub({}); }
{ const a: boolean = adone.is.netronRemoteStub({}); }
{ const a: boolean = adone.is.netronStream({}); }
{ const a: boolean = adone.is.iterable({}); }
{ const a: boolean = adone.is.windows; }
{ const a: boolean = adone.is.linux; }
{ const a: boolean = adone.is.freebsd; }
{ const a: boolean = adone.is.darwin; }
{ const a: boolean = adone.is.sunos; }
{ const a: boolean = adone.is.uppercase("abc"); }
{ const a: boolean = adone.is.lowercase("abc"); }
{ const a: boolean = adone.is.digits("012"); }
{ const a: boolean = adone.is.identifier("someMethod"); }
{ const a: boolean = adone.is.binaryExtension("mp3"); }
{ const a: boolean = adone.is.binaryPath("a.mp3"); }
{ const a: boolean = adone.is.ip4("192.168.1.1"); }
{ const a: boolean = adone.is.ip6("::192.168.1.1"); }
{ const a: boolean = adone.is.arrayBuffer({}); }
{ const a: boolean = adone.is.arrayBufferView({}); }
{ const a: boolean = adone.is.date({}); }
{ const a: boolean = adone.is.error({}); }
{ const a: boolean = adone.is.map({}); }
{ const a: boolean = adone.is.regexp({}); }
{ const a: boolean = adone.is.set({}); }
{ const a: boolean = adone.is.symbol({}); }
{ const a: boolean = adone.is.validUTF8({}); }
}
namespace x {
{ const a: Error = new adone.x.Exception(); }
{ const a: Error = new adone.x.Exception("message"); }
{ const a: Error = new adone.x.Exception(new Error()); }
{ const a: Error = new adone.x.Exception(new Error(), true); }
{ const a: adone.x.Exception = new adone.x.Runtime(); }
{ const a: adone.x.Exception = new adone.x.IncompleteBufferError(); }
{ const a: adone.x.Exception = new adone.x.NotImplemented(); }
{ const a: adone.x.Exception = new adone.x.IllegalState(); }
{ const a: adone.x.Exception = new adone.x.NotValid(); }
{ const a: adone.x.Exception = new adone.x.Unknown(); }
{ const a: adone.x.Exception = new adone.x.NotExists(); }
{ const a: adone.x.Exception = new adone.x.Exists(); }
{ const a: adone.x.Exception = new adone.x.Empty(); }
{ const a: adone.x.Exception = new adone.x.InvalidAccess(); }
{ const a: adone.x.Exception = new adone.x.NotSupported(); }
{ const a: adone.x.Exception = new adone.x.InvalidArgument(); }
{ const a: adone.x.Exception = new adone.x.InvalidNumberOfArguments(); }
{ const a: adone.x.Exception = new adone.x.NotFound(); }
{ const a: adone.x.Exception = new adone.x.Timeout(); }
{ const a: adone.x.Exception = new adone.x.Incorrect(); }
{ const a: adone.x.Exception = new adone.x.NotAllowed(); }
{ const a: adone.x.Exception = new adone.x.LimitExceeded(); }
{ const a: adone.x.Exception = new adone.x.Encoding(); }
{ const a: adone.x.Exception = new adone.x.Network(); }
{ const a: adone.x.Exception = new adone.x.Bind(); }
{ const a: adone.x.Exception = new adone.x.Connect(); }
{ const a: adone.x.Exception = new adone.x.Database(); }
{ const a: adone.x.Exception = new adone.x.DatabaseInitialization(); }
{ const a: adone.x.Exception = new adone.x.DatabaseOpen(); }
{ const a: adone.x.Exception = new adone.x.DatabaseRead(); }
{ const a: adone.x.Exception = new adone.x.DatabaseWrite(); }
{ const a: adone.x.Exception = new adone.x.NetronIllegalState(); }
{ const a: adone.x.Exception = new adone.x.NetronPeerDisconnected(); }
{ const a: adone.x.Exception = new adone.x.NetronTimeout(); }
}
namespace EventEmitter {
namespace static {
const a: number = adone.EventEmitter.listenerCount(new adone.EventEmitter(), "event");
const b: number = adone.EventEmitter.defaultMaxListeners;
}
namespace addListener {
const a: adone.EventEmitter = new adone.EventEmitter().addListener("event", () => { });
const b: adone.EventEmitter = new adone.EventEmitter().addListener(Symbol("event"), () => { });
}
namespace on {
const a: adone.EventEmitter = new adone.EventEmitter().on("event", () => { });
const b: adone.EventEmitter = new adone.EventEmitter().on(Symbol("event"), () => { });
}
namespace once {
const a: adone.EventEmitter = new adone.EventEmitter().once("event", () => { });
const b: adone.EventEmitter = new adone.EventEmitter().once(Symbol("event"), () => { });
}
namespace prependListener {
const a: adone.EventEmitter = new adone.EventEmitter().prependListener("event", () => { });
const b: adone.EventEmitter = new adone.EventEmitter().prependListener(Symbol("event"), () => { });
}
namespace prependOnceListener {
const a: adone.EventEmitter = new adone.EventEmitter().prependOnceListener("event", () => { });
const b: adone.EventEmitter = new adone.EventEmitter().prependOnceListener(Symbol("event"), () => { });
}
namespace prependOnceListener {
const a: adone.EventEmitter = new adone.EventEmitter().prependOnceListener("event", () => { });
const b: adone.EventEmitter = new adone.EventEmitter().prependOnceListener(Symbol("event"), () => { });
}
namespace removeListener {
const a: adone.EventEmitter = new adone.EventEmitter().removeListener("event", () => { });
const b: adone.EventEmitter = new adone.EventEmitter().removeListener(Symbol("event"), () => { });
}
namespace removeAllListeners {
const a: adone.EventEmitter = new adone.EventEmitter().removeAllListeners("event");
const b: adone.EventEmitter = new adone.EventEmitter().removeAllListeners(Symbol("event"));
}
namespace setMaxListeners {
const a: adone.EventEmitter = new adone.EventEmitter().setMaxListeners(10);
}
namespace getMaxListeners {
const a: number = new adone.EventEmitter().getMaxListeners();
}
namespace listeners {
const a: Array<(...args: any[]) => any> = new adone.EventEmitter().listeners("event");
const b: Array<(...args: any[]) => any> = new adone.EventEmitter().listeners(Symbol("event"));
}
namespace emit {
const a: boolean = new adone.EventEmitter().emit("event", 1, 2, 3);
const b: boolean = new adone.EventEmitter().emit(Symbol("event"), 1, 2, 3);
}
namespace eventNames {
const a: Array<string | symbol> = new adone.EventEmitter().eventNames();
const b: Array<string | symbol> = new adone.EventEmitter().eventNames();
}
namespace listenerCount {
const a: number = new adone.EventEmitter().listenerCount("event");
const b: number = new adone.EventEmitter().listenerCount(Symbol("event"));
}
}
namespace AsyncEmitter {
const a: adone.EventEmitter = new adone.AsyncEmitter();
new adone.AsyncEmitter(10);
namespace setConcurrency {
const a: adone.AsyncEmitter = new adone.AsyncEmitter().setConcurrency();
const b: adone.AsyncEmitter = new adone.AsyncEmitter().setConcurrency(10);
}
namespace emitParallel {
const a: Promise<any[]> = new adone.AsyncEmitter().emitParallel("even");
const b: Promise<any[]> = new adone.AsyncEmitter().emitParallel("even", 1, 2, 3);
}
namespace emitSerial {
const a: Promise<any[]> = new adone.AsyncEmitter().emitSerial("even");
const b: Promise<any[]> = new adone.AsyncEmitter().emitSerial("even", 1, 2, 3);
}
namespace emitReduce {
const a: Promise<any[]> = new adone.AsyncEmitter().emitReduce("even");
const b: Promise<any[]> = new adone.AsyncEmitter().emitReduce("even", 1, 2, 3);
}
namespace emitReduceRight {
const a: Promise<any[]> = new adone.AsyncEmitter().emitReduceRight("even");
const b: Promise<any[]> = new adone.AsyncEmitter().emitReduceRight("even", 1, 2, 3);
}
namespace subscribe {
const a: () => void = new adone.AsyncEmitter().subscribe("event", () => { });
const b: () => void = new adone.AsyncEmitter().subscribe("event", () => { }, true);
}
}
namespace ExBuffer {
new adone.ExBuffer();
new adone.ExBuffer(10);
new adone.ExBuffer(10, true);
const buffer = new adone.ExBuffer();
namespace readBitSet {
const a: number[] = buffer.readBitSet();
const b: number[] = buffer.readBitSet(10);
}
namespace read {
const a: adone.ExBuffer = buffer.read(1);
const b: adone.ExBuffer = buffer.read(1, 10);
}
namespace readInt8 {
const a: number = buffer.readInt8();
const b: number = buffer.readInt8(10);
}
namespace readUInt8 {
const a: number = buffer.readUInt8();
const b: number = buffer.readUInt8(10);
}
namespace readInt16LE {
const a: number = buffer.readInt16LE();
const b: number = buffer.readInt16LE(10);
}
namespace readUInt16LE {
const a: number = buffer.readUInt16LE();
const b: number = buffer.readUInt16LE(10);
}
namespace readInt16BE {
const a: number = buffer.readInt16BE();
const b: number = buffer.readInt16BE(10);
}
namespace readUInt16BE {
const a: number = buffer.readUInt16BE();
const b: number = buffer.readUInt16BE(10);
}
namespace readInt32LE {
const a: number = buffer.readInt32LE();
const b: number = buffer.readInt32LE(10);
}
namespace readUInt32LE {
const a: number = buffer.readUInt32LE();
const b: number = buffer.readUInt32LE(10);
}
namespace readInt32BE {
const a: number = buffer.readInt32BE();
const b: number = buffer.readInt32BE(10);
}
namespace readUInt32BE {
const a: number = buffer.readUInt32BE();
const b: number = buffer.readUInt32BE(10);
}
namespace readInt64LE {
const a: adone.math.Long = buffer.readInt64LE();
const b: adone.math.Long = buffer.readInt64LE(10);
}
namespace readUInt64LE {
const a: adone.math.Long = buffer.readUInt64LE();
const b: adone.math.Long = buffer.readUInt64LE(10);
}
namespace readInt64BE {
const a: adone.math.Long = buffer.readInt64BE();
const b: adone.math.Long = buffer.readInt64BE(10);
}
namespace readUInt64BE {
const a: adone.math.Long = buffer.readUInt64BE();
const b: adone.math.Long = buffer.readUInt64BE(10);
}
namespace readFloatLE {
const a: number = buffer.readFloatLE();
const b: number = buffer.readFloatLE(10);
}
namespace readFloatBE {
const a: number = buffer.readFloatBE();
const b: number = buffer.readFloatBE(10);
}
namespace readDoubleLE {
const a: number = buffer.readDoubleLE();
const b: number = buffer.readDoubleLE(10);
}
namespace readDoubleBE {
const a: number = buffer.readDoubleBE();
const b: number = buffer.readDoubleBE(10);
}
namespace write {
const a: adone.ExBuffer = buffer.write("1");
const b: adone.ExBuffer = buffer.write(new adone.ExBuffer());
const c: adone.ExBuffer = buffer.write(Buffer.alloc(10));
const d: adone.ExBuffer = buffer.write(new Uint8Array([1, 2, 3]));
const e: adone.ExBuffer = buffer.write(new ArrayBuffer(10));
const f: adone.ExBuffer = buffer.write("1", 10);
const g: adone.ExBuffer = buffer.write("1", 10, 10);
const h: adone.ExBuffer = buffer.write("1", 10, 10, "utf8");
}
namespace writeBitSet {
const a: adone.ExBuffer = buffer.writeBitSet([1, 2, 3]);
const b: number = buffer.writeBitSet([1, 2, 3], 10);
}
namespace writeInt8 {
const a: adone.ExBuffer = buffer.writeInt8(10);
const b: adone.ExBuffer = buffer.writeInt8(10, 10);
}
namespace writeUInt8 {
const a: adone.ExBuffer = buffer.writeUInt8(10);
const b: adone.ExBuffer = buffer.writeUInt8(10, 10);
}
namespace writeInt16LE {
const a: adone.ExBuffer = buffer.writeInt16LE(10);
const b: adone.ExBuffer = buffer.writeInt16LE(10, 10);
}
namespace writeInt16BE {
const a: adone.ExBuffer = buffer.writeInt16BE(10);
const b: adone.ExBuffer = buffer.writeInt16BE(10, 10);
}
namespace writeUInt16LE {
const a: adone.ExBuffer = buffer.writeUInt16LE(10);
const b: adone.ExBuffer = buffer.writeUInt16LE(10, 10);
}
namespace writeUInt16BE {
const a: adone.ExBuffer = buffer.writeUInt16BE(10);
const b: adone.ExBuffer = buffer.writeUInt16BE(10, 10);
}
namespace writeInt32LE {
const a: adone.ExBuffer = buffer.writeInt32LE(10);
const b: adone.ExBuffer = buffer.writeInt32LE(10, 10);
}
namespace writeInt32BE {
const a: adone.ExBuffer = buffer.writeInt32BE(10);
const b: adone.ExBuffer = buffer.writeInt32BE(10, 10);
}
namespace writeUInt32LE {
const a: adone.ExBuffer = buffer.writeUInt32LE(10);
const b: adone.ExBuffer = buffer.writeUInt32LE(10, 10);
}
namespace writeUInt32BE {
const a: adone.ExBuffer = buffer.writeUInt32BE(10);
const b: adone.ExBuffer = buffer.writeUInt32BE(10, 10);
}
namespace writeInt64LE {
const a: adone.ExBuffer = buffer.writeInt64LE(10);
const b: adone.ExBuffer = buffer.writeInt64LE(10, 10);
}
namespace writeInt64BE {
const a: adone.ExBuffer = buffer.writeInt64BE(10);
const b: adone.ExBuffer = buffer.writeInt64BE(10, 10);
}
namespace writeUInt64LE {
const a: adone.ExBuffer = buffer.writeUInt64LE(10);
const b: adone.ExBuffer = buffer.writeUInt64LE(10, 10);
}
namespace writeUInt64BE {
const a: adone.ExBuffer = buffer.writeUInt64BE(10);
const b: adone.ExBuffer = buffer.writeUInt64BE(10, 10);
}
namespace writeFloatLE {
const a: adone.ExBuffer = buffer.writeFloatLE(10);
const b: adone.ExBuffer = buffer.writeFloatLE(10, 10);
}
namespace writeFloatBE {
const a: adone.ExBuffer = buffer.writeFloatBE(10);
const b: adone.ExBuffer = buffer.writeFloatBE(10, 10);
}
namespace writeDoubleLE {
const a: adone.ExBuffer = buffer.writeDoubleLE(10);
const b: adone.ExBuffer = buffer.writeDoubleLE(10, 10);
}
namespace writeDoubleBE {
const a: adone.ExBuffer = buffer.writeDoubleBE(10);
const b: adone.ExBuffer = buffer.writeDoubleBE(10, 10);
}
namespace writeVarInt32 {
const a: adone.ExBuffer = buffer.writeVarint32(10);
const b: number = buffer.writeVarint32(10, 10);
}
namespace writeVarInt32ZigZag {
const a: adone.ExBuffer = buffer.writeVarint32ZigZag(10);
const b: number = buffer.writeVarint32ZigZag(10, 10);
}
namespace readVarint32 {
const a: number = buffer.readVarint32();
const b: { value: number, length: number } = buffer.readVarint32(10);
}
namespace readVarint32ZigZag {
const a: number = buffer.readVarint32ZigZag();
const b: { value: number, length: number } = buffer.readVarint32ZigZag(10);
}
namespace writeVarint64 {
const a: adone.ExBuffer = buffer.writeVarint64(10);
const b: number = buffer.writeVarint64(10, 10);
}
namespace writeVarint64ZigZag {
const a: adone.ExBuffer = buffer.writeVarint64ZigZag(10);
const b: number = buffer.writeVarint64ZigZag(10, 10);
}
namespace readVarint64 {
const a: adone.math.Long = buffer.readVarint64();
const b: { value: adone.math.Long, length: number } = buffer.readVarint64(10);
}
namespace readVarint64ZigZag {
const a: adone.math.Long = buffer.readVarint64ZigZag();
const b: { value: adone.math.Long, length: number } = buffer.readVarint64ZigZag(10);
}
namespace writeCString {
const a: adone.ExBuffer = buffer.writeCString("asd");
const b: number = buffer.writeCString("123", 10);
}
namespace readCString {
const a: string = buffer.readCString();
const b: { string: string, length: number } = buffer.readCString(10);
}
namespace writeString {
const a: adone.ExBuffer = buffer.writeString("abc");
const b: number = buffer.writeString("abc", 10);
}
namespace readString {
const a: string = buffer.readString(10);
const b: string = buffer.readString(10, "b");
const c: string = buffer.readString(10, "c");
const d: { string: string, length: number } = buffer.readString(10, "c", 10);
}
namespace writeVString {
const a: adone.ExBuffer = buffer.writeVString("abc");
const b: number = buffer.writeVString("abc", 10);
}
namespace readVString {
const a: string = buffer.readVString();
const b: { string: string, length: number } = buffer.readVString(10);
}
namespace appendTo {
const a: adone.ExBuffer = buffer.appendTo(new adone.ExBuffer());
const b: adone.ExBuffer = buffer.appendTo(new adone.ExBuffer(), 10);
}
namespace assert {
const a: adone.ExBuffer = buffer.assert();
const b: adone.ExBuffer = buffer.assert(true);
}
namespace capacity {
const a: number = buffer.capacity();
}
namespace clear {
const a: adone.ExBuffer = buffer.clear();
}
namespace compact {
const a: adone.ExBuffer = buffer.compact();
const b: adone.ExBuffer = buffer.compact(1);
const c: adone.ExBuffer = buffer.compact(1, 10);
}
namespace copyTo {
const a: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer());
const b: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer(), 0);
const c: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer(), 0, 0);
const d: adone.ExBuffer = buffer.copyTo(new adone.ExBuffer(), 0, 0, 10);
}
namespace ensureCapacity {
const a: adone.ExBuffer = buffer.ensureCapacity(10);
}
namespace fill {
const a: adone.ExBuffer = buffer.fill("0");
const b: adone.ExBuffer = buffer.fill(0);
const c: adone.ExBuffer = buffer.fill(0, 0);
const d: adone.ExBuffer = buffer.fill(0, 0, 10);
}
namespace flip {
const a: adone.ExBuffer = buffer.flip();
}
namespace mark {
const a: adone.ExBuffer = buffer.mark();
const b: adone.ExBuffer = buffer.mark(10);
}
namespace prepend {
const a: adone.ExBuffer = buffer.prepend("");
const b: adone.ExBuffer = buffer.prepend(new adone.ExBuffer());
const c: adone.ExBuffer = buffer.prepend(Buffer.alloc(10));
const d: adone.ExBuffer = buffer.prepend(new Uint8Array([1, 2, 3]));
const e: adone.ExBuffer = buffer.prepend(new ArrayBuffer(10));
const f: adone.ExBuffer = buffer.prepend("", "utf8");
const g: adone.ExBuffer = buffer.prepend("", "utf8", 10);
const h: adone.ExBuffer = buffer.prepend("", 10);
}
namespace prependTo {
const a: adone.ExBuffer = buffer.prependTo(new adone.ExBuffer());
const b: adone.ExBuffer = buffer.prependTo(new adone.ExBuffer(), 10);
}
namespace remaining {
const a: number = buffer.remaining();
}
namespace reset {
const a: adone.ExBuffer = buffer.reset();
}
namespace resize {
const a: adone.ExBuffer = buffer.resize(10);
}
namespace reverse {
const a: adone.ExBuffer = buffer.reverse();
const b: adone.ExBuffer = buffer.reverse(1);
const c: adone.ExBuffer = buffer.reverse(1, 10);
}
namespace skip {
const a: adone.ExBuffer = buffer.skip(10);
}
namespace slice {
const a: adone.ExBuffer = buffer.slice();
const b: adone.ExBuffer = buffer.slice(1);
const c: adone.ExBuffer = buffer.slice(1, 10);
}
namespace toBuffer {
const a: Buffer = buffer.toBuffer();
const b: Buffer = buffer.toBuffer(true);
const c: Buffer = buffer.toBuffer(true, 0);
const d: Buffer = buffer.toBuffer(true, 0, 10);
}
namespace toArrayBuffer {
const a: ArrayBuffer = buffer.toArrayBuffer();
}
namespace toString {
const a: string = buffer.toString();
const b: string = buffer.toString("utf8");
const c: string = buffer.toString("utf8", 0);
const d: string = buffer.toString("utf8", 0, 10);
}
namespace toBase64 {
const a: string = buffer.toBase64();
const b: string = buffer.toBase64(0);
const c: string = buffer.toBase64(0, 10);
}
namespace toBinary {
const a: string = buffer.toBinary();
const b: string = buffer.toBinary(0);
const c: string = buffer.toBinary(0, 10);
}
namespace toDebug {
const a: string = buffer.toDebug();
const b: string = buffer.toDebug(true);
}
namespace toUTF8 {
const a: string = buffer.toUTF8();
const b: string = buffer.toUTF8(0);
const c: string = buffer.toUTF8(0, 10);
}
namespace static {
namespace accessor {
const a: typeof Buffer = adone.ExBuffer.accessor();
}
namespace allocate {
const a: adone.ExBuffer = adone.ExBuffer.allocate();
const b: adone.ExBuffer = adone.ExBuffer.allocate(10);
const c: adone.ExBuffer = adone.ExBuffer.allocate(10, true);
}
namespace concat {
const a: adone.ExBuffer = adone.ExBuffer.concat([
new adone.ExBuffer(),
Buffer.alloc(10),
new Uint8Array([1, 2, 3]),
new ArrayBuffer(10)
]);
const b: adone.ExBuffer = adone.ExBuffer.concat([
new adone.ExBuffer(),
Buffer.alloc(10),
new Uint8Array([1, 2, 3]),
new ArrayBuffer(10)
], "utf8");
const c: adone.ExBuffer = adone.ExBuffer.concat([
new adone.ExBuffer(),
Buffer.alloc(10),
new Uint8Array([1, 2, 3]),
new ArrayBuffer(10)
], "utf8", true);
}
namespace type {
const a: typeof Buffer = adone.ExBuffer.type();
}
namespace wrap {
const a: adone.ExBuffer = adone.ExBuffer.wrap("");
const b: adone.ExBuffer = adone.ExBuffer.wrap(new adone.ExBuffer());
const c: adone.ExBuffer = adone.ExBuffer.wrap(Buffer.alloc(10));
const d: adone.ExBuffer = adone.ExBuffer.wrap(new Uint8Array([1, 2, 3]));
const e: adone.ExBuffer = adone.ExBuffer.wrap(new ArrayBuffer(10));
const f: adone.ExBuffer = adone.ExBuffer.wrap("", "utf8");
const g: adone.ExBuffer = adone.ExBuffer.wrap("", "utf8", true);
}
namespace calculateVarint32 {
const a: number = adone.ExBuffer.calculateVarint32(10);
}
namespace zigZagEncode32 {
const a: number = adone.ExBuffer.zigZagEncode32(10);
}
namespace zigZagDecode32 {
const a: number = adone.ExBuffer.zigZagDecode32(10);
}
namespace calculateVarint64 {
const a: number = adone.ExBuffer.calculateVarint64(10);
const b: number = adone.ExBuffer.calculateVarint64("10");
}
namespace zigZagEncode64 {
const a: adone.math.Long = adone.ExBuffer.zigZagEncode64(10);
const b: adone.math.Long = adone.ExBuffer.zigZagEncode64("10");
const c: adone.math.Long = adone.ExBuffer.zigZagEncode64(adone.math.Long.fromValue(10));
}
namespace zigZagDecode64 {
const a: adone.math.Long = adone.ExBuffer.zigZagDecode64(10);
const b: adone.math.Long = adone.ExBuffer.zigZagDecode64("10");
const c: adone.math.Long = adone.ExBuffer.zigZagDecode64(adone.math.Long.fromValue(10));
}
namespace calculateUTF8Chars {
const a: number = adone.ExBuffer.calculateUTF8Chars("123");
}
namespace calculateString {
const a: number = adone.ExBuffer.calculateString("123");
}
namespace fromBase64 {
const a: adone.ExBuffer = adone.ExBuffer.fromBase64("123");
}
namespace btoa {
const a: string = adone.ExBuffer.btoa("123");
}
namespace atob {
const a: string = adone.ExBuffer.atob("123");
}
namespace fromBinary {
const a: adone.ExBuffer = adone.ExBuffer.fromBinary("123");
}
namespace fromDebug {
const a: adone.ExBuffer = adone.ExBuffer.fromDebug("12");
const b: adone.ExBuffer = adone.ExBuffer.fromDebug("12", true);
}
namespace fromHex {
const a: adone.ExBuffer = adone.ExBuffer.fromHex("192");
const b: adone.ExBuffer = adone.ExBuffer.fromHex("192", true);
}
namespace fromUTF8 {
const a: adone.ExBuffer = adone.ExBuffer.fromUTF8("123");
const b: adone.ExBuffer = adone.ExBuffer.fromUTF8("123", true);
}
namespace constants {
const a: number = adone.ExBuffer.DEFAULT_CAPACITY;
const b: boolean = adone.ExBuffer.DEFAULT_NOASSERT;
const c: number = adone.ExBuffer.MAX_VARINT32_BYTES;
const d: number = adone.ExBuffer.MAX_VARINT64_BYTES;
const e: string = adone.ExBuffer.METRICS_CHARS;
const f: string = adone.ExBuffer.METRICS_BYTES;
}
}
}
}
+259
View File
@@ -0,0 +1,259 @@
const { math } = adone;
namespace mathTests {
namespace Long {
new math.Long();
new math.Long(0);
new math.Long(0, 0);
new math.Long(0, 0, true);
namespace toInt {
const a: number = new math.Long().toInt();
}
namespace toNumber {
const a: number = new math.Long().toNumber();
}
namespace toString {
const a: string = new math.Long().toString();
const b: string = new math.Long().toString(16);
}
namespace getHighBits {
const a: number = new math.Long().getHighBits();
}
namespace getLowBits {
const a: number = new math.Long().getLowBits();
}
namespace getLowBitsUnsigned {
const a: number = new math.Long().getLowBitsUnsigned();
}
namespace getHighBitsUnsigned {
const a: number = new math.Long().getHighBitsUnsigned();
}
namespace getNumBitsAbs {
const a: number = new math.Long().getNumBitsAbs();
}
namespace isZero {
const a: boolean = new math.Long().isZero();
}
namespace isNegative {
const a: boolean = new math.Long().isNegative();
}
namespace isPositive {
const a: boolean = new math.Long().isPositive();
}
namespace isOdd {
const a: boolean = new math.Long().isOdd();
}
namespace isEven {
const a: boolean = new math.Long().isEven();
}
namespace equals {
const a = new math.Long();
const b: boolean = a.equals(new math.Long());
const c: boolean = a.equals(1);
const d: boolean = a.equals("1");
const e: boolean = a.equals({ low: 0, high: 0 });
}
namespace lessThan {
const a = new math.Long();
const b: boolean = a.lessThan(new math.Long());
const c: boolean = a.lessThan(1);
const d: boolean = a.lessThan("1");
const e: boolean = a.lessThan({ low: 0, high: 0 });
}
namespace lessThanOrEqual {
const a = new math.Long();
const b: boolean = a.lessThanOrEqual(new math.Long());
const c: boolean = a.lessThanOrEqual(1);
const d: boolean = a.lessThanOrEqual("1");
const e: boolean = a.lessThanOrEqual({ low: 0, high: 0 });
}
namespace greaterThan {
const a = new math.Long();
const b: boolean = a.greaterThan(new math.Long());
const c: boolean = a.greaterThan(1);
const d: boolean = a.greaterThan("1");
const e: boolean = a.greaterThan({ low: 0, high: 0 });
}
namespace greaterThanOrEqual {
const a = new math.Long();
const b: boolean = a.greaterThanOrEqual(new math.Long());
const c: boolean = a.greaterThanOrEqual(1);
const d: boolean = a.greaterThanOrEqual("1");
const e: boolean = a.greaterThanOrEqual({ low: 0, high: 0 });
}
namespace greaterThanOrEqual {
const a = new math.Long();
const b: number = a.compare(new math.Long());
const c: number = a.compare(1);
const d: number = a.compare("1");
const e: number = a.compare({ low: 0, high: 0 });
}
namespace negate {
const a: adone.math.Long = new math.Long().negate();
}
namespace add {
const a = new math.Long();
const b: adone.math.Long = a.add(new math.Long());
const c: adone.math.Long = a.add(1);
const d: adone.math.Long = a.add("1");
const e: adone.math.Long = a.add({ low: 0, high: 0 });
}
namespace sub {
const a = new math.Long();
const b: adone.math.Long = a.sub(new math.Long());
const c: adone.math.Long = a.sub(1);
const d: adone.math.Long = a.sub("1");
const e: adone.math.Long = a.sub({ low: 0, high: 0 });
}
namespace mul {
const a = new math.Long();
const b: adone.math.Long = a.mul(new math.Long());
const c: adone.math.Long = a.mul(1);
const d: adone.math.Long = a.mul("1");
const e: adone.math.Long = a.mul({ low: 0, high: 0 });
}
namespace div {
const a = new math.Long();
const b: adone.math.Long = a.div(new math.Long());
const c: adone.math.Long = a.div(1);
const d: adone.math.Long = a.div("1");
const e: adone.math.Long = a.div({ low: 0, high: 0 });
}
namespace mod {
const a = new math.Long();
const b: adone.math.Long = a.mod(new math.Long());
const c: adone.math.Long = a.mod(1);
const d: adone.math.Long = a.mod("1");
const e: adone.math.Long = a.mod({ low: 0, high: 0 });
}
namespace not {
const a: adone.math.Long = new math.Long().not();
}
namespace and {
const a = new math.Long();
const b: adone.math.Long = a.and(new math.Long());
const c: adone.math.Long = a.and(1);
const d: adone.math.Long = a.and("1");
const e: adone.math.Long = a.and({ low: 0, high: 0 });
}
namespace or {
const a = new math.Long();
const b: adone.math.Long = a.or(new math.Long());
const c: adone.math.Long = a.or(1);
const d: adone.math.Long = a.or("1");
const e: adone.math.Long = a.or({ low: 0, high: 0 });
}
namespace xor {
const a = new math.Long();
const b: adone.math.Long = a.xor(new math.Long());
const c: adone.math.Long = a.xor(1);
const d: adone.math.Long = a.xor("1");
const e: adone.math.Long = a.xor({ low: 0, high: 0 });
}
namespace shl {
const a = new math.Long();
const b: adone.math.Long = a.shl(new math.Long());
const c: adone.math.Long = a.shl(1);
}
namespace shr {
const a = new math.Long();
const b: adone.math.Long = a.shr(new math.Long());
const c: adone.math.Long = a.shr(1);
}
namespace shru {
const a = new math.Long();
const b: adone.math.Long = a.shr(new math.Long());
const c: adone.math.Long = a.shr(1);
}
namespace toSigned {
const a: adone.math.Long = new math.Long().toSigned();
}
namespace toUnsigned {
const a: adone.math.Long = new math.Long().toUnsigned();
}
namespace toBytes {
const a: number[] = new math.Long().toBytes();
}
namespace toBytesLE {
const a: number[] = new math.Long().toBytesLE();
}
namespace static {
namespace fromInt {
const a: adone.math.Long = math.Long.fromInt(123);
const b: adone.math.Long = math.Long.fromInt(123, true);
}
namespace fromNumber {
const a: adone.math.Long = math.Long.fromNumber(123);
const b: adone.math.Long = math.Long.fromNumber(123, true);
}
namespace fromBits {
const a: adone.math.Long = math.Long.fromBits(0, 0);
const b: adone.math.Long = math.Long.fromBits(123, 0, true);
}
namespace fromString {
const a: adone.math.Long = math.Long.fromString("123");
const b: adone.math.Long = math.Long.fromString("123", true);
const c: adone.math.Long = math.Long.fromString("123", 16);
const d: adone.math.Long = math.Long.fromString("123", true, 16);
}
namespace fromValue {
const a: adone.math.Long = math.Long.fromValue(new math.Long());
const b: adone.math.Long = math.Long.fromValue(1);
const c: adone.math.Long = math.Long.fromValue("1");
const e: adone.math.Long = math.Long.fromValue({ low: 0, high: 0 });
}
namespace constants {
const a: adone.math.Long = math.Long.MIN_VALUE;
const b: adone.math.Long = math.Long.MAX_VALUE;
const c: adone.math.Long = math.Long.MAX_UNSIGNED_VALUE;
const d: adone.math.Long = math.Long.ZERO;
const e: adone.math.Long = math.Long.UZERO;
const f: adone.math.Long = math.Long.ONE;
const g: adone.math.Long = math.Long.UONE;
const h: adone.math.Long = math.Long.NEG_ONE;
}
}
}
}
+97
View File
@@ -0,0 +1,97 @@
namespace promiseTests {
const { promise } = adone;
namespace defer {
const a = promise.defer();
a.promise.then((x) => 2);
a.resolve(2);
a.reject(3);
const b = promise.defer<string>();
b.resolve("3");
b.reject(2);
b.promise.then((x: string) => x);
}
namespace delay {
const a: Promise<any> = promise.delay(10);
const b: Promise<number> = promise.delay(10, 2);
promise.delay(20, "3").then((x: string) => x);
}
namespace timeout {
promise.timeout(Promise.resolve(2), 100).then((x: number) => x);
}
namespace nodeify {
promise.nodeify(Promise.resolve(2), (err: any, value: number) => value).then((x: number) => x);
promise.nodeify(Promise.resolve(2), () => 42).then((x: number) => x);
}
namespace promisify {
type Callback<T> = (err?: any, result?: T) => void;
namespace noargs {
const f = (cb: Callback<number>) => {
cb(null, 32);
};
promise.promisify(f)().then((x: number) => { });
}
namespace nargs1 {
const f = (a: number, cb: Callback<number>) => {
cb(null, 32);
};
promise.promisify(f)(1).then((x: number) => { });
}
namespace nargs2 {
const f = (a: number, b: string, cb: Callback<number>) => {
cb(null, 32);
};
promise.promisify(f)(1, "1").then((x: number) => { });
}
namespace nargs3 {
const f = (a: number, b: string, c: number, cb: Callback<number>) => {
cb(null, 32);
};
promise.promisify(f)(1, "1", 1).then((x: number) => { });
}
namespace nargs4 {
const f = (a: number, b: string, c: number, d: string, cb: Callback<number>) => {
cb(null, 32);
};
promise.promisify(f)(1, "1", 1, "1").then((x: number) => { });
}
namespace nargs5 {
const f = (a: number, b: string, c: number, d: string, e: number, cb: Callback<number>) => {
cb(null, 32);
};
promise.promisify(f)(1, "1", 1, "1", 1).then((x: number) => { });
}
namespace moreargs {
const f = (a: number, b: string, c: number, d: string, e: number, f: string, cb: Callback<number>) => {
cb(null, 32);
};
promise.promisify(f)(1, 2, 3).then((x) => x);
}
namespace options {
promise.promisify((cb: Callback<number>) => cb(null, 42), {});
promise.promisify((cb: Callback<number>) => cb(null, 42), { context: {} });
}
}
namespace promisifyAll {
const a: object = promise.promisifyAll({});
promise.promisifyAll({}, {});
promise.promisifyAll({}, { context: {} });
promise.promisifyAll({}, { filter: () => true });
promise.promisifyAll({}, { suffix: "Async" });
}
namespace _finally {
promise.finally(Promise.resolve(2), () => 2).then((x: number) => {});
}
}
+163
View File
@@ -0,0 +1,163 @@
namespace shaniGlobalTests {
namespace describeTests {
describe("hello", () => {});
describe("hello", function () {
this.skip();
this.timeout(10);
this.a;
});
describe("1", "2", "3", "4", "45", function () {
this.skip();
this.timeout(10);
this.a;
});
describe("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", function () {
this.skip();
this.timeout(10);
this.a;
});
context("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", function () {
this.skip();
this.timeout(10);
this.a;
});
}
namespace itTests {
it("should be here", () => {});
it("should be here", function () {
this.timeout(100);
this.skip();
this.a;
});
it("should be here", function (done: () => void) {
this.timeout(1000);
done();
this.a;
});
it("hello", {}, () => {});
it("hello", {
skip: true
}, () => {});
it("hello", {
skip: () => true
}, () => {});
it("hello", {
timeout: () => 1202
}, () => {});
it("hello", {
timeout: 1010
}, () => {});
it("hello", {
before() {}
}, () => {});
it("hello", {
before: ["hello", () => {}]
}, () => {});
it("hello", {
after() {}
}, () => {});
it("hello", {
after: ["hello", () => {}]
}, () => {});
specify("hello", {
after: ["hello", () => {}]
}, () => {});
}
namespace beforeTests {
before(function() {
this.timeout(100);
this.a;
});
before("description", function () {
this.timeout(100);
this.a;
});
before("description", function (done) {
this.timeout(100);
done();
this.a;
});
}
namespace afterTests {
after(function () {
this.timeout(10);
this.a;
});
after("description", function () {
this.timeout(10);
this.a;
});
after("description", function (done) {
this.timeout(10);
this.a;
});
}
namespace beforeEachTests {
beforeEach(function () {
this.timeout(100);
this.a;
});
beforeEach("hello", function () {
this.timeout(100);
this.a;
});
beforeEach("hello", function (done) {
this.timeout(100);
done();
this.a;
});
}
namespace afterEachTests {
afterEach(function () {
this.timeout(100);
this.a;
});
afterEach("asd", function () {
this.timeout(100);
this.a;
});
afterEach("asd", function (done) {
this.timeout(100);
done();
this.a;
});
}
expect(1).to.be.a("number");
assert.equal(1, 1);
fakeClock.install().tick(100);
stub()(1, 2, 3);
expect(spy()).to.have.been.calledOnce;
match(2).and(match(2));
mock().alwaysCalledOn({});
request({}).expectBody("");
}
+544
View File
@@ -0,0 +1,544 @@
namespace shaniTests {
const { shani } = adone;
namespace engineOptionsTests {
new shani.Engine();
new shani.Engine({});
new shani.Engine({ callGc: true });
new shani.Engine({ defaultTimeout: 1000 });
new shani.Engine({ defaultHookTimeout: 1000 });
new shani.Engine({ transpilerOptions: {} });
}
namespace contextTests {
const e = new adone.shani.Engine();
const c = e.context();
namespace describeTests {
c.describe("hello", () => {});
c.describe("hello", function () {
this.skip();
this.timeout(10);
this.a;
});
c.describe("1", "2", "3", "4", "45", function () {
this.skip();
this.timeout(10);
this.a;
});
c.describe("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", function () {
this.skip();
this.timeout(10);
this.a;
});
c.context("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", function () {
this.skip();
this.timeout(10);
this.a;
});
}
namespace itTests {
c.it("should be here", () => {});
c.it("should be here", function () {
this.timeout(100);
this.skip();
this.a;
});
c.it("should be here", function (done) {
this.timeout(100);
this.skip();
done();
this.a;
});
c.it("hello", {}, () => { });
c.it("hello", {
skip: true
}, () => { });
c.it("hello", {
skip: () => true
}, () => { });
c.it("hello", {
timeout: () => 1202
}, () => { });
c.it("hello", {
timeout: 1010
}, () => { });
c.it("hello", {
before() { }
}, () => { });
c.it("hello", {
before: ["hello", () => { }]
}, () => { });
c.it("hello", {
after() { }
}, () => { });
c.it("hello", {
after: ["hello", () => { }]
}, () => { });
c.specify("hello", {
after: ["hello", () => { }]
}, () => { });
}
namespace beforeTests {
c.before(function () {
this.timeout(100);
this.a;
});
c.before("description", function () {
this.timeout(100);
this.a;
});
c.before("description", function (done) {
this.timeout(100);
done();
this.a;
});
}
namespace afterTests {
c.after(function () {
this.timeout(10);
this.a;
});
c.after("description", function () {
this.timeout(10);
this.a;
});
c.after("description", function (done) {
this.timeout(10);
done();
this.a;
});
}
namespace beforeEachTests {
c.beforeEach(function () {
this.timeout(100);
this.a;
});
c.beforeEach("hello", function () {
this.timeout(100);
this.a;
});
c.beforeEach("hello", function (done) {
this.timeout(100);
done();
this.a;
});
}
namespace afterEachTests {
c.afterEach(function () {
this.timeout(100);
this.a;
});
c.afterEach("asd", function () {
this.timeout(100);
this.a;
});
c.afterEach("asd", function (done) {
this.timeout(100);
done();
this.a;
});
}
namespace rootTests {
const { root } = c;
root.children[0];
root.prepare().then((x) => { });
root.addChild(root);
const check = (hook: adone.shani.I.Hook) => {
hook.run().then((x) => x);
hook.cause();
hook.failed() === true;
hook.timeout() + 2;
hook.timeout(10).timeout(10).timeout() + 2;
};
for (const hook of root.beforeHooks()) {
check(hook);
}
for (const hook of root.afterHooks()) {
check(hook);
}
for (const hook of root.beforeEachHooks()) {
check(hook);
}
for (const hook of root.afterEachHooks()) {
check(hook);
}
root.isInclusive() === true;
root.isExclusive() === false;
root.hasInclusive() === true;
root.skip().only().skip();
const a: number | null = root.timeout();
root.timeout(100).timeout(100);
root.level() + 2;
root.level(2).level() + 2;
root.chain().toLowerCase();
root.blockChain()[0].blockChain()[0].addChild(root);
}
namespace eventEmitterTests {
const a = c.start();
a.on("enter block", ({ block }) => {
block.addChild(block);
}).on("exit block", ({ block }) => {
block.addChild(block);
}).on("start test", ({ block, test }) => {
block.addChild(test);
test.chain();
}).on("end test", ({ block, test, meta }) => {
block.addChild(test);
test.chain();
meta.err;
meta.elapsed + 2;
}).on("start before hook", ({ block, hook }) => {
block.addChild(block);
hook.desctiption;
}).on("end before hook", ({ block, hook, meta }) => {
block.addChild(block);
hook.desctiption;
meta.err;
meta.elapsed;
}).on("start after hook", ({ block, hook }) => {
block.addChild(block);
hook.desctiption;
}).on("end after hook", ({ block, hook, meta }) => {
block.addChild(block);
hook.desctiption;
meta.err;
meta.elapsed;
}).on("start before each hook", ({ block, hook }) => {
block.addChild(block);
hook.desctiption;
}).on("end before each hook", ({ block, hook, meta }) => {
block.addChild(block);
hook.desctiption;
meta.err;
meta.elapsed;
}).on("start after each hook", ({ block, hook }) => {
block.addChild(block);
hook.desctiption;
}).on("end after each hook", ({ block, hook, meta }) => {
block.addChild(block);
hook.desctiption;
meta.err;
meta.elapsed;
}).on("start before test hook", ({ block, hook }) => {
block.addChild(block);
hook.desctiption;
}).on("end before test hook", ({ block, hook, meta }) => {
block.addChild(block);
hook.desctiption;
meta.err;
meta.elapsed;
}).on("start after test hook", ({ block, hook }) => {
block.addChild(block);
hook.desctiption;
}).on("end after test hook", ({ block, hook, meta }) => {
block.addChild(block);
hook.desctiption;
meta.err;
meta.elapsed;
}).on("error", (err) => {}).on("done", () => {}).stop();
}
}
namespace utilTests {
const { util } = shani;
namespace spyCallTests {
const call = util.spy().firstCall;
call.calledBefore(call) === true;
call.calledAfter(call) === true;
call.calledWithNew(call) === true;
call.thisValue;
call.args[0];
call.exception;
call.returnValue;
call.calledOn({}) === true;
call.calledWith(1, 2, 3) === true;
call.calledWithExactly(1, 2, 3) === true;
call.calledWithMatch(1, 2, 3) === true;
call.notCalledWith(1, 2, 3) === true;
call.notCalledWithMatch(1, 2, 3) === true;
call.returned(1) === true;
call.threw() === true;
call.threw("12") === true;
call.threw({}) === true;
call.callArg(1);
call.callArgOn(1, {});
call.callArgWith(1, 1, 2, 3);
call.callArgOnWith(1, {}, 1, 2, 3);
call.yield(1, 2, 3);
call.yieldOn({}, 1, 2, 3);
call.yieldToOn("a", {}, 1, 2, 3);
}
namespace spyTests {
util.spy().alwaysCalledOn({});
util.spy(() => { }).alwaysCalledOn({});
const a: number = util.spy().callCount;
const s = util.spy();
s.called === true;
s.notCalled === true;
s.calledOnce === true;
s.calledTwice === true;
s.calledThrice === true;
s.firstCall.args;
s.secondCall.args;
s.thirdCall.args;
s.lastCall.args;
s.thisValues[0];
s.args[0][0];
s.exceptions[0];
s.returnValues[0];
s(1, 2, 3);
s.calledBefore(s);
s.calledAfter(s);
s.calledImmediatelyAfter(s);
s.calledImmediatelyBefore(s);
s.calledWithNew() === true;
s.withArgs(1, 2, 3).firstCall.args;
s.alwaysCalledOn({}) === true;
s.alwaysCalledWith(1, 2, 3) === true;
s.alwaysCalledWithExactly(1, 2, 3) === true;
s.alwaysCalledWithMatch(1, 2, 3) === true;
s.neverCalledWith(1, 2, 3) === true;
s.neverCalledWithMatch(1, 2, 3) === true;
s.alwaysThrew() === true;
s.alwaysThrew("a") === true;
s.alwaysThrew({}) === true;
s.alwaysReturned({}) === true;
s.invokeCallback(1, 2, 3);
s.getCall(0).args;
s.getCalls()[0].args;
s.reset();
s.printf("%s", "1").toLowerCase();
s.restore();
}
namespace stubTests {
util.stub({});
class A {
a() {}
}
util.stub(new A(), "a").resetHistory();
const s = util.stub();
s.resetBehavior();
s.resetHistory();
s.usingPromise({}).alwaysCalledOn(2);
s.returns({}).resetBehavior();
s.returnsArg(1).resetBehavior();
s.returnsThis().resetBehavior();
s.resolves().resetBehavior();
s.resolves(1).resetBehavior();
s.throws().resetBehavior();
s.throws("1").resetBehavior();
s.throwsArg(1).resetBehavior();
s.throwsException().resetBehavior();
s.throwsException("1").resetBehavior();
s.throwsException({}).resetBehavior();
s.rejects().resetBehavior();
s.rejects("string").resetBehavior();
s.rejects(1).resetBehavior();
s.callsArg(1).resetBehavior();
s.callThrough().resetBehavior();
s.callsArgOn(1, {}).resetBehavior();
s.callsArgOnWith(1, {}, 123).resetBehavior();
s.callsArgAsync(1).resetBehavior();
s.callsArgOnAsync(1, {}).resetBehavior();
s.callsArgOnWithAsync(1, {}, 1, 2, 3).resetBehavior();
s.callsFake(() => { }).resetBehavior();
s.get(() => { }).resetBehavior();
s.set((v) => 1).resetBehavior();
s.onCall(1).resetBehavior();
s.onFirstCall().resetBehavior();
s.onSecondCall().resetBehavior();
s.onThirdCall().resetBehavior();
s.value(1).resetBehavior();
s.yields(1, 2, 3).resetBehavior();
s.yieldsOn({}, 1, 2).resetBehavior();
s.yieldsRight(1, 2, 3).resetBehavior();
s.yieldsTo("a", 1, 2, 3).resetBehavior();
s.yieldsToOn("a", {}, 1, 2, 3).resetBehavior();
s.yieldsAsync(1, 2, 3).resetBehavior();
s.yieldsOnAsync({}, 1, 2, 3).resetBehavior();
s.yieldsToAsync("a", 1, 2, 3).resetBehavior();
s.yieldsToOnAsync("1", {}, 1, 2, 3).resetBehavior();
s.withArgs(1, 2, 3).resetBehavior();
}
namespace expectationTests {
util.expectation.create("");
const e = util.expectation.create();
e.atLeast(1).never();
e.atMost(2).never();
e.never().never();
e.once().never();
e.twice().never();
e.thrice().never();
e.exactly(1).never();
e.withArgs(1, 2, 3).never();
e.withExactArgs(1, 2, 3).never();
e.on({}).never();
e.verify().never();
e.restore();
}
namespace mockTests {
util.mock().never();
util.mock({}).expects("").restore();
util.mock({}).verify();
}
namespace assertTests {
util.assert.failException;
util.assert.fail();
util.assert.fail("1");
util.assert.pass(1);
const s = util.spy();
util.assert.notCalled(s);
util.assert.called(s);
util.assert.calledOnce(s);
util.assert.calledTwice(s);
util.assert.calledThrice(s);
util.assert.callCount(s, 10);
util.assert.callOrder(s, s, s, s);
util.assert.calledOn(s, {});
util.assert.calledOn(s, {});
util.assert.alwaysCalledOn(s, {});
util.assert.calledWith(s, {});
util.assert.neverCalledWith(s, {});
util.assert.calledWithExactly(s, {});
util.assert.alwaysCalledWithExactly(s, {});
util.assert.calledWithMatch(s, {});
util.assert.alwaysCalledWithMatch(s, {});
util.assert.neverCalledWithMatch(s, {});
util.assert.threw(s);
util.assert.threw(s, "a");
util.assert.threw(s, {});
util.assert.alwaysThrew(s);
util.assert.alwaysThrew(s, "");
util.assert.alwaysThrew(s, {});
util.assert.expose({});
util.assert.expose({}, { includeFail: true });
util.assert.expose({}, { prefix: "a" });
}
namespace matchTests {
util.match(1).and(util.match(1));
util.match("1").and(util.match(1));
util.match(/1/).and(util.match(1));
util.match({}).and(util.match(1));
util.match((v: any) => true).and(util.match(1));
util.match((v: any) => true, "a").and(util.match(1));
util.match.any.and;
util.match.defined.and;
util.match.truthy.and;
util.match.falsy.and;
util.match.bool.and;
util.match.number.and;
util.match.string.and;
util.match.object.and;
util.match.func.and;
util.match.map.contains(new Map());
util.match.map.deepEquals(new Map());
util.match.set.contains(new Set());
util.match.array.contains([]);
util.match.array.deepEquals([]);
util.match.array.endsWith([]);
util.match.array.startsWith([]);
util.match.regexp.and;
util.match.date.and;
util.match.symbol.and;
util.match.same({}).and;
util.match.typeOf("string").and;
util.match.instanceOf({}).and;
util.match.has("a").and;
util.match.has("a", {}).and;
util.match.hasOwn("a").and;
util.match.hasOwn("a", {}).and;
}
namespace sandboxTests {
util.sandbox.create();
util.sandbox.create({});
util.sandbox.create({ injectInto: {} });
util.sandbox.create({ properties: ["a"] });
const s = util.sandbox.create();
s.assert.alwaysCalledOn(s.spy(), {});
s.spy().args;
s.stub().args;
s.mock().args;
s.restore();
s.reset();
s.resetHistory();
s.resetBehavior();
s.usingPromise({}).reset();
s.verify();
s.verifyAndRestore();
}
}
namespace requestTests {
const r = request({});
r.get("/").head("/").post("/").put("/").options("/");
r.attach("fname", "hello");
r.attach("fname", "hello", {});
r.attach("fname", "hello", { type: "application/javascript" });
r.attach("fname", "hello", { filename: "a.js" });
r.field("a", "basd");
r.send("asd");
r.setHeader("Cookie", "key=value");
r.auth("user", "pass");
r.expect(() => true);
r.expect(async () => true);
r.expect((response) => {
assert.equal(response.statusCode, 200);
return response.body.length === 0;
});
r.expectStatus(200);
r.expectStatusMessage("OK");
r.expectBody("body");
r.expectBody(Buffer.from("body"));
r.expectBody(/body/);
r.expectBody({ a: 1 });
r.expectBody("body", {});
r.expectBody("body", { decompress: true });
r.expectEmptyBody();
r.expectHeader("Cookie", "key=value");
r.expectHeaderExists("Cookie");
r.then((x: adone.shani.util.I.Response) => {
x.statusCode === 200;
x.body.fill(0);
});
}
}
+161
View File
@@ -0,0 +1,161 @@
import adone from "adone";
import * as assert from "assert";
import * as fs from "fs";
import * as path from "path";
import * as util from "util";
import * as events from "events";
import * as stream from "stream";
import * as url from "url";
import * as net from "net";
import * as http from "http";
import * as https from "https";
import * as child_process from "child_process";
import * as os from "os";
import * as cluster from "cluster";
import * as repl from "repl";
import * as punycode from "punycode";
import * as readline from "readline";
import * as string_decoder from "string_decoder";
import * as querystring from "querystring";
import * as crypto from "crypto";
import * as vm from "vm";
import * as v8 from "v8";
import * as domain from "domain";
import * as tty from "tty";
import * as buffer from "buffer";
import * as constants from "constants";
import * as zlib from "zlib";
import * as tls from "tls";
import * as console from "console";
import * as dns from "dns";
import * as timers from "timers";
import * as dgram from "dgram";
const { std } = adone;
namespace stdTests {
namespace assert {
std.assert(true);
}
namespace fs {
std.fs.readFileSync("test").length;
}
namespace path {
std.path.join("a", "b").charAt(0);
}
namespace util {
std.util.format("hello").charAt(0);
}
namespace events {
new std.events.EventEmitter().on("event", () => {});
}
namespace steam {
new std.stream.PassThrough().resume();
}
namespace url {
std.url.parse("https://adone.io").hostname;
}
namespace net {
std.net.connect(31337).write("hello");
}
namespace http {
std.http.get("http://localhost").end();
}
namespace https {
std.https.get("https://adone.io").end();
}
namespace child_process {
std.child_process.fork(__filename, [], { stdio: ["ipc"] }).send("hello");
}
namespace os {
std.os.tmpdir().charAt(0);
}
namespace cluster {
std.cluster.fork().kill();
}
namespace repl {
std.repl.start().close();
}
namespace punycode {
std.punycode.decode("ads").charAt(0);
}
namespace readline {
std.readline.clearLine(process.stdout, 1);
}
namespace string_decoder {
new std.string_decoder.StringDecoder().end().charAt(0);
}
namespace querystring {
std.querystring.escape("hello").charAt(0);
}
namespace crypto {
std.crypto.createHash("sha1").update("hello").digest("hex");
}
namespace vm {
std.vm.runInContext("a + 2", std.vm.createContext({ a: 1 }));
}
namespace v8 {
std.v8.getHeapStatistics().heap_size_limit + 2;
}
namespace domain {
std.domain.create().members;
}
namespace tty {
std.tty.isatty(1) === true;
}
namespace buffer {
std.buffer.Buffer.alloc(10);
}
namespace constants {
std.constants.EACCES + 2;
}
namespace zlib {
std.zlib.createDeflate().write("ttt");
}
namespace tls {
std.tls.connect({}).end();
}
namespace console {
std.console.trace("message");
}
namespace dns {
std.dns.resolve4("adone.io", (err, data) => {});
}
namespace timers {
std.timers.setTimeout(() => {}, 2000).unref();
}
namespace dgram {
std.dgram.createSocket("udp4").bind(31337);
}
}
+737
View File
@@ -0,0 +1,737 @@
const { util } = adone;
namespace utilTests {
namespace arrify {
const a: number[] = util.arrify([1, 2, 3]);
const b: number[] = util.arrify(1);
const c: string[] = util.arrify("2");
const d: string[] = util.arrify(["1"]);
}
namespace slice {
const a: number[] = util.slice([1, 2, 3]);
const b: number[] = util.slice([1, 2, 3], 1);
const c: number[] = util.slice([1, 2, 3], 1, 4);
const d: string[] = util.slice(["1"]);
}
namespace spliceOne {
util.spliceOne([1, 2, 3], 0);
}
namespace normalizePath {
const a: string = util.normalizePath("path");
const b: string = util.normalizePath("path", true);
}
namespace unixifyPath {
const a: string = util.unixifyPath("path");
const b: string = util.unixifyPath("path", true);
}
namespace functionName {
const a: string = util.functionName(function f() { });
const b: string = util.functionName((a, b, c) => { });
}
namespace mapArguments {
const a: (...args: any[]) => any = util.mapArguments(() => { });
const b: <T>(...args: T[]) => T[] = util.mapArguments(1);
const c: (...args: any[]) => any = util.mapArguments([1]);
const d: <T>(x: T) => T = util.mapArguments();
}
namespace parseMs {
const result: {
days: number;
hours: number;
milliseconds: number;
minutes: number;
} = util.parseMs(123);
}
namespace pluralizeWord {
const a: string = util.pluralizeWord("day");
const b: string = util.pluralizeWord("day", "days");
const c: string = util.pluralizeWord("day", "days", 1);
}
namespace functionParams {
const a: string[] = util.functionParams((a: any, b: any, c: any) => { });
}
namespace randomChoice {
const a: number = util.randomChoice([1, 2, 3]);
const b: string = util.randomChoice(["1", "2", "3"]);
}
namespace shuffleArray {
const a: number[] = util.shuffleArray([1, 2, 3]);
const b: string[] = util.shuffleArray(["1", "2", "3"]);
}
namespace enumerate {
{
const a = util.enumerate([1, 2, 3]);
const it = a[Symbol.iterator]();
const value: [number, number] = it.next().value;
for (const i of a) {
const [idx, value]: [number, number] = i;
}
}
{
const a = util.enumerate(["1", "2"]);
const it = a[Symbol.iterator]();
const value: [number, string] = it.next().value;
for (const i of a) {
const [idx, value]: [number, string] = i;
}
}
}
namespace zip {
{
const a = util.zip([1, 2, 3], ["4", "5", "6"]);
const it = a[Symbol.iterator]();
const value: [number, string] = it.next().value;
for (const i of a) {
const [i1, i2]: [number, string] = i;
}
}
{
const a = util.zip(
[1, 2, 3],
["4", "5", "6"],
[7, 8, 9]
);
const it = a[Symbol.iterator]();
const value: [number, string, number] = it.next().value;
for (const i of a) {
const [i1, i2, i3]: [number, string, number] = i;
}
}
{
const a = util.zip(
[1, 2, 3],
["4", "5", "6"],
[7, 8, 9],
["10", "11", "12"]
);
const it = a[Symbol.iterator]();
const value: [number, string, number, string] = it.next().value;
for (const i of a) {
const [i1, i2, i3, i4]: [number, string, number, string] = i;
}
}
{
const a = util.zip(
[1, 2, 3],
["4", "5", "6"],
[7, 8, 9],
["10", "11", "12"],
[13, 14, 15, 16]
);
const it = a[Symbol.iterator]();
const value: any[] = it.next().value;
for (const i of a) {
const [i1, i2, i3, i4]: any[] = i;
}
}
}
namespace keys {
const a: string[] = util.keys({});
const b: string[] = util.keys({}, { all: true });
const c: string[] = util.keys({}, { followProto: true });
const d: string[] = util.keys({}, { onlyEnumerable: true });
}
namespace values {
const a: any[] = util.values({});
const b: any[] = util.values({}, { all: true });
const c: any[] = util.values({}, { followProto: true });
const d: any[] = util.values({}, { onlyEnumerable: true });
}
namespace entries {
const a: Array<[string, any]> = util.entries({});
const b: Array<[string, any]> = util.entries({}, { all: true });
const c: Array<[string, any]> = util.entries({}, { followProto: true });
const d: Array<[string, any]> = util.entries({}, { onlyEnumerable: true });
}
namespace toDotNotation {
const a: object = util.toDotNotation({ a: 1 });
}
namespace flatten {
const a: number[] = util.flatten([1, [2, 3]]);
const b: number[] = util.flatten([1, [2, 3]], {});
const c: number[] = util.flatten([1, [2, 3]], { depth: 1 });
}
namespace globParent {
const a: string = util.globParent("a/b/c/**");
}
namespace by {
const a: (a: number, b: number) => any = util.by((x: number): number => x);
const b: (a: number, b: number) => number = util.by((x: number): string => `${x}`, (a: string, b: string) => a.length - b.length);
}
namespace toFastProperties {
const a: object = util.toFastProperties({});
}
namespace stripBom {
const a: string = util.stripBom("123");
}
namespace sortKeys {
const a: object = util.sortKeys({});
const b: object = util.sortKeys({}, {});
const c: object = util.sortKeys({}, { deep: true });
const d: object = util.sortKeys({}, { compare: (a, b) => 2 });
}
namespace globize {
const a: string = util.globize("test");
const b: string = util.globize("test", {});
const c: string = util.globize("test", { exts: "" });
const d: string = util.globize("test", { recursively: true });
}
namespace unique {
const a: number[] = util.unique([1, 2, 3]);
const b: string[] = util.unique(["1", "2", "3"]);
const c: object[] = util.unique([{ a: 1 }, { a: 2 }], (obj: any) => obj.a);
}
namespace invertObject {
const a: object = util.invertObject({});
const b: object = util.invertObject({}, {});
const c: object = util.invertObject({}, { all: true });
const d: object = util.invertObject({}, { followProto: true });
const e: object = util.invertObject({}, { onlyEnumerable: true });
}
namespace humanizeTime {
const a: string = util.humanizeTime(12345);
const b: string = util.humanizeTime(12345, {});
const c: string = util.humanizeTime(12345, { compact: true });
const d: string = util.humanizeTime(12345, { msDecimalDigits: 2 });
const e: string = util.humanizeTime(12345, { secDecimalDigits: 2 });
const f: string = util.humanizeTime(12345, { verbose: true });
}
namespace humanizeSize {
const a: string = util.humanizeSize(12345);
const b: string = util.humanizeSize(12345, "");
}
namespace parseSize {
const a: number | null = util.parseSize(123);
const b: number | null = util.parseSize("123Kb");
}
namespace clone {
const a: object = util.clone({});
const b: object = util.clone({}, {});
const c: object = util.clone({}, { deep: true });
}
namespace toUTF8Array {
const a: number[] = util.toUTF8Array("hello");
}
namespace asyncIter {
util.asyncIter([1, 2, 3], () => { }, () => { });
}
namespace asyncFor {
util.asyncFor({}, () => { }, () => { });
}
namespace once {
{
const f = () => 2;
const a: () => number = util.once(f);
}
{
const f = (a: number) => `${a}`;
const a: (a: number) => string = util.once(f);
}
}
namespace asyncWaterfall {
util.asyncWaterfall([
(callback: (a: any, b: any, c: any) => void) => {
callback(null, 'one', 'two');
}
], (err: any, result: any) => {
//
});
}
namespace xrange {
for (const i of util.xrange(10)) {
const a: number = i;
}
for (const i of util.xrange(1, 10)) {
const a: number = i;
}
for (const i of util.xrange(1, 10, 2)) {
const a: number = i;
}
}
namespace range {
const a: number[] = util.range(10);
const b: number[] = util.range(1, 10);
const c: number[] = util.range(1, 10, 2);
}
namespace reFindAll {
const a: RegExpExecArray[] = util.reFindAll(/\d+/, "1 2 3 4 5");
}
namespace assignDeep {
const a: object = util.assignDeep({ a: 1 }, { a: 2 });
}
namespace match {
const a: number | boolean = util.match(["a", "b", "c"], "a");
const b: (a: any, b: any) => number | boolean = util.match("a", { index: true });
const c: number | boolean = util.match(["a", "b", "c"], "a", { dot: true });
const d: (a: any, b: any) => number | boolean = util.match("a", { end: 2 });
const e: (a: any, b: any) => number | boolean = util.match("a", { start: 2 });
const f: (a: any, b: any) => number | boolean = util.match("a");
}
namespace toposort {
const a: number[] = util.toposort([
[0, 1],
[2, 3],
[4, 5],
[6, 7]
]);
const b: number[] = util.toposort.array([0, 1, 2], [
[0, 1],
[2, 3],
[4, 5],
[6, 7]
]);
}
namespace jsesc {
const a: string = util.jsesc({ a: 1 });
const b: string = util.jsesc({ a: 1 }, { escapeEverything: true });
const c: string = util.jsesc({ a: 1 }, { minimal: true });
const d: string = util.jsesc({ a: 1 }, { isScriptContext: true });
const e: string = util.jsesc({ a: 1 }, { quotes: "'" });
const f: string = util.jsesc({ a: 1 }, { wrap: true });
const g: string = util.jsesc({ a: 1 }, { es6: true });
const h: string = util.jsesc({ a: 1 }, { json: true });
const i: string = util.jsesc({ a: 1 }, { compact: true });
const j: string = util.jsesc({ a: 1 }, { lowercaseHex: true });
const k: string = util.jsesc({ a: 1 }, { numbers: "decimal" });
const l: string = util.jsesc({ a: 1 }, { indent: " " });
const m: string = util.jsesc({ a: 1 }, { indentLevel: 4 });
const n: string = util.jsesc({ a: 1 }, { __inline1__: true });
const o: string = util.jsesc({ a: 1 }, { __inline2__: true });
}
namespace typeOf {
const a: string = util.typeOf(1);
}
namespace memcpy {
const a: number = util.memcpy.utou(Buffer.alloc(10), 0, Buffer.alloc(10), 0, 10);
const b: number = util.memcpy.atoa(new ArrayBuffer(10), 0, new ArrayBuffer(10), 0, 10);
const c: number = util.memcpy.atou(Buffer.alloc(10), 0, new ArrayBuffer(10), 0, 10);
const d: number = util.memcpy.utoa(new ArrayBuffer(10), 0, Buffer.alloc(10), 0, 10);
const e: number = util.memcpy.copy(Buffer.alloc(10), 0, Buffer.alloc(10), 0, 10);
const f: number = util.memcpy.copy(new ArrayBuffer(10), 0, new ArrayBuffer(10), 0, 10);
const g: number = util.memcpy.copy(Buffer.alloc(10), 0, new ArrayBuffer(10), 0, 10);
const h: number = util.memcpy.copy(new ArrayBuffer(10), 0, Buffer.alloc(10), 0, 10);
}
namespace uuid {
namespace v1 {
const a: string = util.uuid.v1();
const b: number[] = util.uuid.v1({}, []);
const c: number[] = util.uuid.v1({}, [], 1);
const d: string = util.uuid.v1({});
const e: string = util.uuid.v1({ clockseq: 1 });
const f: string = util.uuid.v1({ msecs: 1 });
const g: string = util.uuid.v1({ nsecs: 1 });
}
namespace v4 {
const a: string = util.uuid.v4();
const b: number[] = util.uuid.v4({}, []);
const c: number[] = util.uuid.v4({}, [], 1);
const d: string = util.uuid.v4({});
const e: string = util.uuid.v4({ clockseq: 1 });
const f: string = util.uuid.v4({ msecs: 1 });
const g: string = util.uuid.v4({ nsecs: 1 });
}
namespace v5 {
const a: string = util.uuid.v5([], []);
const b: number[] = util.uuid.v5([], [], []);
const c: number[] = util.uuid.v5([], [], [], 1);
}
}
namespace delegate {
const a = util.delegate({}, "a");
a.getter("a").access("b").method("c").setter("d");
}
namespace GlobExp {
{
const glob = new util.GlobExp("*.js");
const a: boolean = glob.hasMagic();
const b: string[] = glob.expandBraces();
const c: RegExp = glob.makeRe();
const d: boolean = glob.test("a.js");
}
{
const a: boolean = util.GlobExp.hasMagic("*.js");
const b: string[] = util.GlobExp.expandBraces("*.js");
const c: RegExp = util.GlobExp.makeRe("*.js");
const d: boolean = util.GlobExp.test("*.js", "a.js");
}
new util.GlobExp("");
new util.GlobExp("", {});
new util.GlobExp("", { dot: true });
new util.GlobExp("", { flipNegate: true });
new util.GlobExp("", { matchBase: true });
new util.GlobExp("", { nobrace: true });
new util.GlobExp("", { nocase: true });
new util.GlobExp("", { nocomment: true });
new util.GlobExp("", { noext: true });
new util.GlobExp("", { noglobstar: true });
new util.GlobExp("", { nonegate: true });
util.GlobExp.hasMagic("", {});
util.GlobExp.hasMagic("", { dot: true });
util.GlobExp.hasMagic("", { flipNegate: true });
util.GlobExp.hasMagic("", { matchBase: true });
util.GlobExp.hasMagic("", { nobrace: true });
util.GlobExp.hasMagic("", { nocase: true });
util.GlobExp.hasMagic("", { nocomment: true });
util.GlobExp.hasMagic("", { noext: true });
util.GlobExp.hasMagic("", { noglobstar: true });
util.GlobExp.hasMagic("", { nonegate: true });
util.GlobExp.expandBraces("", {});
util.GlobExp.expandBraces("", { dot: true });
util.GlobExp.expandBraces("", { flipNegate: true });
util.GlobExp.expandBraces("", { matchBase: true });
util.GlobExp.expandBraces("", { nobrace: true });
util.GlobExp.expandBraces("", { nocase: true });
util.GlobExp.expandBraces("", { nocomment: true });
util.GlobExp.expandBraces("", { noext: true });
util.GlobExp.expandBraces("", { noglobstar: true });
util.GlobExp.expandBraces("", { nonegate: true });
util.GlobExp.makeRe("", {});
util.GlobExp.makeRe("", { dot: true });
util.GlobExp.makeRe("", { flipNegate: true });
util.GlobExp.makeRe("", { matchBase: true });
util.GlobExp.makeRe("", { nobrace: true });
util.GlobExp.makeRe("", { nocase: true });
util.GlobExp.makeRe("", { nocomment: true });
util.GlobExp.makeRe("", { noext: true });
util.GlobExp.makeRe("", { noglobstar: true });
util.GlobExp.makeRe("", { nonegate: true });
util.GlobExp.test("a", "b", {});
util.GlobExp.test("a", "b", { dot: true });
util.GlobExp.test("a", "b", { flipNegate: true });
util.GlobExp.test("a", "b", { matchBase: true });
util.GlobExp.test("a", "b", { nobrace: true });
util.GlobExp.test("a", "b", { nocase: true });
util.GlobExp.test("a", "b", { nocomment: true });
util.GlobExp.test("a", "b", { noext: true });
util.GlobExp.test("a", "b", { noglobstar: true });
util.GlobExp.test("a", "b", { nonegate: true });
}
namespace iconv {
// TODO
}
namespace sqlstring {
namespace escapeId {
const a: string = util.sqlstring.escapeId("asd");
const b: string = util.sqlstring.escapeId(["asd"]);
const c: string = util.sqlstring.escapeId(["asd"], true);
}
namespace dateToString {
const a: string = util.sqlstring.dateToString(Date.now());
const b: string = util.sqlstring.dateToString(123, "local");
}
namespace arrayToList {
const a: string = util.sqlstring.arrayToList(["1", "a"]);
}
namespace bufferToString {
const a: string = util.sqlstring.bufferToString(Buffer.alloc(10));
}
namespace objectToValues {
const a: string = util.sqlstring.objectToValues({ a: 1 });
const b: string = util.sqlstring.objectToValues({ a: 1 }, "local");
}
namespace escape {
const a: string = util.sqlstring.escape(1);
const b: string = util.sqlstring.escape(1, true);
const c: string = util.sqlstring.escape(1, true, "local");
}
namespace format {
const a: string = util.sqlstring.format("??");
const b: string = util.sqlstring.format("??", "a");
const c: string = util.sqlstring.format("??", ["a"]);
const d: string = util.sqlstring.format("??", ["a"], true);
}
}
namespace Editor {
namespace options {
new util.Editor();
new util.Editor({});
new util.Editor({ text: "" });
new util.Editor({ editor: "" });
new util.Editor({ path: "" });
new util.Editor({ ext: "" });
}
const a: string = util.Editor.DEFAULT;
new util.Editor().spawn().then((x: adone.std.child_process.ChildProcess) => { });
new util.Editor().run().then((x: string) => { });
new util.Editor().cleanup().then((x: undefined) => { });
util.Editor.edit().then((x: string) => { });
}
namespace binarySearch {
const a: number = util.binarySearch.GREATEST_LOWER_BOUND;
const b: number = util.binarySearch.GREATEST_LOWER_BOUND;
const c: number = util.binarySearch([1, 2, 3], 2);
const d: number = util.binarySearch([1, 2, 3], 2, 0);
const e: number = util.binarySearch([1, 2, 3], 2, 0, 10);
const f: number = util.binarySearch([1, 2, 3], 2, 0, 10, (a, b) => a - b);
const g: number = util.binarySearch([1, 2, 3], 2, 0, 10, (a, b) => a - b, util.binarySearch.GREATEST_LOWER_BOUND);
}
namespace buffer {
const a: Buffer = util.buffer.concat([Buffer.alloc(10), Buffer.alloc(20)], 30);
util.buffer.mask(Buffer.alloc(10), Buffer.alloc(10), Buffer.alloc(10), 0, 10);
util.buffer.unmask(Buffer.alloc(10), Buffer.alloc(10));
}
namespace shebang {
const a: string | null = util.shebang("#!/bin/sh");
}
namespace ReInterval {
new util.ReInterval(() => { }, 1000);
new util.ReInterval(() => { }, 1000, [1]);
const a = new util.ReInterval(() => { }, 1000);
a.reschedule(400);
a.clear();
a.destroy();
}
namespace RateLimiter {
new util.RateLimiter();
new util.RateLimiter(1);
new util.RateLimiter(1, 1000);
new util.RateLimiter(1, 1000, true);
const a = new util.RateLimiter();
a.removeTokens(1).then((x: number) => { });
const b: boolean = a.tryRemoveTokens(10);
const c: number = a.getTokensRemaining();
}
namespace throttle {
const a: () => Promise<number> = util.throttle(() => 42);
const b: (a: number) => Promise<string> = util.throttle((a: number) => `${a}`);
const c: (a: number, b: string) => Promise<string> = util.throttle((a: number, b: string) => String(a) + b);
const d = util.throttle(() => { }, {});
const e = util.throttle(() => { }, { interval: 1000 });
const f = util.throttle(() => { }, { max: 10 });
const g = util.throttle(() => { }, { ordered: true });
const h = util.throttle(() => { }, { waitForReturn: true });
}
namespace fakeClock {
namespace timers {
const a: typeof global.setTimeout = util.fakeClock.timers.setTimeout;
const b: typeof global.clearTimeout = util.fakeClock.timers.clearTimeout;
const c: typeof global.setInterval = util.fakeClock.timers.setInterval;
const d: typeof global.clearInterval = util.fakeClock.timers.clearInterval;
const e: typeof global.setImmediate = util.fakeClock.timers.setImmediate;
const f: typeof global.clearImmediate = util.fakeClock.timers.clearImmediate;
const g: typeof global.Date = util.fakeClock.timers.Date;
const h: typeof global.process.hrtime = util.fakeClock.timers.hrtime;
const i: typeof global.process.nextTick = util.fakeClock.timers.nextTick;
}
namespace install {
util.fakeClock.install();
util.fakeClock.install(100);
util.fakeClock.install(new Date());
util.fakeClock.install({});
util.fakeClock.install({ advanceTimeDelta: 20 });
util.fakeClock.install({ loopLimit: 20 });
util.fakeClock.install({ now: 20 });
util.fakeClock.install({ shouldAdvanceTime: false });
util.fakeClock.install({ target: {} });
const clock = util.fakeClock.install({ toFake: ["setTimeout", "clearTimeout"] });
{
const timer = clock.setTimeout(() => {}, 100, 1, 2, 3);
const id: number = timer.id;
timer.ref();
timer.unref();
clock.clearTimeout(timer);
}
{
const timer = clock.setInterval(() => {}, 1, 2, 3);
const id: number = timer.id;
timer.ref();
timer.unref();
clock.clearInterval(timer);
}
{
const timer = clock.setImmediate(() => {}, 1, 2, 3);
const id: number = timer.id;
timer.ref();
timer.unref();
clock.clearImmediate(timer);
}
clock.nextTick(() => {}, 1, 2, 3);
clock.updateHrTime(10);
const a: number = clock.tick(100);
const b: number = clock.next();
const c: number = clock.runAll();
const d: number = clock.runToLast();
clock.setSystemTime(100);
const e: [number, number] = clock.hrtime();
const f: [number, number] = clock.hrtime(e);
clock.uninstall();
}
namespace createClock {
util.fakeClock.createClock();
util.fakeClock.createClock(0);
const clock = util.fakeClock.createClock(0, 100);
{
const timer = clock.setTimeout(() => {}, 100, 1, 2, 3);
const id: number = timer.id;
timer.ref();
timer.unref();
clock.clearTimeout(timer);
}
{
const timer = clock.setInterval(() => {}, 1, 2, 3);
const id: number = timer.id;
timer.ref();
timer.unref();
clock.clearInterval(timer);
}
{
const timer = clock.setImmediate(() => {}, 1, 2, 3);
const id: number = timer.id;
timer.ref();
timer.unref();
clock.clearImmediate(timer);
}
clock.nextTick(() => {}, 1, 2, 3);
clock.updateHrTime(10);
const a: number = clock.tick(100);
const b: number = clock.next();
const c: number = clock.runAll();
const d: number = clock.runToLast();
clock.setSystemTime(100);
const e: [number, number] = clock.hrtime();
const f: [number, number] = clock.hrtime(e);
}
namespace ltgt {
namespace contains {
const a: boolean = util.ltgt.contains({ lt: 2 }, 2);
const b: boolean = util.ltgt.contains({ lt: 2 }, 2, (a, b) => b - a);
const c: boolean = util.ltgt.contains({ lt: "2" }, "2");
const d: boolean = util.ltgt.contains({ lt: "2" }, "2", (a, b) => b.charCodeAt(0) - a.charCodeAt(0));
}
namespace filter {
const a: (a: number) => boolean = util.ltgt.filter({ lt: 2 });
const b: (a: number) => boolean = util.ltgt.filter({ lt: 2 }, (a, b) => b - a);
const c: (a: string) => boolean = util.ltgt.filter({ lt: "2" });
const d: (a: string) => boolean = util.ltgt.filter({ lt: "2" }, (a, b) => b.charCodeAt(0) - a.charCodeAt(0));
}
namespace toLtgt {
const a: adone.util.ltgt.I.Range<number> = util.ltgt.toLtgt({ lt: 2 }, {});
const b: adone.util.ltgt.I.Range<string> = util.ltgt.toLtgt({ lt: 2 }, {}, (a) => `${a}`);
const c: adone.util.ltgt.I.Range<number> = util.ltgt.toLtgt({ lt: 2 }, {}, (a) => a, 2);
const d: adone.util.ltgt.I.Range<number> = util.ltgt.toLtgt({ lt: 2 }, {}, (a) => a, 2, 5);
}
namespace endEnclusive {
const a: boolean = util.ltgt.endInclusive({ lt: 2 });
}
namespace startInclusive {
const a: boolean = util.ltgt.startInclusive({ lt: 2 });
}
namespace end {
const a: number | undefined = util.ltgt.end({ lt: 2 });
const b: number | string = util.ltgt.end({ lt: 2 }, "2");
const c: number = util.ltgt.end({ lt: 2 }, 2);
}
namespace start {
const a: number | undefined = util.ltgt.start({ lt: 2 });
const b: number | string = util.ltgt.start({ lt: 2 }, "2");
const c: number = util.ltgt.start({ lt: 2 }, 2);
}
namespace upperBound {
const a: number | undefined = util.ltgt.upperBound({ lt: 2 });
const b: number | string = util.ltgt.upperBound({ lt: 2 }, "2");
const c: number = util.ltgt.upperBound({ lt: 2 }, 2);
}
namespace upperBoundKey {
const a: number | undefined = util.ltgt.upperBoundKey({ lt: 2 });
}
namespace upperBoundExclusive {
const a: boolean = util.ltgt.upperBoundInclusive({ lt: 2 });
}
namespace lowerBoundExclusive {
const a: boolean = util.ltgt.lowerBoundInclusive({ lt: 2 });
}
namespace upperBoundInclusive {
const a: boolean = util.ltgt.upperBoundInclusive({ lt: 2 });
}
namespace lowerBoundInclusive {
const a: boolean = util.ltgt.lowerBoundInclusive({ lt: 2 });
}
namespace lowerBound {
const a: number | undefined = util.ltgt.lowerBound({ lt: 2 });
const b: number | string = util.ltgt.lowerBound({ lt: 2 }, "2");
const c: number = util.ltgt.lowerBound({ lt: 2 }, 2);
}
}
}
}
+6
View File
@@ -0,0 +1,6 @@
import adone from "adone";
namespace AdoneRootImportTests {
adone.falsely() === false;
adone.std.fs.createReadStream(__filename).close();
}
+71
View File
@@ -0,0 +1,71 @@
namespace AdoneRootTests {
{ const a: symbol = adone.null; }
adone.noop();
{ const a: number = adone.identity(2); }
{ const a: string = adone.identity("2"); }
{ const a: number[] = adone.identity([1, 2]); }
{ adone.truly() === true; }
{ adone.falsely() === false; }
{ const a: string = adone.ok; }
{ const a: string = adone.bad; }
{ const a: string[] = adone.exts; }
adone.log();
adone.fatal();
adone.error();
adone.warn();
adone.info();
adone.debug();
adone.trace();
{ const a: object = adone.o(); }
{ const a: object = adone.o({}); }
{ const a: typeof Date = adone.Date; }
{ const a: typeof process.hrtime = adone.hrtime; }
{ const a: typeof global.setTimeout = adone.setTimeout; }
{ const a: typeof clearTimeout = adone.clearTimeout; }
{ const a: typeof setInterval = adone.setInterval; }
{ const a: typeof clearInterval = adone.clearInterval; }
{ const a: typeof global.setImmediate = adone.setImmediate; }
{ const a: typeof clearImmediate = adone.clearImmediate; }
adone.lazify({});
adone.lazify({}, {});
adone.lazify({}, {}, () => { });
adone.lazify({}, {}, () => { }, { configurable: true });
adone.tag.set({}, "123");
adone.tag.has({}, "123") === true;
adone.tag.define("12");
adone.tag.define("123", "456");
{ const a: symbol = adone.tag.SUBSYSTEM; }
{ const a: symbol = adone.tag.APPLICATION; }
{ const a: symbol = adone.tag.TRANSFORM; }
{ const a: symbol = adone.tag.CORE_STREAM; }
{ const a: symbol = adone.tag.LOGGER; }
{ const a: symbol = adone.tag.LONG; }
{ const a: symbol = adone.tag.BIGNUMBER; }
{ const a: symbol = adone.tag.EXBUFFER; }
{ const a: symbol = adone.tag.EXDATE; }
{ const a: symbol = adone.tag.CONFIGURATION; }
{ const a: symbol = adone.tag.GENESIS_NETRON; }
{ const a: symbol = adone.tag.GENESIS_PEER; }
{ const a: symbol = adone.tag.NETRON; }
{ const a: symbol = adone.tag.NETRON_PEER; }
{ const a: symbol = adone.tag.NETRON_ADAPTER; }
{ const a: symbol = adone.tag.NETRON_DEFINITION; }
{ const a: symbol = adone.tag.NETRON_DEFINITIONS; }
{ const a: symbol = adone.tag.NETRON_REFERENCE; }
{ const a: symbol = adone.tag.NETRON_INTERFACE; }
{ const a: symbol = adone.tag.NETRON_STUB; }
{ const a: symbol = adone.tag.NETRON_REMOTESTUB; }
{ const a: symbol = adone.tag.NETRON_STREAM; }
{ const a: symbol = adone.tag.FAST_STREAM; }
{ const a: symbol = adone.tag.FAST_FS_STREAM; }
{ const a: symbol = adone.tag.FAST_FS_MAP_STREAM; }
{ const a: Promise<void> = adone.run({}); }
{ const a: Promise<void> = adone.run({}, false); }
{ const a: object = adone.bind("library"); } // hmm
{ const a: string = adone.getAssetAbsolutePath("asset"); }
{ const a: Buffer | string = adone.loadAsset("asset"); }
{ const a: object = adone.require("path"); }
{ const a: object = adone.package; }
{ const a: typeof adone.assertion.assert = adone.assert; }
{ const a: typeof adone.assertion.expect = adone.expect; }
}
+42
View File
@@ -0,0 +1,42 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es2017",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"adone.d.ts",
"glosses/common.d.ts",
"glosses/math.d.ts",
"glosses/std.d.ts",
"glosses/utils.d.ts",
"glosses/assertion.d.ts",
"glosses/promise.d.ts",
"glosses/shani.d.ts",
"glosses/shani-global.d.ts",
"adone-tests.ts",
"test/index.ts",
"test/index-import.ts",
"test/glosses/common.ts",
"test/glosses/math.ts",
"test/glosses/std.ts",
"test/glosses/utils.ts",
"test/glosses/assertion.ts",
"test/glosses/promise.ts",
"test/glosses/shani.ts",
"test/glosses/shani-global.ts"
]
}
+17
View File
@@ -0,0 +1,17 @@
{
"extends": "dtslint/dt.json",
"rules": {
// TODOs
"align": false,
"no-namespace": false,
"strict-export-declare-modifiers": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-mergeable-namespace": false,
"no-single-declare-module": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"unified-signatures": false,
"space-before-function-paren": false
}
}
+50
View File
@@ -0,0 +1,50 @@
// Global
const threeCamera = new AFRAME.THREE.Camera();
AFRAME.TWEEN.Easing;
// Entity
const entity = document.createElement('a-entity');
entity.emit('rotate');
entity.emit('collide', { target: entity });
entity.emit('sink', null, false);
const position = entity.getAttribute('position');
position.x;
position.y;
position.z;
entity.setAttribute('material', 'color', 'red');
entity.components['geometry'].data;
type MyEntity = AFrame.Entity<{
camera: THREE.Camera;
material: THREE.Material;
sound: { pause(): void };
}>;
const camera = document.querySelector<MyEntity>('a-entity[camera]').components.camera;
const material = document.querySelector<MyEntity>('a-entity[material]').components.material;
document.querySelector<MyEntity>('a-entity[sound]').components.sound.pause();
entity.getDOMAttribute('geometry').primitive;
entity.setAttribute('light', {
type: 'spot',
distance: 30,
intensity: 2.0
});
entity.addEventListener('child-detached', (event) => {
event.detail;
});
// Components
const Component = AFRAME.registerComponent('test', {});
// Scene
const scene = document.querySelector('a-scene');
scene.hasLoaded;
// System
const system = scene.systems['systemName'];
+328
View File
@@ -0,0 +1,328 @@
// Type definitions for AFRAME 0.5
// Project: https://aframe.io/
// Definitions by: Paul Shannon <https://github.com/devpaul>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/**
* Extended tests available at https://github.com/devpaul/aframe-typings.git
*/
/// <reference types="three" />
/// <reference types="tween.js" />
// Globals
declare var AFRAME: AFrame.AFrameGlobal;
declare var hasNativeWebVRImplementation: boolean;
interface NodeSelector {
querySelector(selectors: 'a-scene'): AFrame.Scene;
querySelector<T extends AFrame.Entity<any>>(selectors: string): T;
querySelectorAll(selectors: string): NodeListOf<AFrame.Entity<any> | Element>;
}
interface Document {
createElement(tagName: string): AFrame.Entity;
}
// Interfaces
declare namespace AFrame {
interface ObjectMap<T = any> {
[ key: string ]: T;
}
interface AFrameGlobal {
AEntity: Entity;
ANode: ANode;
AScene: Scene;
components: { [ key: string ]: ComponentDescriptor };
geometries: { [ key: string ]: GeometryDescriptor };
primitives: { [ key: string ]: Entity };
registerComponent(name: string, component: ComponentDefinition): ComponentConstructor;
registerElement(name: string, element: ANode): void;
registerGeometry(name: string, geometery: THREE.Geometry): Geometry;
registerPrimitive(name: string, primitive: PrimitiveDefinition): void;
registerShader(name: string, shader: any): void;
registerSystem(name: string, definition: SystemDefinition): void;
schema: SchemaUtils;
shaders: { [ key: string ]: ShaderDescriptor };
systems: { [key: string]: System };
THREE: typeof THREE;
TWEEN: typeof TWEEN;
utils: Utils;
version: string;
}
interface Animation {
attribute: string;
begin: string | number;
delay: number;
direction: 'alternate' | 'alternateReverse' | 'normal' | 'reverse';
dur: number;
easing(): void;
end: string;
fill: 'backwards' | 'both' | 'forwards' | 'none';
from: any; // TODO type
repeat: number | 'indefinite';
to: number;
}
interface ANode extends HTMLElement {
// Only public APIs added. Many methods intentionally left out.
// createdCallback
// attachedCallback
// attributeChangedCallback
closestScene(): Scene;
closest(selector: string): ANode;
// detachedCallback
hasLoaded: boolean;
load(cb?: () => void, childFilter?: (el: Element) => boolean): void;
// updateMixins
registerMixin(id: string): void;
setAttribute(type: string, newValue: any): void;
unregisterMixin(id: string): void;
removeMixinListener(id: string): void;
attachMixinListener(mixin: HTMLElement): void;
emit(name: string, detail?: any, bubbles?: boolean): void;
emitter(name: string, detail?: any, bubbles?: boolean): () => void;
}
interface Behavior {
tick(): void;
}
interface Component {
attrName?: string;
data?: any;
dependencies?: string[];
el: Entity;
id: string;
multiple?: boolean;
name: string;
schema: Schema;
init(): void;
pause(): void;
play(): void;
remove(): void;
tick?(time: number, timeDelta: number): void;
update(oldData: any): void;
updateSchema?(): void;
extendSchema(update: Schema): void;
flushToDOM(): void;
}
interface ComponentConstructor {
new (el: Entity, name: string, id: string): Component;
}
interface ComponentDefinition {
dependencies?: string[];
el?: Entity;
id?: string;
multiple?: boolean;
schema?: Schema;
init?(): void;
pause?(): void;
play?(): void;
remove?(): void;
tick?(time: number, timeDelta: number): void;
update?(oldData: any): void;
updateSchema?(): void;
[ key: string ]: any;
}
interface ComponentDescriptor {
Component: Component;
dependencies: string[] | null;
multiple: boolean | null;
// internal APIs2
// parse
// parseAttrValueForCache
// schema
// stringify
// type
[ key: string ]: any;
}
interface Coordinate {
x: number;
y: number;
z: number;
}
interface Entity<C = ObjectMap<Component>> extends ANode {
components: C;
isPlaying: boolean;
object3D: THREE.Object3D;
object3DMap: ObjectMap<THREE.Object3D>;
sceneEl?: Scene;
addState(name: string): void;
flushToDOM(recursive?: boolean): void;
/**
* @deprecated since 0.4.0
*/
getComputedAttribute<T = Component>(attr: string): T;
getDOMAttribute<T = any>(attr: string): T;
getObject3D(type: string): THREE.Object3D;
getOrCreateObject3D(type: string, construct: any): THREE.Object3D;
is(stateName: string): boolean;
pause(): void;
play(): void;
setObject3D(type: string, obj: THREE.Object3D): void;
removeAttribute(attr: string, property?: string): void;
removeObject3D(type: string): void;
removeState(stateName: string): void;
// getAttribute specific usages
getAttribute(type: string): any;
getAttribute<T = Component>(attr: string): T;
getAttribute(type: 'position' | 'rotation' | 'scale'): Coordinate;
// setAttribute specific usages
setAttribute(attr: string, value: any): void;
setAttribute(attr: string, property: string, componentAttrValue?: any): void;
setAttribute(type: 'position' | 'rotation' | 'scale', value: Coordinate): void;
// addEventListener specific usages
addEventListener<K extends keyof EntityEventMap>(type: K, listener: (event: Event & EntityEventMap[K]) => void, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
type DetailEvent<D> = Event & { detail: D };
interface EntityEventMap {
'child-attached': DetailEvent<{ el: Element | Entity }>;
'child-detached': DetailEvent<{ el: Element | Entity }>;
'componentchanged': DetailEvent<{ name: string }>;
'componentremoved': DetailEvent<{
name: string,
id: string,
newData: any,
oldData: any
}>;
'loaded': EventListener;
'pause': EventListener;
'play': EventListener;
'stateadded': DetailEvent<{ state: string }>;
'stateremoved': DetailEvent<{ state: string }>;
'schemachanged': DetailEvent<{ componentName: string }>;
}
interface Geometry {
name: string;
geometry: THREE.Geometry;
schema: Schema;
update(data: object): void;
[ key: string ]: any;
}
interface GeometryDescriptor {
Geometry: Geometry;
schema: Schema;
}
interface MultiPropertySchema {
[ key: string ]: SinglePropertySchema<any>;
}
interface PrimitiveDefinition {
defaultComponents?: any; // TODO cleanup type
deprecated?: boolean;
mappings?: any; // TODO cleanup type
transforms?: any; // TODO cleanup type
}
type PropertyTypes = 'array' | 'boolean' | 'color' | 'int' | 'number' | 'selector' |
'selectorAll' | 'src' | 'string' | 'vec2' | 'vec3' | 'vec4';
type SceneEvents = 'enter-vr' | 'exit-vr' | 'loaded' | 'renderstart';
interface Scene extends Entity {
behaviors: Behavior[];
camera: THREE.Camera;
canvas: HTMLCanvasElement;
effect: THREE.VREffect;
isMobile: boolean;
object3D: THREE.Scene;
renderer: THREE.WebGLRenderer;
renderStarted: boolean;
systems: ObjectMap<System>;
time: number;
enterVR(): Promise<void> | void;
exitVR(): Promise<void> | void;
reload(): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
addEventListener(type: SceneEvents, listener: EventListener, useCapture?: boolean): void;
}
type Schema = SinglePropertySchema<any> | MultiPropertySchema;
interface SchemaUtils {
isSingleProperty(schema: Schema): boolean;
process(schema: Schema): boolean;
}
interface Shader {
name: string;
schema: Schema;
}
interface ShaderDescriptor {
Shader: Shader;
schema: Schema;
}
interface SinglePropertySchema<T> {
type?: PropertyTypes;
'default'?: T;
parse?(value: string): T;
stringify?(value: T): string;
[ key: string ]: any;
}
interface System {
data: any;
schema: Schema;
init(): void;
pause(): void;
play(): void;
tick?(): void;
}
interface SystemDefinition {
schema?: Schema;
init?(): void;
pause?(): void;
play?(): void;
tick?(): void;
[ key: string ]: any;
}
interface Utils {
coordinates: {
isCoordinate(value: string): boolean;
parse(value: string): Coordinate;
stringify(coord: Coordinate): string;
};
entity: {
getComponentProperty(entity: Entity, componentName: string, delimiter?: string): any;
setComponentProperty(entity: Entity, componentName: string, value: any, delimiter?: string): void;
};
styleParser: {
parse(value: string): object;
stringify(data: object): string;
};
deepEqual(a: any, b: any): boolean;
diff(a: object, b: object): object;
extend(target: object, ... source: object[]): object;
extendDeep(target: object, ... source: object[]): object;
}
}
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es5",
"dom",
"es2015.iterable",
"es2015.promise"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"aframe-tests.ts"
]
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"no-unnecessary-generics": false
}
}
-136
View File
@@ -1,136 +0,0 @@
checkGridOptions(<ag.grid.GridOptions>{});
checkColDef(<ag.grid.ColDef>{});
function checkGridOptions(gridOptions: ag.grid.GridOptions): void {
gridOptions.virtualPaging = true;
gridOptions.toolPanelSuppressPivot = true;
gridOptions.toolPanelSuppressValues = true;
gridOptions.rowsAlreadyGrouped = true;
gridOptions.suppressRowClickSelection = true;
gridOptions.suppressCellSelection = true;
gridOptions.sortingOrder = ['asc','desc'];
gridOptions.suppressMultiSort = true;
gridOptions.suppressHorizontalScroll = true;
gridOptions.unSortIcon = true;
gridOptions.rowHeight = 0;
gridOptions.rowBuffer = 0;
gridOptions.enableColResize = true;
gridOptions.enableCellExpressions = true;
gridOptions.enableSorting = true;
gridOptions.enableServerSideSorting = true;
gridOptions.enableFilter = true;
gridOptions.enableServerSideFilter = true;
gridOptions.colWidth = 0;
gridOptions.suppressMenuHide = true;
gridOptions.singleClickEdit = true;
gridOptions.debug = true;
gridOptions.icons = {};
gridOptions.angularCompileRows = true;
gridOptions.angularCompileFilters = true;
gridOptions.angularCompileHeaders = true;
gridOptions.localeText = {};
gridOptions.localeTextFunc = function() {}
gridOptions.suppressScrollLag = true;
gridOptions.groupSuppressAutoColumn = true;
gridOptions.groupSelectsChildren = true;
gridOptions.groupHidePivotColumns = true;
gridOptions.groupIncludeFooter = true;
gridOptions.groupUseEntireRow = true;
gridOptions.groupSuppressRow = true;
gridOptions.groupSuppressBlankHeader = true;
gridOptions.forPrint = true;
gridOptions.groupColumnDef = {};
gridOptions.context = {};
gridOptions.rowStyle = {color: 'red'};
gridOptions.rowClass = 'green';
gridOptions.groupDefaultExpanded = false;
gridOptions.slaveGrids = [];
gridOptions.rowSelection = 'single';
gridOptions.rowDeselection = true;
gridOptions.rowData = [];
gridOptions.floatingTopRowData = [];
gridOptions.floatingBottomRowData = [];
gridOptions.showToolPanel = true;
gridOptions.groupKeys = ['a','b']
gridOptions.groupAggFields = ['a','b']
gridOptions.columnDefs = [];
gridOptions.datasource = {};
gridOptions.pinnedColumnCount = 0;
gridOptions.groupHeaders = true;
gridOptions.headerHeight = 0;
gridOptions.groupRowInnerRenderer = function(params) {};
gridOptions.groupRowRenderer = {};
gridOptions.isScrollLag = function() {return true;}
gridOptions.isExternalFilterPresent = function() { return true; };
gridOptions.doesExternalFilterPass = function(node: ag.grid.RowNode) { return false; };
gridOptions.getRowStyle = function() {};
gridOptions.getRowClass = function() {};
gridOptions.headerCellRenderer = function() {};
gridOptions.groupAggFunction = function(nodes: any[]) {};
gridOptions.onReady = function(api: any) {};
gridOptions.onModelUpdated = function() {};
gridOptions.onCellClicked = function(params) {};
gridOptions.onCellDoubleClicked = function(params) {};
gridOptions.onCellContextMenu = function(params) {};
gridOptions.onCellValueChanged = function(params) {};
gridOptions.onCellFocused = function(params) {};
gridOptions.onRowSelected = function(params) {};
gridOptions.onSelectionChanged = function() {};
gridOptions.onBeforeFilterChanged = function() {};
gridOptions.onAfterFilterChanged = function() {};
gridOptions.onFilterModified = function() {};
gridOptions.onBeforeSortChanged = function() {};
gridOptions.onAfterSortChanged = function() {};
gridOptions.onVirtualRowRemoved = function(params) {};
gridOptions.onRowClicked = function(params) {};
gridOptions.api = null;
gridOptions.columnApi = null;
}
function checkColDef(colDef: ag.grid.ColDef): void {
colDef.sort = 'test';
colDef.sortedAt = 0;
colDef.sortingOrder = ['asc','desc'];
colDef.headerName = 'test';
colDef.field = 'test';
colDef.headerValueGetter = 'test';
colDef.colId = 'test';
colDef.hide = true;
colDef.headerTooltip = 'test';
colDef.valueGetter = 'test';
colDef.headerCellRenderer = {};
colDef.headerClass = 'test';
colDef.width = 0;
colDef.minWidth = 0;
colDef.maxWidth = 0;
colDef.cellClass = 'test';
colDef.cellStyle = {color: 'test'};
colDef.cellRenderer = function() {};
colDef.floatingCellRenderer = function() {};
colDef.aggFunc = 'test';
colDef.comparator = function() {};
colDef.checkboxSelection = true;
colDef.suppressMenu = true;
colDef.suppressSorting = true;
colDef.unSortIcon = true;
colDef.suppressSizeToFit = true;
colDef.suppressResize = true;
colDef.headerGroup = 'test';
colDef.headerGroupShow = 'test';
colDef.editable = true;
colDef.newValueHandler = function() {};
colDef.volatile = true;
colDef.template = 'test';
colDef.templateUrl = 'test';
colDef.filter = 'test';
colDef.filterParams = {};
colDef.onCellValueChanged = function() {};
colDef.onCellClicked = function() {};
colDef.onCellDoubleClicked = function() {};
colDef.onCellContextMenu = function() {};
colDef.cellClassRules = {};
}
-1991
View File
File diff suppressed because it is too large Load Diff
-23
View File
@@ -1,23 +0,0 @@
{
"files": [
"index.d.ts",
"ag-grid-tests.ts"
],
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
}
}
+6 -4
View File
@@ -3,16 +3,16 @@ import * as Agenda from "agenda";
var mongoConnectionString = "mongodb://127.0.0.1/agenda";
var agenda = new Agenda({ db: { address: mongoConnectionString } });
agenda.define('delete old users', (job, done) => {
});
agenda.on('ready', () => {
agenda.every('3 minutes', 'delete old users');
// Alternatively, you could also do:
// Alternatively, you could also do:
agenda.every('*/3 * * * *', 'delete old users');
agenda.start();
@@ -81,6 +81,8 @@ agenda.stop(function() {
process.exit(0);
});
job.agenda.now('do the hokey pokey');
job.repeatEvery('10 minutes');
job.repeatAt('3:30pm');
+7 -1
View File
@@ -1,7 +1,8 @@
// Type definitions for Agenda v0.8.9
// Type definitions for Agenda v1.0.0
// Project: https://github.com/rschmukler/agenda
// Definitions by: Meir Gottlieb <https://github.com/meirgottlieb>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="node" />
@@ -336,6 +337,11 @@ declare namespace Agenda {
*/
attrs: JobAttributes;
/**
* The agenda that created the job.
*/
agenda: Agenda;
/**
* Specifies an interval on which the job should repeat.
* @param interval A human-readable format String, a cron format String, or a Number.
@@ -0,0 +1,9 @@
import AggregateError = require('aggregate-error');
const err = new AggregateError([new Error('foo'), 'bar']);
for (const el of Array.from(err)) {
const err: Error = el;
}
throw err;
+12
View File
@@ -0,0 +1,12 @@
// Type definitions for aggregate-error 1.0
// Project: https://github.com/sindresorhus/aggregate-error#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export = AggregateError;
declare class AggregateError extends Error implements Iterable<Error> {
constructor(errors: Iterable<Error | string>);
[Symbol.iterator](): Iterator<Error>;
}
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"aggregate-error-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1 -1
View File
@@ -1,6 +1,6 @@
// Type definitions for alertify 0.3.11
// Project: http://fabien-d.github.io/alertify.js/
// Definitions by: John Jeffery <http://github.com/jjeffery>
// Definitions by: John Jeffery <https://github.com/jjeffery>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare var alertify: alertify.IAlertifyStatic;
+7 -8
View File
@@ -1,21 +1,20 @@
/// <reference types="node"/>
import * as Alexa from "alexa-sdk";
exports.handler = function(event: Alexa.RequestBody, context: Alexa.Context, callback: Function) {
let alexa = Alexa.handler(event, context);
const handler = (event: Alexa.RequestBody<Alexa.Request>, context: Alexa.Context, callback: () => void) => {
const alexa = Alexa.handler(event, context);
alexa.resources = {};
alexa.registerHandlers(handlers);
alexa.execute();
};
let handlers: Alexa.Handlers = {
'LaunchRequest': function () {
const handlers: Alexa.Handlers<Alexa.Request> = {
'LaunchRequest': function() {
this.emit('SayHello');
},
'HelloWorldIntent': function () {
'HelloWorldIntent': function() {
this.emit('SayHello');
},
'SayHello': function () {
'SayHello': function() {
this.emit(':tell', 'Hello World!');
}
};
+77 -37
View File
@@ -1,43 +1,52 @@
// Type definitions for Alexa SDK for Node.js v1.0.3
// Type definitions for Alexa SDK for Node.js 1.0
// Project: https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs
// Definitions by: Pete Beegle <https://github.com/petebeegle>
// Definitions by: Pete Beegle <https://github.com/petebeegle>
// Huw <https://github.com/hoo29>
// pascalwhoop <https://github.com/pascalwhoop>
// Ben <https://github.com/blforce>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
export function handler(event: RequestBody, context: Context, callback?: Function): AlexaObject;
export function handler<T>(event: RequestBody<T>, context: Context, callback?: (err: any, response: any) => void): AlexaObject<T>;
export function CreateStateHandler(state: string, obj: any): any;
export var StateString: string;
export let StateString: string;
interface AlexaObject {
export type ConfirmationStatuses = "NONE" | "DENIED" | "CONFIRMED";
export type DialogStates = "STARTED" | "IN_PROGRESS" | "COMPLETED";
export interface AlexaObject<T> extends Handler<T> {
_event: any;
_context: any;
_callback: any;
state: any;
appId: any;
response: any;
resources: any;
dynamoDBTableName: any;
saveBeforeResponse: boolean;
registerHandlers: (...handlers: Handlers[]) => any;
registerHandlers: (...handlers: Array<Handlers<T>>) => any;
execute: () => void;
}
interface Handlers {
[intent: string]: (this: Handler) => void;
export interface Handlers<T> {
[intent: string]: (this: Handler<T>) => void;
}
interface Handler {
export interface Handler<T> {
on: any;
emit(event: string, ...args: any[]): boolean;
emitWithState: any;
state: any;
handler: any;
event: RequestBody;
event: RequestBody<T>;
attributes: any;
context: any;
name: any;
isOverriden: any;
t: (token: string, ...args: any[]) => void;
}
interface Context {
export interface Context {
callbackWaitsForEmptyEventLoop: boolean;
logGroupName: string;
logStreamName: string;
@@ -48,13 +57,13 @@ interface Context {
awsRequestId: string;
}
interface RequestBody {
export interface RequestBody<T> {
version: string;
session: Session;
request: LaunchRequest | IntentRequest | SessionEndedRequest;
request: T;
}
interface Session {
export interface Session {
new: boolean;
sessionId: string;
attributes: any;
@@ -62,56 +71,89 @@ interface Session {
user: SessionUser;
}
interface SessionApplication {
export interface SessionApplication {
applicationId: string;
}
interface SessionUser {
export interface SessionUser {
userId: string;
accessToken: string;
accessToken?: string;
}
interface LaunchRequest extends IRequest { }
export interface LaunchRequest extends Request { }
interface IntentRequest extends IRequest {
intent: Intent;
export interface IntentRequest extends Request {
dialogState?: DialogStates;
intent?: Intent;
}
interface Intent {
name: string;
slots: any;
export interface SessionEndedRequest extends Request {
reason?: string;
}
interface SessionEndedRequest extends IRequest {
reason: string;
}
interface IRequest {
export interface Request {
type: "LaunchRequest" | "IntentRequest" | "SessionEndedRequest";
requestId: string;
timeStamp: string;
timestamp: string;
locale?: string;
}
interface ResponseBody {
export interface ResolutionStatus {
code: string;
}
export interface ResolutionValue {
name: string;
id: string;
}
export interface ResolutionValueContainer {
value: ResolutionValue;
}
export interface Resolution {
authority: string;
status: ResolutionStatus;
values: ResolutionValueContainer[];
}
export interface Resolutions {
resolutionsPerAuthority: Resolution[];
}
export interface SlotValue {
confirmationStatus?: ConfirmationStatuses;
name: string;
value?: any;
resolutions?: Resolutions;
}
export interface Intent {
confirmationStatus?: ConfirmationStatuses;
name: string;
slots: Record<string, SlotValue>;
}
export interface ResponseBody {
version: string;
sessionAttributes?: any;
response: Response;
}
interface Response {
export interface Response {
outputSpeech?: OutputSpeech;
card?: Card;
reprompt?: Reprompt;
shouldEndSession: boolean;
}
interface OutputSpeech {
export interface OutputSpeech {
type: "PlainText" | "SSML";
text?: string;
ssml?: string;
}
interface Card {
export interface Card {
type: "Simple" | "Standard" | "LinkAccount";
title?: string;
content?: string;
@@ -119,13 +161,11 @@ interface Card {
image?: Image;
}
interface Image {
export interface Image {
smallImageUrl: string;
largeImageUrl: string;
}
interface Reprompt {
export interface Reprompt {
outputSpeech: OutputSpeech;
}

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