From 1d1db373db08b243fcd5ee2cbcd4647e5ac81a8a Mon Sep 17 00:00:00 2001 From: Derek Finlinson Date: Tue, 24 Jul 2018 10:36:11 -0600 Subject: [PATCH 001/197] Change Xrm.Utility.lookupObjects to return array --- types/xrm/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/xrm/index.d.ts b/types/xrm/index.d.ts index fdb6504e96..1b688c1e59 100644 --- a/types/xrm/index.d.ts +++ b/types/xrm/index.d.ts @@ -970,7 +970,7 @@ declare namespace Xrm { * Opens a lookup control to select one or more items. * @param lookupOptions Defines the options for opening the lookup dialog */ - lookupObjects(lookupOptions: LookupOptions): Async.PromiseLike; + lookupObjects(lookupOptions: LookupOptions): Async.PromiseLike; /** * Refreshes the parent grid containing the specified record. From 8a7c70eb95d7727b712acab61e02dbdf3705afde Mon Sep 17 00:00:00 2001 From: Justin Grant Date: Wed, 21 Nov 2018 19:14:37 -0800 Subject: [PATCH 002/197] Updated to clarify versioning behavior Fixed a few things with version-related documentation: * clarified the relationship of typings package version vs. library versions * explained how package versions and library versions can get out of sync * fixed broken links in major-version-upgrade section * clarified major-version-upgrade section See #25677 for more discussion and background for these changes. --- README.md | 40 ++++++++++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 9a31d73da1..8663bbb140 100644 --- a/README.md +++ b/README.md @@ -256,14 +256,43 @@ If the standard is still a draft, it belongs here. Use a name beginning with `dom-` and include a link to the standard as the "Project" link in the header. When it graduates draft mode, we may remove it from DefinitelyTyped and deprecate the associated `@types` package. -#### I want to update a package to a new major version +#### How do DefinitelyTyped package versions relate to versions of the corresponding library? -If you intend to continue updating the older version of the package, you may create a new subfolder with the current version e.g. `v2`, and copy existing files to it. If so, you will need to: +_NOTE: The discussion in this section assumes familiarity with [Semantic versioning](https://semver.org/)_ + +Each DefinitelyTyped package is versioned when published to NPM. The [automated tools](https://github.com/Microsoft/types-publisher) that publish typings packages to NPM will set the typings package's version using the version number listed in the first line of the typings file. For example, below is the first few lines of the latest (as of late 2018) [node.js typings file](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts) for node.js library version `10.12`. Because this version is included in the typings file, the NPM version of the `@types/node` package will also be `10.12`: + +```javascript +// Type definitions for Node.js 10.12 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +``` + +Sometimes typings versions and library versions can get out of sync. Below are a few common reasons why, in order of how much they inconvenience users of a library. Only the last case is typically problematic. + +* The patch version of the typings package is incremented every time an updated typings file is published for the same major and minor version. For example, a library may have only published `2.3.0` but the typings package might have gone through several revisions so its version would be `2.3.4`. If the library is later updated to `2.3.6` without any type updates needed, then the typings version would remain `2.3.4`. +* If a minor release adds new features that don't impact the type system, then there's no need to publish an updated typings file. In cases like this, updates are often skipped to the typings file. For example, imagine a contrived example of a library that formats only integers in its `2.0` release. If a `2.1` release of the library adds the capability to format floating point numbers too without changing API type signatures, then the typings version might remain `2.1.3` even as the library goes to `2.2.0`. +* Users who are updating typings for a library sometimes forget to increment the typings version to match the library version. This doesn't usually result in any problems because `npm update` will usually pick the latest typings version, although it may be confusing for users because they might assume that a library update is missing types that are really present. +* It's common for typings to lag behind library updates because it's often library users, not maintainers, who update DefinitelyTyped when new library features are released. So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the typings for a new library release. + +:exclamation:If you're updating the typings for a library version, always set the major/minor version in the first line of the typings file to match the library version that you're documenting!:exclamation: + +#### If a library is updated to a new major version with breaking changes, how should I update its typings package? + +[Semantic versioning](https://semver.org/) requires that versions with breaking changes must increment the major version number. For example, a library that removes a publicly exported function after its `3.5.8` release must bump its version to `4.0.0` in its next release. Furthermore, when the library's `4.0.0` release is out, its DefinitelyTyped typings should also be updated to `4.0.0`, including any breaking changes to the library's API. + +Many libraries have a large installed base of developers (including mainatiners of other packages using that library as a dependency) who who won't move right away to a new version that has breaking changes, because it might be months until a maintainer has time to rewrite code to adapt to the new version. In the meantime, users of old library versions still may want to udpate typings for older versions. + +If you intend to continue updating the older version of the typings package, you may create a new subfolder (e.g. `/v2/`) named for the current (soon to be "old") version, and copy existing files from the current version to it. + +Because the root folder should always contain the typings for the latest ("new") version, you'll need to make a few changes to the files in your old-version subdirectory to ensure that relative path references point to the subdirectory, not the root. 1. Update the relative paths in `tsconfig.json` as well as `tslint.json`. 2. Add path mapping rules to ensure that tests are running against the intended version. -For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: +For example, the [`history`](https://github.com/ReactTraining/history/) library introduced breaking changes between version `2.x` and `3.x`. Many developers waited a while to update their `package.json` to depend on version `3.x` of `history`. Therefore, there's a `v2` folder inside the history repository that contains typings for the older version. The [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: ```json { @@ -281,10 +310,9 @@ For example [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi } ``` -If there are other packages on DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this for packages depending on packages depending on the old version. +If there are other packages in DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this recursively for packages depending on packages depending on the old version. -For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`; -transitively `react-router-bootstrap` (which depends on `react-router`) also adds a path mapping in its [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json). +For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/v2/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`. Transitively, `react-router-bootstrap` (which depends on `react-router`) also needed to add the same path mapping (`"history": [ "history/v2" ]`) in its `tsconfig.json` until its `react-router` dependency was udpated to the latest version. Also, `/// ` will not work with path mapping, so dependencies must use `import`. From 30c8898e6866fd6820a75998616de91e88fa9207 Mon Sep 17 00:00:00 2001 From: Justin Grant Date: Fri, 23 Nov 2018 18:17:19 -0800 Subject: [PATCH 003/197] Changes in response to @Flarna review --- README.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 8663bbb140..aee5a1d07e 100644 --- a/README.md +++ b/README.md @@ -260,7 +260,7 @@ When it graduates draft mode, we may remove it from DefinitelyTyped and deprecat _NOTE: The discussion in this section assumes familiarity with [Semantic versioning](https://semver.org/)_ -Each DefinitelyTyped package is versioned when published to NPM. The [automated tools](https://github.com/Microsoft/types-publisher) that publish typings packages to NPM will set the typings package's version using the version number listed in the first line of the typings file. For example, below is the first few lines of the latest (as of late 2018) [node.js typings file](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts) for node.js library version `10.12`. Because this version is included in the typings file, the NPM version of the `@types/node` package will also be `10.12`: +Each DefinitelyTyped package is versioned when published to NPM. The [automated tools](https://github.com/Microsoft/types-publisher) that publish typings packages to NPM will set the typings package's version using the version number listed in the first line of the typings file. For example, below are the first few lines of the latest (as of late 2018) [node.js typings file](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts) for node.js library versions `10.12.x`. ```javascript // Type definitions for Node.js 10.12 @@ -270,11 +270,13 @@ Each DefinitelyTyped package is versioned when published to NPM. The [automated // Alberto Schiabel ``` +Because `10.12` is at the end the first line, the NPM version of the `@types/node` package will also be `10.12.x`. Note that the first-line comment in the typings file should only contaiin major/minor versions (e.g. `10.12`) and should not contain a patch version (e.g. `10.12.4`). This is because only the major and minor release numbers are aligned between library packages and typings packages. The patch release number of the typings package (e.g. `.0` in `10.12.0`) is initialized to zero by DefinitelyTyped and is incremented each time a new `@types/node` package is published to NPM for the same major/minor version of the corresponding library. + Sometimes typings versions and library versions can get out of sync. Below are a few common reasons why, in order of how much they inconvenience users of a library. Only the last case is typically problematic. -* The patch version of the typings package is incremented every time an updated typings file is published for the same major and minor version. For example, a library may have only published `2.3.0` but the typings package might have gone through several revisions so its version would be `2.3.4`. If the library is later updated to `2.3.6` without any type updates needed, then the typings version would remain `2.3.4`. -* If a minor release adds new features that don't impact the type system, then there's no need to publish an updated typings file. In cases like this, updates are often skipped to the typings file. For example, imagine a contrived example of a library that formats only integers in its `2.0` release. If a `2.1` release of the library adds the capability to format floating point numbers too without changing API type signatures, then the typings version might remain `2.1.3` even as the library goes to `2.2.0`. -* Users who are updating typings for a library sometimes forget to increment the typings version to match the library version. This doesn't usually result in any problems because `npm update` will usually pick the latest typings version, although it may be confusing for users because they might assume that a library update is missing types that are really present. +* As noted above, the patch version of the typings package is unrelated to the library patch version. This allows DefinitelyTyped to safely update typings for the same major/minor version of a library. +* If a minor release adds new features that don't impact the type system, then there's no need to publish an updated typings file. In cases like this, updates are often skipped to the typings file. For example, imagine a contrived example of a library that formats only integers in its `2.0` release. If a `2.1` release of the library adds the capability to format floating point numbers too without changing API type signatures, then the typings version might remain `2.0.3` even as the library goes to `2.1.0`. +* Users who are updating typings for a library sometimes forget to increment the typings version to match the library version. This doesn't usually result in any problems because `npm update` will usually pick the latest typings version, although it may be confusing for users because they might assume that a library update is missing types that are really present. It will also cause problems when libraries are (see below) updated to a new major release with breaking changes, because users won't know which typings version is the right one to use for older versions of the library. * It's common for typings to lag behind library updates because it's often library users, not maintainers, who update DefinitelyTyped when new library features are released. So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the typings for a new library release. :exclamation:If you're updating the typings for a library version, always set the major/minor version in the first line of the typings file to match the library version that you're documenting!:exclamation: @@ -283,7 +285,7 @@ Sometimes typings versions and library versions can get out of sync. Below are a [Semantic versioning](https://semver.org/) requires that versions with breaking changes must increment the major version number. For example, a library that removes a publicly exported function after its `3.5.8` release must bump its version to `4.0.0` in its next release. Furthermore, when the library's `4.0.0` release is out, its DefinitelyTyped typings should also be updated to `4.0.0`, including any breaking changes to the library's API. -Many libraries have a large installed base of developers (including mainatiners of other packages using that library as a dependency) who who won't move right away to a new version that has breaking changes, because it might be months until a maintainer has time to rewrite code to adapt to the new version. In the meantime, users of old library versions still may want to udpate typings for older versions. +Many libraries have a large installed base of developers (including mainatiners of other packages using that library as a dependency) who won't move right away to a new version that has breaking changes, because it might be months until a maintainer has time to rewrite code to adapt to the new version. In the meantime, users of old library versions still may want to udpate typings for older versions. If you intend to continue updating the older version of the typings package, you may create a new subfolder (e.g. `/v2/`) named for the current (soon to be "old") version, and copy existing files from the current version to it. @@ -292,7 +294,7 @@ Because the root folder should always contain the typings for the latest ("new") 1. Update the relative paths in `tsconfig.json` as well as `tslint.json`. 2. Add path mapping rules to ensure that tests are running against the intended version. -For example, the [`history`](https://github.com/ReactTraining/history/) library introduced breaking changes between version `2.x` and `3.x`. Many developers waited a while to update their `package.json` to depend on version `3.x` of `history`. Therefore, there's a `v2` folder inside the history repository that contains typings for the older version. The [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: +For example, the [`history`](https://github.com/ReactTraining/history/) library introduced breaking changes between version `2.x` and `3.x`. Many developers waited a while to update their `package.json` to depend on version `3.x` of `history`. Therefore, a maintainer of the typings for this library added a `v2` folder inside the history repository that contains typings for the older version. The [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: ```json { From 60a7ec20eebfbe1c0c98100a718e1422dfdeb685 Mon Sep 17 00:00:00 2001 From: Justin Grant Date: Tue, 4 Dec 2018 12:26:57 -0800 Subject: [PATCH 004/197] Updated in response to @DanielRosenwasser feedback Thanks @DanielRosenwasser for feedback! Here's what's different: * Updated typos: contaiin, udpated, udpate, mainatiners * One sentence per line, except bullet points where adding a newline will show up in user-visible text (GitHub markdown doesn't ignore line breaks in bullet points) * Removed "typings", replaced with either "type definition(s)" or "type definition package" depending on context Happy to make more edits, just let me know. --- README.md | 47 +++++++++++++++++++++++++++++++---------------- 1 file changed, 31 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index aee5a1d07e..650cecd1d5 100644 --- a/README.md +++ b/README.md @@ -260,7 +260,9 @@ When it graduates draft mode, we may remove it from DefinitelyTyped and deprecat _NOTE: The discussion in this section assumes familiarity with [Semantic versioning](https://semver.org/)_ -Each DefinitelyTyped package is versioned when published to NPM. The [automated tools](https://github.com/Microsoft/types-publisher) that publish typings packages to NPM will set the typings package's version using the version number listed in the first line of the typings file. For example, below are the first few lines of the latest (as of late 2018) [node.js typings file](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts) for node.js library versions `10.12.x`. +Each DefinitelyTyped package is versioned when published to NPM. +The [automated tools](https://github.com/Microsoft/types-publisher) that publish type declaration packages to NPM will set the type declaration package's version using the version number listed in the first line of its `index.d.ts` file. +For example, below are the first few lines of the latest (as of late 2018) [node.js type declarations](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts) for node.js library versions `10.12.x`. ```javascript // Type definitions for Node.js 10.12 @@ -270,31 +272,42 @@ Each DefinitelyTyped package is versioned when published to NPM. The [automated // Alberto Schiabel ``` -Because `10.12` is at the end the first line, the NPM version of the `@types/node` package will also be `10.12.x`. Note that the first-line comment in the typings file should only contaiin major/minor versions (e.g. `10.12`) and should not contain a patch version (e.g. `10.12.4`). This is because only the major and minor release numbers are aligned between library packages and typings packages. The patch release number of the typings package (e.g. `.0` in `10.12.0`) is initialized to zero by DefinitelyTyped and is incremented each time a new `@types/node` package is published to NPM for the same major/minor version of the corresponding library. +Because `10.12` is at the end the first line, the NPM version of the `@types/node` package will also be `10.12.x`. +Note that the first-line comment in the `index.d.ts` file should only contain major/minor versions (e.g. `10.12`) and should not contain a patch version (e.g. `10.12.4`). +This is because only the major and minor release numbers are aligned between library packages and type declaration packages. +The patch release number of the type declaration package (e.g. `.0` in `10.12.0`) is initialized to zero by DefinitelyTyped and is incremented each time a new `@types/node` package is published to NPM for the same major/minor version of the corresponding library. -Sometimes typings versions and library versions can get out of sync. Below are a few common reasons why, in order of how much they inconvenience users of a library. Only the last case is typically problematic. +Sometimes type declaration package versions and library package versions can get out of sync. +Below are a few common reasons why, in order of how much they inconvenience users of a library. +Only the last case is typically problematic. -* As noted above, the patch version of the typings package is unrelated to the library patch version. This allows DefinitelyTyped to safely update typings for the same major/minor version of a library. -* If a minor release adds new features that don't impact the type system, then there's no need to publish an updated typings file. In cases like this, updates are often skipped to the typings file. For example, imagine a contrived example of a library that formats only integers in its `2.0` release. If a `2.1` release of the library adds the capability to format floating point numbers too without changing API type signatures, then the typings version might remain `2.0.3` even as the library goes to `2.1.0`. -* Users who are updating typings for a library sometimes forget to increment the typings version to match the library version. This doesn't usually result in any problems because `npm update` will usually pick the latest typings version, although it may be confusing for users because they might assume that a library update is missing types that are really present. It will also cause problems when libraries are (see below) updated to a new major release with breaking changes, because users won't know which typings version is the right one to use for older versions of the library. -* It's common for typings to lag behind library updates because it's often library users, not maintainers, who update DefinitelyTyped when new library features are released. So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the typings for a new library release. +* As noted above, the patch version of the type declaration package is unrelated to the library patch version. This allows DefinitelyTyped to safely update type declarations for the same major/minor version of a library. +* If a minor release adds new features that don't impact the type system, then there's no need to publish updated type declarations. In cases like this, updates are often skipped to the type declaration package. For example, imagine a contrived example of a library that formats only integers in its `2.0` release. If a `2.1` release of the library adds the capability to format floating point numbers too without changing API type signatures, then the type declaration package version might remain `2.0.3` even as the library goes to `2.1.0`. +* Users who are updating type declarations for a library sometimes forget to increment the type declaration package's version to match the library version. This doesn't usually result in any problems because `npm update` will usually pick the latest type declaration package version, although it may be confusing for users because they might assume that a library update is missing types that are really present. It will also cause problems when libraries are (see below) updated to a new major release with breaking changes, because users won't know which type declaration package version is the right one to use for older versions of the library. +* It's common for type declaration package updates to lag behind library updates because it's often library users, not maintainers, who update DefinitelyTyped when new library features are released. So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the type declaration package for a new library release. -:exclamation:If you're updating the typings for a library version, always set the major/minor version in the first line of the typings file to match the library version that you're documenting!:exclamation: +:exclamation:If you're updating type declarations for a library, always set the major/minor version in the first line of `index.d.ts` to match the library version that you're documenting!:exclamation: -#### If a library is updated to a new major version with breaking changes, how should I update its typings package? +#### If a library is updated to a new major version with breaking changes, how should I update its type declaration package? -[Semantic versioning](https://semver.org/) requires that versions with breaking changes must increment the major version number. For example, a library that removes a publicly exported function after its `3.5.8` release must bump its version to `4.0.0` in its next release. Furthermore, when the library's `4.0.0` release is out, its DefinitelyTyped typings should also be updated to `4.0.0`, including any breaking changes to the library's API. +[Semantic versioning](https://semver.org/) requires that versions with breaking changes must increment the major version number. +For example, a library that removes a publicly exported function after its `3.5.8` release must bump its version to `4.0.0` in its next release. +Furthermore, when the library's `4.0.0` release is out, its DefinitelyTyped type declaration package should also be updated to `4.0.0`, including any breaking changes to the library's API. -Many libraries have a large installed base of developers (including mainatiners of other packages using that library as a dependency) who won't move right away to a new version that has breaking changes, because it might be months until a maintainer has time to rewrite code to adapt to the new version. In the meantime, users of old library versions still may want to udpate typings for older versions. +Many libraries have a large installed base of developers (including maintainers of other packages using that library as a dependency) who won't move right away to a new version that has breaking changes, because it might be months until a maintainer has time to rewrite code to adapt to the new version. +In the meantime, users of old library versions still may want to update type declarations for older versions. -If you intend to continue updating the older version of the typings package, you may create a new subfolder (e.g. `/v2/`) named for the current (soon to be "old") version, and copy existing files from the current version to it. +If you intend to continue updating the older version of a library's type declarations, you may create a new subfolder (e.g. `/v2/`) named for the current (soon to be "old") version, and copy existing files from the current version to it. -Because the root folder should always contain the typings for the latest ("new") version, you'll need to make a few changes to the files in your old-version subdirectory to ensure that relative path references point to the subdirectory, not the root. +Because the root folder should always contain the type declarations for the latest ("new") version, you'll need to make a few changes to the files in your old-version subdirectory to ensure that relative path references point to the subdirectory, not the root. 1. Update the relative paths in `tsconfig.json` as well as `tslint.json`. 2. Add path mapping rules to ensure that tests are running against the intended version. -For example, the [`history`](https://github.com/ReactTraining/history/) library introduced breaking changes between version `2.x` and `3.x`. Many developers waited a while to update their `package.json` to depend on version `3.x` of `history`. Therefore, a maintainer of the typings for this library added a `v2` folder inside the history repository that contains typings for the older version. The [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: +For example, the [`history`](https://github.com/ReactTraining/history/) library introduced breaking changes between version `2.x` and `3.x`. +Many developers waited a while to update their `package.json` to depend on version `3.x` of `history`. +Therefore, a maintainer of the type declarations for this library added a `v2` folder inside the history repository that contains type declarations for the older version. +The [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: ```json { @@ -312,9 +325,11 @@ For example, the [`history`](https://github.com/ReactTraining/history/) library } ``` -If there are other packages in DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this recursively for packages depending on packages depending on the old version. +If there are other packages in DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. +You will also need to do this recursively for packages depending on packages depending on the old version. -For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/v2/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`. Transitively, `react-router-bootstrap` (which depends on `react-router`) also needed to add the same path mapping (`"history": [ "history/v2" ]`) in its `tsconfig.json` until its `react-router` dependency was udpated to the latest version. +For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/v2/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`. +Transitively, `react-router-bootstrap` (which depends on `react-router`) also needed to add the same path mapping (`"history": [ "history/v2" ]`) in its `tsconfig.json` until its `react-router` dependency was updated to the latest version. Also, `/// ` will not work with path mapping, so dependencies must use `import`. From c4e76c862663d7d6646cd24068cbdc05d6161101 Mon Sep 17 00:00:00 2001 From: Nicolas Penin Date: Sun, 6 Jan 2019 19:41:15 +0100 Subject: [PATCH 005/197] Update index.d.ts fixed typescript compilation issue --- types/debug/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index 2eca1c8fb8..a03d5cd988 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -6,7 +6,7 @@ // Brasten Sager // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var debug: debug.IDebug; +declare var debug: debug.IDebug & {debug:debug.IDebug, default:debug.IDebug}; export = debug; export as namespace debug; From 43f9cfc7f19576a637561ca27eb7e0aaa6f74125 Mon Sep 17 00:00:00 2001 From: Nicolas Penin Date: Mon, 7 Jan 2019 10:51:47 +0100 Subject: [PATCH 006/197] fixed coding convention --- types/debug/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index a03d5cd988..e8cfac264b 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -6,7 +6,7 @@ // Brasten Sager // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var debug: debug.IDebug & {debug:debug.IDebug, default:debug.IDebug}; +declare var debug: debug.IDebug & {debug: debug.IDebug, default: debug.IDebug}; export = debug; export as namespace debug; From 4657145fda72194ffe641ac0042acfd884190a5a Mon Sep 17 00:00:00 2001 From: Nicolas Penin Date: Wed, 16 Jan 2019 10:37:51 +0100 Subject: [PATCH 007/197] fixed header --- types/debug/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index e8cfac264b..ad37e702a0 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for debug +// Type definitions for debug 4.1 // Project: https://github.com/visionmedia/debug // Definitions by: Seon-Wook Park // Gal Talmor // John McLaughlin // Brasten Sager +// Nicolas Penin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var debug: debug.IDebug & {debug: debug.IDebug, default: debug.IDebug}; From f88076efc7f0ac3290bb7075a6ed1c6a2f4bedf2 Mon Sep 17 00:00:00 2001 From: Nicolas Penin Date: Wed, 16 Jan 2019 10:39:08 +0100 Subject: [PATCH 008/197] disabled rules --- types/debug/tslint.json | 78 +---------------------------------------- 1 file changed, 1 insertion(+), 77 deletions(-) diff --git a/types/debug/tslint.json b/types/debug/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/debug/tslint.json +++ b/types/debug/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } From afb8bca54a8982b435cb5fae2a509abd8b75ce69 Mon Sep 17 00:00:00 2001 From: Razvan Muscalu <34776591+RazzM13@users.noreply.github.com> Date: Mon, 21 Jan 2019 22:16:15 +0200 Subject: [PATCH 009/197] [@types/feathersjs__errors] Added typings for the missing "code", "className", "data" and "errors" property members of the FeathersError object. --- types/feathersjs__errors/index.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/types/feathersjs__errors/index.d.ts b/types/feathersjs__errors/index.d.ts index 056acff676..9adcdc6dbf 100644 --- a/types/feathersjs__errors/index.d.ts +++ b/types/feathersjs__errors/index.d.ts @@ -5,7 +5,11 @@ // TypeScript Version: 2.2 export class FeathersError extends Error { - constructor(msg: string | Error, name: string, code: number, className: string, data: any) + code: number; + className: string; + data: any; + errors: any; + constructor(msg: string | Error, name: string, code: number, className: string, data: any); } export class BadRequest extends FeathersError { From 3c55900c9c6c09ca616377e4a66d0fb62f85314a Mon Sep 17 00:00:00 2001 From: Razvan Muscalu <34776591+RazzM13@users.noreply.github.com> Date: Mon, 21 Jan 2019 22:16:46 +0200 Subject: [PATCH 010/197] [@types/feathersjs__errors] Added "RazzM13" to "Definitions by" section as per the contribution guidelines. --- types/feathersjs__errors/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/feathersjs__errors/index.d.ts b/types/feathersjs__errors/index.d.ts index 9adcdc6dbf..01969de8a3 100644 --- a/types/feathersjs__errors/index.d.ts +++ b/types/feathersjs__errors/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for @feathersjs/errors 3.2 // Project: http://feathersjs.com/ // Definitions by: Jan Lohage +// RazzM13 // Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript // TypeScript Version: 2.2 From e44c615c7086bab0479fa4e401712e942223c430 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=A6=E7=94=B0=20=E6=86=B2=E5=A4=AA=E9=83=8E?= Date: Sat, 26 Jan 2019 20:03:10 +0900 Subject: [PATCH 011/197] Added type definition for hexo --- types/hexo/hexo-tests.ts | 462 ++++++++++++++++++ types/hexo/index.d.ts | 976 +++++++++++++++++++++++++++++++++++++++ types/hexo/tsconfig.json | 23 + types/hexo/tslint.json | 7 + 4 files changed, 1468 insertions(+) create mode 100644 types/hexo/hexo-tests.ts create mode 100644 types/hexo/index.d.ts create mode 100644 types/hexo/tsconfig.json create mode 100644 types/hexo/tslint.json diff --git a/types/hexo/hexo-tests.ts b/types/hexo/hexo-tests.ts new file mode 100644 index 0000000000..3c00489c3a --- /dev/null +++ b/types/hexo/hexo-tests.ts @@ -0,0 +1,462 @@ +import Hexo = require('hexo'); +import fs = require('fs'); +import Bunyan = require('bunyan'); +import { ParsedArgs } from 'minimist'; +import util = require('hexo-util'); +import http = require('http'); + +const config: Hexo.InstanceOptions = {}; +config.debug = false; +config.safe = false; +config.silent = false; +config.config = '_config.yml'; + +let h: Hexo; +h = hexo; +h = new Hexo(); +h = new Hexo('./'); +h = new Hexo('./', config); + +const logger: Bunyan = h.log; +console.log(h.base_dir); +console.log(h.public_dir); +console.log(h.source_dir); +console.log(h.plugin_dir); +console.log(h.script_dir); +console.log(h.scaffold_dir); +console.log(h.theme_dir); +console.log(h.theme_script_dir); +console.log(h.config_path); +console.log(h.env.args); +console.log(h.env.debug); +console.log(h.env.safe); +console.log(h.env.silent); +console.log(h.env.env); +console.log(h.env.version); +console.log(h.env.init); +console.log(h.config.title); +console.log(h.config.subtitle); +console.log(h.config.description); +console.log(h.config.author); +console.log(h.config.language); +console.log(h.config.timezone); +console.log(h.config.url); +console.log(h.config.root); +console.log(h.config.permalink); +console.log(h.config.permalink_defaults); +console.log(h.config.source_dir); +console.log(h.config.public_dir); +console.log(h.config.tag_dir); +console.log(h.config.archive_dir); +console.log(h.config.category_dir); +console.log(h.config.code_dir); +console.log(h.config.i18n_dir); +console.log(h.config.skip_render); +console.log(h.config.new_post_name); +console.log(h.config.default_layout); +console.log(h.config.titlecase); +console.log(h.config.external_link); +console.log(h.config.filename_case); +console.log(h.config.render_drafts); +console.log(h.config.post_asset_folder); +console.log(h.config.relative_link); +console.log(h.config.future); +console.log(h.config.highlight.enable); +console.log(h.config.highlight.line_number); +console.log(h.config.highlight.auto_detect); +console.log(h.config.highlight.tab_replace); +console.log(h.config.default_category); +console.log(h.config.category_map); +console.log(h.config.tag_map); +console.log(h.config.time_format); +console.log(h.config.per_page); +console.log(h.config.pagination_dir); +console.log(h.config.theme); +console.log(h.config.theme_config); +console.log(h.config.deploy); +console.log(h.config.include); +console.log(h.config.exclude); +console.log(h.config.ignore); + +h.init().then(async () => { + await h.watch(); + h.unwatch(); + + await h.theme.watch(); + h.theme.unwatch(); + + await h.source.watch(); + h.source.unwatch(); + + await h.load(); + h.call('config', {_: ['arg1']}, (err, value) => {}); + + await h.exit(); +}); + +h.on('ready', () => { + h.on('deployBefore', () => {}); + h.on('deployAfter', () => {}); + h.on('exit', err => { + console.log(err); + }); + h.on('generateBefore', () => {}); + h.on('generateAfter', () => {}); + h.on('new', param => { + const path: string = param.path; + const content: string = param.content; + }); + h.on('processBefore', (type, path) => { + const t: Hexo.Box.File['type'] = type; + const p: string = path; + }); + h.on('processAfter', (type, path) => { + const t: Hexo.Box.File['type'] = type; + const p: string = path; + }); + h.on('ready', () => {}); + + { + let local: Hexo.Locals.Post[] = []; + const model = hexo.locals.get('posts'); + + local = model.toArray(); + const count: number = model.count(); + model.filter(v => true); + model.forEach(v => {}); + model.map(v => v.name); + } + + { + let local: Hexo.Locals.Page[] = []; + const model = hexo.locals.get('pages'); + + local = model.toArray(); + const count: number = model.count(); + model.filter(v => true); + model.forEach(v => {}); + model.map(v => v.name); + } + + { + let local: Hexo.Locals.Category[] = []; + const model = hexo.locals.get('categories'); + + local = model.toArray(); + const count: number = model.count(); + model.filter(v => true); + model.forEach(v => {}); + model.map(v => v.name); + } + + { + let local: Hexo.Locals.Tag[] = []; + const model = hexo.locals.get('tags'); + + local = model.toArray(); + const count: number = model.count(); + model.filter(v => true); + model.forEach(v => {}); + model.map(v => v.name); + } + + { + h.locals.set('some-data', () => 'some vlue'); + h.locals.remove('some-data'); + h.locals.toObject(); + h.locals.invalidate(); + } + + { + const route = h.route.get('index.html'); + if (route) { + console.log(route.modified); + console.log(route.read()); + } + + const data: Hexo.Router.Data = { + data: 'some data', + modified: true, + }; + data.data = new Buffer([]); + data.data = () => 'return'; + + let router: Hexo.Router; + router = h.route; + router = h.route.set('index.html', 'content'); + router = h.route.set('index.html', new Buffer([])); + router = h.route.set('index.html', new util.Pattern(() => false)); + router = h.route.set('index.html', { data: 'index', modified: false }); + + router = h.route.remove('index.html'); + + const list: string[] = h.route.list(); + const format: string = h.route.format('/'); + } + + { + h.source.process(() => {}); + h.source.addProcessor('path', file => { + console.log(file.source); + console.log(file.path); + console.log(file.type); + console.log(file.params); + + file.read((err, content) => { + console.log(err, content.toString()); + console.log(content); + }); + + file.read({encoding: 'utf8', flag: 'r'}, (err, content) => { + console.log(err, content.toString()); + console.log(content); + }); + + file.readSync({encoding: 'utf8', flag: 'r'}); + + file.stat((err, stat) => { + console.log(err); + console.log(stat.mtime); + console.log(stat.ctime); + console.log(stat.atime); + }); + + file.stat().then(stat => { + console.log(stat.mtime); + console.log(stat.ctime); + console.log(stat.atime); + }); + + const stat: fs.Stats = file.statSync(); + + let render = ''; + file.render({}, (err, result) => { + render = result; + }); + file.render((err, result) => { + render = result; + }); + file.render().then(result => { + render = result; + }); + render = file.renderSync(); + }); + } + + { + let _bool = true; + _bool = h.render.isRenderable('path'); + _bool = h.render.isRenderableSync('path'); + + const option: Hexo.Render.Data = { + engine: 'ejs', + text: 'test', + path: __filename, + }; + + let _string = ''; + h.render.render({text: 'example', engine: 'swig'}).then(result => { + _string = result; + }); + h.render.render({path: __filename}).then(result => { + _string = result; + }); + h.render.render({text: ''}, {foo: 'foo'}).then(result => { + _string = result; + }); + _string = h.render.renderSync({text: 'example'}); + + _string = h.render.getOutput('ejs'); + } + + { + const data: Hexo.Post.Data = {}; + data.title = 'Title'; + data.slug = 'URL'; + data.layout = 'layout_name'; + data.path = 'path'; + data.date = new Date(); + + h.post.create(data, false, () => {}); + h.post.create(data, () => {}); + + h.post.publish(data, false, () => {}); + h.post.publish(data, () => {}); + + const renderData: Hexo.Post.RenderData = {}; + renderData.content = 'content'; + renderData.engine = 'ejs'; + h.post.render(null, renderData, () => {}); + } + + { + h.scaffold.get('post').then(result => ''); + h.scaffold.set('post', '').then(() => {}); + h.scaffold.remove('post').then(() => {}); + } + + { + const themeConfig: Hexo['config'] = h.theme.config; + let v: Hexo.View | undefined; + h.theme.setView('path-name', {}); + v = h.theme.getView('post'); + if (v) { + console.log(v.path); + console.log(v.source); + + v.render().then(result => {}); + v.renderSync(); + } + + h.theme.removeView('path-name'); + h.theme.process(() => {}); + } + + { + const options: Hexo.extend.Console.Options = {}; + options.usage = '[layout] '; + options.arguments = [ + {name: 'layout', desc: 'Post layout'}, + {name: 'title', desc: 'Post title'}, + ]; + options.options = [ + {name: '-r, --replace', desc: 'Replace existing files'}, + ]; + options.desc = 'desc'; + + h.extend.console.register('name', 'description', options, args => { + const a: ParsedArgs = args; + }); + h.extend.console.register('name', options, args => {}); + h.extend.console.register('name', 'description', args => {}); + h.extend.console.register('name', args => {}); + } + + { + h.extend.deployer.register('name', args => { + console.log(args.type); + console.log(args.someExtraArg); + }); + } + + { + h.extend.filter.register('before_post_render', data => data); + h.extend.filter.register('before_post_render', data => undefined); + h.extend.filter.register('before_post_render', data => undefined, 1); + + h.extend.filter.register('after_post_render', data => data); + h.extend.filter.register('after_post_render', data => undefined); + h.extend.filter.register('after_post_render', data => undefined, 1); + + h.extend.filter.register('before_exit', () => {}); + h.extend.filter.register('before_exit', () => {}, 1); + + h.extend.filter.register('before_generate', data => data); + h.extend.filter.register('before_generate', data => undefined); + h.extend.filter.register('before_generate', data => undefined, 1); + + h.extend.filter.register('after_generate', () => {}); + h.extend.filter.register('after_generate', () => {}, 1); + + h.extend.filter.register('template_locals', locals => locals); + h.extend.filter.register('template_locals', locals => undefined); + h.extend.filter.register('template_locals', locals => undefined, 1); + + h.extend.filter.register('after_init', () => {}); + h.extend.filter.register('after_init', () => {}, 1); + + h.extend.filter.register('new_post_path', (data, replace) => undefined); + h.extend.filter.register('new_post_path', (data, replace) => undefined, 1); + + h.extend.filter.register('post_permalink', permalink => permalink); + h.extend.filter.register('post_permalink', permalink => permalink, 1); + + h.extend.filter.register('after_render:html', (result, data) => result); + h.extend.filter.register('after_render:html', (result, data) => result, 1); + + h.extend.filter.register('after_clean', () => {}); + h.extend.filter.register('after_clean', () => {}, 1); + + h.extend.filter.register('server_middleware', app => { + app.use((req: http.IncomingMessage, res: http.ServerResponse) => { + res.setHeader('X-Powered-By', 'Hexo'); + }); + }); + + const filter = (data: any) => data; + h.extend.filter.register('custom_filter', filter); + h.extend.filter.unregister('custom_filter', filter); + + const options: Hexo.extend.Filter.Options = {}; + options.args = ['foo', 'bar']; + options.context = h; + h.extend.filter.exec('custom_filter', options); + h.extend.filter.exec('custom_filter'); + h.extend.filter.execSync('custom_filter', options); + h.extend.filter.execSync('custom_filter'); + } + + { + const ret: Hexo.extend.Generator.Return = { + data: {}, + layout: 'layout-name', + path: '/', + }; + h.extend.generator.register('name', local => ret); + h.extend.generator.register('name', local => [ret]); + h.extend.generator.register('name', local => { + console.log(local.data); + const categories: Hexo.Locals.Category[] = local.categories.toArray(); + const pages: Hexo.Locals.Page[] = local.pages.toArray(); + const posts: Hexo.Locals.Post[] = local.posts.toArray(); + const tags: Hexo.Locals.Tag[] = local.tags.toArray(); + + return ret; + }); + } + + { + h.extend.helper.register('name', (...args) => { + return 'ret'; + }); + } + + { + h.extend.migrator.register('name', args => { + const a: ParsedArgs = args; + }); + } + + { + let f: Hexo.Box.File; + h.extend.processor.register('pattern', file => f = file); + h.extend.processor.register(/pattern/, file => f = file); + h.extend.processor.register((str) => true , file => f = file); + h.extend.processor.register(file => f = file); + } + + { + h.extend.renderer.register('ts', 'js', (data, options) => { + console.log(data.path); + console.log(data.text); + return 'result'; + }, true); + + h.extend.renderer.register('ts', 'js', (data, options) => Promise.resolve('result'), false); + h.extend.renderer.register('ts', 'js', (data, options) => Promise.resolve('result')); + } + + { + const option: Hexo.extend.Tag.Options = {}; + option.async = true; + option.ends = true; + + h.extend.tag.register('name', (args, content) => { + if (content) { + const c: string = content; + } + const a: string[] = args; + return 'content'; + }); + } +}); diff --git a/types/hexo/index.d.ts b/types/hexo/index.d.ts new file mode 100644 index 0000000000..0688b1631a --- /dev/null +++ b/types/hexo/index.d.ts @@ -0,0 +1,976 @@ +// Type definitions for hexo 3.8 +// Project: https://hexo.io/ +// Definitions by: KentarouTakeda <https://github.com/kentarouTakeda> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import EventEmitter = require('events'); +import moment = require('moment'); +import { ParsedArgs } from 'minimist'; +import Logger = require('bunyan'); +import underscore = require('underscore'); +import connect = require('connect'); +import Stream = require('stream'); +import util = require('hexo-util'); +import fs = require('fs'); + +declare global { + const hexo: Hexo; +} + +interface HexoConfig { + [key: string]: any; + /** + * The title of your website + */ + readonly title: string; + + /** + * The subtitle of your website + */ + readonly subtitle: string; + + /** + * The description of your website + */ + readonly description: string; + + /* + * Your name + */ + readonly author: string; + + /** + * The language of your website. Use a 2-lettter ISO-639-1 code. Default is en. + */ + readonly language: string; + + /** + * The timezone of your website. Hexo uses the setting on your computer by default. + * You can find the list of available timezones [here]{@link https://en.wikipedia.org/wiki/List_of_tz_database_time_zones} . + * Some examples are `America/New_York` , `Japan` , and `UTC` . + */ + readonly timezone: string; + + /* + * The URL of your website + */ + readonly url: string; + + /** + * The root directory of your website + */ + readonly root: string; + + /** + * The permalink format of articles + */ + readonly permalink: string; + + /** + * Default values of each segment in permalink + */ + readonly permalink_defaults: string|null; + + /** + * Source folder. Where your content is stored + */ + readonly source_dir: string; + + /** + * Public folder. Where the static site will be generated + */ + readonly public_dir: string; + + /** + * Tag directory + */ + readonly tag_dir: string; + + /** + * Archive directory + */ + readonly archive_dir: string; + + /** + * Category directory + */ + readonly category_dir: string; + + /** + * Include code directory (subdirectory of source_dir) + */ + readonly code_dir: string; + + /** + * i18n directory + */ + readonly i18n_dir: string; + + /** + * Paths that will be copied to public raw, without being rendered. You can use glob expressions for path matching. + */ + readonly skip_render: string|string[]|null; + + /** + * The filename format for new posts + */ + readonly new_post_name: string; + + /** + * Default layout + */ + readonly default_layout: string; + + /** + * Transform titles into title case? + */ + readonly titlecase: boolean; + + /** + * Open external links in a new tab? + */ + readonly external_link: boolean; + + /** + * Transform filenames to 1 lower case; 2 upper case + */ + readonly filename_case: number; + + /** + * Display drafts? + */ + readonly render_drafts: boolean; + + /** + * Enable the Asset Folder? + */ + readonly post_asset_folder: boolean; + + /** + * Make links relative to the root folder? + */ + readonly relative_link: boolean; + + /** + * Display future posts? + */ + readonly future: boolean; + + /** + * Code block settings + */ + readonly highlight: { + readonly enable: boolean; + readonly line_number: boolean; + readonly auto_detect: boolean; + readonly tab_replace: string|null; + }; + + /** + * Default category + */ + readonly default_category: string; + + /** + * Category slugs + */ + readonly category_map: {[key: string]: string|number}; + + /** + * Tag slugs + */ + readonly tag_map: {[key: string]: string|number}; + + /** + * Date format + * https://momentjs.com/ + */ + readonly date_format: string; + + /** + * Time format + * https://momentjs.com/ + */ + readonly time_format: string; + + /** + * The amount of posts displayed on a single page. 0 disables pagination + */ + readonly per_page: number; + + /** + * Pagination directory + */ + readonly pagination_dir: string; + + /** + * Theme name. false disables theming + */ + readonly theme: string|false; + + /** + * Theme configuration. Include any custom theme settings under this key to override theme defaults. + */ + readonly theme_config: {[key: string]: string|number}; + + /** + * Deployment settings + */ + readonly deploy: Hexo.extend.Deployer.Config | Hexo.extend.Deployer.Config | null; + + /** + * Hexo by default ignores hidden files and folders, but setting this field will make Hexo process them + */ + readonly include ?: string[]; + + /** + * Hexo process will ignore files list under this field + */ + readonly exclude ?: string[]; + readonly ignore: string[]; +} + +interface Model<T> { + /** + * Warehouse method + * https://hexojs.github.io/warehouse/ + */ + toArray(): T[]; + /** + * Warehouse method + * https://hexojs.github.io/warehouse/ + */ + count(): number; + /** + * Warehouse method + * https://hexojs.github.io/warehouse/ + */ + forEach(fn: (v: T, i: number) => void): void; + /** + * Warehouse method + * https://hexojs.github.io/warehouse/ + */ + filter(fn: (v: T, i: number) => boolean): Model<T>; + /** + * Warehouse method + * https://hexojs.github.io/warehouse/ + */ + map<U>(fn: (v: T, i: number) => U): U[]; +} + +interface Site { + posts: Model<Hexo.Locals.Post>; + pages: Model<Hexo.Locals.Page>; + categories: Model<Hexo.Locals.Category>; + tags: Model<Hexo.Locals.Tag>; + data: {[key: string]: any}; +} + +declare class Hexo extends EventEmitter { + /** + * Create a Hexo instance. + * @param base the root directory of the website, `base_dir` . + * @param args an object containing the initialization options. + */ + constructor(base?: string, args?: Hexo.InstanceOptions); + + /** + * Load configuration and plugins. + */ + init(): Promise<void>; + + /** + * Loading all files in the `source` folder as well as the theme data. + */ + load(fn?: (err: any, value: any) => void): Promise<any>; + + /** + * The same things `load` does, but will also start watching for file changes continuously. + */ + watch(fn?: (err: any, value: any) => void): Promise<any>; + + unwatch(): void; + + /** + * Any console command can be called explicitly using the call method on the Hexo instance. + */ + call(name: string, args?: any, fn?: (err: any, value: any) => void): Promise<any>; + call(name: string, fn?: (err: any, value: any) => void): Promise<any>; + + /** + * You should call the `exit` method upon successful or unsuccessful completion of a console command. + * This allows Hexo to exit gracefully and finish up important things such as saving the database. + */ + exit(err?: any): Promise<void>; + + /** + * Site settings in `_config.yml` + */ + readonly config: HexoConfig; + + readonly theme: Hexo.Theme; + readonly source: Hexo.Box; + readonly post: Hexo.Post; + readonly render: Hexo.Render; + + /** + * Local variables are used for template rendering, which is the `site` variable in templates. + * https://hexo.io/api/locals + */ + readonly locals: Hexo.Locals; + + readonly base_dir: string; + + /** + * Public folder. Where the static site will be generated + */ + readonly public_dir: string; + + /** + * Source folder. Where your content is stored + */ + readonly source_dir: string; + + readonly plugin_dir: string; + readonly script_dir: string; + readonly scaffold_dir: string; + readonly theme_dir: string; + readonly theme_script_dir: string; + readonly config_path: string; + readonly env: { + readonly args: ParsedArgs; + readonly debug: boolean; + readonly safe: boolean; + readonly silent: boolean; + readonly env: string; + readonly version: string; + readonly init: boolean; + }; + + /** + * Logger object + * https://www.npmjs.com/package/bunyan + */ + readonly log: Logger; + + readonly extend: { + /** + * The console forms the bridge between Hexo and its users. It registers and describes the available console commands. + */ + readonly console: Hexo.extend.Console; + /** + * A deployer helps users quickly deploy their site to a remote server without complicated commands. + */ + readonly deployer: Hexo.extend.Deployer; + /** + * A filter is used to modify some specified data. Hexo passes data to filters in sequence and the filters then modify the data one after the other. + */ + readonly filter: Hexo.extend.Filter; + /** + * A generator builds routes based on processed files. + */ + readonly generator: Hexo.extend.Generator; + /** + * A helper makes it easy to quickly add snippets to your templates. We recommend using helpers instead of templates when you’re dealing with more complicated code. + */ + readonly helper: Hexo.extend.Helper; + /** + * A migrator helps users migrate from other systems to Hexo. + */ + readonly migrator: Hexo.extend.Migrator; + /** + * A processor is used to process source files in the source folder. + */ + readonly processor: Hexo.extend.Processor; + /** + * A renderer is used to render content. + */ + readonly renderer: Hexo.extend.Renderer; + /** + * A tag allows users to quickly and easily insert snippets into their posts. + */ + readonly tag: Hexo.extend.Tag; + }; + + readonly route: Hexo.Router; + readonly scaffold: Hexo.Scaffold; + + /** + * Emitted before deployment begins. + */ + on(ev: 'deployBefore', fn: () => void): this; + + /** + * Emitted after deployment finishes. + */ + on(ev: 'deployAfter', fn: () => void): this; + + /** + * Emitted before Hexo exits. + */ + on(ev: 'exit', fn: (err: any) => void): this; + + /** + * Emitted before generation begins. + */ + on(ev: 'generateBefore', fn: () => void): this; + + /** + * Emitted after generation finishes. + */ + on(ev: 'generateAfter', fn: () => void): this; + + /** + * Emitted after a new post has been created. This event returns the post data: + */ + on(ev: 'new', fn: (post: {path: string, content: string}) => void): this; + + /** + * Emitted before processing begins. This event returns a path representing the root directory of the box. + */ + on(ev: 'processBefore', fn: (type: Hexo.Box.File['type'], path: string) => void): this; + + /** + * Emitted after processing finishes. This event returns a path representing the root directory of the box. + */ + on(ev: 'processAfter', fn: (type: Hexo.Box.File['type'], path: string) => void): this; + + /** + * Emitted after initialization finishes. + */ + on(ev: 'ready', fn: () => void): this; +} + +declare namespace Hexo { + interface InstanceOptions { + debug?: boolean; + safe?: boolean; + silent?: boolean; + config?: string; + } + + interface Locals { + get(type: 'posts'): Model<Locals.Post>; + get(type: 'pages'): Model<Locals.Page>; + get(type: 'categories'): Model<Locals.Category>; + get(type: 'tags'): Model<Locals.Tag>; + /** + * Get a Variable + */ + get(type: string): any; + + /** + * Set a Variable + */ + set(type: string, fn: () => any): this; + + /** + * Remove a Variable + */ + remove(type: string): this; + + /** + * Get All Variable + */ + toObject(): any; + + /** + * Invalidate the cache + */ + invalidate(): this; + } + namespace Locals { + interface Page { + title: string; + date: moment.Moment; + updated?: moment.Moment; + comments: boolean; + layout: string; + content: string; + excerpt?: string; + more?: string; + source: string; + full_source: string; + path: string; + permalink: string; + prev?: null|Page; + next?: null|Page; + raw?: string; + photos?: string[]; + link?: string; + [key: string]: any; + } + + interface Post extends Page { + published?: boolean; + categories?: string[]; + tags: string[]; + } + + interface Tag { + name: string; + slug: string; + path: string; + permalink: string; + posts: Model<Post>; + length: number; + } + interface Category extends Tag { + parent: string; + } + } + + namespace extend { + interface Console { + register(name: string, desc: string, options: Console.Options, fn: (args: ParsedArgs) => void): void; + register(name: string, options: Console.Options, fn: (args: ParsedArgs) => void): void; + register(name: string, desc: string, fn: (args: ParsedArgs) => void): void; + register(name: string, fn: (args: ParsedArgs) => void): void; + } + namespace Console { + interface Options { + /** + * The usage of a console command. + */ + usage?: string; + + /** + * The description of each argument of a console command. + */ + arguments?: Array<{name: string, desc: string}>; + + /** + * The description of each option of a console command. + */ + options?: Array<{name: string, desc: string}>; + + /** + * More detailed information about a console command. + */ + desc?: string; + } + } + + interface Deployer { + register(name: string, fn: (args: Deployer.Config) => void): void; + } + namespace Deployer { + interface Config { + readonly type: string|undefined; + readonly [key: string]: any; + } + } + + interface Filter { + register(type: string, fn: (data: any, ...args: any[]) => any, priority?: number): void; + + /** + * Executed before a post is rendered. Refer to post rendering to learn the execution steps. + */ + register(type: 'before_post_render', fn: (data: { content: string, [key: string]: any }) => { content: string, [key: string]: any }|void, priority?: number): void; + + /** + * Executed after a post is rendered. Refer to post rendering to learn the execution steps. + */ + register(type: 'after_post_render', fn: (data: { content: string, [key: string]: any }) => { content: string, [key: string]: any }|void, priority?: number): void; + + /** + * Executed before Hexo is about to exit – this will run right after `hexo.exit` is called. + */ + register(type: 'before_exit', fn: () => void, priority?: number): void; + + /** + * Executed before generation begins. + */ + register(type: 'before_generate', fn: (data: any) => any, priority?: number): void; + + /** + * Executed after generation finishes. + */ + register(type: 'after_generate', fn: () => void, priority?: number): void; + + /** + * Modify [local variables](https://hexo.io/docs/variables) in templates. + */ + register(type: 'template_locals', fn: (locals: TemplateLocals) => TemplateLocals|void, priority?: number): void; + + /** + * Executed after Hexo is initialized – this will run right after `hexo.init` completes. + */ + register(type: 'after_init', fn: () => void, priority?: number): void; + + /** + * Executed when creating a post to determine the path of new posts. + */ + register(type: 'new_post_path', fn: (data: Post.Data, replace?: boolean) => void, priority?: number): void; + + /** + * Used to determine the permalink of posts. + */ + register(type: 'post_permalink', fn: (permalink: string) => string, priority?: number): void; + + /** + * Executed after rendering finishes. You can see rendering for more info. + */ + register(type: 'after_render:html', fn: (result: string, data: {path: string, text: string, [key: string]: any}) => string|void, priority?: number): void; + + /** + * Executed after generated files and cache are removed with hexo clean command. + */ + register(type: 'after_clean', fn: () => void, priority?: number): void; + + /** + * Add middleware to the server. app is a Connect instance. + */ + register(type: 'server_middleware', fn: (app: connect.Server) => connect.Server|void, priority?: number): void; + + unregister(type: string, fn: (...args: any[]) => any): void; + exec(type: string, data?: any, options?: Filter.Options): any; + execSync(type: string, data?: any, options?: Filter.Options): any; + } + namespace Filter { + interface Options { + /** + * `hexo` object. + */ + context?: Hexo; + /** + * Arguments. This must be an array. + */ + args?: any[]; + } + } + + interface Generator { + register(name: string, fn: (locals: Site) => Generator.Return| Generator.Return[]): void; + } + namespace Generator { + interface Return { + /** + * Path not including the prefixing `/` . + */ + path: string; + + /** + * Layout. Specify the layouts for rendering. The value can be a string or an array. If it’s ignored then the route will return data directly. + */ + layout: string|string[]; + + data: any; + } + } + + interface Helper { + register(name: string, fn: (...args: any[]) => any): void; + } + + interface Migrator { + register(name: string, fn: (args: ParsedArgs, fn: (err: any) => void) => void): void; + } + + interface Processor { + register(pattern: RegExp | string | ((str: string) => any), fn: (file: Box.File) => void): void; + register(fn: (file: Box.File) => void): void; + } + + interface Renderer { + register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options?: any) => string, sync: true): void; + register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options?: any) => Promise<string>, sync: false): void; + register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options?: any) => Promise<string>): void; + } + + interface Tag { + register(name: string, fn: (args: string[], content?: string) => string, options?: Tag.Options): void; + } + namespace Tag { + interface Options { + ends?: boolean; + async?: boolean; + } + } + } + + interface Router { + /** + * The `get` method returns a `Stream`. + */ + get(path: string): Router.RouteStream|undefined; + + /** + * The `set` method takes a string, a `Buffer` or a function. + */ + set(path: string, data: string|Buffer|util.Pattern<boolean>|Router.Data): this; + + /** + * Remove a Path + */ + remove(path: string): this; + + /** + * Get the List of Routes + */ + list(): string[]; + + /** + * The `format` method transforms a string to a valid path. + */ + format(path: string): string; + } + namespace Router { + interface Data { + data: string | Buffer | Callback; + modified: boolean; + } + + interface RouteStream extends Stream.Readable { + readonly modified: boolean; + } + + type Callback = ((err: any, result: string) => void) | (() => Promise<string>); + } + + interface Scaffold { + /** + * Get a Scaffold + */ + get(name: string, fn?: (err: any, result: string) => void): Promise<string>; + /** + * Set a Scaffold + */ + set(name: string, content: string, fn?: (err: any) => void): Promise<void>; + /** + * Remove a Scaffold + */ + remove(name: string, fn?: (err: any) => void): Promise<void>; + } + + interface Box extends EventEmitter { + /** + * Loads all files in the folder. + */ + process(fn: (err: any) => void): Promise<void>; + /** + * Loads all files in the folder and start watching for file changes. + */ + watch(fn?: (err: any) => void): Promise<void>; + /** + * Stop watching. + */ + unwatch(): void; + + /** + * A processor is an essential element of `Box` and is used to process files. + * You can use path matching as described above to restrict what exactly the processor should process. + * Register a new processor with the `addProcessor` method. + */ + addProcessor(pattern: string|RegExp|util.Pattern<boolean>, fn: (file: Box.File) => void): void; + } + namespace Box { + interface File { + /** + * Full path of the file + */ + readonly source: string; + + /** + * Relative path to the box of the file + */ + readonly path: string; + + /** + * File type. The value can be `create` , `update` , `skip`, `delete` . + */ + readonly type: 'create' | 'update' | 'skip' | 'delete'; + + /** + * The information from path matching. + */ + readonly params: any; + + /** + * Read a file + */ + read(option?: {encoding?: string|null, flag?: string}, fn?: (err: any, result: string|Buffer) => void): Promise<string|Buffer>; + read(fn?: (err: any, result: string|Buffer) => void): Promise<string|Buffer>; + + /** + * Read a file synchronously + */ + readSync(option?: {encoding?: string|null, flag?: string}): string|Buffer; + + /** + * Read the status of a file + */ + stat(fn?: (err: any, result: fs.Stats) => void): Promise<fs.Stats>; + + /** + * Read the status of a file synchronously + */ + statSync(): fs.Stats; + + /** + * Render a file + */ + render(fn?: (err: any, result: string) => void): Promise<string>; + render(option?: any, fn?: (err: any, result: string) => void): Promise<string>; + + /** + * Render a file synchronously + */ + renderSync(option?: any): string; + } + } + + interface Render { + render(data: Render.Data, option?: any, fn?: (err: any, result: string) => void): Promise<string>; + render(data: Render.Data, fn?: (err: any, result: string) => void): Promise<string>; + renderSync(data: Render.Data, option?: any): string; + + /** + * Check whether a file is renderable synchronously. + */ + isRenderable(path: string): boolean; + + /** + * Check whether a file is renderable. + */ + isRenderableSync(path: string): boolean; + + /** + * Get the Output Extension + */ + getOutput(path: string): string; + } + namespace Render { + interface Data { + text?: string; + engine?: string; + path?: string; + } + } + + interface Post { + /** + * Create a Post + */ + create(data: Post.Data, replace?: boolean, fn?: (err: any) => void): Promise<void>; + create(data: Post.Data, fn?: (err: any) => void): Promise<void>; + + /** + * Publish a Draft + */ + publish(data: Post.Data, replace?: boolean, fn?: (err: any) => void): Promise<void>; + publish(data: Post.Data, fn?: (err: any) => void): Promise<void>; + + render(source: string|null|undefined, data: Post.RenderData, fn: (err: any) => void): Promise<void>; + } + namespace Post { + interface Data { + title?: string; + slug?: string; + layout?: string; + path?: string; + date?: moment.MomentInput; + } + interface RenderData { + engine?: string; + content?: string; + } + } + + interface Theme extends Box { + config: HexoConfig; + + /** + * Get a View + */ + getView(path: string): View|undefined; + + /** + * Set a View + */ + setView(path: string, data: any): void; + + /** + * Remove a View + */ + removeView(path: string): void; + } + + interface View { + readonly path: string; + readonly source: string; + + /** + * Remove a View + */ + render(options?: any, fn?: (err: any, result: string) => void): Promise<string>; + render(fn: (err: any, result: string) => void): Promise<any>; + + /** + * Remove a View synchronously. + */ + renderSync(options?: any): string; + } +} + +interface TemplateLocals { + /** + * Underscore object + */ + _: underscore.UnderscoreStatic; + page: Hexo.Locals.Post | Hexo.Locals.Page | Hexo.Locals.Category | Hexo.Locals.Tag | IndexPage | ArchivePage | CategoryPage | TagPage; + path: string; + url: string; + + /** + * Site settings in `_config.yml` + */ + config: HexoConfig; + theme: HexoConfig; + env: Hexo['env']; + layout: string; + view_dir: string; + site: any; +} + +interface IndexPage { + per_page?: number; + total?: number; + current?: number; + current_url?: string; + posts?: object; + prev?: number; + prev_link?: string; + next?: number; + next_link?: string; + path?: string; +} + +interface ArchivePage extends IndexPage { + archive?: boolean; + year?: number; + month?: number; +} + +interface CategoryPage extends IndexPage { + category: string; +} + +interface TagPage extends IndexPage { + tag: string; +} + +interface HexoRendererData { + /** + * File content. + */ + readonly text: string; + /** + * File path. + */ + readonly path?: string; +} + +export = Hexo; diff --git a/types/hexo/tsconfig.json b/types/hexo/tsconfig.json new file mode 100644 index 0000000000..6e37a832a0 --- /dev/null +++ b/types/hexo/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hexo-tests.ts" + ] +} diff --git a/types/hexo/tslint.json b/types/hexo/tslint.json new file mode 100644 index 0000000000..d2e0e4cec1 --- /dev/null +++ b/types/hexo/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "unified-signatures": false + } + +} From 5493a2aed147071f6f52e5429cebca1d05b69038 Mon Sep 17 00:00:00 2001 From: Joao Peixoto <joao.hartimer@gmail.com> Date: Sat, 26 Jan 2019 22:21:51 -0800 Subject: [PATCH 012/197] Make userHandle optional --- types/webappsec-credential-management/index.d.ts | 3 ++- .../webappsec-credential-management-tests.ts | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/types/webappsec-credential-management/index.d.ts b/types/webappsec-credential-management/index.d.ts index 4c47ee7cc8..c8fbf8ec60 100644 --- a/types/webappsec-credential-management/index.d.ts +++ b/types/webappsec-credential-management/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for W3C (WebAppSec) Credential Management API Level 1, 0.3 // Project: https://github.com/w3c/webappsec-credential-management // Definitions by: Iain McGinniss <https://github.com/iainmcgin> +// Joao Peixoto <https://github.com/Hartimer> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.7 @@ -493,7 +494,7 @@ interface AuthenticatorAttestationResponse extends AuthenticatorResponse { interface AuthenticatorAssertionResponse extends AuthenticatorResponse { readonly authenticatorData: ArrayBuffer; readonly signature: ArrayBuffer; - readonly userHandle: ArrayBuffer; + readonly userHandle?: ArrayBuffer; } /** diff --git a/types/webappsec-credential-management/webappsec-credential-management-tests.ts b/types/webappsec-credential-management/webappsec-credential-management-tests.ts index 2afa9f8785..1e0500dfce 100644 --- a/types/webappsec-credential-management/webappsec-credential-management-tests.ts +++ b/types/webappsec-credential-management/webappsec-credential-management-tests.ts @@ -352,3 +352,16 @@ function webauthnAuthenticate() { console.log(e.message); }); } + +function mockAuthenticatorAssertionResponse() { + if (!navigator.credentials) { + return; + } + + const sampleResponse: AuthenticatorAssertionResponse = { + clientDataJSON: new ArrayBuffer(0), + authenticatorData: new ArrayBuffer(0), + signature: new ArrayBuffer(0), + }; + sampleResponse.userHandle === undefined; +} From c2ce3512058edf773a51c0c58a1f2f777b128d2a Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.Fr> Date: Sun, 27 Jan 2019 10:41:49 +0100 Subject: [PATCH 013/197] Update debug-tests.ts fixed tslint issues --- types/debug/debug-tests.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/types/debug/debug-tests.ts b/types/debug/debug-tests.ts index bad51ed584..ddfd698825 100644 --- a/types/debug/debug-tests.ts +++ b/types/debug/debug-tests.ts @@ -1,11 +1,9 @@ - - import debug = require("debug"); debug.disable(); debug.enable("DefinitelyTyped:*"); -var log:debug.IDebugger = debug("DefinitelyTyped:log"); +const log: debug.IDebugger = debug("DefinitelyTyped:log"); log("Just text"); log("Formatted test (%d arg)", 1); @@ -15,12 +13,12 @@ log("Enabled?: %s", debug.enabled("DefinitelyTyped:log")); log("Name Enabled: %s", debug.names.some(name => name.test("DefinitelyTyped:log"))); log("Namespace: %s", log.namespace); -var error:debug.IDebugger = debug("DefinitelyTyped:error"); +const error: debug.IDebugger = debug("DefinitelyTyped:error"); error.log = console.error.bind(console); error("This should be printed to stderr"); -var extendedLog: debug.IDebugger = log.extend('extended'); +const extendedLog: debug.IDebugger = log.extend('extended'); extendedLog("Testing this is also an IDebugger."); -var extendedWithCustomDelimiter: debug.IDebugger = log.extend('with-delim', '.'); -extendedWithCustomDelimiter("Testing this is an IDebugger, too."); \ No newline at end of file +const extendedWithCustomDelimiter: debug.IDebugger = log.extend('with-delim', '.'); +extendedWithCustomDelimiter("Testing this is an IDebugger, too."); From 99c9aff07f708e974a0e9ade9a7457682f0a13b1 Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.Fr> Date: Sun, 27 Jan 2019 10:50:23 +0100 Subject: [PATCH 014/197] Update index.d.ts --- types/debug/index.d.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index ad37e702a0..9d6814cf9a 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -13,29 +13,29 @@ export = debug; export as namespace debug; declare namespace debug { - export interface IDebug { - (namespace: string): debug.IDebugger, - coerce: (val: any) => any, - disable: () => void, - enable: (namespaces: string) => void, - enabled: (namespaces: string) => boolean, + interface Debug { + (namespace: string): debug.Debugger; + coerce: (val: any) => any; + disable: () => void; + enable: (namespaces: string) => void; + enabled: (namespaces: string) => boolean; - names: RegExp[], - skips: RegExp[], + names: RegExp[]; + skips: RegExp[]; - formatters: IFormatters + formatters: Formatters; } - export interface IFormatters { - [formatter: string]: Function + interface Formatters { + [formatter: string]: (v:Object)=>string; } - export interface IDebugger { + interface Debugger { (formatter: any, ...args: any[]): void; enabled: boolean; log: Function; namespace: string; - extend: (namespace: string, delimiter?: string) => debug.IDebugger; + extend: (namespace: string, delimiter?: string) => debug.Debugger; } } From 753941216112d4f4cdb0280ff6c444f1a97dd692 Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.Fr> Date: Sun, 27 Jan 2019 11:26:13 +0100 Subject: [PATCH 015/197] Update index.d.ts --- types/debug/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index 9d6814cf9a..ccc2c363af 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -7,7 +7,7 @@ // Nicolas Penin <https://github.com/npenin> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var debug: debug.IDebug & {debug: debug.IDebug, default: debug.IDebug}; +declare var debug: debug.Debug & {debug: debug.Debug, default: debug.Debug}; export = debug; export as namespace debug; From 2943797f768de0d4e9a9f486e9fae11fad778f70 Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.Fr> Date: Sun, 27 Jan 2019 11:27:07 +0100 Subject: [PATCH 016/197] Update debug-tests.ts --- types/debug/debug-tests.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/debug/debug-tests.ts b/types/debug/debug-tests.ts index ddfd698825..22ac083a14 100644 --- a/types/debug/debug-tests.ts +++ b/types/debug/debug-tests.ts @@ -3,7 +3,7 @@ import debug = require("debug"); debug.disable(); debug.enable("DefinitelyTyped:*"); -const log: debug.IDebugger = debug("DefinitelyTyped:log"); +const log: debug.Debugger = debug("DefinitelyTyped:log"); log("Just text"); log("Formatted test (%d arg)", 1); @@ -13,12 +13,12 @@ log("Enabled?: %s", debug.enabled("DefinitelyTyped:log")); log("Name Enabled: %s", debug.names.some(name => name.test("DefinitelyTyped:log"))); log("Namespace: %s", log.namespace); -const error: debug.IDebugger = debug("DefinitelyTyped:error"); +const error: debug.Debugger = debug("DefinitelyTyped:error"); error.log = console.error.bind(console); error("This should be printed to stderr"); -const extendedLog: debug.IDebugger = log.extend('extended'); +const extendedLog: debug.Debugger = log.extend('extended'); extendedLog("Testing this is also an IDebugger."); -const extendedWithCustomDelimiter: debug.IDebugger = log.extend('with-delim', '.'); +const extendedWithCustomDelimiter: debug.Debugger = log.extend('with-delim', '.'); extendedWithCustomDelimiter("Testing this is an IDebugger, too."); From ca16f6f8441cfd7ac63fb7a2a1f614fbddc56f07 Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.Fr> Date: Sun, 27 Jan 2019 11:38:11 +0100 Subject: [PATCH 017/197] Update index.d.ts --- types/debug/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index ccc2c363af..7b4e44dbdd 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -14,7 +14,7 @@ export as namespace debug; declare namespace debug { interface Debug { - (namespace: string): debug.Debugger; + (namespace: string): Debugger; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; @@ -27,15 +27,15 @@ declare namespace debug { } interface Formatters { - [formatter: string]: (v:Object)=>string; + [formatter: string]: (v: any) => string; } interface Debugger { (formatter: any, ...args: any[]): void; enabled: boolean; - log: Function; + log: (v: any) => string; namespace: string; - extend: (namespace: string, delimiter?: string) => debug.Debugger; + extend: (namespace: string, delimiter?: string) => Debugger; } } From 0d2ae95d00b95dd3931255ee67d866beb67f6ccb Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.Fr> Date: Sun, 27 Jan 2019 11:44:16 +0100 Subject: [PATCH 018/197] Update index.d.ts fixed backward compatibility --- types/debug/index.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index 7b4e44dbdd..3dc8d32774 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -25,10 +25,14 @@ declare namespace debug { formatters: Formatters; } + + type IDebug=Debug; interface Formatters { [formatter: string]: (v: any) => string; } + + type IDebugger=Debugger; interface Debugger { (formatter: any, ...args: any[]): void; From 01925c6c8bd763e757ae3fd867a06cf21ab0a24f Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.Fr> Date: Sun, 27 Jan 2019 11:49:04 +0100 Subject: [PATCH 019/197] Update index.d.ts --- types/debug/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index 3dc8d32774..2067b27222 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -25,14 +25,14 @@ declare namespace debug { formatters: Formatters; } - - type IDebug=Debug; + + type IDebug = Debug; interface Formatters { [formatter: string]: (v: any) => string; } - - type IDebugger=Debugger; + + type IDebugger = Debugger; interface Debugger { (formatter: any, ...args: any[]): void; From 35e3d24f055795316c8d0addbcb89546c3195d31 Mon Sep 17 00:00:00 2001 From: Leo Salgueiro <leonardosalgueiro@live.com> Date: Mon, 28 Jan 2019 18:27:05 -0800 Subject: [PATCH 020/197] upgrading react-highlight-words typings to the newest version of the library 0.16.0 --- types/react-highlight-words/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/react-highlight-words/index.d.ts b/types/react-highlight-words/index.d.ts index 9cd72ec411..9dc19130a7 100644 --- a/types/react-highlight-words/index.d.ts +++ b/types/react-highlight-words/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-highlight-words 0.12 +// Type definitions for react-highlight-words 0.16 // Project: https://github.com/bvaughn/react-highlight-words#readme // Definitions by: Mohamed Hegazy <https://github.com/mhegazy> // Diogo Corrêa <https://github.com/diogodca> @@ -25,7 +25,7 @@ interface HighlighterProps { /** The class name to be applied to an active match. Use along with activeIndex */ activeClassName?: string; /** Specify the match index that should be actively highlighted. Use along with activeClassName */ - activeIndex?: string; + activeIndex?: number; /** The inline style to be applied to an active match. Use along with activeIndex */ activeStyle?: React.CSSProperties; /** Escape characters in searchWords which are meaningful in regular expressions */ @@ -48,7 +48,7 @@ interface HighlighterProps { * Type of tag to wrap around highlighted matches; defaults to mark but can also be a React element * (class or functional) */ - highlightTag?: string; + highlightTag?: string | React.ComponentType<any>; /** * Process each search word and text to highlight before comparing (eg remove accents); signature * (text: string): string From 4d254b9d090376b0380b20c7e44a40f93c18bbfa Mon Sep 17 00:00:00 2001 From: Leo Salgueiro <leonardosalgueiro@live.com> Date: Mon, 28 Jan 2019 18:33:37 -0800 Subject: [PATCH 021/197] fixing the test --- .../react-highlight-words/react-highlight-words-tests.tsx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/types/react-highlight-words/react-highlight-words-tests.tsx b/types/react-highlight-words/react-highlight-words-tests.tsx index de63c6d9ec..db8389fe9f 100644 --- a/types/react-highlight-words/react-highlight-words-tests.tsx +++ b/types/react-highlight-words/react-highlight-words-tests.tsx @@ -6,17 +6,20 @@ const findChunks = ({ textToHighlight }: FindChunks) => []; +const CustomHighlight: React.FC = ({children}) => (<span>{children}</span>) + class HighlighterTest extends React.Component { render() { return ( <div> <Highlighter + highlightTag="span" searchWords={["el", "or"]} textToHighlight="Hello World" /> <Highlighter activeClassName="activeClassName" - activeIndex="activeIndex" + activeIndex={1} activeStyle={{ color: "red" }} autoEscape={true} className="className" @@ -24,7 +27,7 @@ class HighlighterTest extends React.Component { findChunks={findChunks} highlightClassName="highlightClassName" highlightStyle={{ color: "red" }} - highlightTag="span" + highlightTag={CustomHighlight} sanitize={(text: string) => text} searchWords={["el", "or"]} textToHighlight="Hello World" From 1a96cde57a30f5377f6545c1244e5934c479f0be Mon Sep 17 00:00:00 2001 From: Leo Salgueiro <leonardosalgueiro@live.com> Date: Mon, 28 Jan 2019 18:40:55 -0800 Subject: [PATCH 022/197] fixing mistake that the linting found --- types/react-highlight-words/react-highlight-words-tests.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-highlight-words/react-highlight-words-tests.tsx b/types/react-highlight-words/react-highlight-words-tests.tsx index db8389fe9f..de1100e0de 100644 --- a/types/react-highlight-words/react-highlight-words-tests.tsx +++ b/types/react-highlight-words/react-highlight-words-tests.tsx @@ -6,7 +6,7 @@ const findChunks = ({ textToHighlight }: FindChunks) => []; -const CustomHighlight: React.FC = ({children}) => (<span>{children}</span>) +const CustomHighlight: React.FC = ({children}) => (<span>{children}</span>); class HighlighterTest extends React.Component { render() { From c24399496d98a1c0ee597569f2e7b00b77cd963b Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 15:15:47 -0800 Subject: [PATCH 023/197] [jscodeshift] Run `npx dts-gen --dt --name jscodeshift --template module` --- types/jscodeshift/index.d.ts | 39 ++++++++++++++++++++++++++ types/jscodeshift/jscodeshift-tests.ts | 0 types/jscodeshift/tsconfig.json | 22 +++++++++++++++ types/jscodeshift/tslint.json | 1 + 4 files changed, 62 insertions(+) create mode 100644 types/jscodeshift/index.d.ts create mode 100644 types/jscodeshift/jscodeshift-tests.ts create mode 100644 types/jscodeshift/tsconfig.json create mode 100644 types/jscodeshift/tslint.json diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts new file mode 100644 index 0000000000..7d1fe12f72 --- /dev/null +++ b/types/jscodeshift/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for jscodeshift 0.6 +// Project: https://github.com/facebook/jscodeshift#readme +// Definitions by: My Self <https://github.com/me> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/*~ If this module is a UMD module that exposes a global variable 'myLib' when + *~ loaded outside a module loader environment, declare that global here. + *~ Otherwise, delete this declaration. + */ +export as namespace myLib; + +/*~ If this module has methods, declare them as functions like so. + */ +export function myMethod(a: string): string; +export function myOtherMethod(a: number): number; + +/*~ You can declare types that are available via importing the module */ +export interface someType { + name: string; + length: number; + extras?: string[]; +} + +/*~ You can declare properties of the module using const, let, or var */ +export const myField: number; + +/*~ If there are types, properties, or methods inside dotted names + *~ of the module, declare them inside a 'namespace'. + */ +export namespace subProp { + /*~ For example, given this definition, someone could write: + *~ import { subProp } from 'yourModule'; + *~ subProp.foo(); + *~ or + *~ import * as yourMod from 'yourModule'; + *~ yourMod.subProp.foo(); + */ + export function foo(): void; +} \ No newline at end of file diff --git a/types/jscodeshift/jscodeshift-tests.ts b/types/jscodeshift/jscodeshift-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/jscodeshift/tsconfig.json b/types/jscodeshift/tsconfig.json new file mode 100644 index 0000000000..726b5b889f --- /dev/null +++ b/types/jscodeshift/tsconfig.json @@ -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", + "jscodeshift-tests.ts" + ] +} diff --git a/types/jscodeshift/tslint.json b/types/jscodeshift/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jscodeshift/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 3d12a04ac4f3591d580eccbcb4e1b6bcbb14f8e1 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 15:39:35 -0800 Subject: [PATCH 024/197] [jscodeshift] Add types for jscodeshift 0.6 --- types/jscodeshift/index.d.ts | 448 +++++++++++++++++++++++-- types/jscodeshift/jscodeshift-tests.ts | 50 +++ types/jscodeshift/package.json | 7 + types/jscodeshift/tsconfig.json | 1 + 4 files changed, 477 insertions(+), 29 deletions(-) create mode 100644 types/jscodeshift/package.json diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts index 7d1fe12f72..3e91d382ba 100644 --- a/types/jscodeshift/index.d.ts +++ b/types/jscodeshift/index.d.ts @@ -1,39 +1,429 @@ // Type definitions for jscodeshift 0.6 // Project: https://github.com/facebook/jscodeshift#readme -// Definitions by: My Self <https://github.com/me> +// Definitions by: Brie Bunge <https://github.com/brieb> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 -/*~ If this module is a UMD module that exposes a global variable 'myLib' when - *~ loaded outside a module loader environment, declare that global here. - *~ Otherwise, delete this declaration. - */ -export as namespace myLib; +declare module "jscodeshift" { + import { Collection, registerMethods } from "jscodeshift/src/Collection"; + import * as JSXElement from "jscodeshift/src/collections/JSXElement"; + import * as VariableDeclarator from "jscodeshift/src/collections/VariableDeclarator"; + import { Template } from "jscodeshift/src/template"; + import recast, { Builders, NamedTypes, NodePath, Options, Parser } from "recast"; + import { ASTNode } from "ast-types/gen/nodes"; -/*~ If this module has methods, declare them as functions like so. - */ -export function myMethod(a: string): string; -export function myOtherMethod(a: number): number; + export type ASTPath<N = ASTNode> = NodePath<N, N>; -/*~ You can declare types that are available via importing the module */ -export interface someType { - name: string; - length: number; - extras?: string[]; + export interface Filters { + JSXElement: JSXElement.FilterMethods; + VariableDeclarator: VariableDeclarator.FilterMethods; + } + + export interface Mappings { + JSXElement: JSXElement.MappingMethods; + } + + export interface Plugin { + (core: Core): void; + } + + export interface FileInfo { + /** The absolute path to the current file. */ + path: string; + /** The source code of the current file. */ + source: string; + } + + export interface Stats { + /** + * Helper function to collect data during --dry runs. + * This function keeps a counter for how often it was called with a specific argument. + * The result is shown in the console. Useful for finding out how many files match a criterion. + */ + (name: string, quantity?: number): void; + } + + interface Core { + (source: string, options?: Options): Collection<any>; + (source: ASTNode | ASTNode[] | ASTPath | ASTPath[]): Collection<any>; + + registerMethods: typeof registerMethods; + + types: typeof recast.types; + + match(path: ASTNode | ASTPath, filter: ((path: ASTNode) => boolean) | ASTNode): boolean; + + /** template, bound to default parser */ + template: Template; + + filters: Filters; + + mappings: Mappings; + + /** + * Utility function for registering plugins. + * + * Plugins are simple functions that are passed the core jscodeshift instance. + * They should extend jscodeshift by calling `registerMethods`, etc. + * This method guards against repeated registrations (the plugin callback will only be called once). + */ + use(plugin: Plugin): void; + + /** + * Returns a version of the core jscodeshift function "bound" to a specific + * parser. + */ + withParser(parser: string | Parser): JSCodeshift; + } + + type JSCodeshift = Core & NamedTypes & Builders; + + const core: JSCodeshift; + export default core; + + export interface API { + j: JSCodeshift; + jscodeshift: JSCodeshift; + stats: Stats; + report: (msg: string) => void; + } + + export interface Options { + [option: string]: any; + } + + export interface Transform { + /** + * If a string is returned and it is different from passed source, the transform is considered to be successful. + * If a string is returned but it's the same as the source, the transform is considered to be unsuccessful. + * If nothing is returned, the file is not supposed to be transformed (which is ok). + */ + (file: FileInfo, api: API, options: Options): string | null | undefined | void; + } + + export * from "ast-types/gen/nodes"; + export { Collection, Parser }; } -/*~ You can declare properties of the module using const, let, or var */ -export const myField: number; +declare module "jscodeshift/src/template" { + import { Parser } from "recast"; -/*~ If there are types, properties, or methods inside dotted names - *~ of the module, declare them inside a 'namespace'. - */ -export namespace subProp { - /*~ For example, given this definition, someone could write: - *~ import { subProp } from 'yourModule'; - *~ subProp.foo(); - *~ or - *~ import * as yourMod from 'yourModule'; - *~ yourMod.subProp.foo(); + export interface Template { + /** Tagged template function. Parses the string as source and returns an array of Statement AST nodes. */ + statements(...args: any[]): any; + /** Tagged template function. Parses the string as source and returns an Statement AST node. */ + statement(...args: any[]): any; + /** Tagged template function. Parses the string as source and returns an Expression AST node. */ + expression(...args: any[]): any; + } + + export default function withParser(parser: Parser): Template; + + export {}; // force module +} + +declare module "jscodeshift/src/Collection" { + import * as JSXElement from "jscodeshift/src/collections/JSXElement"; + import * as NodeCollection from "jscodeshift/src/collections/Node"; + import * as VariableDeclarator from "jscodeshift/src/collections/VariableDeclarator"; + import recast, { ASTNode, NodePath, Options } from "recast"; + + type Type = typeof recast.types.Type; + type ASTPath<N> = NodePath<N, N>; + + interface Collection<N> + extends NodeCollection.TraversalMethods, + NodeCollection.MutationMethods<N>, + VariableDeclarator.GlobalMethods, + VariableDeclarator.TransformMethods<N>, + JSXElement.GlobalMethods, + JSXElement.TraversalMethods { + /** + * @param paths An array of AST paths + * @param parent A parent collection + * @param types An array of types all the paths in the collection + * have in common. If not passed, it will be inferred from the paths. + */ + new (paths: ASTPath<N>[], parent: Collection<any>, types?: Type[]): this; + + /** + * Returns a new collection containing the nodes for which the callback returns true. + */ + filter<S extends N>( + callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => path is ASTPath<S> + ): Collection<S>; + filter( + callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => boolean + ): Collection<N>; + + /** + * Executes callback for each node/path in the collection. + */ + forEach(callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => void): this; + + /** + * Tests whether at-least one path passes the test implemented by the provided callback. + */ + some(callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => boolean): boolean; + + /** + * Tests whether all paths pass the test implemented by the provided callback. + */ + every(callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => boolean): boolean; + + /** + * Executes the callback for every path in the collection and returns a new + * collection from the return values (which must be paths). + * + * The callback can return null to indicate to exclude the element from the + * new collection. + * + * If an array is returned, the array will be flattened into the result + * collection. + * + * @param callback + * @param type Force the new collection to be of a specific type + */ + map<T = ASTNode>( + callback: ( + path: ASTPath<N>, + i: number, + paths: ASTPath<N>[] + ) => ASTPath<T> | ASTPath<T>[] | null | undefined, + type: Type + ): Collection<T>; + + /** Returns the number of elements in this collection. */ + size(): number; + + /** Returns the number of elements in this collection. */ + length: number; + + /** Returns an array of AST nodes in this collection. */ + nodes(): N[]; + + /** Returns an array of ASTPaths in this this collection. */ + paths(): ASTPath<N>[]; + + getAST(): ASTPath<any>[]; + + /** + * Converts the AST back to a string, using recast. + * @param options directly passed to recast's printer + */ + toSource(options?: Options): string; + + /** + * Returns a new collection containing only the element at position index. + * In case of a negative index, the element is taken from the end: + * .at(0) - first element + * .at(-1) - last element + */ + at(index: number): Collection<N>; + + /** Calls "get" on the first path (same as "collection.paths(0).get(...)"). */ + get<T>(...fields: (string | number)[]): T; + + /** + * Returns the type(s) of the collection. This is only used for unit tests, + * don't think other consumers would need it. + */ + getTypes(): string[]; + + /** + * Returns true if this collection has the type 'type'. + */ + isOfType(type: Type): boolean; + } + + /** + * This function adds the provided methods to the prototype of the corresponding + * typed collection. If no type is passed, the methods are added to + * Collection.prototype and are available for all collections. + * + * @param methods Methods to add to the prototype + * @param type Optional type to add the methods to */ - export function foo(): void; -} \ No newline at end of file + export function registerMethods(methods: object, type?: Type): void; +} + +declare module "jscodeshift/src/collections/Node" { + import { Collection } from "jscodeshift/src/Collection"; + import { ASTNode, Type } from "recast"; + + export interface TraversalMethods { + /** + * Find nodes of a specific type within the nodes of this collection. + */ + find<T>(type: Type<T>): Collection<T>; + find<T>(type: Type<T>, filter: (value: any) => boolean): Collection<T>; + find<T>(type: Type<T>, filter: object): Collection<T>; + + /** + * Returns a collection containing the paths that create the scope of the + * currently selected paths. Dedupes the paths. + */ + closestScope<T>(): Collection<T>; + + /** + * Traverse the AST up and finds the closest node of the provided type. + */ + closest<T>(type: Type<T>, filter?: any): Collection<T>; + + /** + * Finds the declaration for each selected path. Useful for member expressions + * or JSXElements. Expects a callback function that maps each path to the name + * to look for. + * + * If the callback returns a falsey value, the element is skipped. + */ + getVariableDeclarators<T>(nameGetter: Function): Collection<T>; + } + + export interface MutationMethods<N> { + /** + * Simply replaces the selected nodes with the provided node. If a function + * is provided it is executed for every node and the node is replaced with the + * functions return value. + * + * @param {Node|Array<Node>|function} nodes + */ + replaceWith<T>(nodes: T | T[] | ((path: any, i: number) => T)): this; + + /** + * Inserts a new node before the current one. + * + * @param {Node|Array<Node>|function} insert + */ + insertBefore(insert: any): Collection<N>; + + /** + * Inserts a new node after the current one. + * + * @param {Node|Array<Node>|function} insert + */ + insertAfter(insert: any): Collection<N>; + + remove(): Collection<N>; + } + + export function register(): void; + + export {}; // force module +} + +declare module "jscodeshift/src/collections/VariableDeclarator" { + import { VariableDeclarator } from "ast-types/gen/nodes"; + import { Collection } from "jscodeshift/src/Collection"; + import recast, { NodePath } from "recast"; + + type Node = typeof recast.types.namedTypes.Node; + type ASTPath<N> = NodePath<N, N>; + + export interface GlobalMethods { + /** + * Finds all variable declarators, optionally filtered by name. + */ + findVariableDeclarators(name?: string): Collection<VariableDeclarator>; + } + + export interface TransformMethods<N> { + /** + * Renames a variable and all its occurrences. + * This method only applies to VariableDeclarator typed collections. + */ + renameTo(newName: string): Collection<N>; + } + + interface Filter { + (path: ASTPath<any>): boolean; + } + + export interface FilterMethods { + /** + * Returns a function that returns true if the provided path is a variable + * declarator and requires one of the specified module names. + * + * @param names A module name or an array of module names + */ + requiresModule(names: string | string[]): Filter; + } + + export function register(): void; + export const filters: FilterMethods; + + export {}; // force module +} + +declare module "jscodeshift/src/collections/JSXElement" { + import { JSXElement } from "ast-types/gen/nodes"; + import { Collection } from "jscodeshift/src/Collection"; + import { NodePath } from "recast"; + + type ASTPath<N> = NodePath<N, N>; + + export interface GlobalMethods { + /** + * Finds all JSXElements optionally filtered by name + */ + findJSXElements(name?: string): Collection<JSXElement>; + + /** + * Finds all JSXElements by module name. Given + * + * var Bar = require('Foo'); + * <Bar /> + * + * findJSXElementsByModuleName('Foo') will find <Bar />, without having to + * know the variable name. + */ + findJSXElementsByModuleName(moduleName: string): Collection<JSXElement>; + } + + type Defined<T> = T extends undefined ? never : T; + type JSXElementChild = Defined<JSXElement["children"]>[0]; + + export interface TraversalMethods { + /** + * Returns all child nodes, including literals and expressions. + * This method only applies to JSXElement typed collections. + */ + childNodes<T>(): Collection<JSXElementChild>; + + /** + * Returns all children that are JSXElements. + * This method only applies to JSXElement typed collections. + */ + childElements(): Collection<JSXElement>; + } + + interface Filter { + (path: ASTPath<any>): boolean; + } + + export interface FilterMethods { + /** + * Filter method for attributes. + */ + hasAttributes(attributeFilter: { [attributeName: string]: any }): Filter; + + /** + * Filter elements which contain a specific child type + */ + hasChildren(name: string): Filter; + } + + export interface MappingMethods { + /** + * Given a JSXElement, returns its "root" name. E.g. it would return "Foo" for + * both <Foo /> and <Foo.Bar />. + */ + getRootName(path: ASTPath<any>): string; + } + + export function register(): void; + export const filters: FilterMethods; + export const mappings: MappingMethods; + + export {}; // force module +} diff --git a/types/jscodeshift/jscodeshift-tests.ts b/types/jscodeshift/jscodeshift-tests.ts index e69de29bb2..8631e400c4 100644 --- a/types/jscodeshift/jscodeshift-tests.ts +++ b/types/jscodeshift/jscodeshift-tests.ts @@ -0,0 +1,50 @@ +import { ASTNode, FileInfo, API, Transform } from "jscodeshift"; + +// Can define transform with `function`. +function replaceWithFooTransform(fileInfo: FileInfo, api: API) { + return api + .jscodeshift(fileInfo.source) + .findVariableDeclarators("foo") + .renameTo("bar") + .toSource(); +} + +// Can define transform with arrow function, using `Transform` type. +const reverseIdentifiersTransform: Transform = (file, api) => { + const j = api.jscodeshift; + + return j(file.source) + .find(j.Identifier) + .forEach(path => { + j(path).replaceWith( + j.identifier( + path.node.name + .split("") + .reverse() + .join("") + ) + ); + }) + .toSource(); +}; + +// `ASTNode` supports type narrowing. +{ + const node = ({} as any) as ASTNode; + if (node.type === "CatchClause") { + // `node` is narrowed to `CatchClause` here + if (node.param && node.param.type === "Identifier") { + // `node.param` is narrowed to `Identifier` here + if ( + node.param.typeAnnotation && + node.param.typeAnnotation.type === "TSTypeAnnotation" + ) { + // `node.param.typeAnnotation` is narrowed to `TSTypeAnnotation` here + if (node.param.typeAnnotation.typeAnnotation.type === "TSArrayType") { + // `node.param.typeAnnotation.typeAnnotation` is narrowed to `TSArrayType` here + node.param.typeAnnotation.typeAnnotation.elementType; + } + } + } + } +} diff --git a/types/jscodeshift/package.json b/types/jscodeshift/package.json new file mode 100644 index 0000000000..65d03a5a7f --- /dev/null +++ b/types/jscodeshift/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "dependencies": { + "ast-types": "^0.12.0", + "recast": "^0.17.0" + } +} diff --git a/types/jscodeshift/tsconfig.json b/types/jscodeshift/tsconfig.json index 726b5b889f..f1ad7409d3 100644 --- a/types/jscodeshift/tsconfig.json +++ b/types/jscodeshift/tsconfig.json @@ -7,6 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" From 3e712a34cb4fca323d48ca5d627fa846947cacde Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 15:51:32 -0800 Subject: [PATCH 025/197] [jscodeshift] Fix lints --- types/jscodeshift/index.d.ts | 46 +++++++++++++++-------------------- types/jscodeshift/tslint.json | 9 ++++++- 2 files changed, 28 insertions(+), 27 deletions(-) diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts index 3e91d382ba..391b4a4f13 100644 --- a/types/jscodeshift/index.d.ts +++ b/types/jscodeshift/index.d.ts @@ -119,7 +119,7 @@ declare module "jscodeshift/src/template" { export default function withParser(parser: Parser): Template; - export {}; // force module + export {}; // to shut off automatic exporting } declare module "jscodeshift/src/Collection" { @@ -131,7 +131,7 @@ declare module "jscodeshift/src/Collection" { type Type = typeof recast.types.Type; type ASTPath<N> = NodePath<N, N>; - interface Collection<N> + export interface Collection<N> extends NodeCollection.TraversalMethods, NodeCollection.MutationMethods<N>, VariableDeclarator.GlobalMethods, @@ -144,32 +144,32 @@ declare module "jscodeshift/src/Collection" { * @param types An array of types all the paths in the collection * have in common. If not passed, it will be inferred from the paths. */ - new (paths: ASTPath<N>[], parent: Collection<any>, types?: Type[]): this; + new (paths: Array<ASTPath<N>>, parent: Collection<any>, types?: Type[]): this; /** * Returns a new collection containing the nodes for which the callback returns true. */ filter<S extends N>( - callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => path is ASTPath<S> + callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => path is ASTPath<S> ): Collection<S>; filter( - callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => boolean + callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean ): Collection<N>; /** * Executes callback for each node/path in the collection. */ - forEach(callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => void): this; + forEach(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => void): this; /** * Tests whether at-least one path passes the test implemented by the provided callback. */ - some(callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => boolean): boolean; + some(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean): boolean; /** * Tests whether all paths pass the test implemented by the provided callback. */ - every(callback: (path: ASTPath<N>, i: number, paths: ASTPath<N>[]) => boolean): boolean; + every(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean): boolean; /** * Executes the callback for every path in the collection and returns a new @@ -188,8 +188,8 @@ declare module "jscodeshift/src/Collection" { callback: ( path: ASTPath<N>, i: number, - paths: ASTPath<N>[] - ) => ASTPath<T> | ASTPath<T>[] | null | undefined, + paths: Array<ASTPath<N>> + ) => ASTPath<T> | Array<ASTPath<T>> | null | undefined, type: Type ): Collection<T>; @@ -203,9 +203,9 @@ declare module "jscodeshift/src/Collection" { nodes(): N[]; /** Returns an array of ASTPaths in this this collection. */ - paths(): ASTPath<N>[]; + paths(): Array<ASTPath<N>>; - getAST(): ASTPath<any>[]; + getAST(): Array<ASTPath<any>>; /** * Converts the AST back to a string, using recast. @@ -222,7 +222,7 @@ declare module "jscodeshift/src/Collection" { at(index: number): Collection<N>; /** Calls "get" on the first path (same as "collection.paths(0).get(...)"). */ - get<T>(...fields: (string | number)[]): T; + get(...fields: Array<string | number>): any; /** * Returns the type(s) of the collection. This is only used for unit tests, @@ -245,6 +245,8 @@ declare module "jscodeshift/src/Collection" { * @param type Optional type to add the methods to */ export function registerMethods(methods: object, type?: Type): void; + + export {}; // to shut off automatic exporting } declare module "jscodeshift/src/collections/Node" { @@ -255,9 +257,7 @@ declare module "jscodeshift/src/collections/Node" { /** * Find nodes of a specific type within the nodes of this collection. */ - find<T>(type: Type<T>): Collection<T>; - find<T>(type: Type<T>, filter: (value: any) => boolean): Collection<T>; - find<T>(type: Type<T>, filter: object): Collection<T>; + find<T>(type: Type<T>, filter?: ((value: any) => boolean) | object): Collection<T>; /** * Returns a collection containing the paths that create the scope of the @@ -277,7 +277,7 @@ declare module "jscodeshift/src/collections/Node" { * * If the callback returns a falsey value, the element is skipped. */ - getVariableDeclarators<T>(nameGetter: Function): Collection<T>; + getVariableDeclarators<T>(nameGetter: (...args: any[]) => any): Collection<T>; } export interface MutationMethods<N> { @@ -285,22 +285,16 @@ declare module "jscodeshift/src/collections/Node" { * Simply replaces the selected nodes with the provided node. If a function * is provided it is executed for every node and the node is replaced with the * functions return value. - * - * @param {Node|Array<Node>|function} nodes */ replaceWith<T>(nodes: T | T[] | ((path: any, i: number) => T)): this; /** * Inserts a new node before the current one. - * - * @param {Node|Array<Node>|function} insert */ insertBefore(insert: any): Collection<N>; /** * Inserts a new node after the current one. - * - * @param {Node|Array<Node>|function} insert */ insertAfter(insert: any): Collection<N>; @@ -309,7 +303,7 @@ declare module "jscodeshift/src/collections/Node" { export function register(): void; - export {}; // force module + export {}; // to shut off automatic exporting } declare module "jscodeshift/src/collections/VariableDeclarator" { @@ -352,7 +346,7 @@ declare module "jscodeshift/src/collections/VariableDeclarator" { export function register(): void; export const filters: FilterMethods; - export {}; // force module + export {}; // to shut off automatic exporting } declare module "jscodeshift/src/collections/JSXElement" { @@ -425,5 +419,5 @@ declare module "jscodeshift/src/collections/JSXElement" { export const filters: FilterMethods; export const mappings: MappingMethods; - export {}; // force module + export {}; // to shut off automatic exporting } diff --git a/types/jscodeshift/tslint.json b/types/jscodeshift/tslint.json index 3db14f85ea..94991f356f 100644 --- a/types/jscodeshift/tslint.json +++ b/types/jscodeshift/tslint.json @@ -1 +1,8 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-declare-current-package": false, + "no-self-import": false, + "no-unnecessary-generics": false + } +} From 0cc491505e8284969ef2720aa10bf42c20b31ac6 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 16:16:12 -0800 Subject: [PATCH 026/197] [jscodeshift] Additional test cases --- types/jscodeshift/index.d.ts | 12 ++++----- types/jscodeshift/jscodeshift-tests.ts | 37 +++++++++++++++++++++----- 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts index 391b4a4f13..b9b15be825 100644 --- a/types/jscodeshift/index.d.ts +++ b/types/jscodeshift/index.d.ts @@ -126,9 +126,8 @@ declare module "jscodeshift/src/Collection" { import * as JSXElement from "jscodeshift/src/collections/JSXElement"; import * as NodeCollection from "jscodeshift/src/collections/Node"; import * as VariableDeclarator from "jscodeshift/src/collections/VariableDeclarator"; - import recast, { ASTNode, NodePath, Options } from "recast"; + import recast, { ASTNode, NodePath, Options, Type } from "recast"; - type Type = typeof recast.types.Type; type ASTPath<N> = NodePath<N, N>; export interface Collection<N> @@ -144,7 +143,7 @@ declare module "jscodeshift/src/Collection" { * @param types An array of types all the paths in the collection * have in common. If not passed, it will be inferred from the paths. */ - new (paths: Array<ASTPath<N>>, parent: Collection<any>, types?: Type[]): this; + new (paths: Array<ASTPath<N>>, parent: Collection<any>, types?: Array<Type<any>>): this; /** * Returns a new collection containing the nodes for which the callback returns true. @@ -190,7 +189,7 @@ declare module "jscodeshift/src/Collection" { i: number, paths: Array<ASTPath<N>> ) => ASTPath<T> | Array<ASTPath<T>> | null | undefined, - type: Type + type: Type<any> ): Collection<T>; /** Returns the number of elements in this collection. */ @@ -233,7 +232,7 @@ declare module "jscodeshift/src/Collection" { /** * Returns true if this collection has the type 'type'. */ - isOfType(type: Type): boolean; + isOfType(type: Type<any>): boolean; } /** @@ -244,7 +243,7 @@ declare module "jscodeshift/src/Collection" { * @param methods Methods to add to the prototype * @param type Optional type to add the methods to */ - export function registerMethods(methods: object, type?: Type): void; + export function registerMethods(methods: object, type?: Type<any>): void; export {}; // to shut off automatic exporting } @@ -311,7 +310,6 @@ declare module "jscodeshift/src/collections/VariableDeclarator" { import { Collection } from "jscodeshift/src/Collection"; import recast, { NodePath } from "recast"; - type Node = typeof recast.types.namedTypes.Node; type ASTPath<N> = NodePath<N, N>; export interface GlobalMethods { diff --git a/types/jscodeshift/jscodeshift-tests.ts b/types/jscodeshift/jscodeshift-tests.ts index 8631e400c4..f426eb37b7 100644 --- a/types/jscodeshift/jscodeshift-tests.ts +++ b/types/jscodeshift/jscodeshift-tests.ts @@ -1,4 +1,4 @@ -import { ASTNode, FileInfo, API, Transform } from "jscodeshift"; +import { ASTNode, FileInfo, API, Transform, Parser } from "jscodeshift"; // Can define transform with `function`. function replaceWithFooTransform(fileInfo: FileInfo, api: API) { @@ -28,21 +28,46 @@ const reverseIdentifiersTransform: Transform = (file, api) => { .toSource(); }; +// Can define a custom parser. +const parser: Parser = { + parse(source, options) { + // return estree compatible AST + return { type: "root" }; + } +}; + +// Can pass options to recast +const transformWithRecastFormattingOptions: Transform = (file, { j }) => { + return j(file.source).toSource({ quote: "single" }); +}; + +const transformWithRecastParseOptions: Transform = (file, { j }) => { + return j(file.source, { + /* ...passes options to recast's parse method... */ + }).toSource(); +}; + // `ASTNode` supports type narrowing. { const node = ({} as any) as ASTNode; if (node.type === "CatchClause") { - // `node` is narrowed to `CatchClause` here + // $ExpectType CatchClause + node; + if (node.param && node.param.type === "Identifier") { - // `node.param` is narrowed to `Identifier` here + // $ExpectType Identifier + node.param; + if ( node.param.typeAnnotation && node.param.typeAnnotation.type === "TSTypeAnnotation" ) { - // `node.param.typeAnnotation` is narrowed to `TSTypeAnnotation` here + // $ExpectType TSTypeAnnotation + node.param.typeAnnotation; + if (node.param.typeAnnotation.typeAnnotation.type === "TSArrayType") { - // `node.param.typeAnnotation.typeAnnotation` is narrowed to `TSArrayType` here - node.param.typeAnnotation.typeAnnotation.elementType; + // $ExpectType TSArrayType + node.param.typeAnnotation.typeAnnotation; } } } From abfdaa340f1fb458f7b76c587a46c90c418ddaae Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 16:17:22 -0800 Subject: [PATCH 027/197] [jscodeshift] Move tests to /test subfolder --- types/jscodeshift/{ => test}/jscodeshift-tests.ts | 0 types/jscodeshift/tsconfig.json | 4 ++-- 2 files changed, 2 insertions(+), 2 deletions(-) rename types/jscodeshift/{ => test}/jscodeshift-tests.ts (100%) diff --git a/types/jscodeshift/jscodeshift-tests.ts b/types/jscodeshift/test/jscodeshift-tests.ts similarity index 100% rename from types/jscodeshift/jscodeshift-tests.ts rename to types/jscodeshift/test/jscodeshift-tests.ts diff --git a/types/jscodeshift/tsconfig.json b/types/jscodeshift/tsconfig.json index f1ad7409d3..c5f4e65e59 100644 --- a/types/jscodeshift/tsconfig.json +++ b/types/jscodeshift/tsconfig.json @@ -16,8 +16,8 @@ "noEmit": true, "forceConsistentCasingInFileNames": true }, - "files": [ + "include": [ "index.d.ts", - "jscodeshift-tests.ts" + "test" ] } From 277387c0b621e630dafb1a269009a7e9c253c037 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 16:50:27 -0800 Subject: [PATCH 028/197] [jscodeshift] Copy js-transforms for use as real-world test cases https://github.com/jhgg/js-transforms/tree/bfdc97240bfc07e30453a81407f98820d67439a8 --- .../bind-this-to-bind-expression.js | 22 +++ ...-bind-this-to-arrow-function-expression.js | 50 +++++++ ...expression-to-arrow-function-expression.js | 46 ++++++ .../js-transforms/props-to-destructuring.js | 137 ++++++++++++++++++ .../pure-to-composite-component.js | 61 ++++++++ 5 files changed, 316 insertions(+) create mode 100755 types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.js create mode 100755 types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.js create mode 100755 types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.js create mode 100755 types/jscodeshift/test/js-transforms/props-to-destructuring.js create mode 100755 types/jscodeshift/test/js-transforms/pure-to-composite-component.js diff --git a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.js b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.js new file mode 100755 index 0000000000..97248a7e35 --- /dev/null +++ b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.js @@ -0,0 +1,22 @@ +/** + * This transform converts stuff like: + * + * let x = this.foo.bind(this); + * + * to + * + * let x = ::this.foo; + * + */ + +module.exports = function (file, api) { + const j = api.jscodeshift; + return j(file.source) + // Find stuff that looks like this.xyz.bind(this) + .find(j.CallExpression, {callee: {object: {object: j.ThisExpression}, property: {name: 'bind'}}}) + // Ensure that .bind() is being called with only one argument, and that argument is "this". + .filter(p => p.value.arguments.length == 1 && p.value.arguments[0].type == "ThisExpression") + // We can now replace it with ::this.xyz + .replaceWith(p => j.bindExpression(null, p.value.callee.object)) + .toSource(); +}; \ No newline at end of file diff --git a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.js b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.js new file mode 100755 index 0000000000..727f2e950d --- /dev/null +++ b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.js @@ -0,0 +1,50 @@ +/** Converts + * onClick(function(a, b) { + * return a + b; + * }.bind(this), + * function(b, c) { + * return 1; + * }.bind(this)); + * + * onClick(function(a) { + * var a = 1; + * return a; + * }.bind(this)); + * + * var a = function(c) { return c; }.bind(this); + * + ** to + * onClick((a, b) => a + b, + * (b, c) => 1); + * + * onClick(a => { + * var a = 1; + * return a; + * }); + * + * var a = c => c; + * + */ + +module.exports = function(file, api) { + const j = api.jscodeshift; + + return j(file.source) + // We're looking for a CallExpression that's calling .bind() onto a FunctionExpression. + .find(j.CallExpression, {callee: {property: {name: 'bind'}, object: {type: 'FunctionExpression'}}}) + // Verify that .bind() is only being called with `this` as it's sole arguments. + .filter(p => p.value.arguments.length == 1 && p.value.arguments[0].type == "ThisExpression") + .replaceWith(p => { + // Grab the function body. Since we looked for the CallExpression originally, the "callee.object" would refer + // to the FunctionExpression that's being called .bind(this) on. We need the body of that function + // to transform into an ArrowFunctionExpression. + var body = p.value.callee.object.body; + // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, + // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } + var useExpression = body.type == 'BlockStatement' && body.body.length == 1 && body.body[0].type == "ReturnStatement"; + body = useExpression ? body.body[0].argument : body; + + return j.arrowFunctionExpression(p.value.callee.object.params, body, useExpression); + }) + .toSource(); +}; \ No newline at end of file diff --git a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.js b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.js new file mode 100755 index 0000000000..fdee1a994b --- /dev/null +++ b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.js @@ -0,0 +1,46 @@ +/** + * Converts a FunctionExpression to an ArrowFunctionExpression when safe to do so. + * + * var a = function(a, b) { + * return a + b; + * } + * + * var b = function(a, b) { + * var c = 0; + * return a + b + c; + * } + * + * var a = function(a, b) { + * return a + b + this.c; + * } + ** + * var a = (a, b) => a + b + * + * var b = (a, b) => { + * var c = 0; + * return a + b + c; + * } + * + * var a = function(a, b) { + * return a + b + this.c; + * } + */ + +module.exports = function (file, api) { + const j = api.jscodeshift; + + return j(file.source) + .find(j.FunctionExpression) + // We check for this expression, as if it's in a function expression, we don't want to re-bind "this" by + // using the arrowFunctionExpression. As that could potentially have some unintended consequences. + .filter(p => j(p).find(j.ThisExpression).size() == 0) + .replaceWith(p => { + var body = p.value.body; + // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, + // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } + var useExpression = body.type == 'BlockStatement' && body.body.length == 1 && body.body[0].type == "ReturnStatement"; + body = useExpression ? body.body[0].argument : body; + return j.arrowFunctionExpression(p.value.params, body, useExpression); + }) + .toSource(); +}; diff --git a/types/jscodeshift/test/js-transforms/props-to-destructuring.js b/types/jscodeshift/test/js-transforms/props-to-destructuring.js new file mode 100755 index 0000000000..87def91d52 --- /dev/null +++ b/types/jscodeshift/test/js-transforms/props-to-destructuring.js @@ -0,0 +1,137 @@ +/** + * Transforms: + * class C extends React.Component() { + * render() { + * return <div foo={this.props.foo} bar={this.props.bar} /> + * } + * } + *** To: + * + * class C extends React.Component() { + * render() { + * const { + * foo, + * bar + * } = this.props; + * + * return <div foo={foo} bar={bar} /> + * } + * } + * + */ + +let keywords = 'this function if return var else for new in typeof while case break try catch delete throw switch continue default instanceof do void finally with debugger implements interface package private protected public static class enum export extends import super true false null abstract boolean byte char const double final float goto int long native short synchronized throws transient volatile'; +keywords = keywords.split(' ').reduce((f, k) => { + f[k] = true; + return f; +}, {}); +const isKeyword = k => keywords.hasOwnProperty(k); + +module.exports = function (file, api) { + const j = api.jscodeshift; + const {statement} = j.template; + + return j(file.source) + .find(j.FunctionExpression) + .replaceWith(p => { + console.log(p); + const root = j(p.value); + const variablesToReplace = {}; + + // Figure out if the variable was defined from props, so that we can re-use that definition. + const isFromProps = (name, resolvedScope) => { + return resolvedScope.getBindings()[name].every( + p => { + const decl = j(p).closest(j.VariableDeclarator); + // What happens when our VariableDeclarator is too high up the parent AST? + + if (!decl.size()) return false; + const node = decl.nodes()[0]; + + if (!(node.init.type == 'MemberExpression' && + node.init.object.type == 'ThisExpression' && + node.init.property.name == 'props')) + return false; + + // Check for the case where it could be aliased (i.e.) { baz: foo } = this.props; + // In this case, we won't do a substitution. + if (p.parentPath.value.type == 'Property' && p.parentPath.value.key.name !== name) + return false; + + return true; + } + ); + }; + + // Transform "this.props.xyz" to "xyz", and record what we've transformed. + // Transform as long as we don't have "xyz" already defined in the scope. + root + .find(j.MemberExpression, { + object: { + type: 'MemberExpression', + object: {type: 'ThisExpression'}, + property: {name: 'props'} + } + }) + .filter(e => { + const resolvedScope = e.scope.lookup(e.value.property.name); + // If the scope is null, that means that this property isn't defined in the scope yet, + // and we can use it. Otherwise, if it is defined, we should see if it was defined from `this.props` + // if none of these cases are true, we can't do substitution. + return resolvedScope == null || isFromProps(e.value.property.name, resolvedScope); + }) + // Ensure that our substitution won't cause us to define a keyword, i.e. `this.props.while` won't + // get converted into `while`. + .filter(p => !isKeyword(p.value.property.name)) + // Now, do the replacement, `this.props.xyz` => `xyz`. + .replaceWith(p => p.value.property) + // Finally, mark the variable as something we will need to define earlier in the function, + // if it's not already defined. + .forEach(p => { + // Is this prop already defined somewhere else. + if (!p.scope.lookup(p.value.name)) + variablesToReplace[p.value.name] = true; + }); + + + // Create property definitions for variables that we've replaced. + const properties = Object.keys(variablesToReplace) + .sort() + .map(k => { + const prop = j.property('init', j.identifier(k), j.identifier(k)); + prop.shorthand = true; + return prop; + }); + + // We have no properties to inject, so we can bail here. + if (!properties.length) + return p.value; + + // See if we already have a VariableDeclarator like { a, b, c } = this.props; + const propDefinitions = root + .find(j.VariableDeclarator, { + id: {type: 'ObjectPattern'}, + init: {type: 'MemberExpression', object: {type: 'ThisExpression'}, property: {name: 'props'}} + }); + + if (propDefinitions.size()) { + const nodePath = propDefinitions.paths()[0]; + const node = nodePath.value; + const newPattern = j.objectPattern(node.id.properties.concat(properties)); + nodePath.replace(j.variableDeclarator(newPattern, node.init)); + return p.value; + } + + // Otherwise, we'll have to create our own, as none were suitable for use. + // Create the variable definition `const { xyz } = this.props;` + const decl = statement`const { ${properties} } = this.props;`; + + // Add the variable definition to the top of the function expression body. + return j.functionExpression( + p.value.id, + p.value.params, + j.blockStatement([decl].concat(p.value.body.body)) + ); + } + ).toSource(); +}; diff --git a/types/jscodeshift/test/js-transforms/pure-to-composite-component.js b/types/jscodeshift/test/js-transforms/pure-to-composite-component.js new file mode 100755 index 0000000000..dd4b3bf5c2 --- /dev/null +++ b/types/jscodeshift/test/js-transforms/pure-to-composite-component.js @@ -0,0 +1,61 @@ +/** For when you've gone too pure and want to go back. **/ +/** Converts + * let HistoryItem = (props) => { + * const { + * item + * } = props; + * return <li>{item}</li>; + * }; + * + * let X = (props) => <div>foo</div>; + * + * to + * + * class HistoryItem extends Component { + * render() { + * const { + * item + * } = this.props; + * return <li>{item}</li>; + * } + * } + * + * class X extends Component { + * render() { + * return <div>foo</div>; + * } + * } + */ + + +module.exports = function (file, api) { + const j = api.jscodeshift; + const {statement} = j.template; + + function hasJSXElement(ast) { + return j(ast).find(j.JSXElement).size() > 0; + } + + return j(file.source) + .find(j.VariableDeclaration) + .filter(p => p.value.declarations.length == 1) + .replaceWith(p => { + const decl = p.value.declarations[0]; + if (decl.init.type !== 'ArrowFunctionExpression' || + (!hasJSXElement(decl.init.body) && decl.init.body.type !== "JSXElement")) + return p.value; + + let body = decl.init.body; + body = body.type == "JSXElement" ? j.returnStatement(body) : body = body.body; + + j(body) + .find(j.Identifier, {name: 'props'}) + .replaceWith(p => j.memberExpression(j.thisExpression(), j.identifier('props'))); + + return statement`class ${decl.id} extends Component { + render() { ${body} } + }`; + + }) + .toSource(); +}; From 81cf624ae165314859216122efedd926d40e6fa5 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 16:52:05 -0800 Subject: [PATCH 029/197] [jscodeshift] Rename js-transforms from JS to TS --- ...this-to-bind-expression.js => bind-this-to-bind-expression.ts} | 0 ... => call-expression-bind-this-to-arrow-function-expression.ts} | 0 ...ion.js => function-expression-to-arrow-function-expression.ts} | 0 .../{props-to-destructuring.js => props-to-destructuring.ts} | 0 ...e-to-composite-component.js => pure-to-composite-component.ts} | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename types/jscodeshift/test/js-transforms/{bind-this-to-bind-expression.js => bind-this-to-bind-expression.ts} (100%) rename types/jscodeshift/test/js-transforms/{call-expression-bind-this-to-arrow-function-expression.js => call-expression-bind-this-to-arrow-function-expression.ts} (100%) rename types/jscodeshift/test/js-transforms/{function-expression-to-arrow-function-expression.js => function-expression-to-arrow-function-expression.ts} (100%) rename types/jscodeshift/test/js-transforms/{props-to-destructuring.js => props-to-destructuring.ts} (100%) rename types/jscodeshift/test/js-transforms/{pure-to-composite-component.js => pure-to-composite-component.ts} (100%) diff --git a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.js b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts similarity index 100% rename from types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.js rename to types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts diff --git a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.js b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts similarity index 100% rename from types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.js rename to types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts diff --git a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.js b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts similarity index 100% rename from types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.js rename to types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts diff --git a/types/jscodeshift/test/js-transforms/props-to-destructuring.js b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts similarity index 100% rename from types/jscodeshift/test/js-transforms/props-to-destructuring.js rename to types/jscodeshift/test/js-transforms/props-to-destructuring.ts diff --git a/types/jscodeshift/test/js-transforms/pure-to-composite-component.js b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts similarity index 100% rename from types/jscodeshift/test/js-transforms/pure-to-composite-component.js rename to types/jscodeshift/test/js-transforms/pure-to-composite-component.ts From 17c8595115965054a9b57670f164d8a4bfe8a9e5 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 17:09:54 -0800 Subject: [PATCH 030/197] [jscodeshift] Fix compiler errors in test/js-transforms --- types/jscodeshift/index.d.ts | 6 ++-- .../jscodeshift/test/js-transforms/README.md | 2 ++ .../bind-this-to-bind-expression.ts | 5 +-- ...-bind-this-to-arrow-function-expression.ts | 19 +++++++--- ...expression-to-arrow-function-expression.ts | 13 +++++-- .../js-transforms/props-to-destructuring.ts | 36 ++++++++++--------- .../pure-to-composite-component.ts | 30 ++++++++-------- 7 files changed, 69 insertions(+), 42 deletions(-) create mode 100644 types/jscodeshift/test/js-transforms/README.md mode change 100755 => 100644 types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts index b9b15be825..95a26cd0a4 100644 --- a/types/jscodeshift/index.d.ts +++ b/types/jscodeshift/index.d.ts @@ -250,7 +250,9 @@ declare module "jscodeshift/src/Collection" { declare module "jscodeshift/src/collections/Node" { import { Collection } from "jscodeshift/src/Collection"; - import { ASTNode, Type } from "recast"; + import { ASTNode, Type, NodePath } from "recast"; + + type ASTPath<N> = NodePath<N, N>; export interface TraversalMethods { /** @@ -285,7 +287,7 @@ declare module "jscodeshift/src/collections/Node" { * is provided it is executed for every node and the node is replaced with the * functions return value. */ - replaceWith<T>(nodes: T | T[] | ((path: any, i: number) => T)): this; + replaceWith<T>(nodes: T | T[] | ((path: ASTPath<N>, i: number) => T)): Collection<T>; /** * Inserts a new node before the current one. diff --git a/types/jscodeshift/test/js-transforms/README.md b/types/jscodeshift/test/js-transforms/README.md new file mode 100644 index 0000000000..f314daaa44 --- /dev/null +++ b/types/jscodeshift/test/js-transforms/README.md @@ -0,0 +1,2 @@ +Sample jscodeshift transforms taken from https://github.com/jhgg/js-transforms +and converted to TypeScript, for use as real-world test cases. diff --git a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts old mode 100755 new mode 100644 index 97248a7e35..65161f8957 --- a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts +++ b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts @@ -8,8 +8,9 @@ * let x = ::this.foo; * */ +import { Transform, MemberExpression } from "jscodeshift"; -module.exports = function (file, api) { +const transform: Transform = function (file, api) { const j = api.jscodeshift; return j(file.source) // Find stuff that looks like this.xyz.bind(this) @@ -17,6 +18,6 @@ module.exports = function (file, api) { // Ensure that .bind() is being called with only one argument, and that argument is "this". .filter(p => p.value.arguments.length == 1 && p.value.arguments[0].type == "ThisExpression") // We can now replace it with ::this.xyz - .replaceWith(p => j.bindExpression(null, p.value.callee.object)) + .replaceWith(p => j.bindExpression(null, (p.value.callee as MemberExpression).object)) .toSource(); }; \ No newline at end of file diff --git a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts index 727f2e950d..08bf424ae8 100755 --- a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts +++ b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts @@ -25,8 +25,9 @@ * var a = c => c; * */ +import { Transform, MemberExpression, FunctionExpression } from "jscodeshift"; -module.exports = function(file, api) { +const transform: Transform = function(file, api) { const j = api.jscodeshift; return j(file.source) @@ -35,16 +36,24 @@ module.exports = function(file, api) { // Verify that .bind() is only being called with `this` as it's sole arguments. .filter(p => p.value.arguments.length == 1 && p.value.arguments[0].type == "ThisExpression") .replaceWith(p => { + var callee = p.value.callee as MemberExpression; + var object = callee.object as FunctionExpression; // Grab the function body. Since we looked for the CallExpression originally, the "callee.object" would refer // to the FunctionExpression that's being called .bind(this) on. We need the body of that function // to transform into an ArrowFunctionExpression. - var body = p.value.callee.object.body; + var body = object.body; // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } - var useExpression = body.type == 'BlockStatement' && body.body.length == 1 && body.body[0].type == "ReturnStatement"; - body = useExpression ? body.body[0].argument : body; + var useExpression = false; + if (body.type == 'BlockStatement' && body.body.length == 1) { + const first = body.body[0]; + if (first.type == "ReturnStatement") { + useExpression = true; + body = first.argument!; + } + } - return j.arrowFunctionExpression(p.value.callee.object.params, body, useExpression); + return j.arrowFunctionExpression(object.params, body, useExpression); }) .toSource(); }; \ No newline at end of file diff --git a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts index fdee1a994b..ed633bc462 100755 --- a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts +++ b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts @@ -25,8 +25,9 @@ * return a + b + this.c; * } */ +import { Transform } from "jscodeshift"; -module.exports = function (file, api) { +const transform: Transform = function (file, api) { const j = api.jscodeshift; return j(file.source) @@ -38,8 +39,14 @@ module.exports = function (file, api) { var body = p.value.body; // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } - var useExpression = body.type == 'BlockStatement' && body.body.length == 1 && body.body[0].type == "ReturnStatement"; - body = useExpression ? body.body[0].argument : body; + var useExpression = false; + if (body.type == 'BlockStatement' && body.body.length == 1) { + const first = body.body[0]; + if (first.type == "ReturnStatement") { + useExpression = true; + body = first.argument!; + } + } return j.arrowFunctionExpression(p.value.params, body, useExpression); }) .toSource(); diff --git a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts index 87def91d52..81f58c5bb7 100755 --- a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts +++ b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts @@ -19,37 +19,40 @@ * } * */ +import { Transform, VariableDeclarator, ObjectPattern, Identifier, BlockStatement } from "jscodeshift"; -let keywords = 'this function if return var else for new in typeof while case break try catch delete throw switch continue default instanceof do void finally with debugger implements interface package private protected public static class enum export extends import super true false null abstract boolean byte char const double final float goto int long native short synchronized throws transient volatile'; -keywords = keywords.split(' ').reduce((f, k) => { +const keywordsStr = 'this function if return var else for new in typeof while case break try catch delete throw switch continue default instanceof do void finally with debugger implements interface package private protected public static class enum export extends import super true false null abstract boolean byte char const double final float goto int long native short synchronized throws transient volatile'; +let keywords = keywordsStr.split(' ').reduce<{ [key: string]: boolean }>((f, k) => { f[k] = true; return f; }, {}); -const isKeyword = k => keywords.hasOwnProperty(k); +const isKeyword = (k: string) => keywords.hasOwnProperty(k); -module.exports = function (file, api) { +const transform: Transform = function (file, api) { const j = api.jscodeshift; const {statement} = j.template; return j(file.source) .find(j.FunctionExpression) .replaceWith(p => { - console.log(p); + // console.log(p); const root = j(p.value); - const variablesToReplace = {}; + const variablesToReplace: { [name: string]: boolean } = {}; // Figure out if the variable was defined from props, so that we can re-use that definition. - const isFromProps = (name, resolvedScope) => { + const isFromProps = (name: string, resolvedScope: any) => { return resolvedScope.getBindings()[name].every( - p => { + (p: any) => { const decl = j(p).closest(j.VariableDeclarator); // What happens when our VariableDeclarator is too high up the parent AST? if (!decl.size()) return false; - const node = decl.nodes()[0]; + const node: VariableDeclarator = decl.nodes()[0]; - if (!(node.init.type == 'MemberExpression' && + if (!(node.init != null && + node.init.type == 'MemberExpression' && node.init.object.type == 'ThisExpression' && + node.init.property.type == 'Identifier' && node.init.property.name == 'props')) return false; @@ -74,17 +77,17 @@ module.exports = function (file, api) { } }) .filter(e => { - const resolvedScope = e.scope.lookup(e.value.property.name); + const resolvedScope = e.scope.lookup((e.value.property as Identifier).name); // If the scope is null, that means that this property isn't defined in the scope yet, // and we can use it. Otherwise, if it is defined, we should see if it was defined from `this.props` // if none of these cases are true, we can't do substitution. - return resolvedScope == null || isFromProps(e.value.property.name, resolvedScope); + return resolvedScope == null || isFromProps((e.value.property as Identifier).name, resolvedScope); }) // Ensure that our substitution won't cause us to define a keyword, i.e. `this.props.while` won't // get converted into `while`. - .filter(p => !isKeyword(p.value.property.name)) + .filter(p => !isKeyword((p.value.property as Identifier).name)) // Now, do the replacement, `this.props.xyz` => `xyz`. - .replaceWith(p => p.value.property) + .replaceWith(p => p.value.property as Identifier) // Finally, mark the variable as something we will need to define earlier in the function, // if it's not already defined. .forEach(p => { @@ -117,7 +120,8 @@ module.exports = function (file, api) { if (propDefinitions.size()) { const nodePath = propDefinitions.paths()[0]; const node = nodePath.value; - const newPattern = j.objectPattern(node.id.properties.concat(properties)); + // TODO(brieb): support narrowing based on second argument to `find` + const newPattern = j.objectPattern((node.id as ObjectPattern).properties.concat(properties)); nodePath.replace(j.variableDeclarator(newPattern, node.init)); return p.value; } @@ -130,7 +134,7 @@ module.exports = function (file, api) { return j.functionExpression( p.value.id, p.value.params, - j.blockStatement([decl].concat(p.value.body.body)) + j.blockStatement([decl].concat((p.value.body as BlockStatement).body)) ); } ).toSource(); diff --git a/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts index dd4b3bf5c2..a0ea249746 100755 --- a/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts +++ b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts @@ -27,12 +27,13 @@ * } */ +import { Transform, ASTNode } from "jscodeshift"; -module.exports = function (file, api) { +const transform: Transform = function (file, api) { const j = api.jscodeshift; const {statement} = j.template; - function hasJSXElement(ast) { + function hasJSXElement(ast: ASTNode) { return j(ast).find(j.JSXElement).size() > 0; } @@ -41,21 +42,22 @@ module.exports = function (file, api) { .filter(p => p.value.declarations.length == 1) .replaceWith(p => { const decl = p.value.declarations[0]; - if (decl.init.type !== 'ArrowFunctionExpression' || - (!hasJSXElement(decl.init.body) && decl.init.body.type !== "JSXElement")) - return p.value; + if (decl.type === "VariableDeclarator" && decl.init != null) { + if (decl.init.type !== 'ArrowFunctionExpression' || + (!hasJSXElement(decl.init.body) && decl.init.body.type !== "JSXElement")) + return p.value; - let body = decl.init.body; - body = body.type == "JSXElement" ? j.returnStatement(body) : body = body.body; + let body: any = decl.init.body; + body = body.type == "JSXElement" ? j.returnStatement(body) : body = body.body; - j(body) - .find(j.Identifier, {name: 'props'}) - .replaceWith(p => j.memberExpression(j.thisExpression(), j.identifier('props'))); - - return statement`class ${decl.id} extends Component { - render() { ${body} } - }`; + j(body) + .find(j.Identifier, {name: 'props'}) + .replaceWith(p => j.memberExpression(j.thisExpression(), j.identifier('props'))); + return statement`class ${decl.id} extends Component { + render() { ${body} } + }`; + } }) .toSource(); }; From 60cec9121ecac6b8cc705f51056076c01980ae90 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 17:15:44 -0800 Subject: [PATCH 031/197] [jscodeshift] Fix lint violations in test/js-transforms --- .../bind-this-to-bind-expression.ts | 6 ++--- ...-bind-this-to-arrow-function-expression.ts | 23 ++++++++++--------- ...expression-to-arrow-function-expression.ts | 14 +++++------ .../js-transforms/props-to-destructuring.ts | 23 ++++++++++--------- .../pure-to-composite-component.ts | 11 +++++---- 5 files changed, 40 insertions(+), 37 deletions(-) diff --git a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts index 65161f8957..6bd9be1fc8 100644 --- a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts +++ b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts @@ -10,14 +10,14 @@ */ import { Transform, MemberExpression } from "jscodeshift"; -const transform: Transform = function (file, api) { +const transform: Transform = (file, api) => { const j = api.jscodeshift; return j(file.source) // Find stuff that looks like this.xyz.bind(this) .find(j.CallExpression, {callee: {object: {object: j.ThisExpression}, property: {name: 'bind'}}}) // Ensure that .bind() is being called with only one argument, and that argument is "this". - .filter(p => p.value.arguments.length == 1 && p.value.arguments[0].type == "ThisExpression") + .filter(p => p.value.arguments.length === 1 && p.value.arguments[0].type === "ThisExpression") // We can now replace it with ::this.xyz .replaceWith(p => j.bindExpression(null, (p.value.callee as MemberExpression).object)) .toSource(); -}; \ No newline at end of file +}; diff --git a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts index 08bf424ae8..cfe672436e 100755 --- a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts +++ b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts @@ -1,4 +1,5 @@ -/** Converts +/** + * Converts * onClick(function(a, b) { * return a + b; * }.bind(this), @@ -13,7 +14,7 @@ * * var a = function(c) { return c; }.bind(this); * - ** to + * to * onClick((a, b) => a + b, * (b, c) => 1); * @@ -27,27 +28,27 @@ */ import { Transform, MemberExpression, FunctionExpression } from "jscodeshift"; -const transform: Transform = function(file, api) { +const transform: Transform = (file, api) => { const j = api.jscodeshift; return j(file.source) // We're looking for a CallExpression that's calling .bind() onto a FunctionExpression. .find(j.CallExpression, {callee: {property: {name: 'bind'}, object: {type: 'FunctionExpression'}}}) // Verify that .bind() is only being called with `this` as it's sole arguments. - .filter(p => p.value.arguments.length == 1 && p.value.arguments[0].type == "ThisExpression") + .filter(p => p.value.arguments.length === 1 && p.value.arguments[0].type === "ThisExpression") .replaceWith(p => { - var callee = p.value.callee as MemberExpression; - var object = callee.object as FunctionExpression; + const callee = p.value.callee as MemberExpression; + const object = callee.object as FunctionExpression; // Grab the function body. Since we looked for the CallExpression originally, the "callee.object" would refer // to the FunctionExpression that's being called .bind(this) on. We need the body of that function // to transform into an ArrowFunctionExpression. - var body = object.body; + let body = object.body; // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } - var useExpression = false; - if (body.type == 'BlockStatement' && body.body.length == 1) { + let useExpression = false; + if (body.type === 'BlockStatement' && body.body.length === 1) { const first = body.body[0]; - if (first.type == "ReturnStatement") { + if (first.type === "ReturnStatement") { useExpression = true; body = first.argument!; } @@ -56,4 +57,4 @@ const transform: Transform = function(file, api) { return j.arrowFunctionExpression(object.params, body, useExpression); }) .toSource(); -}; \ No newline at end of file +}; diff --git a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts index ed633bc462..5a1b50dc6b 100755 --- a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts +++ b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts @@ -13,7 +13,7 @@ * var a = function(a, b) { * return a + b + this.c; * } - ** + * * var a = (a, b) => a + b * * var b = (a, b) => { @@ -27,22 +27,22 @@ */ import { Transform } from "jscodeshift"; -const transform: Transform = function (file, api) { +const transform: Transform = (file, api) => { const j = api.jscodeshift; return j(file.source) .find(j.FunctionExpression) // We check for this expression, as if it's in a function expression, we don't want to re-bind "this" by // using the arrowFunctionExpression. As that could potentially have some unintended consequences. - .filter(p => j(p).find(j.ThisExpression).size() == 0) + .filter(p => j(p).find(j.ThisExpression).size() === 0) .replaceWith(p => { - var body = p.value.body; + let body = p.value.body; // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } - var useExpression = false; - if (body.type == 'BlockStatement' && body.body.length == 1) { + let useExpression = false; + if (body.type === 'BlockStatement' && body.body.length === 1) { const first = body.body[0]; - if (first.type == "ReturnStatement") { + if (first.type === "ReturnStatement") { useExpression = true; body = first.argument!; } diff --git a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts index 81f58c5bb7..6db8fe49dd 100755 --- a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts +++ b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts @@ -5,7 +5,8 @@ * return <div foo={this.props.foo} bar={this.props.bar} /> * } * } - *** To: + * + * To: * * class C extends React.Component() { * render() { @@ -21,14 +22,15 @@ */ import { Transform, VariableDeclarator, ObjectPattern, Identifier, BlockStatement } from "jscodeshift"; +// tslint:disable-next-line max-line-length const keywordsStr = 'this function if return var else for new in typeof while case break try catch delete throw switch continue default instanceof do void finally with debugger implements interface package private protected public static class enum export extends import super true false null abstract boolean byte char const double final float goto int long native short synchronized throws transient volatile'; -let keywords = keywordsStr.split(' ').reduce<{ [key: string]: boolean }>((f, k) => { +const keywords = keywordsStr.split(' ').reduce<{ [key: string]: boolean }>((f, k) => { f[k] = true; return f; }, {}); const isKeyword = (k: string) => keywords.hasOwnProperty(k); -const transform: Transform = function (file, api) { +const transform: Transform = (file, api) => { const j = api.jscodeshift; const {statement} = j.template; @@ -50,15 +52,15 @@ const transform: Transform = function (file, api) { const node: VariableDeclarator = decl.nodes()[0]; if (!(node.init != null && - node.init.type == 'MemberExpression' && - node.init.object.type == 'ThisExpression' && - node.init.property.type == 'Identifier' && - node.init.property.name == 'props')) + node.init.type === 'MemberExpression' && + node.init.object.type === 'ThisExpression' && + node.init.property.type === 'Identifier' && + node.init.property.name === 'props')) return false; // Check for the case where it could be aliased (i.e.) { baz: foo } = this.props; // In this case, we won't do a substitution. - if (p.parentPath.value.type == 'Property' && p.parentPath.value.key.name !== name) + if (p.parentPath.value.type === 'Property' && p.parentPath.value.key.name !== name) return false; return true; @@ -81,10 +83,10 @@ const transform: Transform = function (file, api) { // If the scope is null, that means that this property isn't defined in the scope yet, // and we can use it. Otherwise, if it is defined, we should see if it was defined from `this.props` // if none of these cases are true, we can't do substitution. - return resolvedScope == null || isFromProps((e.value.property as Identifier).name, resolvedScope); + return resolvedScope === null || isFromProps((e.value.property as Identifier).name, resolvedScope); }) // Ensure that our substitution won't cause us to define a keyword, i.e. `this.props.while` won't - // get converted into `while`. + // get converted into `while`. .filter(p => !isKeyword((p.value.property as Identifier).name)) // Now, do the replacement, `this.props.xyz` => `xyz`. .replaceWith(p => p.value.property as Identifier) @@ -96,7 +98,6 @@ const transform: Transform = function (file, api) { variablesToReplace[p.value.name] = true; }); - // Create property definitions for variables that we've replaced. const properties = Object.keys(variablesToReplace) .sort() diff --git a/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts index a0ea249746..6d1a30c378 100755 --- a/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts +++ b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts @@ -1,5 +1,6 @@ -/** For when you've gone too pure and want to go back. **/ -/** Converts +/** For when you've gone too pure and want to go back. */ +/** + * Converts * let HistoryItem = (props) => { * const { * item @@ -29,7 +30,7 @@ import { Transform, ASTNode } from "jscodeshift"; -const transform: Transform = function (file, api) { +const transform: Transform = (file, api) => { const j = api.jscodeshift; const {statement} = j.template; @@ -39,7 +40,7 @@ const transform: Transform = function (file, api) { return j(file.source) .find(j.VariableDeclaration) - .filter(p => p.value.declarations.length == 1) + .filter(p => p.value.declarations.length === 1) .replaceWith(p => { const decl = p.value.declarations[0]; if (decl.type === "VariableDeclarator" && decl.init != null) { @@ -48,7 +49,7 @@ const transform: Transform = function (file, api) { return p.value; let body: any = decl.init.body; - body = body.type == "JSXElement" ? j.returnStatement(body) : body = body.body; + body = body.type === "JSXElement" ? j.returnStatement(body) : body = body.body; j(body) .find(j.Identifier, {name: 'props'}) From 4162211dcc844212a7b7a4282a602b1f6fab0f32 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 9 Jan 2019 17:47:26 -0800 Subject: [PATCH 032/197] [jscodeshift] In tsconfig, don't use "include", must use "files" --- ...-expression-bind-this-to-arrow-function-expression.ts | 0 .../function-expression-to-arrow-function-expression.ts | 0 .../test/js-transforms/props-to-destructuring.ts | 0 .../test/js-transforms/pure-to-composite-component.ts | 0 types/jscodeshift/tsconfig.json | 9 +++++++-- 5 files changed, 7 insertions(+), 2 deletions(-) mode change 100755 => 100644 types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts mode change 100755 => 100644 types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts mode change 100755 => 100644 types/jscodeshift/test/js-transforms/props-to-destructuring.ts mode change 100755 => 100644 types/jscodeshift/test/js-transforms/pure-to-composite-component.ts diff --git a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts old mode 100755 new mode 100644 diff --git a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts old mode 100755 new mode 100644 diff --git a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts old mode 100755 new mode 100644 diff --git a/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts old mode 100755 new mode 100644 diff --git a/types/jscodeshift/tsconfig.json b/types/jscodeshift/tsconfig.json index c5f4e65e59..8ad162be32 100644 --- a/types/jscodeshift/tsconfig.json +++ b/types/jscodeshift/tsconfig.json @@ -16,8 +16,13 @@ "noEmit": true, "forceConsistentCasingInFileNames": true }, - "include": [ + "files": [ "index.d.ts", - "test" + "test/jscodeshift-tests.ts", + "test/js-transforms/bind-this-to-bind-expression.ts", + "test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts", + "test/js-transforms/function-expression-to-arrow-function-expression.ts", + "test/js-transforms/props-to-destructuring.ts", + "test/js-transforms/pure-to-composite-component.ts" ] } From 5a750fd73fbc5f673054c25a2615fdbbf072db45 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Mon, 28 Jan 2019 21:44:19 -0800 Subject: [PATCH 033/197] [jscodeshift] Update ast-types to 0.12.1 and recast to 0.17.2 --- types/jscodeshift/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/jscodeshift/package.json b/types/jscodeshift/package.json index 65d03a5a7f..6fd3d8b70f 100644 --- a/types/jscodeshift/package.json +++ b/types/jscodeshift/package.json @@ -1,7 +1,7 @@ { "private": true, "dependencies": { - "ast-types": "^0.12.0", - "recast": "^0.17.0" + "ast-types": "^0.12.1", + "recast": "^0.17.2" } } From 5fd8f52edf25db7a902cd13658b8b47472fa0df1 Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.fr> Date: Tue, 29 Jan 2019 07:05:37 +0100 Subject: [PATCH 034/197] added tests for default import --- types/debug/debug-tests.ts | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/types/debug/debug-tests.ts b/types/debug/debug-tests.ts index 22ac083a14..b1356f08f9 100644 --- a/types/debug/debug-tests.ts +++ b/types/debug/debug-tests.ts @@ -1,24 +1,31 @@ -import debug = require("debug"); +import * as debug1 from "debug"; -debug.disable(); -debug.enable("DefinitelyTyped:*"); +import debug2 from 'debug'; -const log: debug.Debugger = debug("DefinitelyTyped:log"); +const log2:debug1.Debugger = debug2("DefinitelyTyped:log"); +log2("Just text"); +log2("Formatted test (%d arg)", 1); +log2("Formatted %s (%d args)", "test", 2); + +debug1.disable(); +debug1.enable("DefinitelyTyped:*"); + +const log: debug1.Debugger = debug1("DefinitelyTyped:log"); log("Just text"); log("Formatted test (%d arg)", 1); log("Formatted %s (%d args)", "test", 2); -log("Enabled?: %s", debug.enabled("DefinitelyTyped:log")); -log("Name Enabled: %s", debug.names.some(name => name.test("DefinitelyTyped:log"))); +log("Enabled?: %s", debug1.enabled("DefinitelyTyped:log")); +log("Name Enabled: %s", debug1.names.some(name => name.test("DefinitelyTyped:log"))); log("Namespace: %s", log.namespace); -const error: debug.Debugger = debug("DefinitelyTyped:error"); +const error: debug1.Debugger = debug1("DefinitelyTyped:error"); error.log = console.error.bind(console); error("This should be printed to stderr"); -const extendedLog: debug.Debugger = log.extend('extended'); +const extendedLog: debug1.Debugger = log.extend('extended'); extendedLog("Testing this is also an IDebugger."); -const extendedWithCustomDelimiter: debug.Debugger = log.extend('with-delim', '.'); +const extendedWithCustomDelimiter: debug1.Debugger = log.extend('with-delim', '.'); extendedWithCustomDelimiter("Testing this is an IDebugger, too."); From f3e79d7ac831cf8826a541b12f72025dd097ac77 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Mon, 28 Jan 2019 21:46:09 -0800 Subject: [PATCH 035/197] [jscodeshift] Fix TSC errors and DTS lints --- .../call-expression-bind-this-to-arrow-function-expression.ts | 4 ++-- .../function-expression-to-arrow-function-expression.ts | 4 ++-- .../jscodeshift/test/js-transforms/props-to-destructuring.ts | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts index cfe672436e..09cdf3f29e 100644 --- a/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts +++ b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts @@ -26,7 +26,7 @@ * var a = c => c; * */ -import { Transform, MemberExpression, FunctionExpression } from "jscodeshift"; +import { Transform, MemberExpression, FunctionExpression, ArrowFunctionExpression } from "jscodeshift"; const transform: Transform = (file, api) => { const j = api.jscodeshift; @@ -42,7 +42,7 @@ const transform: Transform = (file, api) => { // Grab the function body. Since we looked for the CallExpression originally, the "callee.object" would refer // to the FunctionExpression that's being called .bind(this) on. We need the body of that function // to transform into an ArrowFunctionExpression. - let body = object.body; + let body: ArrowFunctionExpression['body'] = object.body; // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } let useExpression = false; diff --git a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts index 5a1b50dc6b..b960c920cd 100644 --- a/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts +++ b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts @@ -25,7 +25,7 @@ * return a + b + this.c; * } */ -import { Transform } from "jscodeshift"; +import { Transform, ArrowFunctionExpression } from "jscodeshift"; const transform: Transform = (file, api) => { const j = api.jscodeshift; @@ -36,7 +36,7 @@ const transform: Transform = (file, api) => { // using the arrowFunctionExpression. As that could potentially have some unintended consequences. .filter(p => j(p).find(j.ThisExpression).size() === 0) .replaceWith(p => { - let body = p.value.body; + let body: ArrowFunctionExpression['body'] = p.value.body; // We can get a bit clever here. If we have a function that consists of a single return statement in it's body, // we can transform it to the more compact arrowFunctionExpression (a, b) => a + b, vs (a + b) => { return a + b } let useExpression = false; diff --git a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts index 6db8fe49dd..138d61a620 100644 --- a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts +++ b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts @@ -135,7 +135,7 @@ const transform: Transform = (file, api) => { return j.functionExpression( p.value.id, p.value.params, - j.blockStatement([decl].concat((p.value.body as BlockStatement).body)) + j.blockStatement([decl].concat(p.value.body.body)) ); } ).toSource(); From fe1cfc230b236688db14f184197e544db59c066a Mon Sep 17 00:00:00 2001 From: Frank Wallis <frank@weareadaptive.com> Date: Mon, 28 Jan 2019 19:07:09 +0000 Subject: [PATCH 036/197] update react-datepicker typings to use class instead of const and expose instance methods --- types/react-datepicker/index.d.ts | 9 ++++++++- types/react-datepicker/react-datepicker-tests.tsx | 13 ++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/types/react-datepicker/index.d.ts b/types/react-datepicker/index.d.ts index e2870092dc..4ba65f420e 100644 --- a/types/react-datepicker/index.d.ts +++ b/types/react-datepicker/index.d.ts @@ -127,5 +127,12 @@ export interface ReactDatePickerProps { withPortal?: boolean; yearDropdownItemNumber?: number; } -declare const ReactDatePicker: React.ClassicComponentClass<ReactDatePickerProps>; + +declare class ReactDatePicker extends React.Component<ReactDatePickerProps> { + readonly setBlur: () => void; + readonly setFocus: () => void; + readonly setOpen: (open: boolean) => void; + readonly isCalendarOpen: () => boolean; +} + export default ReactDatePicker; diff --git a/types/react-datepicker/react-datepicker-tests.tsx b/types/react-datepicker/react-datepicker-tests.tsx index 5e913be496..9486d043eb 100644 --- a/types/react-datepicker/react-datepicker-tests.tsx +++ b/types/react-datepicker/react-datepicker-tests.tsx @@ -76,7 +76,8 @@ const defaultLocale = getDefaultLocale(); popperProps={{}} preventOpenOnFocus previousMonthButtonLabel="" - readOnly + readOnly + ref={handleRef} renderCustomHeader={({ date, changeYear, @@ -119,3 +120,13 @@ const defaultLocale = getDefaultLocale(); <div /> <span /> </DatePicker>; + +function handleRef(ref: DatePicker | null) { + if (ref) { + ref.setBlur(); + ref.setFocus(); + if (ref.isCalendarOpen()) { + ref.setOpen(false); + } + } +} From 86ed80563e7a0256cabe7162f78624013443820e Mon Sep 17 00:00:00 2001 From: Nicolas Penin <nicolas.penin@dragon-angel.fr> Date: Tue, 29 Jan 2019 11:10:47 +0100 Subject: [PATCH 037/197] fixed tslint issues --- types/debug/debug-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/debug/debug-tests.ts b/types/debug/debug-tests.ts index b1356f08f9..92d6f5eb8e 100644 --- a/types/debug/debug-tests.ts +++ b/types/debug/debug-tests.ts @@ -1,8 +1,8 @@ import * as debug1 from "debug"; - +/*tslint:disable-next-line:no-duplicate-imports*/ import debug2 from 'debug'; -const log2:debug1.Debugger = debug2("DefinitelyTyped:log"); +const log2: debug1.Debugger = debug2("DefinitelyTyped:log"); log2("Just text"); log2("Formatted test (%d arg)", 1); log2("Formatted %s (%d args)", "test", 2); From 556fe818a8bd84bc0ac5bcedc52f06268dc83ac2 Mon Sep 17 00:00:00 2001 From: Dave Cardwell <hello@davecardwell.com> Date: Tue, 29 Jan 2019 11:59:28 -0500 Subject: [PATCH 038/197] [webpack-dev-server] Add writeToDisk configuration https://github.com/webpack/webpack-dev-server/releases/tag/v3.1.10 https://webpack.js.org/configuration/dev-server/#devserver-writetodisk- --- types/webpack-dev-server/index.d.ts | 3 +++ types/webpack-dev-server/webpack-dev-server-tests.ts | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/types/webpack-dev-server/index.d.ts b/types/webpack-dev-server/index.d.ts index 48abc9a44c..30fd2482e7 100644 --- a/types/webpack-dev-server/index.d.ts +++ b/types/webpack-dev-server/index.d.ts @@ -5,6 +5,7 @@ // Zheyang Song <https://github.com/ZheyangSong> // Alan Agius <https://github.com/alan-agius4> // Artur Androsovych <https://github.com/arturovt> +// Dave Cardwell <https://github.com/davecardwell> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -165,6 +166,8 @@ declare namespace WebpackDevServer { watchContentBase?: boolean; /** Control options related to watching the files. */ watchOptions?: webpack.WatchOptions; + /** Tells devServer to write generated assets to the disk. */ + writeToDisk?: boolean | ((filePath: string) => boolean); } } diff --git a/types/webpack-dev-server/webpack-dev-server-tests.ts b/types/webpack-dev-server/webpack-dev-server-tests.ts index f570dd134e..755245b035 100644 --- a/types/webpack-dev-server/webpack-dev-server-tests.ts +++ b/types/webpack-dev-server/webpack-dev-server-tests.ts @@ -72,6 +72,7 @@ const config: WebpackDevServer.Configuration = { aggregateTimeout: 300, poll: 1000 }, + writeToDisk: true, // It's a required option. publicPath: "/assets/", headers: { "X-Custom-Header": "yes" } @@ -83,6 +84,9 @@ const c2: WebpackDevServer.Configuration = { const c3: WebpackDevServer.Configuration = { stats: "verbose", }; +const c4: WebpackDevServer.Configuration = { + writeToDisk: (filePath: string) => true, +}; // API example server = new WebpackDevServer(compiler, config); From ec53d243ab29017137f070c9f70104fc6d001768 Mon Sep 17 00:00:00 2001 From: JPMaheux <jpmaheux@arcbees.com> Date: Wed, 30 Jan 2019 15:28:53 -0500 Subject: [PATCH 039/197] fix: added scrollEnabled property --- types/react-native-modal-dropdown/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react-native-modal-dropdown/index.d.ts b/types/react-native-modal-dropdown/index.d.ts index 01470ec1cf..01e5dcf30b 100644 --- a/types/react-native-modal-dropdown/index.d.ts +++ b/types/react-native-modal-dropdown/index.d.ts @@ -21,6 +21,7 @@ declare namespace RNModalDropdown { defaultValue?: string; options?: any[]; animated?: boolean; + scrollEnabled?: boolean; showsVerticalScrollIndicator?: boolean; style?: any; textStyle?: any; From 828f081238d78f06c9aa38030b064407c7bee072 Mon Sep 17 00:00:00 2001 From: denis <denisname@users.noreply.github.com> Date: Thu, 31 Jan 2019 15:07:01 +0100 Subject: [PATCH 040/197] Update to 1.2 Add iterations argument to `simulation.tick`. --- types/d3-force/d3-force-tests.ts | 1 + types/d3-force/index.d.ts | 14 ++++++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/types/d3-force/d3-force-tests.ts b/types/d3-force/d3-force-tests.ts index 6b73a1dbf4..9bf424c1b6 100644 --- a/types/d3-force/d3-force-tests.ts +++ b/types/d3-force/d3-force-tests.ts @@ -685,6 +685,7 @@ nodeLinkSimulation = nodeLinkSimulation.stop(); // tick() ----------------------------------------------------------------------------- nodeLinkSimulation.tick(); +nodeLinkSimulation.tick(10); // find() ----------------------------------------------------------------------------- diff --git a/types/d3-force/index.d.ts b/types/d3-force/index.d.ts index 35f4d06657..98f372e2cc 100644 --- a/types/d3-force/index.d.ts +++ b/types/d3-force/index.d.ts @@ -1,9 +1,12 @@ // Type definitions for D3JS d3-force module 1.1 // Project: https://github.com/d3/d3-force/ -// Definitions by: Tom Wanzek <https://github.com/tomwanzek>, Alex Ford <https://github.com/gustavderdrache>, Boris Yankov <https://github.com/borisyankov> +// Definitions by: Tom Wanzek <https://github.com/tomwanzek> +// Alex Ford <https://github.com/gustavderdrache> +// Boris Yankov <https://github.com/borisyankov> +// denisname <https://github.com/denisname> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.1.0 +// Last module patch version validated against: 1.2.0 // ----------------------------------------------------------------------- // Force Simulation @@ -108,13 +111,16 @@ export interface Simulation<NodeDatum extends SimulationNodeDatum, LinkDatum ext stop(): this; /** - * Increments the current alpha by (alphaTarget - alpha) × alphaDecay; then invokes each registered force, passing the new alpha; + * Manually steps the simulation by the specified number of *iterations*, and returns the simulation. If *iterations* is not specified, it defaults to 1 (single step). + * + * For each iteration, it increments the current alpha by (alphaTarget - alpha) × alphaDecay; then invokes each registered force, passing the new alpha; * then decrements each node’s velocity by velocity × velocityDecay; lastly increments each node’s position by velocity. + * * This method does not dispatch events; events are only dispatched by the internal timer when the simulation is started automatically upon * creation or by calling simulation.restart. The natural number of ticks when the simulation is started is * ⌈log(alphaMin) / log(1 - alphaDecay)⌉; by default, this is 300. */ - tick(): void; + tick(iterations?: number): void; /** * Returns the simulation’s array of nodes as specified to the constructor. From 66001ee7644cbbc4101265cbb4be96a730114fb0 Mon Sep 17 00:00:00 2001 From: Anton Astashov <aastashov@indeed.com> Date: Thu, 31 Jan 2019 09:03:56 -0600 Subject: [PATCH 041/197] [@types/koa-compose]: Provide way for typesafe compose Right now it's impossible to compose a bunch of middlewares, and preserve their state/context type. It will be either erased and converted to `any`, or will show an error. For example, we have 3 middlewares: ```ts type FooCtx = { foo: string }; type BarCtx = { bar: string }; type WooCtx = { woo: string }; const fooMiddleware: Koa.Middleware<FooCtx, {}> = async (ctx, next) => { ctx.state.foo = 'foo'; await next(); }; const barMiddleware: Koa.Middleware<BarCtx, {}> = async (ctx, next) => { ctx.state.bar = 'bar'; await next(); }; const wooMiddleware: Koa.Middleware<WooCtx, {}> = async (ctx, next) => { ctx.state.woo = 'woo'; await next(); }; ``` If we try to compose them together, we'll get an error: ```ts const composed = compose([fooMiddleware, barMiddleware, wooMiddleware]); // types of params context and context are incompatible // Type ParameterizedContext<FooCtx, {}> is not assignable to // ParameterizedContext<BarCtx, {}> ``` We can shut it up by providing `<any>` type parameter, but that will erase their types: ```ts const composed = compose<any>([fooMiddleware, barMiddleware, wooMiddleware]); // `composed` type is `compose.ComposedMiddleware<any>`. ``` As a solution, I don't think there's a way to do typesafe `compose` for variable number of middlewares, but we can overload `compose` and make a typesafe one for 2 middlewares. You can then compose `compose`s to compose more than 2 middleares :) Like, instead of: ```ts compose([fooMiddleware, barMiddleware, wooMiddleware]) ``` It will be: ```ts compose([fooMiddleware, compose([barMiddleware, wooMiddleware])) // `composed` type is `Middleware<ParameterizedContext<FooCtx & BarCtx & WooCtx, {}>` ``` What do you think? --- types/koa-compose/index.d.ts | 7 +++++ types/koa-compose/koa-compose-tests.ts | 38 ++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/types/koa-compose/index.d.ts b/types/koa-compose/index.d.ts index 88047abcc9..f35b9ca208 100644 --- a/types/koa-compose/index.d.ts +++ b/types/koa-compose/index.d.ts @@ -2,6 +2,13 @@ // Project: https://github.com/koajs/compose // Definitions by: jKey Lu <https://github.com/jkeylu> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as Koa from "koa"; + +declare function compose<T, U, V, W>( + middleware: [Koa.Middleware<T, U>, Koa.Middleware<V, W>] +): Koa.Middleware<T & V, U & W>; declare function compose<T>(middleware: Array<compose.Middleware<T>>): compose.ComposedMiddleware<T>; diff --git a/types/koa-compose/koa-compose-tests.ts b/types/koa-compose/koa-compose-tests.ts index ed1c705e5d..56b105e900 100644 --- a/types/koa-compose/koa-compose-tests.ts +++ b/types/koa-compose/koa-compose-tests.ts @@ -1,4 +1,5 @@ import compose = require('koa-compose'); +import * as Koa from "koa"; const fn1: compose.Middleware<any> = (context: any, next: () => Promise<void>): Promise<any> => Promise @@ -11,3 +12,40 @@ const fn2: compose.Middleware<any> = (context: any, next: () => Promise<void>): .then(next); const fn = compose([fn1, fn2]); + +interface FooCtx { + foo: string; +} + +const fooMiddleware: Koa.Middleware<FooCtx> = async (ctx, next) => { + ctx.state.foo = "foo"; + await next(); +}; + +interface BarCtx { + bar: string; +} + +const barMiddleware: Koa.Middleware<BarCtx> = async (ctx, next) => { + ctx.state.bar = "bar"; + await next(); +}; + +interface WooCtx { + woo: string; +} + +const wooMiddleware: Koa.Middleware<WooCtx> = async (ctx, next) => { + ctx.state.woo = "woo"; + await next(); +}; + +new Koa<{}, {}>() + .use(compose([compose([fooMiddleware, barMiddleware]), wooMiddleware])) + .use(async (ctx, next) => { + ctx.state.foo; + ctx.state.bar; + ctx.state.woo; + ctx.body = "Something"; + await next(); + }); From d83588bc8f4382187208b7f42f3edf501acec8f9 Mon Sep 17 00:00:00 2001 From: denis <denisname@users.noreply.github.com> Date: Thu, 31 Jan 2019 21:52:59 +0100 Subject: [PATCH 042/197] Update version in definition header --- types/d3-force/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/d3-force/index.d.ts b/types/d3-force/index.d.ts index 98f372e2cc..563ca925c3 100644 --- a/types/d3-force/index.d.ts +++ b/types/d3-force/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3-force module 1.1 +// Type definitions for D3JS d3-force module 1.2 // Project: https://github.com/d3/d3-force/ // Definitions by: Tom Wanzek <https://github.com/tomwanzek> // Alex Ford <https://github.com/gustavderdrache> From 2eb3ca741dbb6ec79af53d0def5c409da43a2dd2 Mon Sep 17 00:00:00 2001 From: Krantisinh Deshmukh <krantisinh@monjin.com> Date: Fri, 1 Feb 2019 10:32:21 +0530 Subject: [PATCH 043/197] [Ramda] - Added type definition for R.move --- types/ramda/es/move.d.ts | 2 ++ types/ramda/index.d.ts | 8 ++++++++ types/ramda/ramda-tests.ts | 17 +++++++++++++++++ 3 files changed, 27 insertions(+) create mode 100644 types/ramda/es/move.d.ts diff --git a/types/ramda/es/move.d.ts b/types/ramda/es/move.d.ts new file mode 100644 index 0000000000..3df4ee626e --- /dev/null +++ b/types/ramda/es/move.d.ts @@ -0,0 +1,2 @@ +import { move } from '../index'; +export default move; diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index d84c148d96..a35b2612ee 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -26,6 +26,7 @@ // Drew Wyatt <https://github.com/drewwyatt> // John Ottenlips <https://github.com/jottenlips> // Nitesh Phadatare <https://github.com/minitesh> +// Krantisinh Deshmukh <https://github.com/krantisinh> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -163,6 +164,7 @@ /// <reference path="./es/minBy.d.ts" /> /// <reference path="./es/min.d.ts" /> /// <reference path="./es/modulo.d.ts" /> +/// <reference path="./es/move.d.ts" /> /// <reference path="./es/multiply.d.ts" /> /// <reference path="./es/nAry.d.ts" /> /// <reference path="./es/negate.d.ts" /> @@ -1575,6 +1577,12 @@ declare namespace R { multiply(a: number, b: number): number; multiply(a: number): (b: number) => number; + /** + * Moves an item, at index `from`, to index `to`, in a list of elements. + * A new list will be created containing the new elements order. + */ + move: CurriedFunction3<number, number, any[], any[]>; + /** * Wraps a function of any arity (including nullary) in a function that accepts exactly n parameters. * Any extraneous parameters will not be passed to the supplied function. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index c67ef3944d..abc7b60775 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -2762,3 +2762,20 @@ class Why { () => { R.bind(console.log, console); }; + +() => { + const sampleList = ['a', 'b', 'c', 'd', 'e', 'f']; + + R.move(0, 2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + R.move(-1, 0, sampleList); // => ['f', 'a', 'b', 'c', 'd', 'e'] list rotation + + const moveCurried1 = R.move(0, 2); + moveCurried1(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + + const moveCurried2 = R.move(0); + moveCurried2(2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + + const moveCurried3 = R.move(0); + const moveCurried4 = moveCurried3(2); + moveCurried4(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] +}; From fe88e628b899dec72ef84ff5255aa4a607b65953 Mon Sep 17 00:00:00 2001 From: Krantisinh Deshmukh <krantisinh@monjin.com> Date: Fri, 1 Feb 2019 12:36:10 +0530 Subject: [PATCH 044/197] [RAMDA] - Moved tests to list category. --- types/ramda/ramda-tests.ts | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index abc7b60775..87c4c7a099 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -1115,6 +1115,23 @@ interface Obj { R.addIndex(R.map)(squareEnds)([8, 5, 3, 0, 9]); // => [64, 5, 3, 0, 81] }; +() => { + const sampleList = ['a', 'b', 'c', 'd', 'e', 'f']; + + R.move(0, 2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + R.move(-1, 0, sampleList); // => ['f', 'a', 'b', 'c', 'd', 'e'] list rotation + + const moveCurried1 = R.move(0, 2); + moveCurried1(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + + const moveCurried2 = R.move(0); + moveCurried2(2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + + const moveCurried3 = R.move(0); + const moveCurried4 = moveCurried3(2); + moveCurried4(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] +}; + () => { R.none(R.isNaN, [1, 2, 3]); // => true R.none(R.isNaN, [1, 2, 3, NaN]); // => false @@ -2762,20 +2779,3 @@ class Why { () => { R.bind(console.log, console); }; - -() => { - const sampleList = ['a', 'b', 'c', 'd', 'e', 'f']; - - R.move(0, 2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] - R.move(-1, 0, sampleList); // => ['f', 'a', 'b', 'c', 'd', 'e'] list rotation - - const moveCurried1 = R.move(0, 2); - moveCurried1(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] - - const moveCurried2 = R.move(0); - moveCurried2(2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] - - const moveCurried3 = R.move(0); - const moveCurried4 = moveCurried3(2); - moveCurried4(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] -}; From 50e5bfc5a78579214d452d71f741bf57a36ee5c7 Mon Sep 17 00:00:00 2001 From: Tobias Gimpel <gimpel@pisa.hom> Date: Fri, 1 Feb 2019 11:56:50 +0100 Subject: [PATCH 045/197] Added types for cordova-plugin-background-download --- ...ordova-plugin-background-download-tests.ts | 25 +++++ .../index.d.ts | 92 +++++++++++++++++++ .../tsconfig.json | 24 +++++ .../tslint.json | 3 + 4 files changed, 144 insertions(+) create mode 100644 types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts create mode 100644 types/cordova-plugin-background-download/index.d.ts create mode 100644 types/cordova-plugin-background-download/tsconfig.json create mode 100644 types/cordova-plugin-background-download/tslint.json diff --git a/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts b/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts new file mode 100644 index 0000000000..3db8c9a4b4 --- /dev/null +++ b/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts @@ -0,0 +1,25 @@ + var fileName = "PointerEventsCordovaPlugin.wmv", + uriString = "http://media.ch9.ms/ch9/8c03/f4fe2512-59e5-4a07-bded-124b06ac8c03/PointerEventsCordovaPlugin.wmv"; + + // open target file for download + window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) { + fileSystem.root.getFile(fileName, { create: true }, function (targetFile) { + + // plugin callbacks to track operation execution status and progress + var onSuccess = function() { + console.log('Done'); + }; + var onError = function (err) { + console.log(err); + }; + var onProgress = function(progress) { + console.log((100 * progress.bytesReceived / progress.totalBytesToReceive) + '%'); + }; + + var downloader = new BackgroundTransfer.BackgroundDownloader(); + // Create a new download operation. + var download = downloader.createDownload(uriString, targetFile); + // Start the download and persist the promise to be able to cancel the download. + app.downloadPromise = download.startAsync().then(onSuccess, onError, onProgress); + }); + }); \ No newline at end of file diff --git a/types/cordova-plugin-background-download/index.d.ts b/types/cordova-plugin-background-download/index.d.ts new file mode 100644 index 0000000000..5a3319ce8e --- /dev/null +++ b/types/cordova-plugin-background-download/index.d.ts @@ -0,0 +1,92 @@ +// Type definitions for cordova-plugin-background-download 0.5.0 +// Project: https://github.com/sgrebnov/cordova-plugin-background-download +// Definitions by: Tobias Gimpel <https://github.com/mrbullfinsh> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.2.2 + +/** + * Provides an advanced file transfer functionality that persists beyond app termination and + * runs in the background. Background transfer doesn't support concurrent downloads of the same uri. + */ +declare var BackgroundTransfer: IBackgroundTransfer; +declare interface IBackgroundTransfer { + BackgroundDownloader: typeof BackgroundDownloader; +} + +declare class BackgroundDownloader { + /** + * Initializes a new instance of BackgroundDownloader object. + * Used to configure downloads prior to the actual creation of the download operation using CreateDownload. + * + * @param {string} uriMatcher The regexp to compare location of the resources with already downloading ones. + */ + constructor(uriMatcher?: RegExp); + /** + * Initializes a DownloadOperation object that contains the specified Uri and the file that the response is written to. + * + * @param {string} uri The location of the resource. + * @param {File} resultFile The file that the response will be written to. + * @param {string} notificationTitle The title for downloading in notification. + */ + createDownload(uri: string, resultFile: File, notificationTitle?: string): DownloadOperation; +} + +declare class DownloadOperation { + /** + * Performs an asynchronous download operation in the background. + * + * @param {string} uri The location of the resource. + * @param {File} resultFile The file that the response will be written to. + * @param {string} uriMatcher The regexp to compare location of the resources with already downloading ones. + * @param {string} notificationTitle The title for downloading in notification. + */ + constructor(uri: string, resultFile: File, uriMatcher?: RegExp, notificationTitle?: string); + /** + * Starts an asynchronous download operation. + */ + startAsync(): BackgroundDownloadPromise; + /** + * Stops a download operation. + */ + stop(): void; +} + +interface BackgroundDownloadProgress { + bytesReceived: number, + totalBytesToReceive: number +} + +declare class BackgroundDownloadPromise { + /** + * Provides a mechanism for managing interactions with asynchronous APIs based on Promises. + * See 'Asynchronous programming in JavaScript' for more details + * http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx + * http://msdn.microsoft.com/en-us/library/windows/apps/br211867.aspx + * Note. Functionality is limited, support of .then and .cancel methods only, other methods are in progress. + */ + constructor(); + static Deferral: typeof Deferral; + _completeCallbacks: Array<Function>; + _errorCallbacks: Array<Function>; + _progressCallbacks: Array<Function>; + _chainedDefer: Deferral; + _state: 'pending' | 'resolved' | 'rejected' | 'cancelled'; + result: any; + then(onComplete?: () => void, onError?: (error: any) => void, onProgress?: (progress: BackgroundDownloadProgress) => void): BackgroundDownloadPromise; + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and + * cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + * http://msdn.microsoft.com/en-us/library/windows/apps/br211667.aspx + * @param {boolean} flag + */ + cancel(flag?: boolean): void; + executeCallback(callback: Function, args: any): void; +} + +declare class Deferral { + constructor(); + resolve(data: any); + reject(error: any); + notify(value: any); + bind(promise: BackgroundDownloadPromise); +} \ No newline at end of file diff --git a/types/cordova-plugin-background-download/tsconfig.json b/types/cordova-plugin-background-download/tsconfig.json new file mode 100644 index 0000000000..830f1483ca --- /dev/null +++ b/types/cordova-plugin-background-download/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cordova-plugin-background-download-tests.ts" + ] +} \ No newline at end of file diff --git a/types/cordova-plugin-background-download/tslint.json b/types/cordova-plugin-background-download/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/cordova-plugin-background-download/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file From 6054156ce1e6b50d2bb9d460338dfe02a707a761 Mon Sep 17 00:00:00 2001 From: Tobias Gimpel <gimpel@pisa.hom> Date: Fri, 1 Feb 2019 15:25:36 +0100 Subject: [PATCH 046/197] [index.d.ts] Applied linting --- ...ordova-plugin-background-download-tests.ts | 27 +++++----- .../index.d.ts | 52 +++++++++---------- 2 files changed, 39 insertions(+), 40 deletions(-) diff --git a/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts b/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts index 3db8c9a4b4..b531c96570 100644 --- a/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts +++ b/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts @@ -1,25 +1,24 @@ - var fileName = "PointerEventsCordovaPlugin.wmv", - uriString = "http://media.ch9.ms/ch9/8c03/f4fe2512-59e5-4a07-bded-124b06ac8c03/PointerEventsCordovaPlugin.wmv"; - + let fileName = "PointerEventsCordovaPlugin.wmv"; + let uriString = "http://media.ch9.ms/ch9/8c03/f4fe2512-59e5-4a07-bded-124b06ac8c03/PointerEventsCordovaPlugin.wmv"; + // open target file for download - window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) { - fileSystem.root.getFile(fileName, { create: true }, function (targetFile) { - + (window as any).requestFileSystem(1, 0, (fileSystem: any) => { + fileSystem.root.getFile(fileName, { create: true }, (targetFile: File) => { // plugin callbacks to track operation execution status and progress - var onSuccess = function() { + const onSuccess = () => { console.log('Done'); }; - var onError = function (err) { + const onError = (err: any) => { console.log(err); }; - var onProgress = function(progress) { + const onProgress = (progress: BackgroundDownloadProgress) => { console.log((100 * progress.bytesReceived / progress.totalBytesToReceive) + '%'); }; - - var downloader = new BackgroundTransfer.BackgroundDownloader(); + + const downloader = new BackgroundTransfer.BackgroundDownloader(); // Create a new download operation. - var download = downloader.createDownload(uriString, targetFile); + const download = downloader.createDownload(uriString, targetFile); // Start the download and persist the promise to be able to cancel the download. - app.downloadPromise = download.startAsync().then(onSuccess, onError, onProgress); + const downloadPromise = download.startAsync().then(onSuccess, onError, onProgress); }); - }); \ No newline at end of file + }); diff --git a/types/cordova-plugin-background-download/index.d.ts b/types/cordova-plugin-background-download/index.d.ts index 5a3319ce8e..f99b655c47 100644 --- a/types/cordova-plugin-background-download/index.d.ts +++ b/types/cordova-plugin-background-download/index.d.ts @@ -1,15 +1,15 @@ -// Type definitions for cordova-plugin-background-download 0.5.0 +// Type definitions for cordova-plugin-background-download 0.5 // Project: https://github.com/sgrebnov/cordova-plugin-background-download // Definitions by: Tobias Gimpel <https://github.com/mrbullfinsh> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.2.2 +// TypeScript Version: 3.2 /** - * Provides an advanced file transfer functionality that persists beyond app termination and + * Provides an advanced file transfer functionality that persists beyond app termination and * runs in the background. Background transfer doesn't support concurrent downloads of the same uri. */ -declare var BackgroundTransfer: IBackgroundTransfer; -declare interface IBackgroundTransfer { +declare var BackgroundTransfer: BackgroundTransferInterface; +interface BackgroundTransferInterface { BackgroundDownloader: typeof BackgroundDownloader; } @@ -17,16 +17,16 @@ declare class BackgroundDownloader { /** * Initializes a new instance of BackgroundDownloader object. * Used to configure downloads prior to the actual creation of the download operation using CreateDownload. - * - * @param {string} uriMatcher The regexp to compare location of the resources with already downloading ones. + * + * @param uriMatcher The regexp to compare location of the resources with already downloading ones. */ constructor(uriMatcher?: RegExp); /** * Initializes a DownloadOperation object that contains the specified Uri and the file that the response is written to. * - * @param {string} uri The location of the resource. - * @param {File} resultFile The file that the response will be written to. - * @param {string} notificationTitle The title for downloading in notification. + * @param uri The location of the resource. + * @param resultFile The file that the response will be written to. + * @param notificationTitle The title for downloading in notification. */ createDownload(uri: string, resultFile: File, notificationTitle?: string): DownloadOperation; } @@ -35,10 +35,10 @@ declare class DownloadOperation { /** * Performs an asynchronous download operation in the background. * - * @param {string} uri The location of the resource. - * @param {File} resultFile The file that the response will be written to. - * @param {string} uriMatcher The regexp to compare location of the resources with already downloading ones. - * @param {string} notificationTitle The title for downloading in notification. + * @param uri The location of the resource. + * @param resultFile The file that the response will be written to. + * @param uriMatcher The regexp to compare location of the resources with already downloading ones. + * @param notificationTitle The title for downloading in notification. */ constructor(uri: string, resultFile: File, uriMatcher?: RegExp, notificationTitle?: string); /** @@ -52,8 +52,8 @@ declare class DownloadOperation { } interface BackgroundDownloadProgress { - bytesReceived: number, - totalBytesToReceive: number + bytesReceived: number; + totalBytesToReceive: number; } declare class BackgroundDownloadPromise { @@ -66,9 +66,9 @@ declare class BackgroundDownloadPromise { */ constructor(); static Deferral: typeof Deferral; - _completeCallbacks: Array<Function>; - _errorCallbacks: Array<Function>; - _progressCallbacks: Array<Function>; + _completeCallbacks: Array<() => void>; + _errorCallbacks: Array<(error: any) => void>; + _progressCallbacks: Array<(progress: BackgroundDownloadProgress) => void>; _chainedDefer: Deferral; _state: 'pending' | 'resolved' | 'rejected' | 'cancelled'; result: any; @@ -77,16 +77,16 @@ declare class BackgroundDownloadPromise { * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and * cancellation is supported, the promise enters the error state with a value of Error("Canceled"). * http://msdn.microsoft.com/en-us/library/windows/apps/br211667.aspx - * @param {boolean} flag + * @param flag */ cancel(flag?: boolean): void; - executeCallback(callback: Function, args: any): void; + executeCallback(callback: (() => void) | ((error: any) => void) | ((progress: BackgroundDownloadProgress) => void), args: any): void; } declare class Deferral { constructor(); - resolve(data: any); - reject(error: any); - notify(value: any); - bind(promise: BackgroundDownloadPromise); -} \ No newline at end of file + resolve(data: any): void; + reject(error: any): void; + notify(value: any): void; + bind(promise: BackgroundDownloadPromise): void; +} From c52b655134afcd571f2642da9fee94ce259191fe Mon Sep 17 00:00:00 2001 From: Dale Fenton <fentondale@gmail.com> Date: Fri, 1 Feb 2019 10:27:31 -0500 Subject: [PATCH 047/197] add types for spellchecker package --- types/spellchecker/index.d.ts | 63 ++++++++++++++++++++++++ types/spellchecker/spellchecker-tests.ts | 41 +++++++++++++++ types/spellchecker/tsconfig.json | 23 +++++++++ types/spellchecker/tslint.json | 1 + 4 files changed, 128 insertions(+) create mode 100644 types/spellchecker/index.d.ts create mode 100644 types/spellchecker/spellchecker-tests.ts create mode 100644 types/spellchecker/tsconfig.json create mode 100644 types/spellchecker/tslint.json diff --git a/types/spellchecker/index.d.ts b/types/spellchecker/index.d.ts new file mode 100644 index 0000000000..0863e19646 --- /dev/null +++ b/types/spellchecker/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for spellchecker 3.5 +// Project: http://atom.github.io/node-spellchecker +// Definitions by: Dale Fenton <https://github.com/dalevfenton> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export as namespace Spellchecker; + +/* --------------------------------------------------------------------------- + Custom Types / Interfaces +--------------------------------------------------------------------------- */ +/** + * MisspelledLocation - shape of an object returned by checkSpelling to + * identify locations of misspelled words in a corpus. + * @description a misspelled word can be found by corpus.slice(start, end) + * start - start index of a misspelled word in a corpus + * end - end index of a misspelled word in a corpus + */ +export interface MisspelledLocation { + start: number; + end: number; +} + +/* --------------------------------------------------------------------------- + Methods +--------------------------------------------------------------------------- */ +/** + * Spellchecker.isMisspelled - Check if a word is misspelled. + * @param word - String word to check. + * @returns boolean - true if the word is misspelled, false otherwise. + */ +export function isMisspelled(word: string): boolean; + +/** + * Spellchecker.getCorrectionsForMisspelling - Get the corrections for a misspelled word. + * @param word - String word to get corrections for. + * @returns array - Returns a non-null but possibly empty array of string corrections. + */ +export function getCorrectionsForMisspelling(word: string): string[]; + +/** + * Spellchecker.checkSpelling - Identify misspelled words in a corpus of text. + * @param corpus - String corpus of text to spellcheck. + * @returns array - Returns an Array containing {start, end} objects that describe an + * index range within the original String that contains a misspelled word. + */ +export function checkSpelling(corpus: string): MisspelledLocation[]; + +/** + * Spellchecker.checkSpellingAsync - Asynchronously identify misspelled words. + * @param corpus - String corpus of text to spellcheck. + * @returns array - Returns a Promise that resolves with the Array described by checkSpelling(). + */ +export function checkSpellingAsync(corpus: string): Promise<MisspelledLocation[]>; + +/** + * Spellchecker.add - Adds a word to the dictionary. + * When using Hunspell, this will not modify the .dic file; + * new words must be added each time the spellchecker is created. Use a custom dictionary file. + * @param word - String word to add. + * @returns void + */ +export function add(word: string): void; diff --git a/types/spellchecker/spellchecker-tests.ts b/types/spellchecker/spellchecker-tests.ts new file mode 100644 index 0000000000..7f53b26ab0 --- /dev/null +++ b/types/spellchecker/spellchecker-tests.ts @@ -0,0 +1,41 @@ +import * as Spellchecker from 'spellchecker'; + +const additionalDictionary = ['Xynoronmalade']; + +// add words to the dictionary +additionalDictionary.forEach(word => Spellchecker.add(word)); + +let testWord = 'kat'; +let testCorpus = 'The queeck brown fox jumped over the lazy dog, from Xynoronmalade'; +let testCorpusAsync = 'The queeck brown fox jumped over the lazy dog, from Xynoronmalade'; + +// check and correct a single word +if (Spellchecker.isMisspelled(testWord)) { + const corrections = Spellchecker.getCorrectionsForMisspelling(testWord); + if (corrections.length > 0) { + testWord = corrections[0]; + } +} + +// check and correct words in a body of text +const misspellings = Spellchecker.checkSpelling(testCorpus); +misspellings.forEach(location => { + const misspelled = testCorpus.slice(location.start, location.end); + const corrections = Spellchecker.getCorrectionsForMisspelling(misspelled); + if (corrections.length > 0) { + testCorpus = testCorpus.replace(misspelled, corrections[0]); + } +}); + +// check for corrections asynchronously +const asyncSpellCheck = async () => { + // check and correct words in a body of text + const misspellings = await Spellchecker.checkSpellingAsync(testCorpusAsync); + misspellings.forEach(location => { + const misspelled = testCorpusAsync.slice(location.start, location.end); + const corrections = Spellchecker.getCorrectionsForMisspelling(misspelled); + if (corrections.length > 0) { + testCorpusAsync = testCorpusAsync.replace(misspelled, corrections[0]); + } + }); +}; diff --git a/types/spellchecker/tsconfig.json b/types/spellchecker/tsconfig.json new file mode 100644 index 0000000000..6817057d8c --- /dev/null +++ b/types/spellchecker/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "spellchecker-tests.ts" + ] +} diff --git a/types/spellchecker/tslint.json b/types/spellchecker/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/spellchecker/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From dbf5f097ccd90edb24dd01c9605ffd19ed0a1bca Mon Sep 17 00:00:00 2001 From: Sara Federico <gretzky@users.noreply.github.com> Date: Fri, 1 Feb 2019 14:11:23 -0500 Subject: [PATCH 048/197] [rebass] fix `as` prop per styled-components docs --- types/rebass/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/rebass/index.d.ts b/types/rebass/index.d.ts index 0536a600ee..20c73079ad 100644 --- a/types/rebass/index.d.ts +++ b/types/rebass/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: rhysd <https://github.com/rhysd> // ryee-dev <https://github.com/ryee-dev> // jamesmckenzie <https://github.com/jamesmckenzie> +// sara f-p <https://github.com/gretzky> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -10,7 +11,7 @@ import * as React from "react"; export interface BaseProps<C> extends React.ClassAttributes<C> { className?: string; - as?: string; + as?: any; } export interface SpaceProps<C> extends BaseProps<C> { From d0b43ffafd0e195c1e00a02d26768f8dd73f7180 Mon Sep 17 00:00:00 2001 From: Kevin Rambaud <kevin.rambaud@gmail.com> Date: Tue, 22 Jan 2019 16:14:57 -0500 Subject: [PATCH 049/197] Export ReactPaginateProps interface in v5 and v6 --- types/react-paginate/index.d.ts | 3 ++- types/react-paginate/v5/index.d.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/types/react-paginate/index.d.ts b/types/react-paginate/index.d.ts index d66309d489..626f459fc5 100644 --- a/types/react-paginate/index.d.ts +++ b/types/react-paginate/index.d.ts @@ -7,12 +7,13 @@ // Yasunori Ohoka <https://github.com/yasupeke> // Shingo Sato <https://github.com/sugarshin> // SPWizard01 <https://github.com/SPWizard01> +// Kevin Rambaud <https://github.com/kevinrambaud> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; -interface ReactPaginateProps { +export interface ReactPaginateProps { /** * The total number of pages. */ diff --git a/types/react-paginate/v5/index.d.ts b/types/react-paginate/v5/index.d.ts index 83a03ac838..7529a6b12f 100644 --- a/types/react-paginate/v5/index.d.ts +++ b/types/react-paginate/v5/index.d.ts @@ -5,12 +5,13 @@ // pegel03 <https://github.com/pegel03> // Simon Archer <https://github.com/archy-bold> // Yasunori Ohoka <https://github.com/yasupeke> +// Kevin Rambaud <https://github.com/kevinrambaud> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; -interface ReactPaginateProps { +export interface ReactPaginateProps { /** * The total number of pages. */ From fbca2f74db132b331c4152cb951ffc965e93deb3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=A6=E7=94=B0=20=E6=86=B2=E5=A4=AA=E9=83=8E?= <takeda@youmind.jp> Date: Sat, 2 Feb 2019 09:26:56 +0900 Subject: [PATCH 050/197] fix `Optional Parameters in Callbacks` http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#optional-parameters-in-callbacks --- types/hexo/index.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/types/hexo/index.d.ts b/types/hexo/index.d.ts index 0688b1631a..0f3a9dcc78 100644 --- a/types/hexo/index.d.ts +++ b/types/hexo/index.d.ts @@ -603,7 +603,7 @@ declare namespace Hexo { /** * Executed when creating a post to determine the path of new posts. */ - register(type: 'new_post_path', fn: (data: Post.Data, replace?: boolean) => void, priority?: number): void; + register(type: 'new_post_path', fn: (data: Post.Data, replace: boolean|undefined) => void, priority?: number): void; /** * Used to determine the permalink of posts. @@ -675,13 +675,13 @@ declare namespace Hexo { } interface Renderer { - register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options?: any) => string, sync: true): void; - register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options?: any) => Promise<string>, sync: false): void; - register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options?: any) => Promise<string>): void; + register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options: any) => string, sync: true): void; + register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options: any) => Promise<string>, sync: false): void; + register(srcExt: string, outExt: string, fn: (data: HexoRendererData, options: any) => Promise<string>): void; } interface Tag { - register(name: string, fn: (args: string[], content?: string) => string, options?: Tag.Options): void; + register(name: string, fn: (args: string[], content: string|undefined) => string, options?: Tag.Options): void; } namespace Tag { interface Options { From b9b4bd8adedee32a8a5182dd743cca7d7a45f937 Mon Sep 17 00:00:00 2001 From: Jeffrey Meng <jeffkmeng@gmail.com> Date: Fri, 1 Feb 2019 18:52:57 -0800 Subject: [PATCH 051/197] Use typescript exports and also export interfaces --- types/list.js/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/list.js/index.d.ts b/types/list.js/index.d.ts index 0c31e24e20..0c2e4fb905 100644 --- a/types/list.js/index.d.ts +++ b/types/list.js/index.d.ts @@ -60,4 +60,5 @@ declare class ListItem { visible(): boolean; } -export = List; +export default List; +export {ListOptions, SortOptions, ListItem, List}; From 1d1af425ff2e542460c927cd90f34eabf577f661 Mon Sep 17 00:00:00 2001 From: Ryo Ota <nwtgck@gmail.com> Date: Sat, 2 Feb 2019 15:35:07 +0900 Subject: [PATCH 052/197] Sort fields in IncomingHttpHeaders --- types/node/http.d.ts | 14 +++++++------- types/node/v4/index.d.ts | 14 +++++++------- types/node/v6/index.d.ts | 14 +++++++------- types/node/v7/index.d.ts | 14 +++++++------- types/node/v8/index.d.ts | 16 ++++++++-------- types/node/v9/index.d.ts | 16 ++++++++-------- 6 files changed, 44 insertions(+), 44 deletions(-) diff --git a/types/node/http.d.ts b/types/node/http.d.ts index e5f3741003..98b730c0c6 100644 --- a/types/node/http.d.ts +++ b/types/node/http.d.ts @@ -7,14 +7,14 @@ declare module "http" { // incoming headers will never contain number interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; @@ -50,9 +50,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index 26210a1857..f52a8d01f8 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -672,14 +672,14 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; @@ -703,9 +703,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 5ed74da702..6dd1ad1dc0 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -741,14 +741,14 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; @@ -772,9 +772,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index 932d988912..a4fde30a97 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -738,14 +738,14 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; @@ -769,9 +769,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index e0e901fea6..1fac090367 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -967,18 +967,18 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; - 'authorization'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; + 'authorization'?: string; 'cache-control'?: string; 'connection'?: string; 'content-disposition'?: string; @@ -999,9 +999,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 5bafe1ec47..220afd9e60 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -1052,18 +1052,18 @@ declare module "http" { // incoming headers will never contain number export interface IncomingHttpHeaders { 'accept'?: string; - 'access-control-allow-origin'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; - 'authorization'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; + 'authorization'?: string; 'cache-control'?: string; 'connection'?: string; 'content-disposition'?: string; @@ -1084,9 +1084,9 @@ declare module "http" { 'retry-after'?: string; 'set-cookie'?: string[]; 'strict-transport-security'?: string; + 'tk'?: string; 'trailer'?: string; 'transfer-encoding'?: string; - 'tk'?: string; 'upgrade'?: string; 'user-agent'?: string; 'vary'?: string; From 2f31fadccb4ccd59ac50f7a7796c9115e897a056 Mon Sep 17 00:00:00 2001 From: Dale Fenton <fentondale@gmail.com> Date: Sat, 2 Feb 2019 09:56:06 -0500 Subject: [PATCH 053/197] remove Spellchecker from global namespace --- types/spellchecker/index.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/types/spellchecker/index.d.ts b/types/spellchecker/index.d.ts index 0863e19646..01064d0688 100644 --- a/types/spellchecker/index.d.ts +++ b/types/spellchecker/index.d.ts @@ -4,8 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -export as namespace Spellchecker; - /* --------------------------------------------------------------------------- Custom Types / Interfaces --------------------------------------------------------------------------- */ From 778a6b93b5cc9d43ba2c5b86838f77a3076947bc Mon Sep 17 00:00:00 2001 From: Dimitri Benin <dimitri.benin@gmail.com> Date: Sat, 2 Feb 2019 19:41:50 +0100 Subject: [PATCH 054/197] [acl] Export all module interfaces, fix lint exceptions --- types/acl/index.d.ts | 289 +++++++++++++++++-------------- types/acl/test/index.ts | 71 ++++---- types/acl/test/mongodbBackend.ts | 4 +- types/acl/test/redisBackend.ts | 4 +- types/acl/tslint.json | 78 +-------- 5 files changed, 199 insertions(+), 247 deletions(-) diff --git a/types/acl/index.d.ts b/types/acl/index.d.ts index 3f4df31aa2..931452dc52 100644 --- a/types/acl/index.d.ts +++ b/types/acl/index.d.ts @@ -1,150 +1,179 @@ -// Type definitions for node_acl 0.4.8 +// Type definitions for acl 0.4 // Project: https://github.com/optimalbits/node_acl // Definitions by: Qubo <https://github.com/tkQubo> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// <reference types="node"/> -/// <reference types="express"/> import http = require('http'); -import Promise = require("bluebird"); -import express = require("express"); +import Promise = require('bluebird'); +import express = require('express'); +import redis = require('redis'); +import mongo = require('mongodb'); -type strings = string|string[]; -type Value = string|number; -type Values = Value|Value[]; +export = AclStatic; + +declare const AclStatic: AclStatic; + +type strings = string | string[]; +type Value = string | number; +type Values = Value | Value[]; type Action = () => any; -type Callback = (err: Error) => any; +type Callback = (err?: Error) => any; type AnyCallback = (err: Error, obj: any) => any; type AllowedCallback = (err: Error, allowed: boolean) => any; type GetUserId = (req: http.IncomingMessage, res: http.ServerResponse) => Value; interface AclStatic { - new (backend: Backend<any>, logger: Logger, options: Option): Acl; - new (backend: Backend<any>, logger: Logger): Acl; - new (backend: Backend<any>): Acl; - memoryBackend: MemoryBackendStatic; + new ( + backend: AclStatic.Backend<any>, + logger?: AclStatic.Logger, + options?: AclStatic.Option + ): AclStatic.Acl; + readonly memoryBackend: AclStatic.MemoryBackendStatic; + readonly mongodbBackend: AclStatic.MongodbBackendStatic; + readonly redisBackend: AclStatic.RedisBackendStatic; } -interface Logger { - debug: (msg: string) => any; -} - -interface Acl { - addUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>; - removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>; - userRoles: (userId: Value, cb?: (err: Error, roles: string[]) => any) => Promise<string[]>; - roleUsers: (role: Value, cb?: (err: Error, users: Values) => any) => Promise<any>; - hasRole: (userId: Value, role: string, cb?: (err: Error, isInRole: boolean) => any) => Promise<boolean>; - addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise<void>; - removeRole: (role: string, cb?: Callback) => Promise<void>; - removeResource: (resource: string, cb?: Callback) => Promise<void>; - allow: { - (roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise<void>; - (aclSets: AclSet | AclSet[]): Promise<void>; +declare namespace AclStatic { + interface Logger { + debug: (msg: string) => any; } - removeAllow: (role: string, resources: strings, permissions: strings, cb?: Callback) => Promise<void>; - removePermissions: (role: string, resources: strings, permissions: strings, cb?: Function) => Promise<void>; - 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, cb?: AnyCallback): Promise<any>; - (roles: strings, permissions: strings, cb?: AnyCallback): Promise<any>; + + interface Acl { + addUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>; + removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>; + userRoles: (userId: Value, cb?: (err: Error, roles: string[]) => any) => Promise<string[]>; + roleUsers: (role: Value, cb?: (err: Error, users: Values) => any) => Promise<any>; + hasRole: ( + userId: Value, + role: string, + cb?: (err: Error, isInRole: boolean) => any + ) => Promise<boolean>; + addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise<void>; + removeRole: (role: string, cb?: Callback) => Promise<void>; + removeResource: (resource: string, cb?: Callback) => Promise<void>; + allow: { + (roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise<void>; + (aclSets: AclSet | AclSet[]): Promise<void>; + }; + removeAllow: ( + role: string, + resources: strings, + permissions: strings, + cb?: Callback + ) => Promise<void>; + removePermissions: ( + role: string, + resources: strings, + permissions: strings, + cb?: Callback + ) => Promise<void>; + 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, cb?: AnyCallback): Promise<any>; + (roles: strings, permissions: strings, cb?: AnyCallback): Promise<any>; + }; + permittedResources: (roles: strings, permissions: strings, cb?: Callback) => Promise<void>; + middleware: ( + numPathComponents?: number, + userId?: Value | GetUserId, + actions?: strings + ) => express.RequestHandler; + } + + interface Option { + buckets?: BucketsOption; + } + + interface BucketsOption { + meta?: string; + parents?: string; + permissions?: string; + resources?: string; + roles?: string; + users?: string; + } + + interface AclSet { + roles: strings; + allows: AclAllow[]; + } + + interface AclAllow { + resources: strings; + permissions: strings; + } + + interface MemoryBackend extends Backend<Action[]> {} + interface MemoryBackendStatic { + new (): MemoryBackend; + } + + // + // For internal use + // + interface Backend<T> { + begin: () => T; + end: (transaction: T, cb?: Action) => void; + clean: (cb?: Action) => void; + get: (bucket: string, key: Value, cb?: Action) => void; + union: (bucket: string, keys: Value[], cb?: Action) => void; + add: (transaction: T, bucket: string, key: Value, values: Values) => void; + del: (transaction: T, bucket: string, keys: Value[]) => void; + remove: (transaction: T, bucket: string, key: Value, values: Values) => void; + + endAsync: (transaction: T, cb?: (err: Error | null) => void) => Promise<void>; + getAsync: ( + bucket: string, + key: Value, + cb?: (err: Error | null, value: any) => void + ) => Promise<any>; + cleanAsync: (cb?: (error?: Error) => void) => Promise<void>; + unionAsync: ( + bucket: string, + keys: Value[], + cb?: (error: Error | undefined, results: any[]) => void + ) => Promise<any[]>; + } + + interface Contract { + (args: IArguments): Contract | NoOp; + debug: boolean; + fulfilled: boolean; + args: any[]; + checkedParams: string[]; + params: (...types: string[]) => Contract | NoOp; + end: () => void; + } + + interface NoOp { + params: (...types: string[]) => NoOp; + end: () => void; + } + + // for redis backend + interface RedisBackend extends Backend<redis.RedisClient> {} + interface RedisBackendStatic { + new (redis: redis.RedisClient, prefix?: string): RedisBackend; + } + + // for mongodb backend + interface MongodbBackend extends Backend<Callback> {} + interface MongodbBackendStatic { + new (db: mongo.Db, prefix?: string, useSingle?: boolean): MongodbBackend; } - permittedResources: (roles: strings, permissions: strings, cb?: Function) => Promise<void>; - middleware: (numPathComponents?: number, userId?: Value | GetUserId, actions?: strings) => express.RequestHandler; } - -interface Option { - buckets?: BucketsOption; -} - -interface BucketsOption { - meta?: string; - parents?: string; - permissions?: string; - resources?: string; - roles?: string; - users?: string; -} - -interface AclSet { - roles: strings; - allows: AclAllow[]; -} - -interface AclAllow { - resources: strings; - permissions: strings; -} - -interface MemoryBackend extends Backend<Action[]> { } -interface MemoryBackendStatic { - new (): MemoryBackend; -} - -// -// For internal use -// -interface Backend<T> { - begin: () => T; - end: (transaction: T, cb?: Action) => void; - clean: (cb?: Action) => void; - get: (bucket: string, key: Value, cb?: Action) => void; - union: (bucket: string, keys: Value[], cb?: Action) => void; - add: (transaction: T, bucket: string, key: Value, values: Values) => void; - del: (transaction: T, bucket: string, keys: Value[]) => void; - remove: (transaction: T, bucket: string, key: Value, values: Values) => void; - - endAsync: Function; //TODO: Give more specific function signature - getAsync: Function; - cleanAsync: Function; - unionAsync: Function; -} - -interface Contract { - (args: IArguments): Contract | NoOp; - debug: boolean; - fulfilled: boolean; - args: any[]; - checkedParams: string[]; - params: (...types: string[]) => Contract | NoOp; - end: () => void; -} - -interface NoOp { - params: (...types: string[]) => NoOp; - end: () => void; -} - -// for redis backend -import redis = require('redis'); - -interface AclStatic { - redisBackend: RedisBackendStatic; -} - -interface RedisBackend extends Backend<redis.RedisClient> { } -interface RedisBackendStatic { - new (redis: redis.RedisClient, prefix: string): RedisBackend; - new (redis: redis.RedisClient): RedisBackend; -} - -// for mongodb backend -import mongo = require('mongodb'); - -interface AclStatic { - mongodbBackend: MongodbBackendStatic; -} - -interface MongodbBackend extends Backend<Callback> { } -interface MongodbBackendStatic { - new (db: mongo.Db, prefix: string, useSingle: boolean): MongodbBackend; - new (db: mongo.Db, prefix: string): MongodbBackend; - new (db: mongo.Db): MongodbBackend; -} - -declare var _: AclStatic; -export = _; diff --git a/types/acl/test/index.ts b/types/acl/test/index.ts index bb3e6fa54e..3485ab3662 100644 --- a/types/acl/test/index.ts +++ b/types/acl/test/index.ts @@ -2,15 +2,15 @@ // https://github.com/OptimalBits/node_acl/blob/master/Readme.md import Acl = require('acl'); -var report = <T>(err: Error, value: T) => { - if (err) { - console.error(err); - } - console.info(value); +const report = (err: Error, value: any) => { + if (err) { + console.error(err); + } + console.info(value); }; // Using the memory backend -var acl = new Acl(new Acl.memoryBackend()); +const acl: Acl.Acl = new Acl(new Acl.memoryBackend()); // middleware with no optional parameters acl.middleware(); @@ -18,11 +18,11 @@ acl.middleware(); acl.middleware(1); acl.middleware(1, () => { - return "joed"; + return 'joed'; }); acl.middleware(1, () => { - return 2; + return 2; }); acl.middleware(1, 'joed'); @@ -33,36 +33,36 @@ acl.middleware(3, 'joed', 'post'); acl.allow('guest', 'blogs', 'view'); // allow function accepts arrays as any parameter -acl.allow('member', 'blogs', ['edit','view', 'delete']); +acl.allow('member', 'blogs', ['edit', 'view', 'delete']); acl.addUserRoles('joed', 'guest'); -acl.addRoleParents('baz', ['foo','bar']); +acl.addRoleParents('baz', ['foo', 'bar']); -acl.allow('foo', ['blogs','forums','news'], ['view', 'delete']); +acl.allow('foo', ['blogs', 'forums', 'news'], ['view', 'delete']); -acl.allow('admin', ['blogs','forums'], '*'); +acl.allow('admin', ['blogs', 'forums'], '*'); acl.allow([ { - roles:['guest','special-member'], - allows:[ - {resources:'blogs', permissions:'get'}, - {resources:['forums','news'], permissions:['get','put','delete']} - ] + roles: ['guest', 'special-member'], + allows: [ + { resources: 'blogs', permissions: 'get' }, + { resources: ['forums', 'news'], permissions: ['get', 'put', 'delete'] }, + ], }, { - roles:['gold','silver'], - allows:[ - {resources:'cash', permissions:['sell','exchange']}, - {resources:['account','deposit'], permissions:['put','delete']} - ] - } + roles: ['gold', 'silver'], + allows: [ + { resources: 'cash', permissions: ['sell', 'exchange'] }, + { resources: ['account', 'deposit'], permissions: ['put', 'delete'] }, + ], + }, ]); acl.isAllowed('joed', 'blogs', 'view', (err, res) => { if (res) { - console.log("User joed is allowed to view blogs"); + console.log('User joed is allowed to view blogs'); } }); @@ -78,15 +78,14 @@ acl.whatResources('foo', 'view', (err, res) => { } }); -acl.isAllowed('jsmith', 'blogs', ['edit','view','delete']) -.then((result) => { - console.dir('jsmith is allowed blogs ' + result); - acl.addUserRoles('jsmith', 'member'); -}).then(() => - acl.isAllowed('jsmith', 'blogs', ['edit','view','delete']) -).then((result) => - console.dir('jsmith is allowed blogs ' + result) -).then(() => { - acl.allowedPermissions('james', ['blogs','forums'], report); - acl.allowedPermissions('jsmith', ['blogs','forums'], report); -}); +acl.isAllowed('jsmith', 'blogs', ['edit', 'view', 'delete']) + .then(result => { + console.dir('jsmith is allowed blogs ' + result); + acl.addUserRoles('jsmith', 'member'); + }) + .then(() => acl.isAllowed('jsmith', 'blogs', ['edit', 'view', 'delete'])) + .then(result => console.dir('jsmith is allowed blogs ' + result)) + .then(() => { + acl.allowedPermissions('james', ['blogs', 'forums'], report); + acl.allowedPermissions('jsmith', ['blogs', 'forums'], report); + }); diff --git a/types/acl/test/mongodbBackend.ts b/types/acl/test/mongodbBackend.ts index ae3b1d03c9..449cefa030 100644 --- a/types/acl/test/mongodbBackend.ts +++ b/types/acl/test/mongodbBackend.ts @@ -5,10 +5,10 @@ import mongodb = require('mongodb'); declare var db: mongodb.Db; // Using the mongo db backend -var acl = new Acl(new Acl.mongodbBackend(db, 'acl_', true)); +const acl = new Acl(new Acl.mongodbBackend(db, 'acl_', true)); // guest is allowed to view blogs acl.allow('guest', 'blogs', 'view'); // allow function accepts arrays as any parameter -acl.allow('member', 'blogs', ['edit','view', 'delete']); +acl.allow('member', 'blogs', ['edit', 'view', 'delete']); diff --git a/types/acl/test/redisBackend.ts b/types/acl/test/redisBackend.ts index ec1924cce6..669d28ed6d 100644 --- a/types/acl/test/redisBackend.ts +++ b/types/acl/test/redisBackend.ts @@ -5,10 +5,10 @@ import redis = require('redis'); declare var client: redis.RedisClient; // Using the redis backend -var acl = new Acl(new Acl.redisBackend(client, 'acl_')); +const acl = new Acl(new Acl.redisBackend(client, 'acl_')); // guest is allowed to view blogs acl.allow('guest', 'blogs', 'view'); // allow function accepts arrays as any parameter -acl.allow('member', 'blogs', ['edit','view', 'delete']); +acl.allow('member', 'blogs', ['edit', 'view', 'delete']); diff --git a/types/acl/tslint.json b/types/acl/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/acl/tslint.json +++ b/types/acl/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } From fed19a461850f2e3881b5efd1d1a62eb26879d06 Mon Sep 17 00:00:00 2001 From: Jeffrey Meng <jeffreymeng@users.noreply.github.com> Date: Sat, 2 Feb 2019 11:37:25 -0800 Subject: [PATCH 055/197] Keep old exports --- types/list.js/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/list.js/index.d.ts b/types/list.js/index.d.ts index 0c2e4fb905..8dd43dd1df 100644 --- a/types/list.js/index.d.ts +++ b/types/list.js/index.d.ts @@ -60,5 +60,6 @@ declare class ListItem { visible(): boolean; } +export = List; export default List; export {ListOptions, SortOptions, ListItem, List}; From 49d2ea60d65c14ac298123bb19b7fe8a9f168388 Mon Sep 17 00:00:00 2001 From: Jeffrey Meng <jeffkmeng@gmail.com> Date: Sat, 2 Feb 2019 11:46:28 -0800 Subject: [PATCH 056/197] Revert "Keep old exports" This reverts commit fed19a461850f2e3881b5efd1d1a62eb26879d06. --- types/list.js/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/list.js/index.d.ts b/types/list.js/index.d.ts index 8dd43dd1df..0c2e4fb905 100644 --- a/types/list.js/index.d.ts +++ b/types/list.js/index.d.ts @@ -60,6 +60,5 @@ declare class ListItem { visible(): boolean; } -export = List; export default List; export {ListOptions, SortOptions, ListItem, List}; From b20f6fa61f901ad3c78af6b44e33b7b776c0fa88 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Sat, 2 Feb 2019 18:56:12 -0800 Subject: [PATCH 057/197] [jscodeshift] Split into multiple files --- types/jscodeshift/index.d.ts | 457 +++--------------- types/jscodeshift/src/Collection.d.ts | 123 +++++ .../src/collections/JSXElement.d.ts | 70 +++ types/jscodeshift/src/collections/Node.d.ts | 57 +++ .../src/collections/VariableDeclarator.d.ts | 39 ++ types/jscodeshift/src/template.d.ts | 14 + types/jscodeshift/tsconfig.json | 5 + types/jscodeshift/tslint.json | 7 +- 8 files changed, 378 insertions(+), 394 deletions(-) create mode 100644 types/jscodeshift/src/Collection.d.ts create mode 100644 types/jscodeshift/src/collections/JSXElement.d.ts create mode 100644 types/jscodeshift/src/collections/Node.d.ts create mode 100644 types/jscodeshift/src/collections/VariableDeclarator.d.ts create mode 100644 types/jscodeshift/src/template.d.ts diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts index 95a26cd0a4..f4cee2db55 100644 --- a/types/jscodeshift/index.d.ts +++ b/types/jscodeshift/index.d.ts @@ -4,420 +4,101 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 -declare module "jscodeshift" { - import { Collection, registerMethods } from "jscodeshift/src/Collection"; - import * as JSXElement from "jscodeshift/src/collections/JSXElement"; - import * as VariableDeclarator from "jscodeshift/src/collections/VariableDeclarator"; - import { Template } from "jscodeshift/src/template"; - import recast, { Builders, NamedTypes, NodePath, Options, Parser } from "recast"; - import { ASTNode } from "ast-types/gen/nodes"; +import { ASTNode } from "ast-types/gen/nodes"; +import recast, { Builders, NamedTypes, NodePath, Options, Parser } from "recast"; +import { Collection, registerMethods } from "./src/Collection"; +import * as JSXElement from "./src/collections/JSXElement"; +import * as VariableDeclarator from "./src/collections/VariableDeclarator"; +import { Template } from "./src/template"; - export type ASTPath<N = ASTNode> = NodePath<N, N>; +export type ASTPath<N = ASTNode> = NodePath<N, N>; - export interface Filters { - JSXElement: JSXElement.FilterMethods; - VariableDeclarator: VariableDeclarator.FilterMethods; - } - - export interface Mappings { - JSXElement: JSXElement.MappingMethods; - } - - export interface Plugin { - (core: Core): void; - } - - export interface FileInfo { - /** The absolute path to the current file. */ - path: string; - /** The source code of the current file. */ - source: string; - } - - export interface Stats { - /** - * Helper function to collect data during --dry runs. - * This function keeps a counter for how often it was called with a specific argument. - * The result is shown in the console. Useful for finding out how many files match a criterion. - */ - (name: string, quantity?: number): void; - } - - interface Core { - (source: string, options?: Options): Collection<any>; - (source: ASTNode | ASTNode[] | ASTPath | ASTPath[]): Collection<any>; - - registerMethods: typeof registerMethods; - - types: typeof recast.types; - - match(path: ASTNode | ASTPath, filter: ((path: ASTNode) => boolean) | ASTNode): boolean; - - /** template, bound to default parser */ - template: Template; - - filters: Filters; - - mappings: Mappings; - - /** - * Utility function for registering plugins. - * - * Plugins are simple functions that are passed the core jscodeshift instance. - * They should extend jscodeshift by calling `registerMethods`, etc. - * This method guards against repeated registrations (the plugin callback will only be called once). - */ - use(plugin: Plugin): void; - - /** - * Returns a version of the core jscodeshift function "bound" to a specific - * parser. - */ - withParser(parser: string | Parser): JSCodeshift; - } - - type JSCodeshift = Core & NamedTypes & Builders; - - const core: JSCodeshift; - export default core; - - export interface API { - j: JSCodeshift; - jscodeshift: JSCodeshift; - stats: Stats; - report: (msg: string) => void; - } - - export interface Options { - [option: string]: any; - } - - export interface Transform { - /** - * If a string is returned and it is different from passed source, the transform is considered to be successful. - * If a string is returned but it's the same as the source, the transform is considered to be unsuccessful. - * If nothing is returned, the file is not supposed to be transformed (which is ok). - */ - (file: FileInfo, api: API, options: Options): string | null | undefined | void; - } - - export * from "ast-types/gen/nodes"; - export { Collection, Parser }; +export interface Filters { + JSXElement: JSXElement.FilterMethods; + VariableDeclarator: VariableDeclarator.FilterMethods; } -declare module "jscodeshift/src/template" { - import { Parser } from "recast"; - - export interface Template { - /** Tagged template function. Parses the string as source and returns an array of Statement AST nodes. */ - statements(...args: any[]): any; - /** Tagged template function. Parses the string as source and returns an Statement AST node. */ - statement(...args: any[]): any; - /** Tagged template function. Parses the string as source and returns an Expression AST node. */ - expression(...args: any[]): any; - } - - export default function withParser(parser: Parser): Template; - - export {}; // to shut off automatic exporting +export interface Mappings { + JSXElement: JSXElement.MappingMethods; } -declare module "jscodeshift/src/Collection" { - import * as JSXElement from "jscodeshift/src/collections/JSXElement"; - import * as NodeCollection from "jscodeshift/src/collections/Node"; - import * as VariableDeclarator from "jscodeshift/src/collections/VariableDeclarator"; - import recast, { ASTNode, NodePath, Options, Type } from "recast"; +export interface Plugin { + (core: Core): void; +} - type ASTPath<N> = NodePath<N, N>; +export interface FileInfo { + /** The absolute path to the current file. */ + path: string; + /** The source code of the current file. */ + source: string; +} - export interface Collection<N> - extends NodeCollection.TraversalMethods, - NodeCollection.MutationMethods<N>, - VariableDeclarator.GlobalMethods, - VariableDeclarator.TransformMethods<N>, - JSXElement.GlobalMethods, - JSXElement.TraversalMethods { - /** - * @param paths An array of AST paths - * @param parent A parent collection - * @param types An array of types all the paths in the collection - * have in common. If not passed, it will be inferred from the paths. - */ - new (paths: Array<ASTPath<N>>, parent: Collection<any>, types?: Array<Type<any>>): this; +export interface Stats { + /** + * Helper function to collect data during --dry runs. + * This function keeps a counter for how often it was called with a specific argument. + * The result is shown in the console. Useful for finding out how many files match a criterion. + */ + (name: string, quantity?: number): void; +} - /** - * Returns a new collection containing the nodes for which the callback returns true. - */ - filter<S extends N>( - callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => path is ASTPath<S> - ): Collection<S>; - filter( - callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean - ): Collection<N>; +interface Core { + (source: string, options?: Options): Collection<any>; + (source: ASTNode | ASTNode[] | ASTPath | ASTPath[]): Collection<any>; - /** - * Executes callback for each node/path in the collection. - */ - forEach(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => void): this; + registerMethods: typeof registerMethods; - /** - * Tests whether at-least one path passes the test implemented by the provided callback. - */ - some(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean): boolean; + types: typeof recast.types; - /** - * Tests whether all paths pass the test implemented by the provided callback. - */ - every(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean): boolean; + match(path: ASTNode | ASTPath, filter: ((path: ASTNode) => boolean) | ASTNode): boolean; - /** - * Executes the callback for every path in the collection and returns a new - * collection from the return values (which must be paths). - * - * The callback can return null to indicate to exclude the element from the - * new collection. - * - * If an array is returned, the array will be flattened into the result - * collection. - * - * @param callback - * @param type Force the new collection to be of a specific type - */ - map<T = ASTNode>( - callback: ( - path: ASTPath<N>, - i: number, - paths: Array<ASTPath<N>> - ) => ASTPath<T> | Array<ASTPath<T>> | null | undefined, - type: Type<any> - ): Collection<T>; + /** template, bound to default parser */ + template: Template; - /** Returns the number of elements in this collection. */ - size(): number; + filters: Filters; - /** Returns the number of elements in this collection. */ - length: number; - - /** Returns an array of AST nodes in this collection. */ - nodes(): N[]; - - /** Returns an array of ASTPaths in this this collection. */ - paths(): Array<ASTPath<N>>; - - getAST(): Array<ASTPath<any>>; - - /** - * Converts the AST back to a string, using recast. - * @param options directly passed to recast's printer - */ - toSource(options?: Options): string; - - /** - * Returns a new collection containing only the element at position index. - * In case of a negative index, the element is taken from the end: - * .at(0) - first element - * .at(-1) - last element - */ - at(index: number): Collection<N>; - - /** Calls "get" on the first path (same as "collection.paths(0).get(...)"). */ - get(...fields: Array<string | number>): any; - - /** - * Returns the type(s) of the collection. This is only used for unit tests, - * don't think other consumers would need it. - */ - getTypes(): string[]; - - /** - * Returns true if this collection has the type 'type'. - */ - isOfType(type: Type<any>): boolean; - } + mappings: Mappings; /** - * This function adds the provided methods to the prototype of the corresponding - * typed collection. If no type is passed, the methods are added to - * Collection.prototype and are available for all collections. + * Utility function for registering plugins. * - * @param methods Methods to add to the prototype - * @param type Optional type to add the methods to + * Plugins are simple functions that are passed the core jscodeshift instance. + * They should extend jscodeshift by calling `registerMethods`, etc. + * This method guards against repeated registrations (the plugin callback will only be called once). */ - export function registerMethods(methods: object, type?: Type<any>): void; + use(plugin: Plugin): void; - export {}; // to shut off automatic exporting + /** + * Returns a version of the core jscodeshift function "bound" to a specific + * parser. + */ + withParser(parser: string | Parser): JSCodeshift; } -declare module "jscodeshift/src/collections/Node" { - import { Collection } from "jscodeshift/src/Collection"; - import { ASTNode, Type, NodePath } from "recast"; +type JSCodeshift = Core & NamedTypes & Builders; - type ASTPath<N> = NodePath<N, N>; +declare const core: JSCodeshift; +export default core; - export interface TraversalMethods { - /** - * Find nodes of a specific type within the nodes of this collection. - */ - find<T>(type: Type<T>, filter?: ((value: any) => boolean) | object): Collection<T>; - - /** - * Returns a collection containing the paths that create the scope of the - * currently selected paths. Dedupes the paths. - */ - closestScope<T>(): Collection<T>; - - /** - * Traverse the AST up and finds the closest node of the provided type. - */ - closest<T>(type: Type<T>, filter?: any): Collection<T>; - - /** - * Finds the declaration for each selected path. Useful for member expressions - * or JSXElements. Expects a callback function that maps each path to the name - * to look for. - * - * If the callback returns a falsey value, the element is skipped. - */ - getVariableDeclarators<T>(nameGetter: (...args: any[]) => any): Collection<T>; - } - - export interface MutationMethods<N> { - /** - * Simply replaces the selected nodes with the provided node. If a function - * is provided it is executed for every node and the node is replaced with the - * functions return value. - */ - replaceWith<T>(nodes: T | T[] | ((path: ASTPath<N>, i: number) => T)): Collection<T>; - - /** - * Inserts a new node before the current one. - */ - insertBefore(insert: any): Collection<N>; - - /** - * Inserts a new node after the current one. - */ - insertAfter(insert: any): Collection<N>; - - remove(): Collection<N>; - } - - export function register(): void; - - export {}; // to shut off automatic exporting +export interface API { + j: JSCodeshift; + jscodeshift: JSCodeshift; + stats: Stats; + report: (msg: string) => void; } -declare module "jscodeshift/src/collections/VariableDeclarator" { - import { VariableDeclarator } from "ast-types/gen/nodes"; - import { Collection } from "jscodeshift/src/Collection"; - import recast, { NodePath } from "recast"; - - type ASTPath<N> = NodePath<N, N>; - - export interface GlobalMethods { - /** - * Finds all variable declarators, optionally filtered by name. - */ - findVariableDeclarators(name?: string): Collection<VariableDeclarator>; - } - - export interface TransformMethods<N> { - /** - * Renames a variable and all its occurrences. - * This method only applies to VariableDeclarator typed collections. - */ - renameTo(newName: string): Collection<N>; - } - - interface Filter { - (path: ASTPath<any>): boolean; - } - - export interface FilterMethods { - /** - * Returns a function that returns true if the provided path is a variable - * declarator and requires one of the specified module names. - * - * @param names A module name or an array of module names - */ - requiresModule(names: string | string[]): Filter; - } - - export function register(): void; - export const filters: FilterMethods; - - export {}; // to shut off automatic exporting +export interface Options { + [option: string]: any; } -declare module "jscodeshift/src/collections/JSXElement" { - import { JSXElement } from "ast-types/gen/nodes"; - import { Collection } from "jscodeshift/src/Collection"; - import { NodePath } from "recast"; - - type ASTPath<N> = NodePath<N, N>; - - export interface GlobalMethods { - /** - * Finds all JSXElements optionally filtered by name - */ - findJSXElements(name?: string): Collection<JSXElement>; - - /** - * Finds all JSXElements by module name. Given - * - * var Bar = require('Foo'); - * <Bar /> - * - * findJSXElementsByModuleName('Foo') will find <Bar />, without having to - * know the variable name. - */ - findJSXElementsByModuleName(moduleName: string): Collection<JSXElement>; - } - - type Defined<T> = T extends undefined ? never : T; - type JSXElementChild = Defined<JSXElement["children"]>[0]; - - export interface TraversalMethods { - /** - * Returns all child nodes, including literals and expressions. - * This method only applies to JSXElement typed collections. - */ - childNodes<T>(): Collection<JSXElementChild>; - - /** - * Returns all children that are JSXElements. - * This method only applies to JSXElement typed collections. - */ - childElements(): Collection<JSXElement>; - } - - interface Filter { - (path: ASTPath<any>): boolean; - } - - export interface FilterMethods { - /** - * Filter method for attributes. - */ - hasAttributes(attributeFilter: { [attributeName: string]: any }): Filter; - - /** - * Filter elements which contain a specific child type - */ - hasChildren(name: string): Filter; - } - - export interface MappingMethods { - /** - * Given a JSXElement, returns its "root" name. E.g. it would return "Foo" for - * both <Foo /> and <Foo.Bar />. - */ - getRootName(path: ASTPath<any>): string; - } - - export function register(): void; - export const filters: FilterMethods; - export const mappings: MappingMethods; - - export {}; // to shut off automatic exporting +export interface Transform { + /** + * If a string is returned and it is different from passed source, the transform is considered to be successful. + * If a string is returned but it's the same as the source, the transform is considered to be unsuccessful. + * If nothing is returned, the file is not supposed to be transformed (which is ok). + */ + (file: FileInfo, api: API, options: Options): string | null | undefined | void; } + +export * from "ast-types/gen/nodes"; +export { Collection, Parser }; diff --git a/types/jscodeshift/src/Collection.d.ts b/types/jscodeshift/src/Collection.d.ts new file mode 100644 index 0000000000..5ddf7b2bdc --- /dev/null +++ b/types/jscodeshift/src/Collection.d.ts @@ -0,0 +1,123 @@ +import { ASTNode, NodePath, Options, Type } from "recast"; +import * as JSXElement from "./collections/JSXElement"; +import * as NodeCollection from "./collections/Node"; +import * as VariableDeclarator from "./collections/VariableDeclarator"; + +type ASTPath<N> = NodePath<N, N>; + +export interface Collection<N> + extends NodeCollection.TraversalMethods, + NodeCollection.MutationMethods<N>, + VariableDeclarator.GlobalMethods, + VariableDeclarator.TransformMethods<N>, + JSXElement.GlobalMethods, + JSXElement.TraversalMethods { + /** + * @param paths An array of AST paths + * @param parent A parent collection + * @param types An array of types all the paths in the collection + * have in common. If not passed, it will be inferred from the paths. + */ + new (paths: Array<ASTPath<N>>, parent: Collection<any>, types?: Array<Type<any>>): this; + + /** + * Returns a new collection containing the nodes for which the callback returns true. + */ + filter<S extends N>( + callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => path is ASTPath<S> + ): Collection<S>; + filter( + callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean + ): Collection<N>; + + /** + * Executes callback for each node/path in the collection. + */ + forEach(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => void): this; + + /** + * Tests whether at-least one path passes the test implemented by the provided callback. + */ + some(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean): boolean; + + /** + * Tests whether all paths pass the test implemented by the provided callback. + */ + every(callback: (path: ASTPath<N>, i: number, paths: Array<ASTPath<N>>) => boolean): boolean; + + /** + * Executes the callback for every path in the collection and returns a new + * collection from the return values (which must be paths). + * + * The callback can return null to indicate to exclude the element from the + * new collection. + * + * If an array is returned, the array will be flattened into the result + * collection. + * + * @param callback + * @param type Force the new collection to be of a specific type + */ + map<T = ASTNode>( + callback: ( + path: ASTPath<N>, + i: number, + paths: Array<ASTPath<N>> + ) => ASTPath<T> | Array<ASTPath<T>> | null | undefined, + type: Type<any> + ): Collection<T>; + + /** Returns the number of elements in this collection. */ + size(): number; + + /** Returns the number of elements in this collection. */ + length: number; + + /** Returns an array of AST nodes in this collection. */ + nodes(): N[]; + + /** Returns an array of ASTPaths in this this collection. */ + paths(): Array<ASTPath<N>>; + + getAST(): Array<ASTPath<any>>; + + /** + * Converts the AST back to a string, using recast. + * @param options directly passed to recast's printer + */ + toSource(options?: Options): string; + + /** + * Returns a new collection containing only the element at position index. + * In case of a negative index, the element is taken from the end: + * .at(0) - first element + * .at(-1) - last element + */ + at(index: number): Collection<N>; + + /** Calls "get" on the first path (same as "collection.paths(0).get(...)"). */ + get(...fields: Array<string | number>): any; + + /** + * Returns the type(s) of the collection. This is only used for unit tests, + * don't think other consumers would need it. + */ + getTypes(): string[]; + + /** + * Returns true if this collection has the type 'type'. + */ + isOfType(type: Type<any>): boolean; +} + +/** + * This function adds the provided methods to the prototype of the corresponding + * typed collection. If no type is passed, the methods are added to + * Collection.prototype and are available for all collections. + * + * @param methods Methods to add to the prototype + * @param type Optional type to add the methods to + */ +export function registerMethods(methods: object, type?: Type<any>): void; + +export { }; // to shut off automatic exporting diff --git a/types/jscodeshift/src/collections/JSXElement.d.ts b/types/jscodeshift/src/collections/JSXElement.d.ts new file mode 100644 index 0000000000..730c33ad90 --- /dev/null +++ b/types/jscodeshift/src/collections/JSXElement.d.ts @@ -0,0 +1,70 @@ +import { JSXElement } from "ast-types/gen/nodes"; +import { NodePath } from "recast"; +import { Collection } from "../Collection"; + +type ASTPath<N> = NodePath<N, N>; + +export interface GlobalMethods { + /** + * Finds all JSXElements optionally filtered by name + */ + findJSXElements(name?: string): Collection<JSXElement>; + + /** + * Finds all JSXElements by module name. Given + * + * var Bar = require('Foo'); + * <Bar /> + * + * findJSXElementsByModuleName('Foo') will find <Bar />, without having to + * know the variable name. + */ + findJSXElementsByModuleName(moduleName: string): Collection<JSXElement>; +} + +type Defined<T> = T extends undefined ? never : T; +type JSXElementChild = Defined<JSXElement["children"]>[0]; + +export interface TraversalMethods { + /** + * Returns all child nodes, including literals and expressions. + * This method only applies to JSXElement typed collections. + */ + childNodes(): Collection<JSXElementChild>; + + /** + * Returns all children that are JSXElements. + * This method only applies to JSXElement typed collections. + */ + childElements(): Collection<JSXElement>; +} + +interface Filter { + (path: ASTPath<any>): boolean; +} + +export interface FilterMethods { + /** + * Filter method for attributes. + */ + hasAttributes(attributeFilter: { [attributeName: string]: any }): Filter; + + /** + * Filter elements which contain a specific child type + */ + hasChildren(name: string): Filter; +} + +export interface MappingMethods { + /** + * Given a JSXElement, returns its "root" name. E.g. it would return "Foo" for + * both <Foo /> and <Foo.Bar />. + */ + getRootName(path: ASTPath<any>): string; +} + +export function register(): void; +export const filters: FilterMethods; +export const mappings: MappingMethods; + +export { }; // to shut off automatic exporting diff --git a/types/jscodeshift/src/collections/Node.d.ts b/types/jscodeshift/src/collections/Node.d.ts new file mode 100644 index 0000000000..e596c8a8ab --- /dev/null +++ b/types/jscodeshift/src/collections/Node.d.ts @@ -0,0 +1,57 @@ +import { VariableDeclarator } from "ast-types/gen/nodes"; +import { ASTNode, NodePath, Type } from "recast"; +import { Collection } from "../Collection"; + +type ASTPath<N> = NodePath<N, N>; + +export interface TraversalMethods { + /** + * Find nodes of a specific type within the nodes of this collection. + */ + find<T>(type: Type<T>, filter?: ((value: any) => boolean) | object): Collection<T>; + + /** + * Returns a collection containing the paths that create the scope of the + * currently selected paths. Dedupes the paths. + */ + closestScope(): Collection<ASTNode>; + + /** + * Traverse the AST up and finds the closest node of the provided type. + */ + closest<T>(type: Type<T>, filter?: any): Collection<T>; + + /** + * Finds the declaration for each selected path. Useful for member expressions + * or JSXElements. Expects a callback function that maps each path to the name + * to look for. + * + * If the callback returns a falsey value, the element is skipped. + */ + getVariableDeclarators(nameGetter: (...args: any[]) => any): Collection<VariableDeclarator>; +} + +export interface MutationMethods<N> { + /** + * Simply replaces the selected nodes with the provided node. If a function + * is provided it is executed for every node and the node is replaced with the + * functions return value. + */ + replaceWith<T>(nodes: T | T[] | ((path: ASTPath<N>, i: number) => T)): Collection<T>; + + /** + * Inserts a new node before the current one. + */ + insertBefore(insert: any): Collection<N>; + + /** + * Inserts a new node after the current one. + */ + insertAfter(insert: any): Collection<N>; + + remove(): Collection<N>; +} + +export function register(): void; + +export { }; // to shut off automatic exporting diff --git a/types/jscodeshift/src/collections/VariableDeclarator.d.ts b/types/jscodeshift/src/collections/VariableDeclarator.d.ts new file mode 100644 index 0000000000..8627b316db --- /dev/null +++ b/types/jscodeshift/src/collections/VariableDeclarator.d.ts @@ -0,0 +1,39 @@ +import { VariableDeclarator } from "ast-types/gen/nodes"; +import { NodePath } from "recast"; +import { Collection } from "../Collection"; + +type ASTPath<N> = NodePath<N, N>; + +export interface GlobalMethods { + /** + * Finds all variable declarators, optionally filtered by name. + */ + findVariableDeclarators(name?: string): Collection<VariableDeclarator>; +} + +export interface TransformMethods<N> { + /** + * Renames a variable and all its occurrences. + * This method only applies to VariableDeclarator typed collections. + */ + renameTo(newName: string): Collection<N>; +} + +interface Filter { + (path: ASTPath<any>): boolean; +} + +export interface FilterMethods { + /** + * Returns a function that returns true if the provided path is a variable + * declarator and requires one of the specified module names. + * + * @param names A module name or an array of module names + */ + requiresModule(names: string | string[]): Filter; +} + +export function register(): void; +export const filters: FilterMethods; + +export { }; // to shut off automatic exporting diff --git a/types/jscodeshift/src/template.d.ts b/types/jscodeshift/src/template.d.ts new file mode 100644 index 0000000000..44bfab9be3 --- /dev/null +++ b/types/jscodeshift/src/template.d.ts @@ -0,0 +1,14 @@ +import { Parser } from "recast"; + +export interface Template { + /** Tagged template function. Parses the string as source and returns an array of Statement AST nodes. */ + statements(...args: any[]): any; + /** Tagged template function. Parses the string as source and returns an Statement AST node. */ + statement(...args: any[]): any; + /** Tagged template function. Parses the string as source and returns an Expression AST node. */ + expression(...args: any[]): any; +} + +export default function withParser(parser: Parser): Template; + +export { }; // to shut off automatic exporting diff --git a/types/jscodeshift/tsconfig.json b/types/jscodeshift/tsconfig.json index 8ad162be32..a2c90ce266 100644 --- a/types/jscodeshift/tsconfig.json +++ b/types/jscodeshift/tsconfig.json @@ -18,6 +18,11 @@ }, "files": [ "index.d.ts", + "src/Collection.d.ts", + "src/collections/JSXElement.d.ts", + "src/collections/Node.d.ts", + "src/collections/VariableDeclarator.d.ts", + "src/template.d.ts", "test/jscodeshift-tests.ts", "test/js-transforms/bind-this-to-bind-expression.ts", "test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts", diff --git a/types/jscodeshift/tslint.json b/types/jscodeshift/tslint.json index 94991f356f..f93cf8562a 100644 --- a/types/jscodeshift/tslint.json +++ b/types/jscodeshift/tslint.json @@ -1,8 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "no-declare-current-package": false, - "no-self-import": false, - "no-unnecessary-generics": false - } + "extends": "dtslint/dt.json" } From 716a420713c9b0f3cc604f7278ae5c559de90f76 Mon Sep 17 00:00:00 2001 From: Jeffrey Meng <jeffkmeng@gmail.com> Date: Sat, 2 Feb 2019 19:12:38 -0800 Subject: [PATCH 058/197] Move interfaces into namespace --- types/list.js/index.d.ts | 69 ++++++++++++++++++++-------------------- 1 file changed, 35 insertions(+), 34 deletions(-) diff --git a/types/list.js/index.d.ts b/types/list.js/index.d.ts index 0c2e4fb905..8209d87e67 100644 --- a/types/list.js/index.d.ts +++ b/types/list.js/index.d.ts @@ -4,25 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.7 -interface ListOptions { - valueNames?: string[]; - item?: string; - listClass?: string; - searchClass?: string; - sortClass?: string; - indexAsync?: boolean; - page?: number; - i?: number; - pagination?: boolean; -} - -interface SortOptions { - order?: string; - alphabet?: string; - insensitive?: boolean; - sortFunction?: ((a: object, b: object) => number|undefined); -} - declare class List { listContainer: HTMLElement; list: HTMLElement; @@ -32,15 +13,15 @@ declare class List { searched: boolean; filtered: boolean; - constructor(element: string|HTMLElement, options?: ListOptions, values?: object[]); + constructor(element: string|HTMLElement, options?: List.ListOptions, values?: object[]); - add(values: object[], callback?: (item: ListItem) => void): void; + add(values: object[], callback?: (item: List.ListItem) => void): void; remove(valueName: string, value: any): number; - get(valueName: string, value: any): ListItem[]; - sort(valueName: string, options: SortOptions): void; + get(valueName: string, value: any): List.ListItem[]; + sort(valueName: string, options: List.SortOptions): void; search(searchString: string, columns?: string[]): void; clear(): void; - filter(filterFunction: (item: ListItem) => boolean): void; + filter(filterFunction: (item: List.ListItem) => boolean): void; size(): number; show(i: number, page: number): void; update(): void; @@ -49,16 +30,36 @@ declare class List { on(event: string, callback: () => void): void; } -declare class ListItem { - elm: HTMLElement; +declare namespace List { + interface ListItem { + elm: HTMLElement; - values(newValues: object): void; - values(): object; - show(): void; - hide(): void; - matching(): boolean; - visible(): boolean; + values(newValues: object): void; + values(): object; + show(): void; + hide(): void; + matching(): boolean; + visible(): boolean; + } + + interface ListOptions { + valueNames?: string[]; + item?: string; + listClass?: string; + searchClass?: string; + sortClass?: string; + indexAsync?: boolean; + page?: number; + i?: number; + pagination?: boolean; + } + + interface SortOptions { + order?: string; + alphabet?: string; + insensitive?: boolean; + sortFunction?: ((a: object, b: object) => number|undefined); + } } -export default List; -export {ListOptions, SortOptions, ListItem, List}; +export = List; From 8ae30e8f89ea9604755aad7c0624fdc99e8f48ba Mon Sep 17 00:00:00 2001 From: Patrick Chatain <patrick.chatain@fullsix.com> Date: Sun, 3 Feb 2019 14:32:30 +0100 Subject: [PATCH 059/197] add toJson job method --- types/bull/index.d.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index bbafa0301c..36f05a7058 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -228,6 +228,25 @@ declare namespace Bull { * Takes a lock for this job so that no other queue worker can process it at the same time. */ takeLock(): Promise<number | false>; + + /** + * Get job properties as Json Object + */ + toJSON(): { + id: JobId, + name: string, + data: T, + opts: JobOptions, + progress: number, + delay: number, + timestamp: number, + attemptsMade: number, + failedReason: string, + stacktrace: string[] | null, + returnvalue: any, + finishedOn: number | null, + processedOn: number | null + }; } type JobStatus = 'completed' | 'waiting' | 'active' | 'delayed' | 'failed'; From fff62884caad593567558d422cf0f15728fa488b Mon Sep 17 00:00:00 2001 From: Krantisinh Deshmukh <krantisinh@monjin.com> Date: Mon, 4 Feb 2019 12:57:43 +0530 Subject: [PATCH 060/197] [Ramda] - Improved type signatures of R.move. --- types/ramda/index.d.ts | 6 ++++-- types/ramda/ramda-tests.ts | 12 ++++-------- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index a35b2612ee..05b629137d 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -1578,10 +1578,12 @@ declare namespace R { multiply(a: number): (b: number) => number; /** - * Moves an item, at index `from`, to index `to`, in a list of elements. + * Moves an item, at index `from`, to index `to`, in a `list` of elements. * A new list will be created containing the new elements order. */ - move: CurriedFunction3<number, number, any[], any[]>; + move<T>(from: number, to: number, list: ReadonlyArray<T>): T[]; + move(from: number, to: number): <T>(list: ReadonlyArray<T>) => T[]; + move(from: number): (<T>(to: number, list: ReadonlyArray<T>) => T[]); /** * Wraps a function of any arity (including nullary) in a function that accepts exactly n parameters. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 87c4c7a099..6c568d4a56 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -1118,18 +1118,14 @@ interface Obj { () => { const sampleList = ['a', 'b', 'c', 'd', 'e', 'f']; - R.move(0, 2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] - R.move(-1, 0, sampleList); // => ['f', 'a', 'b', 'c', 'd', 'e'] list rotation + R.move<string>(0, 2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + R.move<string>(-1, 0, sampleList); // => ['f', 'a', 'b', 'c', 'd', 'e'] list rotation const moveCurried1 = R.move(0, 2); - moveCurried1(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + moveCurried1<string>(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] const moveCurried2 = R.move(0); - moveCurried2(2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] - - const moveCurried3 = R.move(0); - const moveCurried4 = moveCurried3(2); - moveCurried4(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + moveCurried2<string>(2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] }; () => { From b1d57876b3e38aef24d91c0a0c579a8805a83ff2 Mon Sep 17 00:00:00 2001 From: Tobias Gimpel <gimpel@pisa.hom> Date: Mon, 4 Feb 2019 13:02:42 +0100 Subject: [PATCH 061/197] [index.d.ts] Made BackgroundTransfer a namespace, changed inaccessible classes to interfaces --- ...ordova-plugin-background-download-tests.ts | 2 +- .../index.d.ts | 112 +++++++++--------- 2 files changed, 54 insertions(+), 60 deletions(-) diff --git a/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts b/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts index b531c96570..e56d14ce04 100644 --- a/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts +++ b/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts @@ -11,7 +11,7 @@ const onError = (err: any) => { console.log(err); }; - const onProgress = (progress: BackgroundDownloadProgress) => { + const onProgress = (progress: BackgroundTransfer.Progress) => { console.log((100 * progress.bytesReceived / progress.totalBytesToReceive) + '%'); }; diff --git a/types/cordova-plugin-background-download/index.d.ts b/types/cordova-plugin-background-download/index.d.ts index f99b655c47..815d20bf66 100644 --- a/types/cordova-plugin-background-download/index.d.ts +++ b/types/cordova-plugin-background-download/index.d.ts @@ -8,27 +8,61 @@ * Provides an advanced file transfer functionality that persists beyond app termination and * runs in the background. Background transfer doesn't support concurrent downloads of the same uri. */ -declare var BackgroundTransfer: BackgroundTransferInterface; -interface BackgroundTransferInterface { - BackgroundDownloader: typeof BackgroundDownloader; -} +declare namespace BackgroundTransfer { + class BackgroundDownloader { + /** + * Initializes a new instance of BackgroundDownloader object. + * Used to configure downloads prior to the actual creation of the download operation using CreateDownload. + * + * @param uriMatcher The regexp to compare location of the resources with already downloading ones. + */ + constructor(uriMatcher?: RegExp); + /** + * Initializes a DownloadOperation object that contains the specified Uri and the file that the response is written to. + * + * @param uri The location of the resource. + * @param resultFile The file that the response will be written to. + * @param notificationTitle The title for downloading in notification. + */ + createDownload(uri: string, resultFile: File, notificationTitle?: string): DownloadOperation; + } + + interface Progress { + bytesReceived: number; + totalBytesToReceive: number; + } -declare class BackgroundDownloader { /** - * Initializes a new instance of BackgroundDownloader object. - * Used to configure downloads prior to the actual creation of the download operation using CreateDownload. - * - * @param uriMatcher The regexp to compare location of the resources with already downloading ones. + * Provides a mechanism for managing interactions with asynchronous APIs based on Promises. + * See 'Asynchronous programming in JavaScript' for more details + * http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx + * http://msdn.microsoft.com/en-us/library/windows/apps/br211867.aspx + * Note. Functionality is limited, support of .then and .cancel methods only, other methods are in progress. */ - constructor(uriMatcher?: RegExp); - /** - * Initializes a DownloadOperation object that contains the specified Uri and the file that the response is written to. - * - * @param uri The location of the resource. - * @param resultFile The file that the response will be written to. - * @param notificationTitle The title for downloading in notification. - */ - createDownload(uri: string, resultFile: File, notificationTitle?: string): DownloadOperation; + interface Promise { + _completeCallbacks: Array<() => void>; + _errorCallbacks: Array<(error: any) => void>; + _progressCallbacks: Array<(progress: Progress) => void>; + _chainedDefer: Deferral; + _state: 'pending' | 'resolved' | 'rejected' | 'cancelled'; + result: any; + then(onComplete?: () => void, onError?: (error: any) => void, onProgress?: (progress: Progress) => void): Promise; + /** + * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and + * cancellation is supported, the promise enters the error state with a value of Error("Canceled"). + * http://msdn.microsoft.com/en-us/library/windows/apps/br211667.aspx + * @param flag + */ + cancel(flag?: boolean): void; + executeCallback(callback: (() => void) | ((error: any) => void) | ((progress: Progress) => void), args: any): void; + } + + interface Deferral { + resolve(data: any): void; + reject(error: any): void; + notify(value: any): void; + bind(promise: Promise): void; + } } declare class DownloadOperation { @@ -44,49 +78,9 @@ declare class DownloadOperation { /** * Starts an asynchronous download operation. */ - startAsync(): BackgroundDownloadPromise; + startAsync(): BackgroundTransfer.Promise; /** * Stops a download operation. */ stop(): void; } - -interface BackgroundDownloadProgress { - bytesReceived: number; - totalBytesToReceive: number; -} - -declare class BackgroundDownloadPromise { - /** - * Provides a mechanism for managing interactions with asynchronous APIs based on Promises. - * See 'Asynchronous programming in JavaScript' for more details - * http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx - * http://msdn.microsoft.com/en-us/library/windows/apps/br211867.aspx - * Note. Functionality is limited, support of .then and .cancel methods only, other methods are in progress. - */ - constructor(); - static Deferral: typeof Deferral; - _completeCallbacks: Array<() => void>; - _errorCallbacks: Array<(error: any) => void>; - _progressCallbacks: Array<(progress: BackgroundDownloadProgress) => void>; - _chainedDefer: Deferral; - _state: 'pending' | 'resolved' | 'rejected' | 'cancelled'; - result: any; - then(onComplete?: () => void, onError?: (error: any) => void, onProgress?: (progress: BackgroundDownloadProgress) => void): BackgroundDownloadPromise; - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and - * cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - * http://msdn.microsoft.com/en-us/library/windows/apps/br211667.aspx - * @param flag - */ - cancel(flag?: boolean): void; - executeCallback(callback: (() => void) | ((error: any) => void) | ((progress: BackgroundDownloadProgress) => void), args: any): void; -} - -declare class Deferral { - constructor(); - resolve(data: any): void; - reject(error: any): void; - notify(value: any): void; - bind(promise: BackgroundDownloadPromise): void; -} From 8fcf35037f5ed17cf50c4ca6d09eb313e788e13a Mon Sep 17 00:00:00 2001 From: Gerhard Stoebich <18708370+Flarna@users.noreply.github.com> Date: Thu, 31 Jan 2019 13:46:46 +0100 Subject: [PATCH 062/197] [node] correct SlowBuffer --- types/node/buffer.d.ts | 10 ++++++++-- types/node/globals.d.ts | 10 ---------- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/types/node/buffer.d.ts b/types/node/buffer.d.ts index 86fdfdb36c..1d618f2c4b 100644 --- a/types/node/buffer.d.ts +++ b/types/node/buffer.d.ts @@ -1,6 +1,12 @@ declare module "buffer" { export const INSPECT_MAX_BYTES: number; const BuffType: typeof Buffer; - const SlowBuffType: typeof SlowBuffer; - export { BuffType as Buffer, SlowBuffType as SlowBuffer }; + + export const SlowBuffer: { + /** @deprecated since v6.0.0, use Buffer.allocUnsafeSlow() */ + new(size: number): Buffer; + prototype: Buffer; + }; + + export { BuffType as Buffer }; } diff --git a/types/node/globals.d.ts b/types/node/globals.d.ts index e4f6f40fd1..f95386c9cd 100644 --- a/types/node/globals.d.ts +++ b/types/node/globals.d.ts @@ -249,16 +249,6 @@ declare var module: NodeModule; // Same as module.exports declare var exports: any; -declare const SlowBuffer: { - new(str: string, encoding?: string): Buffer; - new(size: number): Buffer; - new(size: Uint8Array): Buffer; - new(array: any[]): Buffer; - prototype: Buffer; - isBuffer(obj: any): boolean; - byteLength(string: string, encoding?: string): number; - concat(list: Buffer[], totalLength?: number): Buffer; -}; // Buffer class type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; From ce19f8a19b9572016cc7e19757e2da9f8be8c5ed Mon Sep 17 00:00:00 2001 From: nossbigg <chenggibson@gmail.com> Date: Sat, 2 Feb 2019 23:48:00 +0800 Subject: [PATCH 063/197] [react-native] Enhance Keyboard API Event typings --- types/react-native/index.d.ts | 37 +++++++++++++++++++++++++++++++ types/react-native/test/index.tsx | 6 +++++ 2 files changed, 43 insertions(+) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 4b06119df2..2be1a48992 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -16,6 +16,7 @@ // Kacper Wiszczuk <https://github.com/esemesek> // Ryan Nickel <https://github.com/mrnickel> // Souvik Ghosh <https://github.com/souvik-ghosh> +// Cheng Gibson <https://github.com/nossbigg> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -8995,8 +8996,44 @@ export interface ARTStatic { Text: typeof ARTText; } +export type KeyboardEventName = + | "keyboardWillShow" + | "keyboardDidShow" + | "keyboardWillHide" + | "keyboardDidHide" + | "keyboardWillChangeFrame" + | "keyboardDidChangeFrame"; + +export type KeyboardEventEasing = + | "easeIn" + | "easeInEaseOut" + | "easeOut" + | "linear" + | "keyboard"; + +type ScreenRect = { + screenX: number; + screenY: number; + width: number; + height: number; +}; + +export interface KeyboardEvent { + duration: number; + easing: KeyboardEventEasing; + endCoordinates: ScreenRect; + startCoordinates: ScreenRect; + isEventFromThisApp: boolean; +} + +type KeyboardEventListener = (event: KeyboardEvent) => void; + export interface KeyboardStatic extends NativeEventEmitter { dismiss: () => void; + addListener( + eventType: KeyboardEventName, + listener: KeyboardEventListener + ): EmitterSubscription; } ////////////////////////////////////////////////////////////////////////// diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 801565dc8d..dfa327ce7b 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -85,6 +85,7 @@ import { DatePickerAndroid, ViewPropTypes, requireNativeComponent, + Keyboard, } from "react-native"; declare module "react-native" { @@ -843,3 +844,8 @@ const ShareTest = () => { } }); }; + +const KeyboardTest = () => { + const subscriber = Keyboard.addListener("keyboardDidHide", (event) => {event}); + subscriber.remove(); +} From 94ca48114444439f8e4bea0cfb451126c62c52a7 Mon Sep 17 00:00:00 2001 From: Kristoffer <hello@kristoffer.is> Date: Tue, 5 Feb 2019 10:44:22 +0100 Subject: [PATCH 064/197] libxmljs: Allow boolean options --- types/libxmljs/index.d.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/types/libxmljs/index.d.ts b/types/libxmljs/index.d.ts index a29a6adeda..db37035f06 100644 --- a/types/libxmljs/index.d.ts +++ b/types/libxmljs/index.d.ts @@ -14,12 +14,15 @@ export const libxml_parser_version: string; // tslint:disable-next-line:strict-export-declare-modifiers interface StringMap { [key: string]: string; } -export function parseXml(source: string, options?: StringMap): Document; -export function parseXmlString(source: string, options?: StringMap): Document; +// tslint:disable-next-line:strict-export-declare-modifiers +interface ParserOptions { [key: string]: boolean | string; } -export function parseHtml(source: string, options?: StringMap): Document; -export function parseHtmlString(source: string, options?: StringMap): Document; -export function parseHtmlFragment(source: string, options?: StringMap): Document; +export function parseXml(source: string, options?: ParserOptions): Document; +export function parseXmlString(source: string, options?: ParserOptions): Document; + +export function parseHtml(source: string, options?: ParserOptions): Document; +export function parseHtmlString(source: string, options?: ParserOptions): Document; +export function parseHtmlFragment(source: string, options?: ParserOptions): Document; export function memoryUsage(): number; export function nodeCount(): number; From b4683d718608a517a0a925d0537ca0783a088fe2 Mon Sep 17 00:00:00 2001 From: Erik Krogh Kristensen <erik@webbies.dk> Date: Tue, 5 Feb 2019 14:20:00 +0100 Subject: [PATCH 065/197] loglevel: Move noConflict and getLogger to a DefaultLogger interface --- types/loglevel/index.d.ts | 48 ++++++++++++++++++++------------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/types/loglevel/index.d.ts b/types/loglevel/index.d.ts index 3ad9faf707..64eee88aa6 100644 --- a/types/loglevel/index.d.ts +++ b/types/loglevel/index.d.ts @@ -6,7 +6,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -declare var log: log.Logger; +declare var log: log.DefaultLogger; export as namespace log; export = log; @@ -44,6 +44,30 @@ declare namespace log { type MethodFactory = (methodName: string, level: LogLevelNumbers, loggerName: string) => LoggingMethod; + interface DefaultLogger extends Logger { + /** + * If you're using another JavaScript library that exposes a 'log' global, you can run into conflicts with loglevel. + * Similarly to jQuery, you can solve this by putting loglevel into no-conflict mode immediately after it is loaded + * onto the page. This resets to 'log' global to its value before loglevel was loaded (typically undefined), and + * returns the loglevel object, which you can then bind to another name yourself. + */ + noConflict(): any; + + /** + * This gets you a new logger object that works exactly like the root log object, but can have its level and + * logging methods set independently. All loggers must have a name (which is a non-empty string). Calling + * getLogger() multiple times with the same name will return an identical logger object. + * In large applications, it can be incredibly useful to turn logging on and off for particular modules as you are + * working with them. Using the getLogger() method lets you create a separate logger for each part of your + * application with its own logging level. Likewise, for small, independent modules, using a named logger instead + * of the default root logger allows developers using your module to selectively turn on deep, trace-level logging + * when trying to debug problems, while logging only errors or silencing logging altogether under normal + * circumstances. + * @param name The name of the produced logger + */ + getLogger(name: string): Logger; + } + interface Logger { /** * Available log levels. @@ -105,14 +129,6 @@ declare namespace log { */ setLevel(level: LogLevelDesc, persist?: boolean): void; - /** - * If you're using another JavaScript library that exposes a 'log' global, you can run into conflicts with loglevel. - * Similarly to jQuery, you can solve this by putting loglevel into no-conflict mode immediately after it is loaded - * onto the page. This resets to 'log' global to its value before loglevel was loaded (typically undefined), and - * returns the loglevel object, which you can then bind to another name yourself. - */ - noConflict(): any; - /** * Returns the current logging level, as a value from LogLevel. * It's very unlikely you'll need to use this for normal application logging; it's provided partly to help plugin @@ -137,20 +153,6 @@ declare namespace log { */ setDefaultLevel(level: LogLevelDesc): void; - /** - * This gets you a new logger object that works exactly like the root log object, but can have its level and - * logging methods set independently. All loggers must have a name (which is a non-empty string). Calling - * getLogger() multiple times with the same name will return an identical logger object. - * In large applications, it can be incredibly useful to turn logging on and off for particular modules as you are - * working with them. Using the getLogger() method lets you create a separate logger for each part of your - * application with its own logging level. Likewise, for small, independent modules, using a named logger instead - * of the default root logger allows developers using your module to selectively turn on deep, trace-level logging - * when trying to debug problems, while logging only errors or silencing logging altogether under normal - * circumstances. - * @param name The name of the produced logger - */ - getLogger(name: string): Logger; - /** * This enables all log messages, and is equivalent to log.setLevel("trace"). * From 7cfcc63349263b36d1dba5a64a7039b5e646145b Mon Sep 17 00:00:00 2001 From: Offir Golan <offirgolan@gmail.com> Date: Tue, 5 Feb 2019 09:38:15 -0800 Subject: [PATCH 066/197] fix(url-parse): Add optional stringify fn to `toString` --- types/url-parse/index.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/url-parse/index.d.ts b/types/url-parse/index.d.ts index 8fc22dbfc0..e9dbd83208 100644 --- a/types/url-parse/index.d.ts +++ b/types/url-parse/index.d.ts @@ -23,6 +23,8 @@ declare namespace URLParse { | 'username'; type QueryParser = (query: string) => object; + + type StringifyQuery = (query: object) => string; } interface URLParse { @@ -40,7 +42,7 @@ interface URLParse { readonly slashes: boolean; readonly username: string; set(part: URLParse.URLPart, value: string | object | number | undefined, fn?: boolean | URLParse.QueryParser): URLParse; - toString(): string; + toString(stringify?: URLParse.StringifyQuery): string; } declare const URLParse: { @@ -57,7 +59,7 @@ declare const URLParse: { location(url: string): object; qs: { parse: URLParse.QueryParser; - stringify(query: object): string; + stringify: URLParse.StringifyQuery; }; }; From f68b114c80675cbec1c6de875c77e6dd0681ccdf Mon Sep 17 00:00:00 2001 From: Offir Golan <offirgolan@gmail.com> Date: Tue, 5 Feb 2019 09:56:48 -0800 Subject: [PATCH 067/197] chore: Remove trailing whitespace --- types/url-parse/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/url-parse/index.d.ts b/types/url-parse/index.d.ts index e9dbd83208..cb3bc75dd5 100644 --- a/types/url-parse/index.d.ts +++ b/types/url-parse/index.d.ts @@ -23,7 +23,7 @@ declare namespace URLParse { | 'username'; type QueryParser = (query: string) => object; - + type StringifyQuery = (query: object) => string; } From 342d8a0a22b6f7d3882a8d8e6de80b6f4fc6ea9a Mon Sep 17 00:00:00 2001 From: Kyra <kyradiscord@gmail.com> Date: Tue, 5 Feb 2019 22:06:15 +0100 Subject: [PATCH 068/197] fix: Added missing properties for FetchError Ref: https://github.com/bitinn/node-fetch/blob/e996bdab73baf996cf2dbf25643c8fe2698c3249/src/fetch-error.js#L20-L25 --- types/node-fetch/index.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/node-fetch/index.d.ts b/types/node-fetch/index.d.ts index 1177e8da25..03ae639d26 100644 --- a/types/node-fetch/index.d.ts +++ b/types/node-fetch/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Torsten Werner <https://github.com/torstenwerner> // Niklas Lindgren <https://github.com/nikcorg> // Vinay Bedre <https://github.com/vinaybedre> +// Antonio Román <https://github.com/kyranet> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> @@ -134,6 +135,9 @@ export class Body { export class FetchError extends Error { name: "FetchError"; constructor(message: string, type: string, systemError: string); + type: string; + code?: string; + errno?: string; } export class Response extends Body { From 8aa0f3f0e0459cdeee0d5511f88dca5d877843aa Mon Sep 17 00:00:00 2001 From: Michal Kaminski <32871390+michal-b-kaminski@users.noreply.github.com> Date: Tue, 5 Feb 2019 20:30:41 +0100 Subject: [PATCH 069/197] Removed HostStatic and HostMapStatic Those classes are not exposed and can not be instantiated from user code --- types/cassandra-driver/index.d.ts | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index 02853c66ba..446cd0f7fb 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -499,8 +499,6 @@ export namespace types { } export let Client: ClientStatic; -export let Host: HostStatic; -export let HostMap: HostMapStatic; export let Encoder: EncoderStatic; export interface ClientOptions { @@ -611,14 +609,10 @@ export interface Client extends events.EventEmitter { stream(query: string, params?: any, options?: QueryOptions, callback?: Callback): NodeJS.ReadableStream; } -export interface HostStatic { - new (address: string, protocolVersion: number, options: ClientOptions): Host; -} - export interface Host extends events.EventEmitter { address: string; cassandraVersion: string; - dataCenter: string; + datacenter: string; rack: string; tokens: string[]; @@ -627,10 +621,6 @@ export interface Host extends events.EventEmitter { isUp(): boolean; } -export interface HostMapStatic { - new (): HostMap; -} - export interface HostMap extends events.EventEmitter { length: number; From ea43dcfd5c15a50235c3b908a329ce2e446565c7 Mon Sep 17 00:00:00 2001 From: Michal Kaminski <32871390+michal-b-kaminski@users.noreply.github.com> Date: Tue, 5 Feb 2019 21:35:18 +0100 Subject: [PATCH 070/197] Fixed metadata namespace Removed constructors for internal classes Added missing Metadata functions Added Promise returning overloads for Metadata functions --- types/cassandra-driver/index.d.ts | 108 ++++++++++++++++++------------ 1 file changed, 66 insertions(+), 42 deletions(-) diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index 446cd0f7fb..264d5ddec8 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -732,19 +732,10 @@ export namespace errors { } export namespace metadata { - let Aggregate: AggregateStatic; - let Index: IndexStatic; - let MaterializedView: MaterializedViewStatic; let Metadata: MetadataStatic; - let SchemaFunction: SchemaFunctionStatic; - let TableMetadata: TableMetadataStatic; type caching = "all" | "keys_only" | "rows_only" | "none"; - interface AggregateStatic { - new (): Aggregate; - } - interface Aggregate { argumentTypes: Array<{ code: number, info: any }>; finalFunction: string; @@ -756,10 +747,6 @@ export namespace metadata { stateType: string; } - interface ClientStateStatic { - new (): ClientState; - } - interface ClientState { getConnectedHosts(): Host[]; getInFlightQueries(host: Host): number; @@ -812,13 +799,6 @@ export namespace metadata { composites } - interface IndexStatic { - new (name: string, target: string, kind: string | IndexType, options: object): Index; - - fromRows(indexRows: types.Row[]): Index[]; - fromColumnRows(columnRows: types.Row[], columnsByName: { [key: string]: ColumnInfo }): Index[]; - } - interface Index { kind: IndexType; name: string; @@ -830,11 +810,43 @@ export namespace metadata { isKeysKind(): boolean; } - interface MaterializedViewStatic { - new (name: string): MaterializedView; + interface MaterializedView extends DataCollection { } + + class Token { + getType(): types.dataTypes; + getValue(): any; + compare(other: Token): number; + equals(other: Token): boolean; } - interface MaterializedView extends DataCollection { } + interface TokenRange { + start: Token; + end: Token; + + splitEvenly(numberOfSplits: number): TokenRange[]; + isEmpty(): boolean; + isWrappedAround(): boolean; + unwrap(): TokenRange[]; + contains(token: Token): boolean; + equals(other: TokenRange): boolean; + compare(other: TokenRange): number; + } + + class ByteOrderedToken extends Token {} + class Murmur3Token extends Token {} + class BytRandomToken extends Token {} + + interface QueryTrace { + requestType: any; + coordinator: any; + parameters: any; + startedAt: any; + duration: any; + clientAddress: any; + events: Array<{ id: any; activity: any; source: any; elapsed: any; thread: any }>; + } + + type MetadataCallback<T> = (err: any, retVal: T) => void; interface MetadataStatic { new (options: ClientOptions, controlConnection: any): Metadata; @@ -843,21 +855,37 @@ export namespace metadata { interface Metadata { clearPrepared(): void; - getAggregate(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: Callback): void; - getAggregates(keyspaceName: string, name: string, callback: Callback): void; - getFunction(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: Callback): void; - getFunctions(keyspaceName: string, name: string, callback: Callback): void; - getMaterializedView(keyspaceName: string, name: string, callback: Callback): void; - getReplicas(keyspaceName: string, tokenBuffer: Buffer): any[]; - getTable(keyspaceName: string, name: string, callback: Callback): void; - getTrace(traceId: types.Uuid, callback: Callback): void; - getUdt(keyspaceName: string, name: string, callback: Callback): void; - refreshKeyspace(name: string, callback?: Callback): void; - refreshKeyspaces(callback?: Callback): void; - } - - interface SchemaFunctionStatic { - new (): SchemaFunction; + getAggregate(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: MetadataCallback<Aggregate>): void; + getAggregate(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>): Promise<Aggregate>; + getAggregates(keyspaceName: string, name: string, callback: MetadataCallback<Aggregate[]>): void; + getAggregates(keyspaceName: string, name: string): Promise<Aggregate[]>; + getFunction(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: MetadataCallback<SchemaFunction>): void; + getFunction(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>): Promise<SchemaFunction>; + getFunctions(keyspaceName: string, name: string, callback: MetadataCallback<SchemaFunction[]>): void; + getFunctions(keyspaceName: string, name: string): Promise<SchemaFunction[]>; + getMaterializedView(keyspaceName: string, name: string, callback: MetadataCallback<MaterializedView>): void; + getMaterializedView(keyspaceName: string, name: string, callback: Callback): Promise<MaterializedView>; + getReplicas(keyspaceName: string, token: Buffer | Token | TokenRange): any[]; // TODO + getTable(keyspaceName: string, name: string, callback: MetadataCallback<TableMetadata>): void; + getTable(keyspaceName: string, name: string): Promise<TableMetadata>; + getTokenRanges(): Set<TokenRange>; + getTokenRangesForHost(keyspaceName: string, host: Host): Set<TokenRange> | null; + getTrace(traceId: types.Uuid, consistency: types.consistencies, callback: MetadataCallback<QueryTrace>): void; + getTrace(traceId: types.Uuid, consistency: types.consistencies, callback: Callback): Promise<QueryTrace>; + getTrace(traceId: types.Uuid, callback: MetadataCallback<QueryTrace>): void; + getTrace(traceId: types.Uuid): Promise<QueryTrace>; + getUdt(keyspaceName: string, name: string, callback: MetadataCallback<any>): void; // TODO + getUdt(keyspaceName: string, name: string): Promise<any>; // TODO + newToken(components: Buffer[] | Buffer | string): Token; + newTokenRange(start: Token, end: Token): TokenRange; + refreshKeyspace(name: string, callback: Callback): void; + refreshKeyspace(name: string): Promise<void>; + refreshKeyspaces(waitReconnect: () => boolean, callback: Callback): void; + refreshKeyspaces(waitReconnect: () => boolean): Promise<void>; + refreshKeyspaces(waitReconnect: boolean, callback: Callback): void; + refreshKeyspaces(waitReconnect: boolean): Promise<void>; + refreshKeyspaces(callback: Callback): void; + refreshKeyspaces(): Promise<void>; } interface SchemaFunction { @@ -872,10 +900,6 @@ export namespace metadata { signature: string[]; } - interface TableMetadataStatic { - new (name: string): TableMetadata; - } - interface TableMetadata extends DataCollection { indexes: Index[]; indexInterval?: number; From 623449259ff9424bec6b6d2dfabcbb2232ece1c4 Mon Sep 17 00:00:00 2001 From: Michal Kaminski <32871390+michal-b-kaminski@users.noreply.github.com> Date: Tue, 5 Feb 2019 22:01:21 +0100 Subject: [PATCH 071/197] Added missing top-level exports token namespace ExecutionProfile constructor defaultOptions function version const --- types/cassandra-driver/index.d.ts | 72 +++++++++++++++++++------------ 1 file changed, 44 insertions(+), 28 deletions(-) diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index 264d5ddec8..81941afde0 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -812,29 +812,6 @@ export namespace metadata { interface MaterializedView extends DataCollection { } - class Token { - getType(): types.dataTypes; - getValue(): any; - compare(other: Token): number; - equals(other: Token): boolean; - } - - interface TokenRange { - start: Token; - end: Token; - - splitEvenly(numberOfSplits: number): TokenRange[]; - isEmpty(): boolean; - isWrappedAround(): boolean; - unwrap(): TokenRange[]; - contains(token: Token): boolean; - equals(other: TokenRange): boolean; - compare(other: TokenRange): number; - } - - class ByteOrderedToken extends Token {} - class Murmur3Token extends Token {} - class BytRandomToken extends Token {} interface QueryTrace { requestType: any; @@ -865,19 +842,19 @@ export namespace metadata { getFunctions(keyspaceName: string, name: string): Promise<SchemaFunction[]>; getMaterializedView(keyspaceName: string, name: string, callback: MetadataCallback<MaterializedView>): void; getMaterializedView(keyspaceName: string, name: string, callback: Callback): Promise<MaterializedView>; - getReplicas(keyspaceName: string, token: Buffer | Token | TokenRange): any[]; // TODO + getReplicas(keyspaceName: string, token: Buffer | token.Token | token.TokenRange): any[]; // TODO getTable(keyspaceName: string, name: string, callback: MetadataCallback<TableMetadata>): void; getTable(keyspaceName: string, name: string): Promise<TableMetadata>; - getTokenRanges(): Set<TokenRange>; - getTokenRangesForHost(keyspaceName: string, host: Host): Set<TokenRange> | null; + getTokenRanges(): Set<token.TokenRange>; + getTokenRangesForHost(keyspaceName: string, host: Host): Set<token.TokenRange> | null; getTrace(traceId: types.Uuid, consistency: types.consistencies, callback: MetadataCallback<QueryTrace>): void; getTrace(traceId: types.Uuid, consistency: types.consistencies, callback: Callback): Promise<QueryTrace>; getTrace(traceId: types.Uuid, callback: MetadataCallback<QueryTrace>): void; getTrace(traceId: types.Uuid): Promise<QueryTrace>; getUdt(keyspaceName: string, name: string, callback: MetadataCallback<any>): void; // TODO getUdt(keyspaceName: string, name: string): Promise<any>; // TODO - newToken(components: Buffer[] | Buffer | string): Token; - newTokenRange(start: Token, end: Token): TokenRange; + newToken(components: Buffer[] | Buffer | string): token.Token; + newTokenRange(start: token.Token, end: token.Token): token.TokenRange; refreshKeyspace(name: string, callback: Callback): void; refreshKeyspace(name: string): Promise<void>; refreshKeyspaces(waitReconnect: () => boolean, callback: Callback): void; @@ -941,6 +918,7 @@ export interface ExecutionOptions { } export let ExecutionOptions: ExecutionOptionsStatic; +export let ExecutionProfile: ExecutionProfileStatic; export namespace mapping { let Mapper: MapperStatic; @@ -1150,3 +1128,41 @@ export namespace metrics { } interface DefaultMetrics extends ClientMetrics {} } + +export namespace token { + interface Tokenizer { + hash(value: Buffer | number[]): Token; + parse(value: string): Token; + minToken(): Token; + split(start: Token, end: Token, numberOfSplits: number): TokenRange[]; + splitBase(start: number, end: number, ringEnd: number, ringLength: number, numberOfSplits: number): number[]; + stringify(token: Token): string; + } + + class Token { + constructor(value: any); + + getType(): { code: number, info: any }; + getValue(): any; + compare(other: Token): number; + equals(other: Token): boolean; + } + + class TokenRange { + start: Token; + end: Token; + + constructor(start: Token, end: Token, tokenizer: Tokenizer); + + splitEvenly(numberOfSplits: number): TokenRange[]; + isEmpty(): boolean; + isWrappedAround(): boolean; + unwrap(): TokenRange[]; + contains(token: Token): boolean; + equals(other: TokenRange): boolean; + compare(other: TokenRange): number; + } +} + +export const defaultOptions: () => ClientOptions; +export const version: string; \ No newline at end of file From 941c30484d0b411deeb4a87bfcaf08055365253d Mon Sep 17 00:00:00 2001 From: Michal Kaminski <32871390+michal-b-kaminski@users.noreply.github.com> Date: Tue, 5 Feb 2019 22:15:57 +0100 Subject: [PATCH 072/197] Rewritten policies.loadBalancing namespace to use classes So it allows writing own policies by extending LoadBalancingPolicy --- types/cassandra-driver/index.d.ts | 38 ++++++++++--------------------- 1 file changed, 12 insertions(+), 26 deletions(-) diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index 81941afde0..70da1c9ce5 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -34,43 +34,29 @@ export namespace policies { } namespace loadBalancing { - let DCAwareRoundRobinPolicy: DCAwareRoundRobinPolicyStatic; - let RoundRobinPolicy: RoundRobinPolicyStatic; - let TokenAwarePolicy: TokenAwarePolicyStatic; - let WhiteListPolicy: WhiteListPolicyStatic; - - interface LoadBalancingPolicy { + class LoadBalancingPolicy { init(client: Client, hosts: HostMap, callback: Callback): void; getDistance(host: Host): types.distance; newQueryPlan(keyspace: string, queryOptions: ExecutionOptions | null, callback: Callback): void; + getOptions(): Map<string, any>; } - interface DCAwareRoundRobinPolicyStatic { - new (localDc?: string): DCAwareRoundRobinPolicy; - } - - interface DCAwareRoundRobinPolicy extends LoadBalancingPolicy { + class DCAwareRoundRobinPolicy extends LoadBalancingPolicy { + localDc: string; localHostsArray: Host[]; - remoteHostsArray: Host[]; + + constructor(localDc?: string); } - interface RoundRobinPolicyStatic { - new (): RoundRobinPolicy; + class RoundRobinPolicy extends LoadBalancingPolicy {} + + class TokenAwarePolicy extends LoadBalancingPolicy { + constructor(childPolicy: LoadBalancingPolicy); } - interface RoundRobinPolicy extends LoadBalancingPolicy { } - - interface TokenAwarePolicyStatic { - new (childPolicy: LoadBalancingPolicy): TokenAwarePolicy; + class WhiteListPolicy extends LoadBalancingPolicy { + constructor(childPolicy: LoadBalancingPolicy, whiteList: string[]); } - - interface TokenAwarePolicy extends LoadBalancingPolicy { } - - interface WhiteListPolicyStatic { - new (childPolicy: LoadBalancingPolicy, whiteList: string[]): WhiteListPolicy; - } - - interface WhiteListPolicy extends LoadBalancingPolicy { } } namespace reconnection { From e2935590f3c0a49b185d5a8402333ac0656a1706 Mon Sep 17 00:00:00 2001 From: Michal Kaminski <32871390+michal-b-kaminski@users.noreply.github.com> Date: Tue, 5 Feb 2019 22:46:51 +0100 Subject: [PATCH 073/197] Fixed specification after testing + linter fixes --- types/cassandra-driver/index.d.ts | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index 70da1c9ce5..18527ed8c5 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -798,7 +798,6 @@ export namespace metadata { interface MaterializedView extends DataCollection { } - interface QueryTrace { requestType: any; coordinator: any; @@ -843,12 +842,9 @@ export namespace metadata { newTokenRange(start: token.Token, end: token.Token): token.TokenRange; refreshKeyspace(name: string, callback: Callback): void; refreshKeyspace(name: string): Promise<void>; - refreshKeyspaces(waitReconnect: () => boolean, callback: Callback): void; - refreshKeyspaces(waitReconnect: () => boolean): Promise<void>; refreshKeyspaces(waitReconnect: boolean, callback: Callback): void; - refreshKeyspaces(waitReconnect: boolean): Promise<void>; + refreshKeyspaces(waitReconnect?: boolean): Promise<void>; refreshKeyspaces(callback: Callback): void; - refreshKeyspaces(): Promise<void>; } interface SchemaFunction { @@ -1150,5 +1146,5 @@ export namespace token { } } -export const defaultOptions: () => ClientOptions; -export const version: string; \ No newline at end of file +export function defaultOptions(): ClientOptions; +export const version: string; From b99f36cd7e36391506c6d2c15cf943bf5ba2cf6a Mon Sep 17 00:00:00 2001 From: Michal Kaminski <32871390+michal-b-kaminski@users.noreply.github.com> Date: Tue, 5 Feb 2019 22:47:05 +0100 Subject: [PATCH 074/197] Updated and extended tests after changes --- .../cassandra-driver-tests.ts | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/types/cassandra-driver/cassandra-driver-tests.ts b/types/cassandra-driver/cassandra-driver-tests.ts index 3e203837b7..b4f850c315 100644 --- a/types/cassandra-driver/cassandra-driver-tests.ts +++ b/types/cassandra-driver/cassandra-driver-tests.ts @@ -102,3 +102,35 @@ const mapper = new cassandra.mapping.Mapper( const videoMapper = mapper.forModel('Video'); videoMapper.insert({ videoId: 'uuid', addedDate: new Date(), userId: 'uuid', name: 'My video', description: 'My desc' }); videoMapper.find({ videoId: 'uuid' }).then(results => results.first()); + +console.log(cassandra.version); + +const metadata = new cassandra.metadata.Metadata(cassandra.defaultOptions(), undefined); +let refreshFinished: Promise<void> = metadata.refreshKeyspaces(); +refreshFinished = metadata.refreshKeyspaces(true); +metadata.refreshKeyspaces(() => {}); +metadata.refreshKeyspaces(true, () => {}); + +const start: cassandra.token.Token = new cassandra.token.Token("x"); +const end: cassandra.token.Token = new cassandra.token.Token("z"); + +const tokenizer: cassandra.token.Tokenizer = { + hash: (value: Buffer | number[]) => new cassandra.token.Token("x"), + parse: (value: string) => new cassandra.token.Token("x"), + minToken: () => new cassandra.token.Token("x"), + split: (start: cassandra.token.Token, end: cassandra.token.Token, numberOfSplits: number) => [], + splitBase: (start: number, end: number, ringEnd: number, ringLength: number, numberOfSplits: number): number[] => [1], + stringify: (token: cassandra.token.Token): string => "asd" +}; + +const range: cassandra.token.TokenRange = new cassandra.token.TokenRange(start, end, tokenizer); + +class MyLoadBalancingPolicy extends cassandra.policies.loadBalancing.LoadBalancingPolicy { + getDistance() { + return cassandra.types.distance.ignored; + } +} + +const myPolicy: cassandra.policies.loadBalancing.LoadBalancingPolicy = new MyLoadBalancingPolicy(); +let existingPolicy: cassandra.policies.loadBalancing.LoadBalancingPolicy = new cassandra.policies.loadBalancing.DCAwareRoundRobinPolicy(); +existingPolicy = new cassandra.policies.loadBalancing.DCAwareRoundRobinPolicy("dc"); From 8803b9e34bcf2eb1de1903125405095648a87b9d Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Tue, 5 Feb 2019 15:19:44 -0800 Subject: [PATCH 075/197] Update README with links to gitter and infrastructure Also reduce the expected time before NPM publishing to "a few minutes" and the allowed time to "an hour" instead of "an hour" and "24 hours". --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index bbf2a6f16e..98d6f6ede4 100644 --- a/README.md +++ b/README.md @@ -11,8 +11,8 @@ Also see the [definitelytyped.org](http://definitelytyped.org) website, although This section tracks the health of the repository and publishing process. It may be helpful for contributors experiencing any issues with their PRs and packages. -* All packages are type-checking/linting cleanly: [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) -* All packages are being published to npm in under 10,000 seconds: [![Publish Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) +* All packages are [type-checking/linting](https://github.com/Microsoft/dtslint) cleanly: [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) +* All packages are being [published to npm](https://github.com/Microsoft/types-publisher) in under an hour: [![Publish Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) * [typescript-bot](https://github.com/typescript-bot) has been active on DefinitelyTyped [![Activity Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) If anything here seems wrong, or any of the above are failing, please raise an issue in [the DefinitelyTyped Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped). @@ -229,7 +229,7 @@ It depends, but most pull requests will be merged within a week. PRs that have b #### 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. +NPM packages should update within a few minutes. If it's been more than an hour, mention the PR number on [the DefinitelyTyped Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped) and the current maintainer will get the correct team member to investigate. #### I'm writing a definition that depends on another definition. Should I use `<reference types="" />` or an import? From a436f6c83f021c9f7f8f31f8377eeffe1c43a32a Mon Sep 17 00:00:00 2001 From: Jonathan Viney <jonathan.viney@gmail.com> Date: Wed, 6 Feb 2019 12:22:33 +1300 Subject: [PATCH 076/197] [video.js]: add player readyState() --- types/video.js/index.d.ts | 14 ++++++++++++++ types/video.js/video.js-tests.ts | 2 ++ 2 files changed, 16 insertions(+) diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index 62bbf83362..7f64f16b7a 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -3713,6 +3713,14 @@ declare namespace videojs { new (player: Player, options?: ComponentOptions): MouseTimeDisplay }; + enum ReadyState { + HaveNothing = 0, + HaveMetadata = 1, + HaveCurrentData = 2, + HaveFutureData = 3, + HaveEnoughData = 4 + } + /** * An instance of the `Player` class is created when any of the Video.js setup methods * are used to initialize a video. @@ -4342,6 +4350,12 @@ declare namespace videojs { */ preload(value?: boolean): string; + /** + * Returns a value that expresses the current state of the element + * with respect to rendering the current playback position. + */ + readyState(): ReadyState; + /** * Calculates how much time is left in the video. Not part * of the native video API. diff --git a/types/video.js/video.js-tests.ts b/types/video.js/video.js-tests.ts index 378a7150f3..910085557a 100644 --- a/types/video.js/video.js-tests.ts +++ b/types/video.js/video.js-tests.ts @@ -57,6 +57,8 @@ videojs("example_video_1").ready(function() { this.height(480); + const readyState: videojs.ReadyState = this.readyState(); + this.requestFullscreen(); testEvents(this); From 471af18e9f7332a9cd2cb115942c37b0caecc14f Mon Sep 17 00:00:00 2001 From: Jonathan Viney <jonathan.viney@gmail.com> Date: Wed, 6 Feb 2019 12:25:26 +1300 Subject: [PATCH 077/197] [video.js]: add player inactivityTimeout option --- types/video.js/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index 62bbf83362..a85081be66 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -4609,6 +4609,7 @@ declare namespace videojs { fluid?: boolean; height?: number; html5?: any; + inactivityTimeout?: number; language?: string; languages?: { [code: string]: LanguageTranslations }; loop?: boolean; From e731bb5edf8d72fccfbf215f5360cc3c643d5170 Mon Sep 17 00:00:00 2001 From: arichter83 <ar@5mm.de> Date: Wed, 6 Feb 2019 00:45:54 +0100 Subject: [PATCH 078/197] Fix $addToSet --- types/meteor/mongo.d.ts | 2 +- types/meteor/test/meteor-tests.ts | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/types/meteor/mongo.d.ts b/types/meteor/mongo.d.ts index 84b2d53528..079bf6272d 100644 --- a/types/meteor/mongo.d.ts +++ b/types/meteor/mongo.d.ts @@ -96,7 +96,7 @@ declare module "meteor/mongo" { { $each?: T[P], $position?: number, $slice?: number, $sort?: 1 | -1 | Dictionary<number> } } type ArraysOrEach<T> = { - [P in keyof T]?: OnlyArrays<T[P]> | { $each: T[P] } + [P in keyof T]?: OnlyElementsOfArrays<T[P]> | { $each: T[P] } } type CurrentDateModifier = { $type: "timestamp" | "date" } | true type Modifier<T> = T | { diff --git a/types/meteor/test/meteor-tests.ts b/types/meteor/test/meteor-tests.ts index 8e14f39fb1..8a9a32ddde 100644 --- a/types/meteor/test/meteor-tests.ts +++ b/types/meteor/test/meteor-tests.ts @@ -246,7 +246,13 @@ Items.insert({ list: groceriesId, name: "Persimmons" }); /** * From Collections, collection.update section */ -var Players = new Mongo.Collection('Players'); + +interface Players { + score: number + badges: string[] +} + +var Players: Mongo.Collection<Players> = new Mongo.Collection('Players'); Template['adminDashboard'].events({ 'click .givePoints': function () { @@ -265,6 +271,17 @@ Meteor.methods({ } }); +/** + * Also from Collections, collection.update section + */ +Meteor.methods({ + declareWinners: function () { + Players.update({ score: { $gt: 10 } }, + { $addToSet: { badges: {$each: ["Winner", "Super"]} } }, + { multi: true }); + } +}); + /** * From Collections, collection.remove section */ From b4efd11169d93b38be16d3ce17984b41d1c33b51 Mon Sep 17 00:00:00 2001 From: Alex Jerabek <aljerabe@microsoft.com> Date: Tue, 5 Feb 2019 16:14:10 -0800 Subject: [PATCH 079/197] Fixing Application.load description --- types/office-js/index.d.ts | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 0b4346ef8b..d53bdedb79 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -20747,22 +20747,20 @@ declare namespace Excel { /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. * + * @remarks + * + * In addition to this signature, this method has the following signatures: + * + * `load(option?: string | string[]): Excel.Application` - Where option is a comma-delimited string or an array of strings that specify the properties to load. + * + * `load(option?: { select?: string; expand?: string; }): Excel.Application` - Where option.select is a comma-delimited string that specifies the properties to load, and options.expand is a comma-delimited string that specifies the navigation properties to load. + * + * `load(option?: { select?: string; expand?: string; top?: number; skip?: number }): Excel.Application` - Only available on collection types. It is similar to the preceding signature. Option.top specifies the maximum number of collection items that can be included in the result. Option.skip specifies the number of items that are to be skipped and not included in the result. If option.top is specified, the result set will start after skipping the specified number of items. + * * @param options Provides options for which properties of the object to load. */ load(option?: Excel.Interfaces.ApplicationLoadOptions): Excel.Application; - /** - * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. - * - * @param options The names of the properties to load. - */ load(option?: string | string[]): Excel.Application; - /** - * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. - * - * @param options Provides options for which properties of the object to load. - * `option.select` is a comma-delimited string that specifies the properties to load, - * and `options.expand` is a comma-delimited string that specifies the navigation properties to load. - */ load(option?: { select?: string; expand?: string; From 219f33284fb726b557ad52d190f05dbbffd94fff Mon Sep 17 00:00:00 2001 From: Krantisinh Deshmukh <krantisinh@monjin.com> Date: Wed, 6 Feb 2019 10:08:43 +0530 Subject: [PATCH 080/197] [Ramda] - Added typings to support all combinations of curried versions of R.move --- types/ramda/index.d.ts | 5 ++++- types/ramda/ramda-tests.ts | 4 ++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 05b629137d..459a351c33 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -1583,7 +1583,10 @@ declare namespace R { */ move<T>(from: number, to: number, list: ReadonlyArray<T>): T[]; move(from: number, to: number): <T>(list: ReadonlyArray<T>) => T[]; - move(from: number): (<T>(to: number, list: ReadonlyArray<T>) => T[]); + move(from: number): { + <T>(to: number, list: ReadonlyArray<T>): T[]; + (to: number): <T>(list: ReadonlyArray<T>) => T[]; + }; /** * Wraps a function of any arity (including nullary) in a function that accepts exactly n parameters. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 6c568d4a56..e4039483da 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -1126,6 +1126,10 @@ interface Obj { const moveCurried2 = R.move(0); moveCurried2<string>(2, sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] + + const moveCurried3 = R.move(0); + const moveCurried4 = moveCurried3(2); + moveCurried4<string>(sampleList); // => ['b', 'c', 'a', 'd', 'e', 'f'] }; () => { From 8dc61af424b338d5829dcbe67a7615a577c16147 Mon Sep 17 00:00:00 2001 From: James Lismore <jlismore@gmail.com> Date: Tue, 5 Feb 2019 20:23:38 -0500 Subject: [PATCH 081/197] Allow for functional styles in victory Add missing VictoryLabel props --- types/victory/index.d.ts | 213 +++++++++++++++++++------------- types/victory/tslint.json | 7 +- types/victory/victory-tests.tsx | 67 +++++++--- 3 files changed, 177 insertions(+), 110 deletions(-) diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index c6909a4886..c1a1a6f394 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -33,17 +33,19 @@ declare module "victory" { "quad" | "quadIn" | "quadOut" | "quadInOut" | "sin" | "sinIn" | "sinOut" | "sinInOut"; // Many victory components accept string or number or callback which returns string or number - type StringOrNumberOrCallback = string | number | { (): string | number }; + type StringOrNumberOrCallback = + | string + | number + | ((datum: any, active: boolean) => string | number); type NumberOrCallback = ((datum: any, active: boolean) => number) | number; /** * Style interface used in components/themeing */ export interface VictoryStyleInterface { - parent?: React.CSSProperties; - data?: React.CSSProperties; - labels?: React.CSSProperties; - tickLabels?: React.CSSProperties; + parent?: { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; + data?: { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; + labels?: { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; } export interface VictoryAnimationProps { @@ -122,16 +124,19 @@ declare module "victory" { * Event handlers are currently only called with their corresponding events. */ events?: React.DOMAttributes<any>; - /** - * All Victory components will pass a text prop to their label component. - * This defines the content of the label when child nodes are absent. It will be ignored if children are provided. - */ - text?: StringOrNumberOrCallback; /** * The children of this component define the content of the label. * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. */ children?: StringOrNumberOrCallback; + /** + * The labelPlacement prop is used to specify the placement of labels relative to the data point they represent. + * This prop may be given as “vertical”, “parallel” or “perpendicular”. This props is particularly useful in polar + * charts, where it may be desireable to position a label either parallel or perpendicular to its corresponding angle. + * When this prop is not set, perpendicular label placement will be used for polar charts, and vertical label + * placement will be used for cartesian charts. + */ + labelPlacement?: "parallel" | "perpendicular" | "vertical"; /** * The lineHeight prop defines how much space a single line of text should take up. * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, @@ -141,10 +146,31 @@ declare module "victory" { * @default 1 */ lineHeight?: StringOrNumberOrCallback; + /** + * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. + * **This prop should not be set manually.** + */ + origin?: { x: number, y: number }; + /** + * Victory components can pass a boolean polar prop to specify whether a label is part of a polar chart. + * **This prop should not be set manually.** + */ + polar?: boolean; + /** + * The renderInPortal prop specifies whether VictoryLabel should render text in place or within a VictoryPortal. + * Setting renderInPortal to true is equivalent to wrapping VictoryLabel in a VictoryPortal. This prop is false by default. + */ + renderInPortal?: boolean; /** * The style prop applies CSS properties to the rendered `<text>` element. */ style?: React.CSSProperties; + /** + * The text prop defines the text VictoryLabel will render. The text prop may be given as a string, number, a function of datum, + * or an array of any of these. Strings may include newline characters, which VictoryLabel will split into separate + * <tspan/> elements. When text is given as an array, separate <tspan/> elements will be created for each element in the array. + */ + text?: string[] | StringOrNumberOrCallback; /** * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. */ @@ -1002,65 +1028,67 @@ declare module "victory" { label?: string | { (data: any): string }; } - export interface VictoryAreaProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryArea events. - * Since VictoryArea only renders a single element, the eventKey property is not used. - * The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. an area), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @example - * events={[ - * { - * target: "data", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - *}} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; - /** - * The interpolation prop determines how data points should be connected when plotting a line - * @default "linear" - */ - interpolation?: InterpolationPropType; - /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - * @default 50 - */ - samples?: number; - /** - * The style prop specifies styles for your VictoryArea. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. - * @example {data: {fill: "red"}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; + export interface VictoryAreaProps + extends VictoryCommonProps, + VictoryDatableProps, + VictorySingleLabableProps { + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryArea events. + * Since VictoryArea only renders a single element, the eventKey property is not used. + * The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. an area), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @example + * events={[ + * { + * target: "data", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; + /** + * The interpolation prop determines how data points should be connected when plotting a line + * @default "linear" + */ + interpolation?: InterpolationPropType; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + * @default 50 + */ + samples?: number; + /** + * The style prop specifies styles for your VictoryArea. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. + * @example {data: {fill: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; } /** @@ -1146,7 +1174,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"axis" | "axisLabel" | "grid" | "ticks" | "tickLabels" | "parent", number | string>[]; /** @@ -1198,20 +1225,40 @@ declare module "victory" { */ orientation?: "top" | "bottom" | "left" | "right"; /** - * The style prop specifies styles for your VictoryAxis. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. - * @example {axis: {stroke: "#756f6a"}, grid: {stroke: "grey"}, ticks: {stroke: "grey"}, - * tickLabels: {fontSize: 10, padding: 5}, axisLabel: {fontSize: 16, padding: 20}} + * The style prop defines the style of the component. The style prop should be given as an object + * with styles defined for parent, axis, axisLabel, grid, ticks, and tickLabels. Any valid svg + * styles are supported, but width, height, and padding should be specified via props as they + * determine relative layout for components in VictoryChart. Functional styles may be defined for + * grid, tick, and tickLabel style properties, and they will be evaluated with each tick. + * + * note: When a component is rendered as a child of another Victory component, or within a custom + * <svg> element with standalone={false} parent styles will be applied to the enclosing <g> tag. + * Many styles that can be applied to a parent <svg> will not be expressed when applied to a <g>. + * + * note: custom angle and verticalAnchor properties may be included in labels styles. */ style?: { parent?: React.CSSProperties; axis?: React.CSSProperties; axisLabel?: React.CSSProperties; - grid?: React.CSSProperties; - ticks?: React.CSSProperties; - tickLabels?: React.CSSProperties; + grid?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + ticks?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + tickLabels?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; }; /** * The tickComponent prop takes in an entire component which will be used @@ -1339,7 +1386,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; /** @@ -1449,7 +1495,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; /** @@ -1580,7 +1625,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; /** @@ -1685,7 +1729,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** @@ -1752,7 +1795,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; /** @@ -1995,7 +2037,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** @@ -2113,7 +2154,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** @@ -2220,7 +2260,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; /** diff --git a/types/victory/tslint.json b/types/victory/tslint.json index d100149dde..2fccde6e9b 100644 --- a/types/victory/tslint.json +++ b/types/victory/tslint.json @@ -5,15 +5,10 @@ "ban-types": false, "callable-types": false, "interface-over-type-literal": false, - "jsdoc-format": false, "no-any-union": false, "no-declare-current-package": false, "no-empty-interface": false, - "no-object-literal-type-assertion": false, "no-single-declare-module": false, - "no-unnecessary-generics": false, - "no-void-expression": false, - "strict-export-declare-modifiers": false, - "void-return": false + "strict-export-declare-modifiers": false } } diff --git a/types/victory/victory-tests.tsx b/types/victory/victory-tests.tsx index fc6ec678d4..fcd18571e3 100644 --- a/types/victory/victory-tests.tsx +++ b/types/victory/victory-tests.tsx @@ -53,6 +53,27 @@ test = <VictoryLabel x={50} y={10} {"data viz \n is \n fun!"} </VictoryLabel>; +test = ( + <VictoryLabel + text={datum => datum.label} + labelPlacement='perpendicular' + renderInPortal={true} + > + {"data viz \n is \n fun!"} + </VictoryLabel> +); + +test = ( + <VictoryLabel + text={['some', 'text', 'strings']} + labelPlacement='vertical' + renderInPortal={true} + lineHeight={'12'} + > + {"data viz \n is \n fun!"} + </VictoryLabel> +); + // VictoryArea test test = ( <VictoryArea @@ -156,32 +177,37 @@ test = ( test = ( <VictoryAxis style={{ - axis: {stroke: "black"}, - grid: {strokeWidth: 2}, - ticks: {stroke: "red"}, - tickLabels: {fontSize: 12}, - axisLabel: {fontSize: 16} + axis: { stroke: "black" }, + grid: { strokeWidth: 2 }, + ticks: { stroke: "red" }, + tickLabels: { fontSize: 12 }, + axisLabel: { fontSize: 16 } }} label="Planets" tickValues={[ - "Mercury", - "Venus", - "Earth", - "Mars", - "Jupiter" - ]}/> + "Mercury", + "Venus", + "Earth", + "Mars", + "Jupiter" + ]} /> ); test = ( <VictoryAxis scale="time" + style={{ + grid: { strokeWidth: tick => tick.x }, + ticks: { stroke: tick => tick.color }, + tickLabels: { fontSize: tick => tick.y }, + }} tickValues={[ new Date(1980, 1, 1), new Date(1990, 1, 1), new Date(2000, 1, 1), new Date(2010, 1, 1), new Date(2020, 1, 1)]} - tickFormat={(x) => x.getFullYear()}/> + tickFormat={(x) => x.getFullYear()} /> ); test = ( @@ -577,12 +603,19 @@ test = ( test = ( <VictoryScatter data={[ - {amount: 1, yield: 1, error: 0.5}, - {amount: 2, yield: 2, error: 1.1}, - {amount: 3, yield: 3, error: 0}, - {amount: 4, yield: 2, error: 0.1}, - {amount: 5, yield: 1, error: 1.5} + { amount: 1, yield: 1, error: 0.5 }, + { amount: 2, yield: 2, error: 1.1 }, + { amount: 3, yield: 3, error: 0 }, + { amount: 4, yield: 2, error: 0.1 }, + { amount: 5, yield: 1, error: 1.5 } ]} + style={{ + data: { + fill: d => d.x, + stroke: (datum, active) => active ? datum.x : datum.y, + strokeWidth: 3 + } + }} x={"amount"} y={(data) => (data.yield + data.error)} /> From fe4db4f74ef8bc5181048bae50734cdd40e11310 Mon Sep 17 00:00:00 2001 From: arichter83 <ar@5mm.de> Date: Wed, 6 Feb 2019 09:13:59 +0100 Subject: [PATCH 082/197] Added Meteor.absoluteUrl.defaultOptions --- types/meteor/meteor.d.ts | 15 ++++++++++----- types/meteor/test/meteor-tests.ts | 7 +++++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/types/meteor/meteor.d.ts b/types/meteor/meteor.d.ts index ca08c31c98..e1a51fe48e 100644 --- a/types/meteor/meteor.d.ts +++ b/types/meteor/meteor.d.ts @@ -63,11 +63,16 @@ declare module "meteor/meteor" { /** Method **/ /** Url **/ - function absoluteUrl(path?: string, options?: { - secure?: boolean; - replaceLocalhost?: boolean; - rootUrl?: string; - }): string; + var absoluteUrl: { + (path?: string, options?: absoluteUrlOptions): string; + defaultOptions: absoluteUrlOptions; + } + + interface absoluteUrlOptions { + secure?: boolean; + replaceLocalhost?: boolean; + rootUrl?: string; + } /** Url **/ /** Timeout **/ diff --git a/types/meteor/test/meteor-tests.ts b/types/meteor/test/meteor-tests.ts index 8a9a32ddde..db6815caf2 100644 --- a/types/meteor/test/meteor-tests.ts +++ b/types/meteor/test/meteor-tests.ts @@ -812,3 +812,10 @@ const collectionWithoutConnection = new Mongo.Collection<MonkeyDAO>("monkey", { }); } // End of namespace + +// absoluteUrl +Meteor.absoluteUrl('/sub', {rootUrl: 'http://wonderful.com'}); +Meteor.absoluteUrl.defaultOptions = { + rootUrl: 'http://123.com', + secure: false +}; From f245a172eb7bffb6a4aebd3768a5a38297131ed1 Mon Sep 17 00:00:00 2001 From: Jessica <jessicamfranco3@gmail.com> Date: Wed, 6 Feb 2019 20:01:40 +0900 Subject: [PATCH 083/197] Fix react-event-listener for breaking change in ts@next Use newfound ts@3.1 powers to improve the types. --- types/react-event-listener/index.d.ts | 2 +- types/react-event-listener/package.json | 7 + .../react-event-listener-tests.tsx | 2 +- types/react-event-listener/ts3.1/index.d.ts | 220 ++++++++++++++++++ .../ts3.1/react-event-listener-tests.tsx | 9 + .../react-event-listener/ts3.1/tsconfig.json | 25 ++ types/react-event-listener/ts3.1/tslint.json | 1 + 7 files changed, 264 insertions(+), 2 deletions(-) create mode 100644 types/react-event-listener/package.json create mode 100644 types/react-event-listener/ts3.1/index.d.ts create mode 100644 types/react-event-listener/ts3.1/react-event-listener-tests.tsx create mode 100644 types/react-event-listener/ts3.1/tsconfig.json create mode 100644 types/react-event-listener/ts3.1/tslint.json diff --git a/types/react-event-listener/index.d.ts b/types/react-event-listener/index.d.ts index c3ff194394..c264735c08 100644 --- a/types/react-event-listener/index.d.ts +++ b/types/react-event-listener/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as React from "react"; +import React = require("react"); export interface EventOptions { /** diff --git a/types/react-event-listener/package.json b/types/react-event-listener/package.json new file mode 100644 index 0000000000..24c89a85ed --- /dev/null +++ b/types/react-event-listener/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*": ["ts3.1/*"] } + } +} \ No newline at end of file diff --git a/types/react-event-listener/react-event-listener-tests.tsx b/types/react-event-listener/react-event-listener-tests.tsx index 8b9aae2c4d..e9a00dcc5f 100644 --- a/types/react-event-listener/react-event-listener-tests.tsx +++ b/types/react-event-listener/react-event-listener-tests.tsx @@ -1,4 +1,4 @@ -import * as React from "react"; +import React = require("react"); import EventListener, { withOptions } from "react-event-listener"; <EventListener target={document} onBeforeUnload={ev => { }} />; diff --git a/types/react-event-listener/ts3.1/index.d.ts b/types/react-event-listener/ts3.1/index.d.ts new file mode 100644 index 0000000000..b6e11bed31 --- /dev/null +++ b/types/react-event-listener/ts3.1/index.d.ts @@ -0,0 +1,220 @@ +import React = require("react"); + +export interface EventOptions extends Pick<AddEventListenerOptions, 'capture' | 'passive'> { } + +export function withOptions<T, TThis = any>(handler: (this: TThis, ev: T) => any, options: EventOptions): (this: TThis, ev: T) => any; + +export type EventListenerThisType<T extends EventTarget | WindowEventTargets> = T extends keyof Window ? Window[T] : T; + +export type OnErrorEventHandlerArgs = OnErrorEventHandlerNonNull extends (...args: infer A) => any ? A : []; + +export interface EventListenerProps<T extends EventTarget | WindowEventTargets> { + // Global events + onPointerCancel?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerCancelCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerDown?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerDownCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerEnter?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerEnterCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerLeave?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerLeaveCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerMove?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerMoveCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerOut?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerOutCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerOver?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerOverCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerUp?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onPointerUpCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onWheel?(this: EventListenerThisType<T>, ev: WheelEvent): any; + onWheelCapture?(this: EventListenerThisType<T>, ev: WheelEvent): any; + onAbort?(this: EventListenerThisType<T>, ev: Event): any; + onAbortCapture?(this: EventListenerThisType<T>, ev: Event): any; + onAfterPrint?(this: EventListenerThisType<T>, ev: Event): any; + onAfterPrintCapture?(this: EventListenerThisType<T>, ev: Event): any; + onBeforePrint?(this: EventListenerThisType<T>, ev: Event): any; + onBeforePrintCapture?(this: EventListenerThisType<T>, ev: Event): any; + onBeforeUnload?(this: EventListenerThisType<T>, ev: BeforeUnloadEvent): any; + onBeforeUnloadCapture?(this: EventListenerThisType<T>, ev: BeforeUnloadEvent): any; + onBlur?(this: EventListenerThisType<T>, ev: FocusEvent): any; + onBlurCapture?(this: EventListenerThisType<T>, ev: FocusEvent): any; + onCanPlay?(this: EventListenerThisType<T>, ev: Event): any; + onCanPlayCapture?(this: EventListenerThisType<T>, ev: Event): any; + onCanPlayThrough?(this: EventListenerThisType<T>, ev: Event): any; + onCanPlayThroughCapture?(this: EventListenerThisType<T>, ev: Event): any; + onChange?(this: EventListenerThisType<T>, ev: Event): any; + onChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onClick?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onClickCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onCompassNeedsCalibration?(this: EventListenerThisType<T>, ev: Event): any; + onCompassNeedsCalibrationCapture?(this: EventListenerThisType<T>, ev: Event): any; + onContextMenu?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onContextMenuCapture?(this: EventListenerThisType<T>, ev: PointerEvent): any; + onDblClick?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onDblClickCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onDeviceMotion?(this: EventListenerThisType<T>, ev: DeviceMotionEvent): any; + onDeviceMotionCapture?(this: EventListenerThisType<T>, ev: DeviceMotionEvent): any; + onDeviceOrientation?(this: EventListenerThisType<T>, ev: DeviceOrientationEvent): any; + onDeviceOrientationCapture?(this: EventListenerThisType<T>, ev: DeviceOrientationEvent): any; + onDrag?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragEnd?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragEndCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragEnter?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragEnterCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragLeave?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragLeaveCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragOver?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragOverCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragStart?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDragStartCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDrop?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDropCapture?(this: EventListenerThisType<T>, ev: DragEvent): any; + onDurationChange?(this: EventListenerThisType<T>, ev: Event): any; + onDurationChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onEmptied?(this: EventListenerThisType<T>, ev: Event): any; + onEmptiedCapture?(this: EventListenerThisType<T>, ev: Event): any; + onEnded?(this: EventListenerThisType<T>, ev: Event): any; + onEndedCapture?(this: EventListenerThisType<T>, ev: Event): any; + onError?(this: EventListenerThisType<T>, ...args: OnErrorEventHandlerArgs): any; + onErrorCapture?(this: EventListenerThisType<T>, ...args: OnErrorEventHandlerArgs): any; + onFocus?(this: EventListenerThisType<T>, ev: FocusEvent): any; + onFocusCapture?(this: EventListenerThisType<T>, ev: FocusEvent): any; + onHashChange?(this: EventListenerThisType<T>, ev: HashChangeEvent): any; + onHashChangeCapture?(this: EventListenerThisType<T>, ev: HashChangeEvent): any; + onInput?(this: EventListenerThisType<T>, ev: Event): any; + onInputCapture?(this: EventListenerThisType<T>, ev: Event): any; + onKeyDown?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onKeyDownCapture?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onKeyPress?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onKeyPressCapture?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onKeyUp?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onKeyUpCapture?(this: EventListenerThisType<T>, ev: KeyboardEvent): any; + onLoad?(this: EventListenerThisType<T>, ev: Event): any; + onLoadCapture?(this: EventListenerThisType<T>, ev: Event): any; + onLoadedData?(this: EventListenerThisType<T>, ev: Event): any; + onLoadedDataCapture?(this: EventListenerThisType<T>, ev: Event): any; + onLoadedMetadata?(this: EventListenerThisType<T>, ev: Event): any; + onLoadedMetadataCapture?(this: EventListenerThisType<T>, ev: Event): any; + onLoadStart?(this: EventListenerThisType<T>, ev: Event): any; + onLoadStartCapture?(this: EventListenerThisType<T>, ev: Event): any; + onMessage?(this: EventListenerThisType<T>, ev: MessageEvent): any; + onMessageCapture?(this: EventListenerThisType<T>, ev: MessageEvent): any; + onMouseDown?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseDownCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseEnter?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseEnterCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseLeave?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseLeaveCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseMove?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseMoveCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseOut?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseOutCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseOver?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseOverCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseUp?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseUpCapture?(this: EventListenerThisType<T>, ev: MouseEvent): any; + onMouseWheel?(this: EventListenerThisType<T>, ev: WheelEvent): any; + onMouseWheelCapture?(this: EventListenerThisType<T>, ev: WheelEvent): any; + onMsGestureChange?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureChangeCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureDoubleTap?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureDoubleTapCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureEnd?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureEndCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureHold?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureHoldCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureStart?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureStartCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureTap?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsGestureTapCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsInertiaStart?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsInertiaStartCapture?(this: EventListenerThisType<T>, ev: MSGestureEvent): any; + onMsPointerCancel?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerCancelCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerDown?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerDownCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerEnter?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerEnterCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerLeave?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerLeaveCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerMove?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerMoveCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerOut?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerOutCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerOver?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onMsPointerOverCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + oNmsPointerUp?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + oNmsPointerUpCapture?(this: EventListenerThisType<T>, ev: MSPointerEvent): any; + onOffline?(this: EventListenerThisType<T>, ev: Event): any; + onOfflineCapture?(this: EventListenerThisType<T>, ev: Event): any; + onOnline?(this: EventListenerThisType<T>, ev: Event): any; + onOnlineCapture?(this: EventListenerThisType<T>, ev: Event): any; + onOrientationChange?(this: EventListenerThisType<T>, ev: Event): any; + onOrientationChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onPageHide?(this: EventListenerThisType<T>, ev: PageTransitionEvent): any; + onPageHideCapture?(this: EventListenerThisType<T>, ev: PageTransitionEvent): any; + onPageShow?(this: EventListenerThisType<T>, ev: PageTransitionEvent): any; + onPageShowCapture?(this: EventListenerThisType<T>, ev: PageTransitionEvent): any; + onPause?(this: EventListenerThisType<T>, ev: Event): any; + onPauseCapture?(this: EventListenerThisType<T>, ev: Event): any; + onPlay?(this: EventListenerThisType<T>, ev: Event): any; + onPlayCapture?(this: EventListenerThisType<T>, ev: Event): any; + onPlaying?(this: EventListenerThisType<T>, ev: Event): any; + onPlayingCapture?(this: EventListenerThisType<T>, ev: Event): any; + onPopState?(this: EventListenerThisType<T>, ev: PopStateEvent): any; + onPopStateCapture?(this: EventListenerThisType<T>, ev: PopStateEvent): any; + onProgress?(this: EventListenerThisType<T>, ev: ProgressEvent): any; + onProgressCapture?(this: EventListenerThisType<T>, ev: ProgressEvent): any; + onRateChange?(this: EventListenerThisType<T>, ev: Event): any; + onRateChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onReadyStateChange?(this: EventListenerThisType<T>, ev: ProgressEvent): any; + onReadyStateChangeCapture?(this: EventListenerThisType<T>, ev: ProgressEvent): any; + onReset?(this: EventListenerThisType<T>, ev: Event): any; + onResetCapture?(this: EventListenerThisType<T>, ev: Event): any; + onResize?(this: EventListenerThisType<T>, ev: UIEvent): any; + onResizeCapture?(this: EventListenerThisType<T>, ev: UIEvent): any; + onScroll?(this: EventListenerThisType<T>, ev: UIEvent): any; + onScrollCapture?(this: EventListenerThisType<T>, ev: UIEvent): any; + onSeeked?(this: EventListenerThisType<T>, ev: Event): any; + onSeekedCapture?(this: EventListenerThisType<T>, ev: Event): any; + onSeeking?(this: EventListenerThisType<T>, ev: Event): any; + onSeekingCapture?(this: EventListenerThisType<T>, ev: Event): any; + onSelect?(this: EventListenerThisType<T>, ev: UIEvent): any; + onSelectCapture?(this: EventListenerThisType<T>, ev: UIEvent): any; + onSelectionChange?(this: EventListenerThisType<T>, ev: Event): any; + onSelectionChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onStalled?(this: EventListenerThisType<T>, ev: Event): any; + onStalledCapture?(this: EventListenerThisType<T>, ev: Event): any; + onStorage?(this: EventListenerThisType<T>, ev: StorageEvent): any; + onStorageCapture?(this: EventListenerThisType<T>, ev: StorageEvent): any; + onSubmit?(this: EventListenerThisType<T>, ev: Event): any; + onSubmitCapture?(this: EventListenerThisType<T>, ev: Event): any; + onSuspend?(this: EventListenerThisType<T>, ev: Event): any; + onSuspendCapture?(this: EventListenerThisType<T>, ev: Event): any; + onTimeUpdate?(this: EventListenerThisType<T>, ev: Event): any; + onTimeUpdateCapture?(this: EventListenerThisType<T>, ev: Event): any; + onTouchCancel?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchCancelCapture?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchEnd?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchEndCapture?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchMove?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchMoveCapture?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchStart?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onTouchStartCapture?(this: EventListenerThisType<T>, ev: TouchEvent): any; + onUnload?(this: EventListenerThisType<T>, ev: Event): any; + onUnloadCapture?(this: EventListenerThisType<T>, ev: Event): any; + onVolumeChange?(this: EventListenerThisType<T>, ev: Event): any; + onVolumeChangeCapture?(this: EventListenerThisType<T>, ev: Event): any; + onWaiting?(this: EventListenerThisType<T>, ev: Event): any; + onWaitingCapture?(this: EventListenerThisType<T>, ev: Event): any; + + /** + * Target (window or document) + */ + target: T; +} + +export type WindowEventTargets = {[K in keyof Window]: Window[K] extends EventTarget ? K : never}[keyof Window]; + +export default class EventListener<T extends EventTarget | WindowEventTargets> extends React.PureComponent<EventListenerProps<T>> { } diff --git a/types/react-event-listener/ts3.1/react-event-listener-tests.tsx b/types/react-event-listener/ts3.1/react-event-listener-tests.tsx new file mode 100644 index 0000000000..238b05237b --- /dev/null +++ b/types/react-event-listener/ts3.1/react-event-listener-tests.tsx @@ -0,0 +1,9 @@ +import React = require("react"); +import EventListener, { withOptions } from "react-event-listener"; + +<EventListener target={document} onBeforeUnload={ev => { }} />; +<EventListener target={window} onResize={withOptions((ev: UIEvent) => { }, { passive: true, capture: true })} />; +<EventListener target="window" onResize={() => { }}/>; +<EventListener target={document} onSelectionChange={ev => { }} />; +<EventListener target="document" onError={function() { this.documentElement; }} />; +<EventListener target={window} onBlurCapture={function() { this.pageXOffset; }} />; diff --git a/types/react-event-listener/ts3.1/tsconfig.json b/types/react-event-listener/ts3.1/tsconfig.json new file mode 100644 index 0000000000..8b6f2935ea --- /dev/null +++ b/types/react-event-listener/ts3.1/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-event-listener-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/react-event-listener/ts3.1/tslint.json b/types/react-event-listener/ts3.1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-event-listener/ts3.1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 58da7330ea25ead450a8ee3ec3e83b742f2d0a9e Mon Sep 17 00:00:00 2001 From: Jessica <jessicamfranco3@gmail.com> Date: Wed, 6 Feb 2019 18:30:44 +0900 Subject: [PATCH 084/197] Update react-dom, react-test-renderer to 16.8.0 --- types/react-dom/index.d.ts | 3 ++- types/react-dom/react-dom-tests.tsx | 14 ++++++++++++++ types/react-dom/test-utils/index.d.ts | 14 ++++++++++++++ types/react-dom/tsconfig.json | 2 +- types/react-test-renderer/index.d.ts | 17 ++++++++++++++++- .../react-test-renderer-tests.ts | 11 +++++++++-- 6 files changed, 56 insertions(+), 5 deletions(-) diff --git a/types/react-dom/index.d.ts b/types/react-dom/index.d.ts index 518c0c617c..a6ac5c9d11 100644 --- a/types/react-dom/index.d.ts +++ b/types/react-dom/index.d.ts @@ -1,10 +1,11 @@ -// Type definitions for React (react-dom) 16.0 +// Type definitions for React (react-dom) 16.8 // Project: http://facebook.github.io/react/ // Definitions by: Asana <https://asana.com> // AssureSign <http://www.assuresign.com> // Microsoft <https://microsoft.com> // MartynasZilinskas <https://github.com/MartynasZilinskas> // Josh Rutherford <https://github.com/theruther4d> +// Jessica Franco <https://github.com/Jessidhia> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/react-dom/react-dom-tests.tsx b/types/react-dom/react-dom-tests.tsx index c7ccb0052d..e81c500f9c 100644 --- a/types/react-dom/react-dom-tests.tsx +++ b/types/react-dom/react-dom-tests.tsx @@ -178,4 +178,18 @@ describe('React dom test utils', () => { shallowRenderer.getRenderOutput(); }); }); + + describe('act', () => { + it('accepts a sync callback that is void', () => { + ReactTestUtils.act(() => {}); + }); + it('rejects an async callback even if void', () => { + // $ExpectError + ReactTestUtils.act(async () => {}); + }); + it('rejects a callback that returns null', () => { + // $ExpectError + ReactTestUtils.act(() => null); + }); + }); }); diff --git a/types/react-dom/test-utils/index.d.ts b/types/react-dom/test-utils/index.d.ts index f60d088515..f1eae65df6 100644 --- a/types/react-dom/test-utils/index.d.ts +++ b/types/react-dom/test-utils/index.d.ts @@ -278,3 +278,17 @@ export function findRenderedComponentWithType<T extends Component<any>, C extend * Call this in your tests to create a shallow renderer. */ export function createRenderer(): ShallowRenderer; + +/** + * Wrap any code rendering and triggering updates to your components into `act()` calls. + * + * Ensures that the behavior in your tests matches what happens in the browser + * more closely by executing pending `useEffect`s before returning. This also + * reduces the amount of re-renders done. + * + * @param callback A synchronous, void callback that will execute as a single, complete React commit. + * + * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks + */ +// the "void | undefined" is here to forbid any sneaky "Promise" returns. +export function act(callback: () => void | undefined): void; diff --git a/types/react-dom/tsconfig.json b/types/react-dom/tsconfig.json index f63325026f..6d7d943c8b 100644 --- a/types/react-dom/tsconfig.json +++ b/types/react-dom/tsconfig.json @@ -14,7 +14,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/react-test-renderer/index.d.ts b/types/react-test-renderer/index.d.ts index c147d5c190..040ec3a513 100644 --- a/types/react-test-renderer/index.d.ts +++ b/types/react-test-renderer/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for react-test-renderer 16.0 +// Type definitions for react-test-renderer 16.8 // Project: https://facebook.github.io/react/ // Definitions by: Arvitaly <https://github.com/arvitaly> // Lochbrunner <https://github.com/lochbrunner> // John Reilly <https://github.com/johnnyreilly> // John Gozde <https://github.com/jgoz> +// Jessica Franco <https://github.com/Jessidhia> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -50,3 +51,17 @@ export interface TestRendererOptions { createNodeMock(element: ReactElement<any>): any; } export function create(nextElement: ReactElement<any>, options?: TestRendererOptions): ReactTestRenderer; + +/** + * Wrap any code rendering and triggering updates to your components into `act()` calls. + * + * Ensures that the behavior in your tests matches what happens in the browser + * more closely by executing pending `useEffect`s before returning. This also + * reduces the amount of re-renders done. + * + * @param callback A synchronous, void callback that will execute as a single, complete React commit. + * + * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks + */ +// the "void | undefined" is here to forbid any sneaky "Promise" returns. +export function act(callback: () => void | undefined): void; diff --git a/types/react-test-renderer/react-test-renderer-tests.ts b/types/react-test-renderer/react-test-renderer-tests.ts index 83dc510e2b..b7e23caf25 100644 --- a/types/react-test-renderer/react-test-renderer-tests.ts +++ b/types/react-test-renderer/react-test-renderer-tests.ts @@ -1,5 +1,5 @@ -import * as React from "react"; -import { create, ReactTestInstance } from "react-test-renderer"; +import React = require("react"); +import { act, create, ReactTestInstance } from "react-test-renderer"; import { createRenderer } from 'react-test-renderer/shallow'; class TestComponent extends React.Component { } @@ -66,3 +66,10 @@ const shallowRenderer = createRenderer(); shallowRenderer.render(component); shallowRenderer.getRenderOutput(); shallowRenderer.getMountedInstance(); + +// Only synchronous, void callbacks are acceptable for act() +act(() => {}); +// $ExpectError +act(async () => {}); +// $ExpectError +act(() => null); From 1755edd5fc18384333ed91db9b4d60098ee5e32c Mon Sep 17 00:00:00 2001 From: Jessica <jessicamfranco3@gmail.com> Date: Wed, 6 Feb 2019 18:39:55 +0900 Subject: [PATCH 085/197] Forbid returning non-void from the useEffect destructor too There is a runtime warning. --- types/react/index.d.ts | 16 +++++++++------- types/react/test/hooks.tsx | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 929a698775..9e46bc5ca9 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -783,11 +783,9 @@ declare namespace React { // TODO (TypeScript 3.0): ReadonlyArray<unknown> type DependencyList = ReadonlyArray<any>; - // NOTE: Currently, in alpha.0, the effect callbacks are actually allowed to return anything, - // but functions are treated specially. The next version published with hooks will warn if you actually - // return anything besides `void` or a callback. Async effects need to call an async function inside - // them. - type EffectCallback = () => (void | (() => void)); + // NOTE: callbacks are _only_ allowed to return either void, or a destructor. + // The destructor is itself only allowed to return void. + type EffectCallback = () => (void | (() => void | undefined)); interface MutableRefObject<T> { current: T; @@ -853,12 +851,16 @@ declare namespace React { * @version 16.8.0 * @see https://reactjs.org/docs/hooks-reference.html#usereducer */ + // I'm not sure if I keep this 2-ary or if I make it (2,3)-ary; it's currently (2,3)-ary. // The Flow types do have an overload for 3-ary invocation with undefined initializer. - // NOTE: the documentation or any alphas aren't updated, this is current for master. - // NOTE 2: without the ReducerState indirection, TypeScript would reduce S to be the most common + + // NOTE: without the ReducerState indirection, TypeScript would reduce S to be the most common // supertype between the reducer's return type and the initialState (or the initializer's return type), // which would prevent autocompletion from ever working. + + // TODO: double-check if this weird overload logic is necessary. It is possible it's either a bug + // in older versions, or a regression in newer versions of the typescript completion service. function useReducer<R extends Reducer<any, any>>( reducer: R, initialState: ReducerState<R>, diff --git a/types/react/test/hooks.tsx b/types/react/test/hooks.tsx index 12fcc28222..26ff634e89 100644 --- a/types/react/test/hooks.tsx +++ b/types/react/test/hooks.tsx @@ -120,6 +120,23 @@ function useEveryHook(ref: React.Ref<{ id: number }>|undefined): () => boolean { setState(reducerState.age); }, []); + // effects are only allowed to either be actually void or return actually void functions + React.useEffect(() => () => {}); + // indistinguishable + React.useEffect(() => () => undefined); + // $ExpectError + React.useEffect(() => null); + // $ExpectError + React.useEffect(() => Math.random() ? null : undefined); + // $ExpectError + React.useEffect(() => () => null); + // $ExpectError + React.useEffect(() => () => Math.random() ? null : undefined); + // $ExpectError + React.useEffect(() => async () => {}); + // $ExpectError + React.useEffect(async () => () => {}); + React.useDebugValue(id, value => value.toFixed()); React.useDebugValue(id); From 8af624afbe50926ee476cbad993b80da2ce07802 Mon Sep 17 00:00:00 2001 From: Jessica <jessicamfranco3@gmail.com> Date: Wed, 6 Feb 2019 19:07:43 +0900 Subject: [PATCH 086/197] Use contrivances to present something close to act()'s real return type Make it harder to accidentally use it in contexts where a Promise may be expected. --- types/react-dom/react-dom-tests.tsx | 5 +++++ types/react-dom/test-utils/index.d.ts | 11 ++++++++++- types/react-test-renderer/index.d.ts | 11 ++++++++++- .../react-test-renderer/react-test-renderer-tests.ts | 2 ++ 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/types/react-dom/react-dom-tests.tsx b/types/react-dom/react-dom-tests.tsx index e81c500f9c..46274e3ffd 100644 --- a/types/react-dom/react-dom-tests.tsx +++ b/types/react-dom/react-dom-tests.tsx @@ -191,5 +191,10 @@ describe('React dom test utils', () => { // $ExpectError ReactTestUtils.act(() => null); }); + it('returns a Promise-like that errors out on use', () => { + const result = ReactTestUtils.act(() => {}); + // $ExpectError + Promise.resolve(result); + }); }); }); diff --git a/types/react-dom/test-utils/index.d.ts b/types/react-dom/test-utils/index.d.ts index f1eae65df6..fb98181847 100644 --- a/types/react-dom/test-utils/index.d.ts +++ b/types/react-dom/test-utils/index.d.ts @@ -291,4 +291,13 @@ export function createRenderer(): ShallowRenderer; * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks */ // the "void | undefined" is here to forbid any sneaky "Promise" returns. -export function act(callback: () => void | undefined): void; +// the actual return value is always a "DebugPromiseLike", +// but having an "| {}" makes it harder to accidentally use. +export function act(callback: () => void | undefined): DebugPromiseLike | {}; + +// Intentionally doesn't extend PromiseLike<never>. +// Ideally this should be as hard to accidentally use as possible. +interface DebugPromiseLike { + // the actual then() in here is 0-ary, but that doesn't count as a PromiseLike. + then(onfulfilled: (value: never) => never, onrejected: (reason: never) => never): never; +} diff --git a/types/react-test-renderer/index.d.ts b/types/react-test-renderer/index.d.ts index 040ec3a513..34ddb2502c 100644 --- a/types/react-test-renderer/index.d.ts +++ b/types/react-test-renderer/index.d.ts @@ -64,4 +64,13 @@ export function create(nextElement: ReactElement<any>, options?: TestRendererOpt * @see https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks */ // the "void | undefined" is here to forbid any sneaky "Promise" returns. -export function act(callback: () => void | undefined): void; +// the actual return value is always a "DebugPromiseLike", +// but having an "| {}" makes it harder to accidentally use. +export function act(callback: () => void | undefined): DebugPromiseLike | {}; + +// Intentionally doesn't extend PromiseLike<never>. +// Ideally this should be as hard to accidentally use as possible. +interface DebugPromiseLike { + // the actual then() in here is 0-ary, but that doesn't count as a PromiseLike. + then(onfulfilled: (value: never) => never, onrejected: (reason: never) => never): never; +} diff --git a/types/react-test-renderer/react-test-renderer-tests.ts b/types/react-test-renderer/react-test-renderer-tests.ts index b7e23caf25..48d861cf62 100644 --- a/types/react-test-renderer/react-test-renderer-tests.ts +++ b/types/react-test-renderer/react-test-renderer-tests.ts @@ -73,3 +73,5 @@ act(() => {}); act(async () => {}); // $ExpectError act(() => null); +// $ExpectError +Promise.resolve(act(() => {})); From 987f88cc20bd60a60a23640ab76f52fe1f7fca08 Mon Sep 17 00:00:00 2001 From: Jessica <jessicamfranco3@gmail.com> Date: Wed, 6 Feb 2019 19:53:52 +0900 Subject: [PATCH 087/197] Add missing export annotations --- types/react-dom/test-utils/index.d.ts | 2 +- types/react-test-renderer/index.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/react-dom/test-utils/index.d.ts b/types/react-dom/test-utils/index.d.ts index fb98181847..8730dc9447 100644 --- a/types/react-dom/test-utils/index.d.ts +++ b/types/react-dom/test-utils/index.d.ts @@ -297,7 +297,7 @@ export function act(callback: () => void | undefined): DebugPromiseLike | {}; // Intentionally doesn't extend PromiseLike<never>. // Ideally this should be as hard to accidentally use as possible. -interface DebugPromiseLike { +export interface DebugPromiseLike { // the actual then() in here is 0-ary, but that doesn't count as a PromiseLike. then(onfulfilled: (value: never) => never, onrejected: (reason: never) => never): never; } diff --git a/types/react-test-renderer/index.d.ts b/types/react-test-renderer/index.d.ts index 34ddb2502c..abdae1c908 100644 --- a/types/react-test-renderer/index.d.ts +++ b/types/react-test-renderer/index.d.ts @@ -70,7 +70,7 @@ export function act(callback: () => void | undefined): DebugPromiseLike | {}; // Intentionally doesn't extend PromiseLike<never>. // Ideally this should be as hard to accidentally use as possible. -interface DebugPromiseLike { +export interface DebugPromiseLike { // the actual then() in here is 0-ary, but that doesn't count as a PromiseLike. then(onfulfilled: (value: never) => never, onrejected: (reason: never) => never): never; } From acd0e1cb6de77123798368dbcf48d62a9f1d5006 Mon Sep 17 00:00:00 2001 From: Erik Krogh Kristensen <erik@webbies.dk> Date: Wed, 6 Feb 2019 13:10:33 +0100 Subject: [PATCH 088/197] platform: The parse and toString methods are not maybe present, they are definitely present. --- types/platform/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/platform/index.d.ts b/types/platform/index.d.ts index b0f640d522..c1db7431f3 100644 --- a/types/platform/index.d.ts +++ b/types/platform/index.d.ts @@ -18,8 +18,8 @@ declare interface Platform { version?: string; toString(): string; }; - parse?(ua: string): Platform; - toString?(): string; + parse(ua: string): Platform; + toString(): string; } declare var platform: Platform; From 8ab3765a87c465c8273308ea09ace21281ee4c40 Mon Sep 17 00:00:00 2001 From: Erik Krogh Kristensen <erik@webbies.dk> Date: Wed, 6 Feb 2019 13:20:10 +0100 Subject: [PATCH 089/197] platform: fixed the tests --- types/platform/platform-tests.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/platform/platform-tests.ts b/types/platform/platform-tests.ts index 65433ffb13..ce8648e876 100644 --- a/types/platform/platform-tests.ts +++ b/types/platform/platform-tests.ts @@ -16,7 +16,8 @@ var tests: TestContainer = { prerelease: null, product: null, ua: "Mozilla/5.0 (Linux; U; Android 4.0.3; zh-cn; HTC Sensation XE with Beats Audio Build/IML74K) AppleWebKit/535.7 (KHTML, like Gecko) CrMo/16.0.912.77 Mobile Safari/535.7", - version: "16.0.912.77" + version: "16.0.912.77", + parse: function () {throw new Error()} }, 'WebKit Nightly 528.4 (like Safari 4.x) on Mac OS X 10.4.11': { description: "WebKit Nightly 528.4 (like Safari 4.x) on Mac OS X 10.4.11", @@ -31,7 +32,8 @@ var tests: TestContainer = { prerelease: "alpha", product: null, ua: "Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_4_11; tr) AppleWebKit/528.4+ (KHTML, like Gecko) Version/4.0dp1 Safari/526.11.2", - version: "528.4" + version: "528.4", + parse: function () {throw new Error()} } }; From 970fc9d48471d2834e24f327610ce56e3010477c Mon Sep 17 00:00:00 2001 From: Martin Probst <martin@probst.io> Date: Wed, 6 Feb 2019 14:08:06 +0100 Subject: [PATCH 090/197] Angular IPromise interop with platform Promise. Angular promises support `.then()` chaining of functions that return arbitrary `then()`able values. https://docs.angularjs.org/api/ng/service/$q#the-promise-api This change updates the definition of `ng.IPromise.then()` to match that by overloading the function to handle `PromiseLike` values. --- types/angular/angular-tests.ts | 8 ++++++++ types/angular/index.d.ts | 14 ++++++++++++++ types/angular/tsconfig.json | 5 +++-- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/types/angular/angular-tests.ts b/types/angular/angular-tests.ts index b83a41a6df..7470fb08bb 100644 --- a/types/angular/angular-tests.ts +++ b/types/angular/angular-tests.ts @@ -294,6 +294,14 @@ foo.then((x) => { x.toFixed(); }); +namespace TestPromiseInterop { + declare const promiseInterop: ng.IPromise<number>; + const ngStringPromise: ng.IPromise<string> = + promiseInterop.then((num) => Promise.resolve(String(num))); + const caughtStringPromise: ng.IPromise<string|number> = + promiseInterop.catch((reason) => Promise.resolve('oh noes')); +} + // $q signature tests namespace TestQ { interface AbcObject { diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 4a8b26fba9..0c28ddbf27 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -1197,6 +1197,15 @@ declare namespace angular { * the `notifyCallback` method. The promise can not be resolved or rejected from the * `notifyCallback` method. */ + then<TResult1 = T, TResult2 = never>( + successCallback?: + | ((value: T) => PromiseLike<never> | PromiseLike<TResult1> | TResult1) + | null, + errorCallback?: + | ((reason: any) => PromiseLike<never> | PromiseLike<TResult2> | TResult2) + | null, + notifyCallback?: (state: any) => any + ): IPromise<TResult1 | TResult2>; then<TResult1 = T, TResult2 = never>( successCallback?: | ((value: T) => IPromise<never> | IPromise<TResult1> | TResult1) @@ -1210,6 +1219,11 @@ declare namespace angular { /** * Shorthand for promise.then(null, errorCallback) */ + catch<TResult = never>( + onRejected?: + | ((reason: any) => PromiseLike<never> | PromiseLike<TResult> | TResult) + | null + ): IPromise<T | TResult>; catch<TResult = never>( onRejected?: | ((reason: any) => IPromise<never> | IPromise<TResult> | TResult) diff --git a/types/angular/tsconfig.json b/types/angular/tsconfig.json index 46eeb69c7a..590c9c7798 100644 --- a/types/angular/tsconfig.json +++ b/types/angular/tsconfig.json @@ -11,7 +11,8 @@ "lib": [ "es5", "dom", - "es2015.iterable" + "es2015.iterable", + "es2015.promise" ], "noImplicitAny": false, "noImplicitThis": false, @@ -25,4 +26,4 @@ "noEmit": true, "forceConsistentCasingInFileNames": true } -} \ No newline at end of file +} From 89d2235d1d4d655f3f2a1584f41e7797029c6fc5 Mon Sep 17 00:00:00 2001 From: Kristoffer <hello@kristoffer.is> Date: Wed, 6 Feb 2019 14:32:30 +0100 Subject: [PATCH 091/197] Add addPrevSibling typing --- types/libxmljs/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/libxmljs/index.d.ts b/types/libxmljs/index.d.ts index db37035f06..5ba3fc294f 100644 --- a/types/libxmljs/index.d.ts +++ b/types/libxmljs/index.d.ts @@ -116,6 +116,7 @@ export class Element extends Node { prevElement(): Element|null; nextElement(): Element|null; addNextSibling(siblingNode: Node): Node; + addPrevSibling(siblingNode: Node): Node; find(xpath: string, ns_uri?: string): Node[]; find(xpath: string, namespaces: StringMap): Node[]; From 7f68109ad68f2c4f68f7dd6461a4ba44249f6123 Mon Sep 17 00:00:00 2001 From: Paito Anderson <pj.paito@gmail.com> Date: Wed, 6 Feb 2019 09:28:43 -0500 Subject: [PATCH 092/197] Update react-native-popup-dialog --- types/react-native-popup-dialog/index.d.ts | 8 +++--- .../react-native-popup-dialog-tests.tsx | 25 +++++++++++++------ 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/types/react-native-popup-dialog/index.d.ts b/types/react-native-popup-dialog/index.d.ts index d0a9d22a4b..b81533a6bc 100644 --- a/types/react-native-popup-dialog/index.d.ts +++ b/types/react-native-popup-dialog/index.d.ts @@ -17,7 +17,7 @@ export interface DialogContentProps { style?: StyleProp<ViewStyle>; } -export interface DialogActionListProps { +export interface DialogFooterProps { bordered?: boolean; style?: StyleProp<ViewStyle>; } @@ -70,9 +70,7 @@ export interface DialogProps { onDismiss?: () => void; onTouchOutside?: () => void; onHardwareBackPress?: () => boolean; - actions?: any[]; - actionContainerStyle?: StyleProp<ViewStyle>; - actionsBordered?: boolean; + footer?: any; useNativeDriver?: boolean; } @@ -97,7 +95,7 @@ export class SlideAnimation { } export class DialogContent extends React.Component<DialogContentProps, any> { } -export class DialogActionList extends React.Component<DialogActionListProps, any> { } +export class DialogFooter extends React.Component<DialogFooterProps, any> { } export class DialogButton extends React.Component<DialogButtonProps, any> { } export class DialogTitle extends React.Component<DialogTitleProps, any> { } export class Overlay extends React.Component<OverlayProps, any> { } diff --git a/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx b/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx index 55f979f506..2dc943d35b 100644 --- a/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx +++ b/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx @@ -7,6 +7,7 @@ import Dialog, { SlideAnimation, ScaleAnimation, FadeAnimation, + DialogFooter, } from 'react-native-popup-dialog'; const slideAnimation = new SlideAnimation({ slideFrom: 'bottom' }); @@ -50,14 +51,22 @@ class Test extends React.Component<any> { <Dialog ref={(popupDialog) => this.scalingPopupDialog = popupDialog} dialogTitle={<DialogTitle title="Popup Dialog - Scale Animation" />} dialogAnimation={scaleAnimation} - actions={[ - <DialogButton - text="CLOSE" - onPress={(event) => this.dismissPopupDialog(this.scalingPopupDialog)} - textStyle={{ color: "red" }} - key="button-1" - />, - ]} + footer={ + <DialogFooter> + <DialogButton + text="CLOSE" + onPress={(event) => this.dismissPopupDialog(this.scalingPopupDialog)} + textStyle={{ color: "red" }} + bordered + key="button-1" + /> + <DialogButton + text="OK" + onPress={() => {}} + key="button-2" + /> + </DialogFooter> + } /> <Dialog ref={(popupDialog) => this.slidingPopupDialog = popupDialog} dialogTitle={<DialogTitle title="Popup Dialog - Slide Animation" />} From 97fa13c0b88946d6d2bb9c97d5f6e432baa1c00e Mon Sep 17 00:00:00 2001 From: James Lismore <jlismore@gmail.com> Date: Wed, 6 Feb 2019 11:18:11 -0500 Subject: [PATCH 093/197] Extract functional style def to type Use type in box plot styles --- types/victory/index.d.ts | 3849 +++++++++++++++++++------------------- 1 file changed, 1925 insertions(+), 1924 deletions(-) diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index c1a1a6f394..43bf4378e6 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -11,20 +11,20 @@ /// <reference types="react"/> declare module "victory" { - import * as React from "react"; + import * as React from "react"; - /** - * Single animation object to interpolate - */ + /** + * Single animation object to interpolate + */ export type AnimationStyle = { [key: string ]: string | number }; - /** - * Animation styles to interpolate - */ + /** + * Animation styles to interpolate + */ - export type AnimationData = AnimationStyle | AnimationStyle[]; + export type AnimationData = AnimationStyle | AnimationStyle[]; - export type AnimationEasing = + export type AnimationEasing = "back" | "backIn" | "backOut" | "backInOut" | "bounce" | "bounceIn" | "bounceOut" | "bounceInOut" | "circle" | "circleIn" | "circleOut" | "circleInOut" | "linear" | "linearIn" | "linearOut" | "linearInOut" | "cubic" | "cubicIn" | "cubicOut" | @@ -32,793 +32,794 @@ declare module "victory" { "expIn" | "expOut" | "expInOut" | "poly" | "polyIn" | "polyOut" | "polyInOut" | "quad" | "quadIn" | "quadOut" | "quadInOut" | "sin" | "sinIn" | "sinOut" | "sinInOut"; - // Many victory components accept string or number or callback which returns string or number - type StringOrNumberOrCallback = - | string - | number - | ((datum: any, active: boolean) => string | number); - type NumberOrCallback = ((datum: any, active: boolean) => number) | number; + // Many victory components accept string or number or callback which returns string or number + type StringOrNumberOrCallback = + | string + | number + | ((datum: any, active: boolean) => string | number); + type NumberOrCallback = ((datum: any, active: boolean) => number) | number; - /** - * Style interface used in components/themeing - */ - export interface VictoryStyleInterface { - parent?: { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; - data?: { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; - labels?: { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; - } + type VictoryStyleObject = { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; + /** + * Style interface used in components/themeing + */ + export interface VictoryStyleInterface { + parent?: VictoryStyleObject; + data?: VictoryStyleObject; + labels?: VictoryStyleObject; + } - export interface VictoryAnimationProps { - /** - * The child of should be a function that takes an object of tweened values and returns a component to render. - * @param style - */ - children?: (style: AnimationStyle) => React.ReactElement<any>; - /** - * The number of milliseconds the animation should take to complete. - * @default 1000 - */ - duration?: number; - /** - * The easing prop specifies an easing function name to use for tweening. - * @default "quadInOut" - */ - easing?: AnimationEasing; - /** - * The delay prop specifies a delay in milliseconds before the animation begins. - * If multiple values are in the animation queue, it is the delay between each animation. - * @default 0 - */ - delay?: number; - /** - * The onEnd prop specifies a function to run when the animation ends. If multiple animations are in the queue, it is called after the last animation. - */ - onEnd?: () => void; - /** - * The data prop specifies the latest set of values to tween to. - * When this prop changes, VictoryAnimation will begin animating from the current value to the new value. - * When given an array of values, VictoryAnimation will use it as an animation queue. - * @default {} - */ - data?: AnimationData; - } + export interface VictoryAnimationProps { + /** + * The child of should be a function that takes an object of tweened values and returns a component to render. + * @param style + */ + children?: (style: AnimationStyle) => React.ReactElement<any>; + /** + * The number of milliseconds the animation should take to complete. + * @default 1000 + */ + duration?: number; + /** + * The easing prop specifies an easing function name to use for tweening. + * @default "quadInOut" + */ + easing?: AnimationEasing; + /** + * The delay prop specifies a delay in milliseconds before the animation begins. + * If multiple values are in the animation queue, it is the delay between each animation. + * @default 0 + */ + delay?: number; + /** + * The onEnd prop specifies a function to run when the animation ends. If multiple animations are in the queue, it is called after the last animation. + */ + onEnd?: () => void; + /** + * The data prop specifies the latest set of values to tween to. + * When this prop changes, VictoryAnimation will begin animating from the current value to the new value. + * When given an array of values, VictoryAnimation will use it as an animation queue. + * @default {} + */ + data?: AnimationData; + } - /** - * VictoryAnimation animates prop changes for any React component. - * Just use a child function inside VictoryAnimation that accepts an object of tweened values and returns a component to render. - */ + /** + * VictoryAnimation animates prop changes for any React component. + * Just use a child function inside VictoryAnimation that accepts an object of tweened values and returns a component to render. + */ export class VictoryAnimation extends React.Component<VictoryAnimationProps, any> {} - /** - * Text anchor type - */ - type TextAnchorType = "start" | "middle" | "end" | "inherit"; + /** + * Text anchor type + */ + type TextAnchorType = "start" | "middle" | "end" | "inherit"; - /** - * Vertical anchor type - */ - type VerticalAnchorType = "start" | "middle" | "end"; + /** + * Vertical anchor type + */ + type VerticalAnchorType = "start" | "middle" | "end"; - export interface VictoryLabelProps { - /** - * Specifies the angle to rotate the text by. - */ - angle?: string | number; - /** - * The capHeight prop defines a text metric for the font being used: the expected height of capital letters. - * This is necessary because of SVG, which (a) positions the *bottom* of the text at `y`, and (b) has no notion of line height. - * The value should ideally use the same units as `lineHeight` and `dy`, preferably ems. If given a unitless number, it is assumed to be ems. - * @default "0.71em" - */ - capHeight?: StringOrNumberOrCallback; - /** - * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine child text - */ - datum?: {}; - /** - * Labels that apply to an entire data series will recieve the entire series as `data` instead of an individual datum prop. - */ - data?: any[]; - /** - * The events prop attaches arbitrary event handlers to the label component. - * Event handlers are currently only called with their corresponding events. - */ - events?: React.DOMAttributes<any>; - /** - * The children of this component define the content of the label. - * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. - */ - children?: StringOrNumberOrCallback; - /** - * The labelPlacement prop is used to specify the placement of labels relative to the data point they represent. - * This prop may be given as “vertical”, “parallel” or “perpendicular”. This props is particularly useful in polar - * charts, where it may be desireable to position a label either parallel or perpendicular to its corresponding angle. - * When this prop is not set, perpendicular label placement will be used for polar charts, and vertical label - * placement will be used for cartesian charts. - */ - labelPlacement?: "parallel" | "perpendicular" | "vertical"; - /** - * The lineHeight prop defines how much space a single line of text should take up. - * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, - * but the result is similar: a roughly equal amount of extra space is distributed above and below the line of text. - * The value should ideally use the same units as `capHeight` and `dy`, preferably ems. - * If given a unitless number, it is assumed to be ems. - * @default 1 - */ - lineHeight?: StringOrNumberOrCallback; - /** - * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. - * **This prop should not be set manually.** - */ + export interface VictoryLabelProps { + /** + * Specifies the angle to rotate the text by. + */ + angle?: string | number; + /** + * The capHeight prop defines a text metric for the font being used: the expected height of capital letters. + * This is necessary because of SVG, which (a) positions the *bottom* of the text at `y`, and (b) has no notion of line height. + * The value should ideally use the same units as `lineHeight` and `dy`, preferably ems. If given a unitless number, it is assumed to be ems. + * @default "0.71em" + */ + capHeight?: StringOrNumberOrCallback; + /** + * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine child text + */ + datum?: {}; + /** + * Labels that apply to an entire data series will recieve the entire series as `data` instead of an individual datum prop. + */ + data?: any[]; + /** + * The events prop attaches arbitrary event handlers to the label component. + * Event handlers are currently only called with their corresponding events. + */ + events?: React.DOMAttributes<any>; + /** + * The children of this component define the content of the label. + * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. + */ + children?: StringOrNumberOrCallback; + /** + * The labelPlacement prop is used to specify the placement of labels relative to the data point they represent. + * This prop may be given as “vertical”, “parallel” or “perpendicular”. This props is particularly useful in polar + * charts, where it may be desireable to position a label either parallel or perpendicular to its corresponding angle. + * When this prop is not set, perpendicular label placement will be used for polar charts, and vertical label + * placement will be used for cartesian charts. + */ + labelPlacement?: "parallel" | "perpendicular" | "vertical"; + /** + * The lineHeight prop defines how much space a single line of text should take up. + * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, + * but the result is similar: a roughly equal amount of extra space is distributed above and below the line of text. + * The value should ideally use the same units as `capHeight` and `dy`, preferably ems. + * If given a unitless number, it is assumed to be ems. + * @default 1 + */ + lineHeight?: StringOrNumberOrCallback; + /** + * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. + * **This prop should not be set manually.** + */ origin?: { x: number, y: number }; - /** - * Victory components can pass a boolean polar prop to specify whether a label is part of a polar chart. - * **This prop should not be set manually.** - */ - polar?: boolean; - /** - * The renderInPortal prop specifies whether VictoryLabel should render text in place or within a VictoryPortal. - * Setting renderInPortal to true is equivalent to wrapping VictoryLabel in a VictoryPortal. This prop is false by default. - */ - renderInPortal?: boolean; - /** - * The style prop applies CSS properties to the rendered `<text>` element. - */ - style?: React.CSSProperties; - /** - * The text prop defines the text VictoryLabel will render. The text prop may be given as a string, number, a function of datum, - * or an array of any of these. Strings may include newline characters, which VictoryLabel will split into separate - * <tspan/> elements. When text is given as an array, separate <tspan/> elements will be created for each element in the array. - */ - text?: string[] | StringOrNumberOrCallback; - /** - * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. - */ - textAnchor?: TextAnchorType | { (): TextAnchorType }; - /** - * The verticalAnchor prop defines how the text is vertically positioned relative to the given `x` and `y` coordinates. - */ - verticalAnchor?: VerticalAnchorType | { (): VerticalAnchorType }; - /** - * The transform prop applies a transform to the rendered `<text>` element. - * In addition to being a string, it can be an object containing transform definitions for easier authoring. - */ - transform?: string | {} | { (): string | {} }; - /** - * The x prop defines the x coordinate to use as a basis for horizontal positioning. - */ - x?: number; - /** - * The y prop defines the y coordinate to use as a basis for vertical positioning. - */ - y?: number; - /** - * The dx prop defines a horizontal shift from the `x` coordinate. - */ - dx?: StringOrNumberOrCallback; - /** - * The dy prop defines a vertical shift from the `y` coordinate. - * Since this component already accounts for `capHeight`, `lineHeight`, and `verticalAnchor`, this will usually not be necessary. - */ - dy?: StringOrNumberOrCallback; - } + /** + * Victory components can pass a boolean polar prop to specify whether a label is part of a polar chart. + * **This prop should not be set manually.** + */ + polar?: boolean; + /** + * The renderInPortal prop specifies whether VictoryLabel should render text in place or within a VictoryPortal. + * Setting renderInPortal to true is equivalent to wrapping VictoryLabel in a VictoryPortal. This prop is false by default. + */ + renderInPortal?: boolean; + /** + * The style prop applies CSS properties to the rendered `<text>` element. + */ + style?: React.CSSProperties; + /** + * The text prop defines the text VictoryLabel will render. The text prop may be given as a string, number, a function of datum, + * or an array of any of these. Strings may include newline characters, which VictoryLabel will split into separate + * <tspan/> elements. When text is given as an array, separate <tspan/> elements will be created for each element in the array. + */ + text?: string[] | StringOrNumberOrCallback; + /** + * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. + */ + textAnchor?: TextAnchorType | { (): TextAnchorType }; + /** + * The verticalAnchor prop defines how the text is vertically positioned relative to the given `x` and `y` coordinates. + */ + verticalAnchor?: VerticalAnchorType | { (): VerticalAnchorType }; + /** + * The transform prop applies a transform to the rendered `<text>` element. + * In addition to being a string, it can be an object containing transform definitions for easier authoring. + */ + transform?: string | {} | { (): string | {} }; + /** + * The x prop defines the x coordinate to use as a basis for horizontal positioning. + */ + x?: number; + /** + * The y prop defines the y coordinate to use as a basis for vertical positioning. + */ + y?: number; + /** + * The dx prop defines a horizontal shift from the `x` coordinate. + */ + dx?: StringOrNumberOrCallback; + /** + * The dy prop defines a vertical shift from the `y` coordinate. + * Since this component already accounts for `capHeight`, `lineHeight`, and `verticalAnchor`, this will usually not be necessary. + */ + dy?: StringOrNumberOrCallback; + } - /** - * VictoryLabel is a text component that provides several enhancements over SVG’s <text> element. - */ - export class VictoryLabel extends React.Component<VictoryLabelProps, any> {} + /** + * VictoryLabel is a text component that provides several enhancements over SVG’s <text> element. + */ + export class VictoryLabel extends React.Component<VictoryLabelProps, any> {} - export interface VictoryContainerProps { - /** - * The responsive prop specifies whether the rendered container should be a responsive container - * with a viewBox attribute, or a static container with absolute width and height. - * @default true - */ - responsive?: boolean; - /** - * The style prop specifies styles for your VictoryContainer. Any valid inline style properties - * will be applied. Height and width should be specified via the height - * and width props, as they are used to calculate the alignment of - * components within the container. Styles from the child component will - * also be passed, if any exist. - * @examples {border: 1px solid red} - */ - style?: React.CSSProperties; - /** - * The height props specifies the height the svg viewBox of the container. - * This value should be given as a number of pixels. If no height prop - * is given, the height prop from the child component passed will be used. - */ - height?: number; - /** - * The width props specifies the width of the svg viewBox of the container - * This value should be given as a number of pixels. If no width prop - * is given, the width prop from the child component passed will be used. - */ - width?: number; - /** - * The events prop attaches arbitrary event handlers to the container component. - * Event handlers passed from other Victory components are called with their - * corresponding events as well as scale, style, width, height, and data when - * applicable. Use the invert method to convert event coordinate information to - * data. `scale.x.invert(evt.offsetX)`. - * @examples {{ onClick: (evt) => alert(`x: ${evt.clientX}, y: ${evt.clientY}`)}} - */ - events?: React.DOMAttributes<any>; - /** - * The title prop specifies the title to be applied to the SVG to assist - * accessibility for screen readers. The more descriptive this title is, the more - * useful it will be. If no title prop is passed, it will default to Victory Chart. - * @example "Popularity of Dog Breeds by Percentage" - * @default "Victory Chart" - */ - title?: string; - /** - * The desc prop specifies the description of the chart/SVG to assist with - * accessibility for screen readers. The more info about the chart provided in - * the description, the more usable it will be for people using screen readers. - * This prop defaults to an empty string. - * @example "Golden retreivers make up 30%, Labs make up 25%, and other dog breeds are - * not represented above 5% each." - * @default "" - */ - desc?: string; - } + export interface VictoryContainerProps { + /** + * The responsive prop specifies whether the rendered container should be a responsive container + * with a viewBox attribute, or a static container with absolute width and height. + * @default true + */ + responsive?: boolean; + /** + * The style prop specifies styles for your VictoryContainer. Any valid inline style properties + * will be applied. Height and width should be specified via the height + * and width props, as they are used to calculate the alignment of + * components within the container. Styles from the child component will + * also be passed, if any exist. + * @examples {border: 1px solid red} + */ + style?: React.CSSProperties; + /** + * The height props specifies the height the svg viewBox of the container. + * This value should be given as a number of pixels. If no height prop + * is given, the height prop from the child component passed will be used. + */ + height?: number; + /** + * The width props specifies the width of the svg viewBox of the container + * This value should be given as a number of pixels. If no width prop + * is given, the width prop from the child component passed will be used. + */ + width?: number; + /** + * The events prop attaches arbitrary event handlers to the container component. + * Event handlers passed from other Victory components are called with their + * corresponding events as well as scale, style, width, height, and data when + * applicable. Use the invert method to convert event coordinate information to + * data. `scale.x.invert(evt.offsetX)`. + * @examples {{ onClick: (evt) => alert(`x: ${evt.clientX}, y: ${evt.clientY}`)}} + */ + events?: React.DOMAttributes<any>; + /** + * The title prop specifies the title to be applied to the SVG to assist + * accessibility for screen readers. The more descriptive this title is, the more + * useful it will be. If no title prop is passed, it will default to Victory Chart. + * @example "Popularity of Dog Breeds by Percentage" + * @default "Victory Chart" + */ + title?: string; + /** + * The desc prop specifies the description of the chart/SVG to assist with + * accessibility for screen readers. The more info about the chart provided in + * the description, the more usable it will be for people using screen readers. + * This prop defaults to an empty string. + * @example "Golden retreivers make up 30%, Labs make up 25%, and other dog breeds are + * not represented above 5% each." + * @default "" + */ + desc?: string; + } export class VictoryContainer extends React.Component<VictoryContainerProps, any> {} - type CursorData = { - x: number; - y: number; - }; + type CursorData = { + x: number; + y: number; + }; - export interface VictoryCursorContainerProps extends VictoryContainerProps { - /** - * The cursorComponent prop takes a component instance which will be used to render a cursor element. - * The new element created will be supplied with x1, y1, x2 and y2 positioning props. - * If a cursorComponent is not supplied, a new Line component will be rendered. - * @default cursorComponent={<Line/>} - */ - cursorComponent?: React.ReactElement<any>; - /** - * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). - * When this prop is not specified, the cursor will be a 2-dimensional crosshair. - * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; - * the cursor will then be a vertical line that will inspect the time value of the current mouse position. - * @example cursorDimension="x" - */ + export interface VictoryCursorContainerProps extends VictoryContainerProps { + /** + * The cursorComponent prop takes a component instance which will be used to render a cursor element. + * The new element created will be supplied with x1, y1, x2 and y2 positioning props. + * If a cursorComponent is not supplied, a new Line component will be rendered. + * @default cursorComponent={<Line/>} + */ + cursorComponent?: React.ReactElement<any>; + /** + * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). + * When this prop is not specified, the cursor will be a 2-dimensional crosshair. + * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; + * the cursor will then be a vertical line that will inspect the time value of the current mouse position. + * @example cursorDimension="x" + */ cursorDimension?: 'x' | 'y'; - /** - * The cursorLabel prop defines the label that will appear next to the cursor. - * A label will only appear if cursorLabel is set. This prop should be given as a - * function of a point (an Object with x and y properties). - * @example cursorLabel={(point) => point.x} - */ - cursorLabel?: (point: CursorData) => void; - /** - * The cursorLabelComponent prop takes a component instance which will be - * used to render a label for the cursor. The new element created from the passed - * cursorLabelComponent will be supplied with the following props: x, y, - * active, text. If cursorLabelComponent is omitted, a new VictoryLabel will be created with the props described above. - * @default cursorLabelComponent={<VictoryLabel/>} - */ - cursorLabelComponent?: React.ReactElement<any>; - /** - * The cursorLabelOffset prop determines the pixel offset of the cursor label - * from the cursor point. This prop should be an Object with x and y properties, or a - * number to be used for both dimensions. - * @default "{ x: 5, y: -10 }" - */ - cursorLabelOffset?: number | CursorData; - /** - * Whenever the mouse is not over the chart, the cursor will not be displayed. - * If instead you would like to keep it displayed, use the defaultCursorValue prop to set the default value. - * The prop should be a point (an Object with x and y properties) for 2-dimensional cursors, or a number for 1-dimensional cursors. - * @example defaultCursorValue={{x: 1, y: 1}}, defaultCursorValue={0}} - */ - defaultCursorValue?: number | CursorData; - /** - * When the disable prop is set to true, VictoryCursorContainer events will not fire. - */ - disable?: boolean; - /** - * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). - * When this prop is not specified, the cursor will be a 2-dimensional crosshair. - * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; - * the cursor will then be a vertical line that will inspect the time value of the current mouse position. - * @example onChange={(value, props) => this.setState({cursorValue: value})} - */ + /** + * The cursorLabel prop defines the label that will appear next to the cursor. + * A label will only appear if cursorLabel is set. This prop should be given as a + * function of a point (an Object with x and y properties). + * @example cursorLabel={(point) => point.x} + */ + cursorLabel?: (point: CursorData) => void; + /** + * The cursorLabelComponent prop takes a component instance which will be + * used to render a label for the cursor. The new element created from the passed + * cursorLabelComponent will be supplied with the following props: x, y, + * active, text. If cursorLabelComponent is omitted, a new VictoryLabel will be created with the props described above. + * @default cursorLabelComponent={<VictoryLabel/>} + */ + cursorLabelComponent?: React.ReactElement<any>; + /** + * The cursorLabelOffset prop determines the pixel offset of the cursor label + * from the cursor point. This prop should be an Object with x and y properties, or a + * number to be used for both dimensions. + * @default "{ x: 5, y: -10 }" + */ + cursorLabelOffset?: number | CursorData; + /** + * Whenever the mouse is not over the chart, the cursor will not be displayed. + * If instead you would like to keep it displayed, use the defaultCursorValue prop to set the default value. + * The prop should be a point (an Object with x and y properties) for 2-dimensional cursors, or a number for 1-dimensional cursors. + * @example defaultCursorValue={{x: 1, y: 1}}, defaultCursorValue={0}} + */ + defaultCursorValue?: number | CursorData; + /** + * When the disable prop is set to true, VictoryCursorContainer events will not fire. + */ + disable?: boolean; + /** + * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). + * When this prop is not specified, the cursor will be a 2-dimensional crosshair. + * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; + * the cursor will then be a vertical line that will inspect the time value of the current mouse position. + * @example onChange={(value, props) => this.setState({cursorValue: value})} + */ onCursorChange?: (value: CursorData, props: VictoryCursorContainerProps) => void; - } + } export class VictoryCursorContainer extends React.Component<VictoryCursorContainerProps, any> {} - export interface VictoryBrushContainerProps extends VictoryContainerProps { - /** - * The optional allowDrag prop accepts a boolean that enables dragging behavior - * for the highlighted brush area. Resizing will still be enabled when the allowDrag - * prop is set to false. - * @default true - */ - allowDrag?: boolean; - /** - * The optional allowResize prop accepts a boolean that enables resizing the - * highlighted brush area. Dragging will still be enabled when the allowResize - * prop is set to false, but the dimensions of the brush area will be fixed. - * @default true - */ - allowResize?: boolean; - /** - * The brushComponent prop specifies the component to be rendered for the - * highlighted area. This component will be supplied with the following props: x, y, - * width, height, and style. When this prop is not specified, a <rect/> will be rendered. - * @default brushComponent={<rect/>} - */ - brushComponent?: React.ReactElement<any>; - /** - * When the brushDimension prop is set, brushing will only be specific to the to - * the given dimension (either "x" or "y"), and the entire domain of the other - * dimension will be highlighted. When this prop is not specified, highlighting will - * occur along both dimensions. - * @example brushDimension="x" - */ + export interface VictoryBrushContainerProps extends VictoryContainerProps { + /** + * The optional allowDrag prop accepts a boolean that enables dragging behavior + * for the highlighted brush area. Resizing will still be enabled when the allowDrag + * prop is set to false. + * @default true + */ + allowDrag?: boolean; + /** + * The optional allowResize prop accepts a boolean that enables resizing the + * highlighted brush area. Dragging will still be enabled when the allowResize + * prop is set to false, but the dimensions of the brush area will be fixed. + * @default true + */ + allowResize?: boolean; + /** + * The brushComponent prop specifies the component to be rendered for the + * highlighted area. This component will be supplied with the following props: x, y, + * width, height, and style. When this prop is not specified, a <rect/> will be rendered. + * @default brushComponent={<rect/>} + */ + brushComponent?: React.ReactElement<any>; + /** + * When the brushDimension prop is set, brushing will only be specific to the to + * the given dimension (either "x" or "y"), and the entire domain of the other + * dimension will be highlighted. When this prop is not specified, highlighting will + * occur along both dimensions. + * @example brushDimension="x" + */ brushDimension?: 'x' | 'y'; - /** - * The optional brushDomain prop describes the highlighted state. This prop is an - * object that specifies separate arrays for x and y. Each array is a tuple that - * describes the minimum and maximum values to render. If this prop is not provided - * initially, the chart will render with the entire domain highlighted. When this prop - * changes, the chart will render with a new highlighted domain. - * @example brushDomain={{ x: [50, 100], y: [0, 100] }} - */ - brushDomain?: DomainPropType; - /** - * The brushStyle adds custom styles to the brushComponent. This prop - * should be given as an object of SVG style attributes. - * @default "brushStyle={{ stroke: "transparent", fill: "black", fillOpacity: 0.1 }}" - */ - brushStyle?: React.CSSProperties; - /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the - * prop is set to "all", the entire domain will be selected. When the prop is set to "none", - * no new region will be selected, and any existing active brush will be cleared. When - * the prop is set to "disable" the new selected region will default to the current active brush. - */ + /** + * The optional brushDomain prop describes the highlighted state. This prop is an + * object that specifies separate arrays for x and y. Each array is a tuple that + * describes the minimum and maximum values to render. If this prop is not provided + * initially, the chart will render with the entire domain highlighted. When this prop + * changes, the chart will render with a new highlighted domain. + * @example brushDomain={{ x: [50, 100], y: [0, 100] }} + */ + brushDomain?: DomainPropType; + /** + * The brushStyle adds custom styles to the brushComponent. This prop + * should be given as an object of SVG style attributes. + * @default "brushStyle={{ stroke: "transparent", fill: "black", fillOpacity: 0.1 }}" + */ + brushStyle?: React.CSSProperties; + /** + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the + * prop is set to "all", the entire domain will be selected. When the prop is set to "none", + * no new region will be selected, and any existing active brush will be cleared. When + * the prop is set to "disable" the new selected region will default to the current active brush. + */ defaultBrushArea?: 'all' | 'none' | 'disable'; - /** - * When the disable prop is set to true, VictoryBrushContainer events will not fire. - */ - disable?: boolean; - /** - * The handleComponent prop specifies the component to be rendered for each - * handle for the highlighted area. This component will be supplied with the following - * props: x, y, width, height, cursor, and style. When this prop is not - * specified, a <rect/> will be rendered. - * @default handleComponent={<rect/>} - */ - handleComponent?: React.ReactElement<any>; - /** - * The handleStyle adds custom styles to the handleComponents. This prop should be given as an object of SVG style attributes. - * - * Handles refer to the region on each highlighted area where the area may be - * expanded. Only handles relevant to the given dimension will be rendered. For - * example, when brushDimension="x" only "left" and "right" handles will be - * rendered. Handles are automatically styled with cursors appropriate to their orientation. - * @default "handleStyle={{ stroke: 'transparent', fill: 'transparent' }}" - */ - handleStyle?: React.CSSProperties; - /** - * The optional onBrushDomainChange prop accepts an function to be called on - * each update to the highlighted domain. The function accepts the parameters of - * domain (the updated domain), and props (the props used by VictoryBrushContainer). - * @example onBrushDomainChange={(domain, props) => handleDomainChange(domain, props)} - */ + /** + * When the disable prop is set to true, VictoryBrushContainer events will not fire. + */ + disable?: boolean; + /** + * The handleComponent prop specifies the component to be rendered for each + * handle for the highlighted area. This component will be supplied with the following + * props: x, y, width, height, cursor, and style. When this prop is not + * specified, a <rect/> will be rendered. + * @default handleComponent={<rect/>} + */ + handleComponent?: React.ReactElement<any>; + /** + * The handleStyle adds custom styles to the handleComponents. This prop should be given as an object of SVG style attributes. + * + * Handles refer to the region on each highlighted area where the area may be + * expanded. Only handles relevant to the given dimension will be rendered. For + * example, when brushDimension="x" only "left" and "right" handles will be + * rendered. Handles are automatically styled with cursors appropriate to their orientation. + * @default "handleStyle={{ stroke: 'transparent', fill: 'transparent' }}" + */ + handleStyle?: React.CSSProperties; + /** + * The optional onBrushDomainChange prop accepts an function to be called on + * each update to the highlighted domain. The function accepts the parameters of + * domain (the updated domain), and props (the props used by VictoryBrushContainer). + * @example onBrushDomainChange={(domain, props) => handleDomainChange(domain, props)} + */ onBrushDomainChange?: (domain: DomainPropType, props: VictoryBrushContainerProps) => void; - } + } export class VictoryBrushContainer extends React.Component<VictoryBrushContainerProps, any> {} - export interface VictoryZoomContainerProps extends VictoryContainerProps { - /** - * The optional allowPan prop accepts a boolean that enables the panning - * functionality. Zooming will still be enabled when the allowPan prop is set to false. - * @default true - */ - allowPan?: boolean; - /** - * The optional allowZoom prop accepts a boolean that enables the zoom - * functionality. Panning will still be enabled when the allowZoom prop is set to false. - * @default true - */ - allowZoom?: boolean; - /** - * VictoryZoomContainer works by clipping data outside of a given domain. - * VictoryZoomContainer uses VictoryClipContainer by default. - * This prop should not be replaced with a custom component, but you may want to set - * props on VictoryClipContainer, such as clipPadding. - * @example clipContainerComponent={<VictoryClipContainer clipPadding={{top: 10, right: 10}}}/>} - */ - clipContainerComponent?: React.ReactElement<any>; - /** - * When the zoomDimension prop is set, panning and zooming will be restricted to - * the given dimension (either x or y), and the domain of the other dimension will - * remain static. When this prop is not specified, both x and y dimensions will pan and zoom. - * @example zoomDimension="x" - */ + export interface VictoryZoomContainerProps extends VictoryContainerProps { + /** + * The optional allowPan prop accepts a boolean that enables the panning + * functionality. Zooming will still be enabled when the allowPan prop is set to false. + * @default true + */ + allowPan?: boolean; + /** + * The optional allowZoom prop accepts a boolean that enables the zoom + * functionality. Panning will still be enabled when the allowZoom prop is set to false. + * @default true + */ + allowZoom?: boolean; + /** + * VictoryZoomContainer works by clipping data outside of a given domain. + * VictoryZoomContainer uses VictoryClipContainer by default. + * This prop should not be replaced with a custom component, but you may want to set + * props on VictoryClipContainer, such as clipPadding. + * @example clipContainerComponent={<VictoryClipContainer clipPadding={{top: 10, right: 10}}}/>} + */ + clipContainerComponent?: React.ReactElement<any>; + /** + * When the zoomDimension prop is set, panning and zooming will be restricted to + * the given dimension (either x or y), and the domain of the other dimension will + * remain static. When this prop is not specified, both x and y dimensions will pan and zoom. + * @example zoomDimension="x" + */ zoomDimension?: 'x' | 'y'; - /** - * The zoomDomain prop describes the zoomed state. This prop is an object that - * specifies separate arrays for x and y. Each array is a tuple that describes the - * minimum and maximum values to render. If this prop is not provided initially, the - * chart will render without an initial zoom, displaying the entire dataset. Updates to - * zoomDomain will trigger a re-render of the chart with the new domain. - * @example zoomDomain={{x: [0, 100]}} - */ - zoomDomain?: DomainPropType; - /** - * The brushStyle adds custom styles to the brushComponent. This prop - * should be given as an object of SVG style attributes. - * @default "brushStyle={{ stroke: 'transparent', fill: 'black', fillOpacity: 0.1 }}" - */ - brushStyle?: React.CSSProperties; - /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the - * prop is set to "all", the entire domain will be selected. When the prop is set to "none", - * no new region will be selected, and any existing active brush will be cleared. When - * the prop is set to "disable" the new selected region will default to the current active brush. - */ + /** + * The zoomDomain prop describes the zoomed state. This prop is an object that + * specifies separate arrays for x and y. Each array is a tuple that describes the + * minimum and maximum values to render. If this prop is not provided initially, the + * chart will render without an initial zoom, displaying the entire dataset. Updates to + * zoomDomain will trigger a re-render of the chart with the new domain. + * @example zoomDomain={{x: [0, 100]}} + */ + zoomDomain?: DomainPropType; + /** + * The brushStyle adds custom styles to the brushComponent. This prop + * should be given as an object of SVG style attributes. + * @default "brushStyle={{ stroke: 'transparent', fill: 'black', fillOpacity: 0.1 }}" + */ + brushStyle?: React.CSSProperties; + /** + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the + * prop is set to "all", the entire domain will be selected. When the prop is set to "none", + * no new region will be selected, and any existing active brush will be cleared. When + * the prop is set to "disable" the new selected region will default to the current active brush. + */ defaultBrushArea?: 'all' | 'none' | 'disable'; - /** - * When the disable prop is set to true, VictoryBrushContainer events will not fire. - */ - disable?: boolean; - /** - * When the disable prop is set to true, VictoryZoomContainer events will not fire. - */ - downsample?: number | boolean; - /** - * The minimumZoom prop sets a minimum domain extent for the zoomed chart. - * When the difference between the maximum and minimum of a zoomed domain is equal to the minimumZoom - * in either dimension, the component will stop responding to events that would normally trigger zooming in. - * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum - * zoom will cover 1 / 1000th of the original domain. This prop should be given as an object - * with numeric values for x and y. - * @example minimumZoom={{x: 1, y: 0.01}} - */ - minimumZoom?: CursorData; - /** - * The optional onZoomDomainChange prop accepts an function to be called on each update to the visible domain. - * The function accepts the parameters domain (the updated domain) and props (the props used by VictoryZoomContainer). - * @example onZoomDomainChange={(domain, props) => handleDomainChange(domain, props)} - */ + /** + * When the disable prop is set to true, VictoryBrushContainer events will not fire. + */ + disable?: boolean; + /** + * When the disable prop is set to true, VictoryZoomContainer events will not fire. + */ + downsample?: number | boolean; + /** + * The minimumZoom prop sets a minimum domain extent for the zoomed chart. + * When the difference between the maximum and minimum of a zoomed domain is equal to the minimumZoom + * in either dimension, the component will stop responding to events that would normally trigger zooming in. + * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum + * zoom will cover 1 / 1000th of the original domain. This prop should be given as an object + * with numeric values for x and y. + * @example minimumZoom={{x: 1, y: 0.01}} + */ + minimumZoom?: CursorData; + /** + * The optional onZoomDomainChange prop accepts an function to be called on each update to the visible domain. + * The function accepts the parameters domain (the updated domain) and props (the props used by VictoryZoomContainer). + * @example onZoomDomainChange={(domain, props) => handleDomainChange(domain, props)} + */ onZoomDomainChange?: (domain: DomainPropType, props: VictoryZoomContainerProps) => void; - } + } export class VictoryZoomContainer extends React.Component<VictoryZoomContainerProps, any> {} - // Note: Many SVG attributes are missed in CSSProperties interface - export interface VictoryThemeDefinition { - area?: VictoryStyleInterface; - axis?: { - axis: React.CSSProperties; - axisLabel: React.CSSProperties; - grid: React.CSSProperties; - ticks: React.CSSProperties; - tickLabels: React.CSSProperties; - }; - bar?: VictoryStyleInterface; - candlestick?: VictoryStyleInterface & { - props: { - width: number; - height: number; - candleColors: { - positive: string; - negative: string; + // Note: Many SVG attributes are missed in CSSProperties interface + export interface VictoryThemeDefinition { + area?: VictoryStyleInterface; + axis?: { + axis: React.CSSProperties; + axisLabel: React.CSSProperties; + grid: React.CSSProperties; + ticks: React.CSSProperties; + tickLabels: React.CSSProperties; }; - }; - }; - line?: VictoryStyleInterface; - pie?: { - props: { - width: number; - height: number; - colorScale: string[]; - }; - style: VictoryStyleInterface; - }; - scatter?: VictoryStyleInterface; - props?: { - width: number; - height: number; - colorScale: string[]; - }; - } + bar?: VictoryStyleInterface; + candlestick?: VictoryStyleInterface & { + props: { + width: number; + height: number; + candleColors: { + positive: string; + negative: string; + }; + }; + }; + line?: VictoryStyleInterface; + pie?: { + props: { + width: number; + height: number; + colorScale: string[]; + }; + style: VictoryStyleInterface; + }; + scatter?: VictoryStyleInterface; + props?: { + width: number; + height: number; + colorScale: string[]; + }; + } - interface VictoryThemeInterface { - /** - * Default theme - */ - grayscale: VictoryThemeDefinition; - material: VictoryThemeDefinition; - } + interface VictoryThemeInterface { + /** + * Default theme + */ + grayscale: VictoryThemeDefinition; + material: VictoryThemeDefinition; + } - /** - * Available themes - */ - export const VictoryTheme: VictoryThemeInterface; + /** + * Available themes + */ + export const VictoryTheme: VictoryThemeInterface; - type OrientationTypes = "top" | "bottom" | "left" | "right"; + type OrientationTypes = "top" | "bottom" | "left" | "right"; - export interface VictoryTooltipProps { - /** - * The active prop specifies whether the tooltip component should be displayed. - */ - active?: boolean; - /** - * When true, tooltip events will set the active prop on both data and label elements. - * @default false - */ - activateData?: boolean; - /** - * The angle prop specifies the angle to rotate the tooltip around its origin point. - */ - angle?: string | number; - /** - * The cornerRadius prop determines corner radius of the flyout container. This prop may be given as a positive number or a function of datum. - */ - cornerRadius?: NumberOrCallback; - /** - * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine text. - */ - datum?: {}; - /** - * Victory components can pass a data prop to their label component. This can be useful in custom components that need to make use of the entire dataset. - */ - data?: any[]; - /** - * The dx prop defines a horizontal shift from the x coordinate. - */ - dx?: StringOrNumberOrCallback; - /** - * The dy prop defines a vertical shift from the y coordinate. - */ - dy?: StringOrNumberOrCallback; - /** - * The events prop attaches arbitrary event handlers to the label component. This prop should be given as an object of event names and corresponding event handlers. - * When events are provided via Victory’s event system, event handlers will be called with the event, the props of the component is attached to, and an eventKey. - * Examples: events={{onClick: (evt) => alert("x: " + evt.clientX)}} - */ - events?: {}; - /** - * The style prop applies SVG style properties to the rendered flyout container. These props will be passed to the flyoutComponent. - */ - flyoutStyle?: React.CSSProperties; - /** - * The flyoutComponent prop takes a component instance which will be used to create the flyout path for each tooltip. - * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, - * index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. - * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. - * If flyoutComponent is omitted, a default Flyout component will be created with props described above. - * Examples: flyoutComponent={<Flyout x={50} y={50}/>}, flyoutComponent={<MyCustomFlyout/>} - * @default <Flyout/> - */ - flyoutComponent?: React.ReactElement<any>; - /** - * The groupComponent prop takes a component instance which will be used to create group elements for use within container elements. This prop defaults to a <g> tag. - * @default groupComponent={<g/>} - */ - groupComponent?: React.ReactElement<any>; - /** - * The height prop defines the height of the tooltip flyout. This prop may be given as a positive number or a function of datum. - * If this prop is not set, height will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. - */ - height?: NumberOrCallback; - /** - * The horizontal prop determines whether to plot the flyouts to the left / right of the (x, y) coordinate rather than top / bottom. - * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. - * negative values result in a left orientation and positive values will result in a right orientation by default. - */ - horizontal?: boolean; - /** - * The index prop represents the index of the datum in the data array. - */ - index?: number | string; - /** - * The labelComponent prop takes a component instance which will be used to render each tooltip label. - * The new element created from the passed labelComponent will be supplied with the following properties: x, y, index, datum, verticalAnchor, textAnchor, style, text, and events. - * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. - * If labelComponent is omitted, a new VictoryLabel will be created with the props described above. - * Examples: labelComponent={<VictoryLabel dy={20}/>}, labelComponent={<MyCustomLabel/>} - * @default <VictoryLabel/> - */ - labelComponent?: React.ReactElement<any>; - /** - * The orientation prop determines which side of the (x, y) coordinate the tooltip should be rendered on. - * This prop can be given as “top”, “bottom”, “left”, “right”, or as a function of datum that returns one of these values. - * If this prop is not provided it will be determined from the sign of the datum, and the value of the horizontal prop. - */ - orientation?: OrientationTypes; - /** - * The pointerLength prop determines the length of the triangular pointer extending from the flyout. This prop may be given as a positive number or a function of datum. - */ - pointerLength?: NumberOrCallback; - /** - * The pointerWidth prop determines the width of the base of the triangular pointer extending from - * the flyout. This prop may be given as a positive number or a function of datum. - */ - pointerWidth?: NumberOrCallback; - /** - * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element - * within VictoryContainer. Note: This prop should not be set to true when using a custom container element. - */ - renderInPortal?: boolean; - /** - * The style prop applies CSS properties to the rendered `<text>` element. - */ - style?: React.CSSProperties; - /** - * The text prop defines the text VictoryTooltip will render. The text prop may be given as a string, number, or function of datum. - * When VictoryLabel is used as the labelComponent, strings may include newline characters, which VictoryLabel will split in to separate <tspan/> elements. - */ - text?: StringOrNumberOrCallback | string[] | number[]; - /** - * VictoryAxis uses the standard theme prop. Read about it here - * @default VictoryTheme.grayscale - */ - theme?: VictoryThemeDefinition; - /** - * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. - * If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. - */ - width?: NumberOrCallback; - /** - * The x prop defines the x coordinate to use as a basis for horizontal positioning. - */ - x?: number; - /** - * The y prop defines the y coordinate to use as a basis for vertical positioning. - */ - y?: number; - } + export interface VictoryTooltipProps { + /** + * The active prop specifies whether the tooltip component should be displayed. + */ + active?: boolean; + /** + * When true, tooltip events will set the active prop on both data and label elements. + * @default false + */ + activateData?: boolean; + /** + * The angle prop specifies the angle to rotate the tooltip around its origin point. + */ + angle?: string | number; + /** + * The cornerRadius prop determines corner radius of the flyout container. This prop may be given as a positive number or a function of datum. + */ + cornerRadius?: NumberOrCallback; + /** + * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine text. + */ + datum?: {}; + /** + * Victory components can pass a data prop to their label component. This can be useful in custom components that need to make use of the entire dataset. + */ + data?: any[]; + /** + * The dx prop defines a horizontal shift from the x coordinate. + */ + dx?: StringOrNumberOrCallback; + /** + * The dy prop defines a vertical shift from the y coordinate. + */ + dy?: StringOrNumberOrCallback; + /** + * The events prop attaches arbitrary event handlers to the label component. This prop should be given as an object of event names and corresponding event handlers. + * When events are provided via Victory’s event system, event handlers will be called with the event, the props of the component is attached to, and an eventKey. + * Examples: events={{onClick: (evt) => alert("x: " + evt.clientX)}} + */ + events?: {}; + /** + * The style prop applies SVG style properties to the rendered flyout container. These props will be passed to the flyoutComponent. + */ + flyoutStyle?: VictoryStyleObject; + /** + * The flyoutComponent prop takes a component instance which will be used to create the flyout path for each tooltip. + * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, + * index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. + * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. + * If flyoutComponent is omitted, a default Flyout component will be created with props described above. + * Examples: flyoutComponent={<Flyout x={50} y={50}/>}, flyoutComponent={<MyCustomFlyout/>} + * @default <Flyout/> + */ + flyoutComponent?: React.ReactElement<any>; + /** + * The groupComponent prop takes a component instance which will be used to create group elements for use within container elements. This prop defaults to a <g> tag. + * @default groupComponent={<g/>} + */ + groupComponent?: React.ReactElement<any>; + /** + * The height prop defines the height of the tooltip flyout. This prop may be given as a positive number or a function of datum. + * If this prop is not set, height will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. + */ + height?: NumberOrCallback; + /** + * The horizontal prop determines whether to plot the flyouts to the left / right of the (x, y) coordinate rather than top / bottom. + * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. + * negative values result in a left orientation and positive values will result in a right orientation by default. + */ + horizontal?: boolean; + /** + * The index prop represents the index of the datum in the data array. + */ + index?: number | string; + /** + * The labelComponent prop takes a component instance which will be used to render each tooltip label. + * The new element created from the passed labelComponent will be supplied with the following properties: x, y, index, datum, verticalAnchor, textAnchor, style, text, and events. + * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. + * If labelComponent is omitted, a new VictoryLabel will be created with the props described above. + * Examples: labelComponent={<VictoryLabel dy={20}/>}, labelComponent={<MyCustomLabel/>} + * @default <VictoryLabel/> + */ + labelComponent?: React.ReactElement<any>; + /** + * The orientation prop determines which side of the (x, y) coordinate the tooltip should be rendered on. + * This prop can be given as “top”, “bottom”, “left”, “right”, or as a function of datum that returns one of these values. + * If this prop is not provided it will be determined from the sign of the datum, and the value of the horizontal prop. + */ + orientation?: OrientationTypes; + /** + * The pointerLength prop determines the length of the triangular pointer extending from the flyout. This prop may be given as a positive number or a function of datum. + */ + pointerLength?: NumberOrCallback; + /** + * The pointerWidth prop determines the width of the base of the triangular pointer extending from + * the flyout. This prop may be given as a positive number or a function of datum. + */ + pointerWidth?: NumberOrCallback; + /** + * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element + * within VictoryContainer. Note: This prop should not be set to true when using a custom container element. + */ + renderInPortal?: boolean; + /** + * The style prop applies CSS properties to the rendered `<text>` element. + */ + style?: React.CSSProperties; + /** + * The text prop defines the text VictoryTooltip will render. The text prop may be given as a string, number, or function of datum. + * When VictoryLabel is used as the labelComponent, strings may include newline characters, which VictoryLabel will split in to separate <tspan/> elements. + */ + text?: StringOrNumberOrCallback | string[] | number[]; + /** + * VictoryAxis uses the standard theme prop. Read about it here + * @default VictoryTheme.grayscale + */ + theme?: VictoryThemeDefinition; + /** + * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. + * If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. + */ + width?: NumberOrCallback; + /** + * The x prop defines the x coordinate to use as a basis for horizontal positioning. + */ + x?: number; + /** + * The y prop defines the y coordinate to use as a basis for vertical positioning. + */ + y?: number; + } - /** - * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label - * component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. - * VictoryTooltip renders text as well as a configurable Flyout container. - */ - export class VictoryTooltip extends React.Component< - VictoryTooltipProps, - any + /** + * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label + * component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. + * VictoryTooltip renders text as well as a configurable Flyout container. + */ + export class VictoryTooltip extends React.Component< + VictoryTooltipProps, + any > {} - /** - * Animate object used in components - */ - export interface AnimatePropTypeInterface { /** - * Animation duration + * Animate object used in components */ - duration: number; - /** - * Animation end callback - */ - onEnd?: () => void; - /** - * Animation exit transition configuration - */ - onExit?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - }; - /** - * Animation enter transition configuration - */ - onEnter?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - after?: (datum: any) => AnimationStyle; - }; - /** - * Animation load transition configuration - */ - onLoad?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - after?: (datum: any) => AnimationStyle; - }; - /** - * The easing prop specifies an easing function name to use for tweening. - * @default "quadInOut" - */ - easing?: AnimationEasing; - } + export interface AnimatePropTypeInterface { + /** + * Animation duration + */ + duration: number; + /** + * Animation end callback + */ + onEnd?: () => void; + /** + * Animation exit transition configuration + */ + onExit?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + }; + /** + * Animation enter transition configuration + */ + onEnter?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + after?: (datum: any) => AnimationStyle; + }; + /** + * Animation load transition configuration + */ + onLoad?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + after?: (datum: any) => AnimationStyle; + }; + /** + * The easing prop specifies an easing function name to use for tweening. + * @default "quadInOut" + */ + easing?: AnimationEasing; + } - /** - * Return value for eventHandlers values - */ - interface EventCallbackInterface<TTarget, TEventKey> { /** - * Use only in: - * - VictoryChart - * - VictoryStack + * Return value for eventHandlers values */ - childName?: string; - target?: TTarget; - eventKey?: TEventKey; - /** - * Will be called with the calculated props for the individual selected element and result will override - * props of selected element via object assignment - * @param props - */ - mutation: (props: any) => any; - } + interface EventCallbackInterface<TTarget, TEventKey> { + /** + * Use only in: + * - VictoryChart + * - VictoryStack + */ + childName?: string; + target?: TTarget; + eventKey?: TEventKey; + /** + * Will be called with the calculated props for the individual selected element and result will override + * props of selected element via object assignment + * @param props + */ + mutation: (props: any) => any; + } - export interface EventPropTypeInterface<TTarget, TEventKey> { - /** - * Use only in: - * - VictoryChart - * - VictoryStack - */ - childName?: string; - /** - * Targets may be any valid style namespace for a given component - */ - target: TTarget; + export interface EventPropTypeInterface<TTarget, TEventKey> { + /** + * Use only in: + * - VictoryChart + * - VictoryStack + */ + childName?: string; + /** + * Targets may be any valid style namespace for a given component + */ + target: TTarget; - eventKey?: TEventKey; - /** - * Event handlers map. Keys are standard event names (such as onClick) and values are event callbacks - */ - eventHandlers: { + eventKey?: TEventKey; + /** + * Event handlers map. Keys are standard event names (such as onClick) and values are event callbacks + */ + eventHandlers: { [key: string]: { (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey> } | { (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey>[] - } - }; - } + } + }; + } - /** - * Data domain type - */ - type DomainTuple = [number, number] | [Date, Date]; + /** + * Data domain type + */ + type DomainTuple = [number, number] | [Date, Date]; type DomainPropType = DomainTuple | { x?: DomainTuple; y: DomainTuple; } | { x: DomainTuple; y?: DomainTuple; }; - /** - * Domain padding - */ + /** + * Domain padding + */ type DomainPaddingPropType = number | { x?: number | [ number, number]; y?: number | [ number, number]; - }; + }; - /** - * D3 scale function shape. Don't want to introduce typing dependency to d3 - */ - interface D3Scale { - domain: () => any; - range: () => any; - copy: () => any; - } + /** + * D3 scale function shape. Don't want to introduce typing dependency to d3 + */ + interface D3Scale { + domain: () => any; + range: () => any; + copy: () => any; + } - /** - * Acceptable scale types - */ - type ScalePropType = "linear" | "time" | "log" | "sqrt"; + /** + * Acceptable scale types + */ + type ScalePropType = "linear" | "time" | "log" | "sqrt"; - /** - * Category prop type - */ + /** + * Category prop type + */ type CategoryPropType = string[] | { x: string[] y: string[] - }; + }; - /** - * Data getter property type - */ + /** + * Data getter property type + */ type DataGetterPropType = number | string | string[] | { (data: any): number | string | string[] }; type InterpolationPropType = "basis" | "basisClosed" | "basisOpen" | "bundle" | @@ -829,606 +830,606 @@ declare module "victory" { type ColorScalePropType = "greyscale" | "qualitative" | "heatmap" | "warm" | "cool" | "red" | "green" | "blue" | string[]; - /** - * Common properties - */ - interface VictoryCommonProps { /** - * The animate prop specifies props for VictoryAnimation to use. - * The animate prop should also be used to specify enter and exit - * transition configurations with the `onExit` and `onEnter` namespaces respectively. - * @example - * {duration: 500, onExit: () => {}, onEnter: {duration: 500, before: () => ({y: 0})})} - */ - animate?: AnimatePropTypeInterface; - /** - * The name prop is used to reference a component instance when defining shared events. - */ - name?: string; - /** - * The height props specifies the height the svg viewBox of the chart container. - * This value should be given as a number of pixels - */ - height?: number; - /** - * The padding props specifies the amount of padding in number of pixels between - * the edge of the chart and any rendered child components. This prop can be given - * as a number or as an object with padding specified for top, bottom, left - * and right. - * @default 50 + * Common properties */ + interface VictoryCommonProps { + /** + * The animate prop specifies props for VictoryAnimation to use. + * The animate prop should also be used to specify enter and exit + * transition configurations with the `onExit` and `onEnter` namespaces respectively. + * @example + * {duration: 500, onExit: () => {}, onEnter: {duration: 500, before: () => ({y: 0})})} + */ + animate?: AnimatePropTypeInterface; + /** + * The name prop is used to reference a component instance when defining shared events. + */ + name?: string; + /** + * The height props specifies the height the svg viewBox of the chart container. + * This value should be given as a number of pixels + */ + height?: number; + /** + * The padding props specifies the amount of padding in number of pixels between + * the edge of the chart and any rendered child components. This prop can be given + * as a number or as an object with padding specified for top, bottom, left + * and right. + * @default 50 + */ padding?: number | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - /** - * The scale prop determines which scales your chart should use. This prop can be - * given as a string specifying a supported scale ("linear", "time", "log", "sqrt"), - * as a d3 scale function, or as an object with scales specified for x and y - * @example d3Scale.time(), {x: "linear", y: "log"} - * @default "linear" - */ + top?: number; + bottom?: number; + left?: number; + right?: number; + }; + /** + * The scale prop determines which scales your chart should use. This prop can be + * given as a string specifying a supported scale ("linear", "time", "log", "sqrt"), + * as a d3 scale function, or as an object with scales specified for x and y + * @example d3Scale.time(), {x: "linear", y: "log"} + * @default "linear" + */ scale?: ScalePropType | D3Scale | { - x?: ScalePropType | D3Scale; - y?: ScalePropType | D3Scale; - }; - /** - * The standalone prop determines whether the component will render a standalone svg - * or a <g> tag that will be included in an external svg. Set standalone to false to - * compose VictoryAxis with other components within an enclosing <svg> tag. - * @default true - */ - standalone?: boolean; - /** - * The width props specifies the width of the svg viewBox of the chart container - * This value should be given as a number of pixels - */ - width?: number; - /** - * The containerComponent prop takes an entire component which will be used to - * create a container element for standalone charts. - * The new element created from the passed containerComponent wil be provided with - * these props from VictoryArea: height, width, children - * (the chart itself) and style. Props that are not provided by the - * child chart component include title and desc, both of which - * are intended to add accessibility to Victory components. The more descriptive these props - * are, the more accessible your data will be for people using screen readers. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a dataComponent is - * not provided, VictoryArea will use the default VictoryContainer component. - * @example <VictoryContainer title="Chart of Dog Breeds" desc="This chart shows how popular each dog breed is by percentage in Seattle." /> - * @default <VictoryContainer/> - */ - containerComponent?: React.ReactElement<any>; - /** - * The theme prop takes a style object with nested data, labels, and parent objects. - * You can create this object yourself, or you can use a theme provided by Victory. - * When using VictoryArea as a solo component, implement the theme directly on - * VictoryArea. If you are wrapping VictoryArea in VictoryChart, VictoryStack, or - * VictoryGroup, please call the theme on the outermost wrapper component instead. - * @example theme={VictoryTheme.material} - * http://www.github.com/FormidableLabs/victory-core/tree/master/src/victory-theme/material.js - */ - theme?: VictoryThemeDefinition; - /** - * The groupComponent prop takes an entire component which will be used to - * create group elements for use within container elements. This prop defaults - * to a <g> tag on web, and a react-native-svg <G> tag on mobile - * @default <g/> - */ - groupComponent?: React.ReactElement<any>; - } + x?: ScalePropType | D3Scale; + y?: ScalePropType | D3Scale; + }; + /** + * The standalone prop determines whether the component will render a standalone svg + * or a <g> tag that will be included in an external svg. Set standalone to false to + * compose VictoryAxis with other components within an enclosing <svg> tag. + * @default true + */ + standalone?: boolean; + /** + * The width props specifies the width of the svg viewBox of the chart container + * This value should be given as a number of pixels + */ + width?: number; + /** + * The containerComponent prop takes an entire component which will be used to + * create a container element for standalone charts. + * The new element created from the passed containerComponent wil be provided with + * these props from VictoryArea: height, width, children + * (the chart itself) and style. Props that are not provided by the + * child chart component include title and desc, both of which + * are intended to add accessibility to Victory components. The more descriptive these props + * are, the more accessible your data will be for people using screen readers. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a dataComponent is + * not provided, VictoryArea will use the default VictoryContainer component. + * @example <VictoryContainer title="Chart of Dog Breeds" desc="This chart shows how popular each dog breed is by percentage in Seattle." /> + * @default <VictoryContainer/> + */ + containerComponent?: React.ReactElement<any>; + /** + * The theme prop takes a style object with nested data, labels, and parent objects. + * You can create this object yourself, or you can use a theme provided by Victory. + * When using VictoryArea as a solo component, implement the theme directly on + * VictoryArea. If you are wrapping VictoryArea in VictoryChart, VictoryStack, or + * VictoryGroup, please call the theme on the outermost wrapper component instead. + * @example theme={VictoryTheme.material} + * http://www.github.com/FormidableLabs/victory-core/tree/master/src/victory-theme/material.js + */ + theme?: VictoryThemeDefinition; + /** + * The groupComponent prop takes an entire component which will be used to + * create group elements for use within container elements. This prop defaults + * to a <g> tag on web, and a react-native-svg <G> tag on mobile + * @default <g/> + */ + groupComponent?: React.ReactElement<any>; + } - /** - * Common properties for all data components - */ - interface VictoryDatableProps { /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these arrays of values specified for x and y. If this prop is not set, - * categorical data will be plotted in the order it was given in the data array - * @example ["dogs", "cats", "mice"] + * Common properties for all data components */ - categories?: CategoryPropType; - /** - * The data prop specifies the data to be plotted. Data should be in the form of an array - * of data points, or an array of arrays of data points for multiple datasets. - * Each data point may be any format you wish (depending on the `x` and `y` accessor props), - * but by default, an object with x and y properties is expected. - * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], - * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] - */ - data?: any[]; - /** - * The dataComponent prop takes an entire component which will be used to create an area. - * The new element created from the passed dataComponent will be provided with the - * following properties calculated by VictoryArea: a scale, style, events, interpolation, - * and an array of modified data objects (including x, y, and calculated y0 and y1). - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a dataComponent is - * not provided, VictoryArea will use its default Area component. - * @default <Area/> - */ - dataComponent?: React.ReactElement<any>; - /** - * The domain prop describes the range of values your chart will cover. This prop can be - * given as a array of the minimum and maximum expected values for your bar chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The x prop specifies how to access the X value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) - * @default "x" - */ - x?: DataGetterPropType; - /** - * The y prop specifies how to access the Y value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) - * @default "y" - */ - y?: DataGetterPropType; - } + interface VictoryDatableProps { + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these arrays of values specified for x and y. If this prop is not set, + * categorical data will be plotted in the order it was given in the data array + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The data prop specifies the data to be plotted. Data should be in the form of an array + * of data points, or an array of arrays of data points for multiple datasets. + * Each data point may be any format you wish (depending on the `x` and `y` accessor props), + * but by default, an object with x and y properties is expected. + * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], + * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] + */ + data?: any[]; + /** + * The dataComponent prop takes an entire component which will be used to create an area. + * The new element created from the passed dataComponent will be provided with the + * following properties calculated by VictoryArea: a scale, style, events, interpolation, + * and an array of modified data objects (including x, y, and calculated y0 and y1). + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a dataComponent is + * not provided, VictoryArea will use its default Area component. + * @default <Area/> + */ + dataComponent?: React.ReactElement<any>; + /** + * The domain prop describes the range of values your chart will cover. This prop can be + * given as a array of the minimum and maximum expected values for your bar chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The x prop specifies how to access the X value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) + * @default "x" + */ + x?: DataGetterPropType; + /** + * The y prop specifies how to access the Y value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) + * @default "y" + */ + y?: DataGetterPropType; + } - // Common labable interface - interface VictoryLabableProps { - /** - * The labelComponent prop takes in an entire label component which will be used - * to create a label for the area. The new element created from the passed labelComponent - * will be supplied with the following properties: x, y, index, data, verticalAnchor, - * textAnchor, angle, style, text, and events. any of these props may be overridden - * by passing in props to the supplied component, or modified or ignored within - * the custom component itself. If labelComponent is omitted, a new VictoryLabel - * will be created with props described above. This labelComponent prop should be used to - * provide a series label for VictoryArea. If individual labels are required for each - * data point, they should be created by composing VictoryArea with VictoryScatter - * @default <VictoryLabel/> - */ - labelComponent?: React.ReactElement<any>; - } + // Common labable interface + interface VictoryLabableProps { + /** + * The labelComponent prop takes in an entire label component which will be used + * to create a label for the area. The new element created from the passed labelComponent + * will be supplied with the following properties: x, y, index, data, verticalAnchor, + * textAnchor, angle, style, text, and events. any of these props may be overridden + * by passing in props to the supplied component, or modified or ignored within + * the custom component itself. If labelComponent is omitted, a new VictoryLabel + * will be created with props described above. This labelComponent prop should be used to + * provide a series label for VictoryArea. If individual labels are required for each + * data point, they should be created by composing VictoryArea with VictoryScatter + * @default <VictoryLabel/> + */ + labelComponent?: React.ReactElement<any>; + } - interface VictoryMultiLabeableProps extends VictoryLabableProps { - /** - * The labels prop defines labels that will appear above each bar in your chart. - * This prop should be given as an array of values or as a function of data. - * If given as an array, the number of elements in the array should be equal to - * the length of the data array. Labels may also be added directly to the data object - * like data={[{x: 1, y: 1, label: "first"}]}. - * @example ["spring", "summer", "fall", "winter"], (datum) => datum.title - */ - labels?: string[] | { (data: any): string }; - } + interface VictoryMultiLabeableProps extends VictoryLabableProps { + /** + * The labels prop defines labels that will appear above each bar in your chart. + * This prop should be given as an array of values or as a function of data. + * If given as an array, the number of elements in the array should be equal to + * the length of the data array. Labels may also be added directly to the data object + * like data={[{x: 1, y: 1, label: "first"}]}. + * @example ["spring", "summer", "fall", "winter"], (datum) => datum.title + */ + labels?: string[] | { (data: any): string }; + } - interface VictorySingleLabableProps extends VictoryLabableProps { - /** - * The label prop defines the label that will appear at the edge of the area. - * This prop should be given a string or as a function of data. If individual - * labels are required for each data point, they should be created by composing - * VictoryArea with VictoryScatter - * @example: "Series 1", (data) => `${data.length} points` - */ - label?: string | { (data: any): string }; - } + interface VictorySingleLabableProps extends VictoryLabableProps { + /** + * The label prop defines the label that will appear at the edge of the area. + * This prop should be given a string or as a function of data. If individual + * labels are required for each data point, they should be created by composing + * VictoryArea with VictoryScatter + * @example: "Series 1", (data) => `${data.length} points` + */ + label?: string | { (data: any): string }; + } - export interface VictoryAreaProps - extends VictoryCommonProps, - VictoryDatableProps, - VictorySingleLabableProps { - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryArea events. - * Since VictoryArea only renders a single element, the eventKey property is not used. - * The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. an area), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @example - * events={[ - * { - * target: "data", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; - /** - * The interpolation prop determines how data points should be connected when plotting a line - * @default "linear" - */ - interpolation?: InterpolationPropType; - /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - * @default 50 - */ - samples?: number; - /** - * The style prop specifies styles for your VictoryArea. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. - * @example {data: {fill: "red"}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; - } + export interface VictoryAreaProps + extends VictoryCommonProps, + VictoryDatableProps, + VictorySingleLabableProps { + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryArea events. + * Since VictoryArea only renders a single element, the eventKey property is not used. + * The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. an area), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @example + * events={[ + * { + * target: "data", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; + /** + * The interpolation prop determines how data points should be connected when plotting a line + * @default "linear" + */ + interpolation?: InterpolationPropType; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + * @default 50 + */ + samples?: number; + /** + * The style prop specifies styles for your VictoryArea. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. + * @example {data: {fill: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + } - /** - * Draw area charts with React. VictoryArea is a composable component, so it doesn't include axes. - * Add VictoryArea as a child of VictoryChart for a complete chart. - */ - export class VictoryArea extends React.Component<VictoryAreaProps, any> {} + /** + * Draw area charts with React. VictoryArea is a composable component, so it doesn't include axes. + * Add VictoryArea as a child of VictoryChart for a complete chart. + */ + export class VictoryArea extends React.Component<VictoryAreaProps, any> {} - export interface VictoryAxisProps extends VictoryCommonProps { - /** - * The axisComponent prop takes in an entire component which will be used - * to create the axis line. The new element created from the passed axisComponent - * will be supplied with the following properties: x1, y1, x2, y2, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If an axisComponent - * is not supplied, VictoryAxis will render its default AxisLine component. - * @default <AxisLine/> - */ - axisComponent?: React.ReactElement<any>; - /** - * The axisLabelComponent prop takes in an entire component which will be used - * to create the axis label. The new element created from the passed axisLabelComponent - * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, - * angle, transform, style and events. Any of these props may be overridden by - * passing in props to the supplied component, or modified or ignored within - * the custom component itself. If an axisLabelComponent is not supplied, a new - * VictoryLabel will be created with props described above - * @default <VictoryLabel/> - */ - axisLabelComponent?: React.ReactElement<any>; - /** - * This prop specifies whether a given axis is intended to cross another axis. - */ - crossAxis?: boolean; - /** - * The dependentAxis prop specifies whether the axis corresponds to the - * dependent variable (usually y). This prop is useful when composing axis - * with other components to form a chart. - */ - dependentAxis?: boolean; - /** - * The domain prop describes the range of values your axis will include. This prop should be - * given as a array of the minimum and maximum expected values for your axis. - * If this value is not given it will be calculated based on the scale or tickValues. - * @examples [-1, 1] - */ - domain?: DomainPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "axis", "axisLabel", "ticks", "tickLabels", and "grid" are - * all valid targets for VictoryAxis events. The eventKey may optionally be used to select a - * single element by index rather than an entire set. The eventHandlers object - * should be given as an object whose keys are standard event names (i.e. onClick) - * and whose values are event callbacks. The return value of an event handler - * be used to modify other elemnts. The return value should be given as an object or - * an array of objects with optional target and eventKey keys, and a mutation - * key whose value is a function. The target and eventKey keys will default to those - * corresponding to the element the event handler was attached to. The mutation - * function will be called with the calculated props for the individual selected - * element (i.e. a single tick), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "grid", - * eventKey: 2, - * eventHandlers: { - * onClick: () => { - * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {stroke: "orange"})}; - * } - * }, { - * target: "tickLabels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ + export interface VictoryAxisProps extends VictoryCommonProps { + /** + * The axisComponent prop takes in an entire component which will be used + * to create the axis line. The new element created from the passed axisComponent + * will be supplied with the following properties: x1, y1, x2, y2, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If an axisComponent + * is not supplied, VictoryAxis will render its default AxisLine component. + * @default <AxisLine/> + */ + axisComponent?: React.ReactElement<any>; + /** + * The axisLabelComponent prop takes in an entire component which will be used + * to create the axis label. The new element created from the passed axisLabelComponent + * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, + * angle, transform, style and events. Any of these props may be overridden by + * passing in props to the supplied component, or modified or ignored within + * the custom component itself. If an axisLabelComponent is not supplied, a new + * VictoryLabel will be created with props described above + * @default <VictoryLabel/> + */ + axisLabelComponent?: React.ReactElement<any>; + /** + * This prop specifies whether a given axis is intended to cross another axis. + */ + crossAxis?: boolean; + /** + * The dependentAxis prop specifies whether the axis corresponds to the + * dependent variable (usually y). This prop is useful when composing axis + * with other components to form a chart. + */ + dependentAxis?: boolean; + /** + * The domain prop describes the range of values your axis will include. This prop should be + * given as a array of the minimum and maximum expected values for your axis. + * If this value is not given it will be calculated based on the scale or tickValues. + * @examples [-1, 1] + */ + domain?: DomainPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "axis", "axisLabel", "ticks", "tickLabels", and "grid" are + * all valid targets for VictoryAxis events. The eventKey may optionally be used to select a + * single element by index rather than an entire set. The eventHandlers object + * should be given as an object whose keys are standard event names (i.e. onClick) + * and whose values are event callbacks. The return value of an event handler + * be used to modify other elemnts. The return value should be given as an object or + * an array of objects with optional target and eventKey keys, and a mutation + * key whose value is a function. The target and eventKey keys will default to those + * corresponding to the element the event handler was attached to. The mutation + * function will be called with the calculated props for the individual selected + * element (i.e. a single tick), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "grid", + * eventKey: 2, + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {stroke: "orange"})}; + * } + * }, { + * target: "tickLabels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ events?: EventPropTypeInterface<"axis" | "axisLabel" | "grid" | "ticks" | "tickLabels" | "parent", number | string>[]; - /** - * When true, this prop reduces the number of tick labels to fit the length of the axis. - * Labels are removed at approximately even intervals from the original array of labels. - * This feature only works well for labels that are approximately evenly spaced. - * @default false - */ - fixLabelOverlap?: boolean; - /** - * The gridComponent prop takes in an entire component which will be used - * to create grid lines. The new element created from the passed gridComponent - * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a gridComponent - * is not supplied, VictoryAxis will render its default GridLine component. - * @default <GridLine/> - */ - gridComponent?: React.ReactElement<any>; - /** - * If true, this value will flip the domain of a given axis. - */ - invertAxis?: boolean; - /** - * The label prop defines the label that will appear along the axis. This - * prop should be given as a value or an entire, HTML-complete label - * component. If a label component is given, it will be cloned. The new - * element's properties x, y, textAnchor, verticalAnchor, and transform - * will have defaults provided by the axis; styles filled out with - * defaults provided by the axis, and overrides from the label component. - * If a value is given, a new VictoryLabel will be created with props and - * styles from the axis. - */ - label?: any; - /** - * This value describes how far from the "edge" of its permitted area each axis - * will be set back in the x-direction. If this prop is not given, - * the offset is calculated based on font size, axis orientation, and label padding. - */ - offsetX?: number; - /** - * This value describes how far from the "edge" of its permitted area each axis - * will be set back in the y-direction. If this prop is not given, - * the offset is calculated based on font size, axis orientation, and label padding. - */ - offsetY?: number; - /** - * The orientation prop specifies the position and orientation of your axis. - */ - orientation?: "top" | "bottom" | "left" | "right"; - /** - * The style prop defines the style of the component. The style prop should be given as an object - * with styles defined for parent, axis, axisLabel, grid, ticks, and tickLabels. Any valid svg - * styles are supported, but width, height, and padding should be specified via props as they - * determine relative layout for components in VictoryChart. Functional styles may be defined for - * grid, tick, and tickLabel style properties, and they will be evaluated with each tick. - * - * note: When a component is rendered as a child of another Victory component, or within a custom - * <svg> element with standalone={false} parent styles will be applied to the enclosing <g> tag. - * Many styles that can be applied to a parent <svg> will not be expressed when applied to a <g>. - * - * note: custom angle and verticalAnchor properties may be included in labels styles. - */ - style?: { - parent?: React.CSSProperties; - axis?: React.CSSProperties; - axisLabel?: React.CSSProperties; - grid?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - ticks?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - tickLabels?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - }; - /** - * The tickComponent prop takes in an entire component which will be used - * to create tick lines. The new element created from the passed tickComponent - * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a tickComponent - * is not supplied, VictoryAxis will render its default Tick component. - * @default <Tick/> - */ - tickComponent?: React.ReactElement<any>; - /** - * The tickCount prop specifies approximately how many ticks should be drawn on the axis if - * tickValues are not explicitly provided. This value is calculated by d3 scale and - * prioritizes returning "nice" values and evenly spaced ticks over an exact number of ticks. - * If you need an exact number of ticks, please specify them via the tickValues prop. - * This prop must have a value greater than zero. - * @default 5 - */ - tickCount?: number; - /** - * The tickLabelComponent prop takes in an entire component which will be used - * to create the tick labels. The new element created from the passed tickLabelComponent - * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, - * angle, tick, style and events. Any of these props may be overridden by - * passing in props to the supplied component, or modified or ignored within - * the custom component itself. If an tickLabelComponent is not supplied, a new - * VictoryLabel will be created with props described above - * @default <VictoryLabel/> - */ - tickLabelComponent?: React.ReactElement<any>; - /** - * The tickFormat prop specifies how tick values should be expressed visually. - * tickFormat can be given as a function to be applied to every tickValue, or as - * an array of display values for each tickValue. - * @example d3.time.format("%Y"), (x) => x.toPrecision(2), ["first", "second", "third"] - */ + /** + * When true, this prop reduces the number of tick labels to fit the length of the axis. + * Labels are removed at approximately even intervals from the original array of labels. + * This feature only works well for labels that are approximately evenly spaced. + * @default false + */ + fixLabelOverlap?: boolean; + /** + * The gridComponent prop takes in an entire component which will be used + * to create grid lines. The new element created from the passed gridComponent + * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a gridComponent + * is not supplied, VictoryAxis will render its default GridLine component. + * @default <GridLine/> + */ + gridComponent?: React.ReactElement<any>; + /** + * If true, this value will flip the domain of a given axis. + */ + invertAxis?: boolean; + /** + * The label prop defines the label that will appear along the axis. This + * prop should be given as a value or an entire, HTML-complete label + * component. If a label component is given, it will be cloned. The new + * element's properties x, y, textAnchor, verticalAnchor, and transform + * will have defaults provided by the axis; styles filled out with + * defaults provided by the axis, and overrides from the label component. + * If a value is given, a new VictoryLabel will be created with props and + * styles from the axis. + */ + label?: any; + /** + * This value describes how far from the "edge" of its permitted area each axis + * will be set back in the x-direction. If this prop is not given, + * the offset is calculated based on font size, axis orientation, and label padding. + */ + offsetX?: number; + /** + * This value describes how far from the "edge" of its permitted area each axis + * will be set back in the y-direction. If this prop is not given, + * the offset is calculated based on font size, axis orientation, and label padding. + */ + offsetY?: number; + /** + * The orientation prop specifies the position and orientation of your axis. + */ + orientation?: "top" | "bottom" | "left" | "right"; + /** + * The style prop defines the style of the component. The style prop should be given as an object + * with styles defined for parent, axis, axisLabel, grid, ticks, and tickLabels. Any valid svg + * styles are supported, but width, height, and padding should be specified via props as they + * determine relative layout for components in VictoryChart. Functional styles may be defined for + * grid, tick, and tickLabel style properties, and they will be evaluated with each tick. + * + * note: When a component is rendered as a child of another Victory component, or within a custom + * <svg> element with standalone={false} parent styles will be applied to the enclosing <g> tag. + * Many styles that can be applied to a parent <svg> will not be expressed when applied to a <g>. + * + * note: custom angle and verticalAnchor properties may be included in labels styles. + */ + style?: { + parent?: React.CSSProperties; + axis?: React.CSSProperties; + axisLabel?: React.CSSProperties; + grid?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + ticks?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + tickLabels?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + }; + /** + * The tickComponent prop takes in an entire component which will be used + * to create tick lines. The new element created from the passed tickComponent + * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a tickComponent + * is not supplied, VictoryAxis will render its default Tick component. + * @default <Tick/> + */ + tickComponent?: React.ReactElement<any>; + /** + * The tickCount prop specifies approximately how many ticks should be drawn on the axis if + * tickValues are not explicitly provided. This value is calculated by d3 scale and + * prioritizes returning "nice" values and evenly spaced ticks over an exact number of ticks. + * If you need an exact number of ticks, please specify them via the tickValues prop. + * This prop must have a value greater than zero. + * @default 5 + */ + tickCount?: number; + /** + * The tickLabelComponent prop takes in an entire component which will be used + * to create the tick labels. The new element created from the passed tickLabelComponent + * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, + * angle, tick, style and events. Any of these props may be overridden by + * passing in props to the supplied component, or modified or ignored within + * the custom component itself. If an tickLabelComponent is not supplied, a new + * VictoryLabel will be created with props described above + * @default <VictoryLabel/> + */ + tickLabelComponent?: React.ReactElement<any>; + /** + * The tickFormat prop specifies how tick values should be expressed visually. + * tickFormat can be given as a function to be applied to every tickValue, or as + * an array of display values for each tickValue. + * @example d3.time.format("%Y"), (x) => x.toPrecision(2), ["first", "second", "third"] + */ tickFormat?: any[] | { (tick: any, index: number, ticks: any[]): string | number }; - /** - * The tickValues prop explicitly specifies which tick values to draw on the axis. - * @example ["apples", "bananas", "oranges"], [2, 4, 6, 8] - */ - tickValues?: any[]; - } + /** + * The tickValues prop explicitly specifies which tick values to draw on the axis. + * @example ["apples", "bananas", "oranges"], [2, 4, 6, 8] + */ + tickValues?: any[]; + } - /** - * VictoryAxis draws an SVG chart axis with React. - * Styles and data can be customized by passing in your own values as properties to the component. - * Data changes are animated with VictoryAnimation. - */ - export class VictoryAxis extends React.Component<VictoryAxisProps, any> {} + /** + * VictoryAxis draws an SVG chart axis with React. + * Styles and data can be customized by passing in your own values as properties to the component. + * Data changes are animated with VictoryAnimation. + */ + export class VictoryAxis extends React.Component<VictoryAxisProps, any> {} export interface VictoryBarProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { - /** - * The alignment prop specifies how bars should be aligned relative to their data points. - * This prop may be given as “start”, “middle” or “end”. When this prop is not specified, - * bars will have “middle” alignment relative to their data points. - */ - alignment?: "start" | "middle" | "end"; - /** - * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. - * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will - * be used to calculate a default width for each bar given the total number of bars in the data series - * and the overall width of the chart. - */ - barRatio?: number; - /** - * The barWidth prop is used to specify the width of each bar. This prop may be given as - * a number of pixels or as a function that returns a number. When this prop is given as - * a function, it will be evaluated with the arguments datum, and active. When this value - * is not given, a default value will be calculated based on the overall dimensions of - * the chart, and the number of bars. - */ - barWidth?: NumberOrCallback; - /** - * The cornerRadius prop specifies a radius to apply to each bar. - * If this prop is given as a single number, the radius will only be applied to the top of each bar. - * When this prop is given as a function, it will be evaluated with the arguments datum, and active. - */ + /** + * The alignment prop specifies how bars should be aligned relative to their data points. + * This prop may be given as “start”, “middle” or “end”. When this prop is not specified, + * bars will have “middle” alignment relative to their data points. + */ + alignment?: "start" | "middle" | "end"; + /** + * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. + * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will + * be used to calculate a default width for each bar given the total number of bars in the data series + * and the overall width of the chart. + */ + barRatio?: number; + /** + * The barWidth prop is used to specify the width of each bar. This prop may be given as + * a number of pixels or as a function that returns a number. When this prop is given as + * a function, it will be evaluated with the arguments datum, and active. When this value + * is not given, a default value will be calculated based on the overall dimensions of + * the chart, and the number of bars. + */ + barWidth?: NumberOrCallback; + /** + * The cornerRadius prop specifies a radius to apply to each bar. + * If this prop is given as a single number, the radius will only be applied to the top of each bar. + * When this prop is given as a function, it will be evaluated with the arguments datum, and active. + */ cornerRadius?: NumberOrCallback - | { + | { top?: number | (NumberOrCallback), topLeft?: number | (NumberOrCallback), topRight?: number | (NumberOrCallback), bottom?: number | (NumberOrCallback), bottomLeft?: number | (NumberOrCallback), bottomRight?: number | (NumberOrCallback) - }; - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryBar events. - * The eventKey may optionally be used to select a single element by index rather than an entire - * set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @example - * events={[ - * { - * target: "data", - * eventKey: "thisOne", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * eventKey: "theOtherOne", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * eventKey: "theOtherOne", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ + }; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryBar events. + * The eventKey may optionally be used to select a single element by index rather than an entire + * set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @example + * events={[ + * { + * target: "data", + * eventKey: "thisOne", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: "theOtherOne", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: "theOtherOne", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The style prop specifies styles for your VictoryBar. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. In addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; - } + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The style prop specifies styles for your VictoryBar. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. In addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + } - /** - * Draw SVG bar charts with React. VictoryBar is a composable component, so it doesn't include axes - * Check out VictoryChart for complete bar charts and more. - */ - export class VictoryBar extends React.Component<VictoryBarProps, any> {} + /** + * Draw SVG bar charts with React. VictoryBar is a composable component, so it doesn't include axes + * Check out VictoryChart for complete bar charts and more. + */ + export class VictoryBar extends React.Component<VictoryBarProps, any> {} export interface VictoryBoxPlotStyleInterface extends VictoryStyleInterface { - max?: React.CSSProperties; - maxLabels?: React.CSSProperties; - min?: React.CSSProperties; - minLabels?: React.CSSProperties; - median?: React.CSSProperties; - medianLabels?: React.CSSProperties; - q1?: React.CSSProperties; - q1Labels?: React.CSSProperties; - q3?: React.CSSProperties; - q3Labels?: React.CSSProperties; + max?: VictoryStyleObject; + maxLabels?: VictoryStyleObject; + min?: VictoryStyleObject; + minLabels?: VictoryStyleObject; + median?: VictoryStyleObject; + medianLabels?: VictoryStyleObject; + q1?: VictoryStyleObject; + q1Labels?: VictoryStyleObject; + q3?: VictoryStyleObject; + q3Labels?: VictoryStyleObject; } export interface VictoryBoxPlotProps @@ -1655,179 +1656,179 @@ declare module "victory" { export class VictoryChart extends React.Component<VictoryChartProps, any> {} export interface VictoryGroupProps extends VictoryCommonProps, VictoryMultiLabeableProps { - /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these values for x and y. When categories are not given as an object - * When this prop is set on a wrapper component, it will dictate the categories of - * its the children. If this prop is not set, any categories on child component - * or categorical data, will be merged to create a shared set of categories. - * @example ["dogs", "cats", "mice"] - */ - categories?: CategoryPropType; - /** - * The colorScale prop is an optional prop that defines the color scale the chart's bars - * will be created on. This prop should be given as an array of CSS colors, or as a string - * corresponding to one of the built in color scales. VictoryBar will automatically assign - * values from this color scale to the bars unless colors are explicitly provided in the - * `dataAttributes` prop. - */ - colorScale?: ColorScalePropType; - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @examples: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryGroup, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these values for x and y. When categories are not given as an object + * When this prop is set on a wrapper component, it will dictate the categories of + * its the children. If this prop is not set, any categories on child component + * or categorical data, will be merged to create a shared set of categories. + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The colorScale prop is an optional prop that defines the color scale the chart's bars + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryBar will automatically assign + * values from this color scale to the bars unless colors are explicitly provided in the + * `dataAttributes` prop. + */ + colorScale?: ColorScalePropType; + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @examples: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryGroup, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The offset prop determines the number of pixels each element in a group should - * be offset from its original position of the on the independent axis. In the - * case of groups of bars, this number should be equal to the width of the bar - * plus the desired spacing between bars. - */ - offset?: number; - /** - * The style prop specifies styles for your grouped chart. These styles will be - * applied to all grouped children - */ - style?: VictoryStyleInterface; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The offset prop determines the number of pixels each element in a group should + * be offset from its original position of the on the independent axis. In the + * case of groups of bars, this number should be equal to the width of the bar + * plus the desired spacing between bars. + */ + offset?: number; + /** + * The style prop specifies styles for your grouped chart. These styles will be + * applied to all grouped children + */ + style?: VictoryStyleInterface; } export class VictoryGroup extends React.Component<VictoryGroupProps, any> {} export interface VictoryLineProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryLine events. - * Since VictoryLine only renders a single element, the eventKey property is not used. - * The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a line), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {stroke: "orange"})}; - * } - * }, { - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryLine events. + * Since VictoryLine only renders a single element, the eventKey property is not used. + * The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a line), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {stroke: "orange"})}; + * } + * }, { + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; - /** - * The interpolation prop determines how data points should be connected - * when plotting a line - */ - interpolation?: InterpolationPropType; - /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - */ - samples?: number; - /** - * The labels prop defines the labels that will appear above each point. - * This prop should be given as an array or as a function of data. - */ + /** + * The interpolation prop determines how data points should be connected + * when plotting a line + */ + interpolation?: InterpolationPropType; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + */ + samples?: number; + /** + * The labels prop defines the labels that will appear above each point. + * This prop should be given as an array or as a function of data. + */ labels?: string[]|number[]|Function; - /** - * Use the sortKey prop to indicate how data should be sorted. This prop - * is given directly to the lodash sortBy function to be executed on the - * final dataset. - */ + /** + * Use the sortKey prop to indicate how data should be sorted. This prop + * is given directly to the lodash sortBy function to be executed on the + * final dataset. + */ sortKey?: string|string[]|Function; - /** - * The style prop specifies styles for your VictoryLine. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. in addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @examples{data: {stroke: "red"}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; + /** + * The style prop specifies styles for your VictoryLine. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. in addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @examples{data: {stroke: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; } /** @@ -1837,152 +1838,152 @@ declare module "victory" { export class VictoryLine extends React.Component<VictoryLineProps, any> {} export interface VictoryLegendProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { - /** - * The colorScale prop defines a color scale to be applied to each data - * symbol in VictoryLegend. This prop should be given as an array of CSS - * colors, or as a string corresponding to one of the built in color - * scales: "grayscale", "qualitative", "heatmap", "warm", "cool", "red", - * "green", "blue". VictoryLegend will assign a color to each symbol by - * index, unless they are explicitly specified in the data object. - * Colors will repeat when there are more symbols than colors in the - * provided colorScale. - */ - colorScale?: ColorScalePropType; - /** - * The style prop defines the style of the VictoryLegend component. - * The style prop should be given as an object with styles defined for data, labels and - * parent. Any valid svg styles are supported, but width, height, and - * padding should be specified via props as they determine relative - * layout for components in VictoryLegend. - */ - style?: VictoryStyleInterface; - /** - * The containerComponent prop takes a component instance which will be - * used to create a container element for standalone legends. The new - * element created from the passed containerComponent will be provided - * with the following props: height, width, children (the legend itself) - * and style. If a containerComponent is not provided, the default - * VictoryContainer component will be used. VictoryContainer supports - * title and desc props, which are intended to add accessibility to - * Victory components. The more descriptive these props are, the more - * accessible your data will be for people using screen readers. These - * props may be set by passing them directly to the supplied component. - * By default, VictoryContainer renders a responsive svg using the - * viewBox attribute. To render a static container, set - * responsive={false} directly on the instance of VictoryContainer - * supplied via the containerComponent prop. VictoryContainer also - * renders a Portal element that may be used in conjunction with - * VictoryPortal to force components to render above other children. - * @default <VictoryContainer/> - */ - containerComponent?: React.ReactElement<any>; - /** - * Specify data via the data prop. VictoryLegend expects data as an - * array of objects with name (required), symbol, and labels properties. - * The data prop must be given as an array. - */ - data?: Array<{ - name?: string; - symbol?: { - fill?: string; - type?: string; - }; - }>; - /** - * The itemsPerRow prop determines how many items to render in each row - * of a horizontal legend, or in each column of a vertical legend. This - * prop should be given as an integer. When this prop is not given, - * legend items will be rendered in a single row or column. - */ - itemsPerRow?: number; - /** - * The dataComponent prop takes a component instance which will be - * responsible for rendering a data element used to associate a symbol - * or color with each data series. The new element created from the - * passed dataComponent will be provided with the following properties - * calculated by VictoryLegend: x, y, size, style, and symbol. Any of - * these props may be overridden by passing in props to the supplied - * component, or modified or ignored within the custom component itself. - * If a dataComponent is not provided, VictoryLegend will use its - * default Point component. - */ - dataComponent?: React.ReactElement<any>; - /** - * The groupComponent prop takes an entire component which will be used to - * create group elements for use within container elements. This prop defaults - * to a <g> tag on web, and a react-native-svg <G> tag on mobile - * @default <g/> - */ - groupComponent?: React.ReactElement<any>; - /** - * The gutter prop defines the number of pixels between legend rows or - * columns, depending on orientation. When orientation is horizontal, - * gutters are between columns. When orientation is vertical, gutters - * are the space between rows. - */ - gutter?: number; - /** - * The labelComponent prop takes a component instance which will be used - * to render each legend label. The new element created from the passed - * labelComponent will be supplied with the following properties: x, y, - * style, and text. Any of these props may be overridden by passing in - * props to the supplied component, or modified or ignored within the - * custom component itself. If labelComponent is omitted, a new - * VictoryLabel will be created with the props described above. - */ - labelComponent?: React.ReactElement<any>; - /** - * The orientation prop takes a string that defines whether legend data - * are displayed in a row or column. When orientation is "horizontal", - * legend items will be displayed in a single row. When orientation is - * "vertical", legend items will be displayed in a single column. Line - * and text-wrapping is not currently supported, so "vertical" - * orientation is both the default setting and recommended for - * displaying many series of data. - * @default 'vertical' - */ + /** + * The colorScale prop defines a color scale to be applied to each data + * symbol in VictoryLegend. This prop should be given as an array of CSS + * colors, or as a string corresponding to one of the built in color + * scales: "grayscale", "qualitative", "heatmap", "warm", "cool", "red", + * "green", "blue". VictoryLegend will assign a color to each symbol by + * index, unless they are explicitly specified in the data object. + * Colors will repeat when there are more symbols than colors in the + * provided colorScale. + */ + colorScale?: ColorScalePropType; + /** + * The style prop defines the style of the VictoryLegend component. + * The style prop should be given as an object with styles defined for data, labels and + * parent. Any valid svg styles are supported, but width, height, and + * padding should be specified via props as they determine relative + * layout for components in VictoryLegend. + */ + style?: VictoryStyleInterface; + /** + * The containerComponent prop takes a component instance which will be + * used to create a container element for standalone legends. The new + * element created from the passed containerComponent will be provided + * with the following props: height, width, children (the legend itself) + * and style. If a containerComponent is not provided, the default + * VictoryContainer component will be used. VictoryContainer supports + * title and desc props, which are intended to add accessibility to + * Victory components. The more descriptive these props are, the more + * accessible your data will be for people using screen readers. These + * props may be set by passing them directly to the supplied component. + * By default, VictoryContainer renders a responsive svg using the + * viewBox attribute. To render a static container, set + * responsive={false} directly on the instance of VictoryContainer + * supplied via the containerComponent prop. VictoryContainer also + * renders a Portal element that may be used in conjunction with + * VictoryPortal to force components to render above other children. + * @default <VictoryContainer/> + */ + containerComponent?: React.ReactElement<any>; + /** + * Specify data via the data prop. VictoryLegend expects data as an + * array of objects with name (required), symbol, and labels properties. + * The data prop must be given as an array. + */ + data?: Array<{ + name?: string; + symbol?: { + fill?: string; + type?: string; + }; + }>; + /** + * The itemsPerRow prop determines how many items to render in each row + * of a horizontal legend, or in each column of a vertical legend. This + * prop should be given as an integer. When this prop is not given, + * legend items will be rendered in a single row or column. + */ + itemsPerRow?: number; + /** + * The dataComponent prop takes a component instance which will be + * responsible for rendering a data element used to associate a symbol + * or color with each data series. The new element created from the + * passed dataComponent will be provided with the following properties + * calculated by VictoryLegend: x, y, size, style, and symbol. Any of + * these props may be overridden by passing in props to the supplied + * component, or modified or ignored within the custom component itself. + * If a dataComponent is not provided, VictoryLegend will use its + * default Point component. + */ + dataComponent?: React.ReactElement<any>; + /** + * The groupComponent prop takes an entire component which will be used to + * create group elements for use within container elements. This prop defaults + * to a <g> tag on web, and a react-native-svg <G> tag on mobile + * @default <g/> + */ + groupComponent?: React.ReactElement<any>; + /** + * The gutter prop defines the number of pixels between legend rows or + * columns, depending on orientation. When orientation is horizontal, + * gutters are between columns. When orientation is vertical, gutters + * are the space between rows. + */ + gutter?: number; + /** + * The labelComponent prop takes a component instance which will be used + * to render each legend label. The new element created from the passed + * labelComponent will be supplied with the following properties: x, y, + * style, and text. Any of these props may be overridden by passing in + * props to the supplied component, or modified or ignored within the + * custom component itself. If labelComponent is omitted, a new + * VictoryLabel will be created with the props described above. + */ + labelComponent?: React.ReactElement<any>; + /** + * The orientation prop takes a string that defines whether legend data + * are displayed in a row or column. When orientation is "horizontal", + * legend items will be displayed in a single row. When orientation is + * "vertical", legend items will be displayed in a single column. Line + * and text-wrapping is not currently supported, so "vertical" + * orientation is both the default setting and recommended for + * displaying many series of data. + * @default 'vertical' + */ orientation?: 'horizontal'|'vertical'; - /** - * The padding prop specifies the amount of padding in pixels between - * the edge of the legend and any rendered child components. This prop - * can be given as a number or as an object with padding specified for - * top, bottom, left and right. As with width and height, the absolute - * padding will depend on whether the component is rendered in a - * responsive container. When a component is nested within - * VictoryLegend, setting padding on the child component will have no - * effect. - */ + /** + * The padding prop specifies the amount of padding in pixels between + * the edge of the legend and any rendered child components. This prop + * can be given as a number or as an object with padding specified for + * top, bottom, left and right. As with width and height, the absolute + * padding will depend on whether the component is rendered in a + * responsive container. When a component is nested within + * VictoryLegend, setting padding on the child component will have no + * effect. + */ padding?: number | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - /** - * The standalone props specifies whether the component should be - * rendered in an independent <svg> element or in a <g> tag. This prop - * defaults to true, and renders an svg. - */ - standalone?: boolean; - /** - * The symbolSpacer prop defines the number of pixels between data - * components and label components. - */ - symbolSpacer?: number; - /** - * The width and height props define the width and height of the legend. - * These props may be given as positive numbers or functions of data. If - * these props are not set, width and height will be determined based on - * an approximate text size calculated from the text and style props - * provided to VictoryLegend. - */ - width?: number; - height?: number; - /** - * The x and y props define the base position of the legend element. - */ - x?: number; - y?: number; + top?: number; + bottom?: number; + left?: number; + right?: number; + }; + /** + * The standalone props specifies whether the component should be + * rendered in an independent <svg> element or in a <g> tag. This prop + * defaults to true, and renders an svg. + */ + standalone?: boolean; + /** + * The symbolSpacer prop defines the number of pixels between data + * components and label components. + */ + symbolSpacer?: number; + /** + * The width and height props define the width and height of the legend. + * These props may be given as positive numbers or functions of data. If + * these props are not set, width and height will be determined based on + * an approximate text size calculated from the text and style props + * provided to VictoryLegend. + */ + width?: number; + height?: number; + /** + * The x and y props define the base position of the legend element. + */ + x?: number; + y?: number; } /** @@ -1993,84 +1994,84 @@ declare module "victory" { type ScatterSymbolType = "circle" | "diamond" | "plus" | "square" | "star" | "triangleDown" | "triangleUp"; export interface VictoryScatterProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { - /** - * The bubbleProperty prop indicates which property of the data object should be used - * to scale data points in a bubble chart - */ - bubbleProperty?: string; - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryScatter - * events. The eventKey may optionally be used to select a single element by index rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * eventKey: "thisOne", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * eventKey: "theOtherOne", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * eventKey: "theOtherOne", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ + /** + * The bubbleProperty prop indicates which property of the data object should be used + * to scale data points in a bubble chart + */ + bubbleProperty?: string; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryScatter + * events. The eventKey may optionally be used to select a single element by index rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventKey: "thisOne", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: "theOtherOne", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: "theOtherOne", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The maxBubbleSize prop sets an upper limit for scaling data points in a bubble chart - */ - maxBubbleSize?: number; - /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - */ - samples?: number; - /** - * The size prop determines how to scale each data point - */ - size?: number | { (data: any): number }; - /** - * The style prop specifies styles for your VictoryScatter. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. In addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @example {data: {fill: "red"}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; - /** - * The symbol prop determines which symbol should be drawn to represent data points. - */ - symbol?: ScatterSymbolType | { (data: any): ScatterSymbolType }; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The maxBubbleSize prop sets an upper limit for scaling data points in a bubble chart + */ + maxBubbleSize?: number; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + */ + samples?: number; + /** + * The size prop determines how to scale each data point + */ + size?: number | { (data: any): number }; + /** + * The style prop specifies styles for your VictoryScatter. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. In addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @example {data: {fill: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + /** + * The symbol prop determines which symbol should be drawn to represent data points. + */ + symbol?: ScatterSymbolType | { (data: any): ScatterSymbolType }; } /** @@ -2080,248 +2081,248 @@ declare module "victory" { export class VictoryScatter extends React.Component<VictoryScatterProps, any> {} export interface VictoryStackProps extends VictoryCommonProps, VictoryMultiLabeableProps { - /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these values for x and y. When categories are not given as an object - * When this prop is set on a wrapper component, it will dictate the categories of - * its the children. If this prop is not set, any categories on child component - * or catigorical data, will be merged to create a shared set of categories. - * @example ["dogs", "cats", "mice"] - */ - categories?: CategoryPropType; - /** - * The colorScale prop is an optional prop that defines the color scale the chart's bars - * will be created on. This prop should be given as an array of CSS colors, or as a string - * corresponding to one of the built in color scales. VictoryBar will automatically assign - * values from this color scale to the bars unless colors are explicitly provided in the - * `dataAttributes` prop. - */ - colorScale?: ColorScalePropType; - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryStack, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these values for x and y. When categories are not given as an object + * When this prop is set on a wrapper component, it will dictate the categories of + * its the children. If this prop is not set, any categories on child component + * or catigorical data, will be merged to create a shared set of categories. + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The colorScale prop is an optional prop that defines the color scale the chart's bars + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryBar will automatically assign + * values from this color scale to the bars unless colors are explicitly provided in the + * `dataAttributes` prop. + */ + colorScale?: ColorScalePropType; + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryStack, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The style prop specifies styles for your grouped chart. These styles will be - * applied to all grouped children - */ - style?: VictoryStyleInterface; - /** - * The xOffset prop is used for grouping stacks of bars. This prop will be set - * by the VictoryGroup component wrapper, or can be set manually. - */ - xOffset?: number; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The style prop specifies styles for your grouped chart. These styles will be + * applied to all grouped children + */ + style?: VictoryStyleInterface; + /** + * The xOffset prop is used for grouping stacks of bars. This prop will be set + * by the VictoryGroup component wrapper, or can be set manually. + */ + xOffset?: number; } export class VictoryStack extends React.Component<VictoryStackProps, any> {} export interface VictoryPieProps extends VictoryCommonProps, VictoryMultiLabeableProps { - /** - * The colorScale prop is an optional prop that defines the color scale the pie - * will be created on. This prop should be given as an array of CSS colors, or as a string - * corresponding to one of the built in color scales. VictoryPie will automatically assign - * values from this color scale to the pie slices unless colors are explicitly provided in the - * data object - */ - colorScale?: ColorScalePropType; - /** - * The data prop specifies the data to be plotted, - * where data X-value is the slice label (string or number), - * and Y-value is the corresponding number value represented by the slice - * Data should be in the form of an array of data points. - * Each data point may be any format you wish (depending on the `x` and `y` accessor props), - * but by default, an object with x and y properties is expected. - * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], - * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] - */ - data?: any[]; - /** - * The dataComponent prop takes an entire, HTML-complete data component which will be used to - * create slices for each datum in the pie chart. The new element created from the passed - * dataComponent will have the property datum set by the pie chart for the point it renders; - * properties style and pathFunction calculated by VictoryPie; an index property set - * corresponding to the location of the datum in the data provided to the pie; events bound to - * the VictoryPie; and the d3 compatible slice object. - * If a dataComponent is not provided, VictoryPie's Slice component will be used. - */ - dataComponent?: React.ReactElement<any>; - /** - * The labelRadius prop defines the radius of the arc that will be used for positioning each slice label. - * If this prop is not set, the label radius will default to the radius of the pie + label padding. - */ - labelRadius?: number; - /** - * The overall end angle of the pie in degrees. This prop is used in conjunction with - * startAngle to create a pie that spans only a segment of a circle. - */ - endAngle?: number; - /** - * The event prop takes an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryPie - * events. The eventKey may optionally be used to select a single element by index rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * eventKey: 1, - * eventHandlers: { - * onClick: () => { - * return [ - * { - * eventKey: 2, - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * eventKey: 2, - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ + /** + * The colorScale prop is an optional prop that defines the color scale the pie + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryPie will automatically assign + * values from this color scale to the pie slices unless colors are explicitly provided in the + * data object + */ + colorScale?: ColorScalePropType; + /** + * The data prop specifies the data to be plotted, + * where data X-value is the slice label (string or number), + * and Y-value is the corresponding number value represented by the slice + * Data should be in the form of an array of data points. + * Each data point may be any format you wish (depending on the `x` and `y` accessor props), + * but by default, an object with x and y properties is expected. + * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], + * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] + */ + data?: any[]; + /** + * The dataComponent prop takes an entire, HTML-complete data component which will be used to + * create slices for each datum in the pie chart. The new element created from the passed + * dataComponent will have the property datum set by the pie chart for the point it renders; + * properties style and pathFunction calculated by VictoryPie; an index property set + * corresponding to the location of the datum in the data provided to the pie; events bound to + * the VictoryPie; and the d3 compatible slice object. + * If a dataComponent is not provided, VictoryPie's Slice component will be used. + */ + dataComponent?: React.ReactElement<any>; + /** + * The labelRadius prop defines the radius of the arc that will be used for positioning each slice label. + * If this prop is not set, the label radius will default to the radius of the pie + label padding. + */ + labelRadius?: number; + /** + * The overall end angle of the pie in degrees. This prop is used in conjunction with + * startAngle to create a pie that spans only a segment of a circle. + */ + endAngle?: number; + /** + * The event prop takes an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryPie + * events. The eventKey may optionally be used to select a single element by index rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventKey: 1, + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: 2, + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: 2, + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * Specifies the radius of the chart. If this property is not provided it is computed - * from width, height, and padding props - * - */ - radius?: number; - /** - * When creating a donut chart, this prop determines the number of pixels between - * the center of the chart and the inner edge of a donut. When this prop is set to zero - * a regular pie chart is rendered. - */ - innerRadius?: number; - /** - * Set the cornerRadius for every dataComponent (Slice by default) within VictoryPie - */ - cornerRadius?: number; - /** - * The padAngle prop determines the amount of separation between adjacent data slices - * in number of degrees - */ - padAngle?: number; - /** - * The overall start angle of the pie in degrees. This prop is used in conjunction with - * endAngle to create a pie that spans only a segment of a circle. - */ - startAngle?: number; - /** - * The style prop specifies styles for your pie. VictoryPie relies on Radium, - * so valid Radium style objects should work for this prop. Height, width, and - * padding should be specified via the height, width, and padding props. - * @example {data: {stroke: "black"}, label: {fontSize: 10}} - */ - style?: VictoryStyleInterface; - /** - * The x prop specifies how to access the X value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) - */ - x?: DataGetterPropType; - /** - * The y prop specifies how to access the Y value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) - */ - y?: DataGetterPropType; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * Specifies the radius of the chart. If this property is not provided it is computed + * from width, height, and padding props + * + */ + radius?: number; + /** + * When creating a donut chart, this prop determines the number of pixels between + * the center of the chart and the inner edge of a donut. When this prop is set to zero + * a regular pie chart is rendered. + */ + innerRadius?: number; + /** + * Set the cornerRadius for every dataComponent (Slice by default) within VictoryPie + */ + cornerRadius?: number; + /** + * The padAngle prop determines the amount of separation between adjacent data slices + * in number of degrees + */ + padAngle?: number; + /** + * The overall start angle of the pie in degrees. This prop is used in conjunction with + * endAngle to create a pie that spans only a segment of a circle. + */ + startAngle?: number; + /** + * The style prop specifies styles for your pie. VictoryPie relies on Radium, + * so valid Radium style objects should work for this prop. Height, width, and + * padding should be specified via the height, width, and padding props. + * @example {data: {stroke: "black"}, label: {fontSize: 10}} + */ + style?: VictoryStyleInterface; + /** + * The x prop specifies how to access the X value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) + */ + x?: DataGetterPropType; + /** + * The y prop specifies how to access the Y value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) + */ + y?: DataGetterPropType; } /** @@ -2330,4 +2331,4 @@ declare module "victory" { * Data changes are animated with VictoryAnimation. */ export class VictoryPie extends React.Component<VictoryPieProps, any> {} - } +} From bd167704d48dfc551d2eb367a727ba0b5ff52879 Mon Sep 17 00:00:00 2001 From: James Lismore <jlismore@gmail.com> Date: Wed, 6 Feb 2019 11:29:40 -0500 Subject: [PATCH 094/197] Revert prettier whitespace changes --- types/victory/index.d.ts | 3013 +++++++++++++++++++------------------- 1 file changed, 1507 insertions(+), 1506 deletions(-) diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index 43bf4378e6..c3468151ba 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -12,33 +12,33 @@ declare module "victory" { import * as React from "react"; - + /** * Single animation object to interpolate */ - export type AnimationStyle = { [key: string ]: string | number }; - + export type AnimationStyle = { [key: string ]: string | number }; + /** * Animation styles to interpolate */ - + export type AnimationData = AnimationStyle | AnimationStyle[]; - + export type AnimationEasing = - "back" | "backIn" | "backOut" | "backInOut" | "bounce" | "bounceIn" | "bounceOut" | - "bounceInOut" | "circle" | "circleIn" | "circleOut" | "circleInOut" | "linear" | - "linearIn" | "linearOut" | "linearInOut" | "cubic" | "cubicIn" | "cubicOut" | - "cubicInOut" | "elastic" | "elasticIn" | "elasticOut" | "elasticInOut" | "exp" | - "expIn" | "expOut" | "expInOut" | "poly" | "polyIn" | "polyOut" | "polyInOut" | - "quad" | "quadIn" | "quadOut" | "quadInOut" | "sin" | "sinIn" | "sinOut" | "sinInOut"; - + "back" | "backIn" | "backOut" | "backInOut" | "bounce" | "bounceIn" | "bounceOut" | + "bounceInOut" | "circle" | "circleIn" | "circleOut" | "circleInOut" | "linear" | + "linearIn" | "linearOut" | "linearInOut" | "cubic" | "cubicIn" | "cubicOut" | + "cubicInOut" | "elastic" | "elasticIn" | "elasticOut" | "elasticInOut" | "exp" | + "expIn" | "expOut" | "expInOut" | "poly" | "polyIn" | "polyOut" | "polyInOut" | + "quad" | "quadIn" | "quadOut" | "quadInOut" | "sin" | "sinIn" | "sinOut" | "sinInOut"; + // Many victory components accept string or number or callback which returns string or number type StringOrNumberOrCallback = - | string - | number - | ((datum: any, active: boolean) => string | number); + | string + | number + | ((datum: any, active: boolean) => string | number); type NumberOrCallback = ((datum: any, active: boolean) => number) | number; - + type VictoryStyleObject = { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; /** * Style interface used in components/themeing @@ -48,987 +48,987 @@ declare module "victory" { data?: VictoryStyleObject; labels?: VictoryStyleObject; } - + export interface VictoryAnimationProps { - /** - * The child of should be a function that takes an object of tweened values and returns a component to render. - * @param style - */ - children?: (style: AnimationStyle) => React.ReactElement<any>; - /** - * The number of milliseconds the animation should take to complete. - * @default 1000 - */ - duration?: number; - /** - * The easing prop specifies an easing function name to use for tweening. - * @default "quadInOut" - */ - easing?: AnimationEasing; - /** - * The delay prop specifies a delay in milliseconds before the animation begins. - * If multiple values are in the animation queue, it is the delay between each animation. - * @default 0 - */ - delay?: number; - /** - * The onEnd prop specifies a function to run when the animation ends. If multiple animations are in the queue, it is called after the last animation. - */ - onEnd?: () => void; - /** - * The data prop specifies the latest set of values to tween to. - * When this prop changes, VictoryAnimation will begin animating from the current value to the new value. - * When given an array of values, VictoryAnimation will use it as an animation queue. - * @default {} - */ - data?: AnimationData; + /** + * The child of should be a function that takes an object of tweened values and returns a component to render. + * @param style + */ + children?: (style: AnimationStyle) => React.ReactElement<any>; + /** + * The number of milliseconds the animation should take to complete. + * @default 1000 + */ + duration?: number; + /** + * The easing prop specifies an easing function name to use for tweening. + * @default "quadInOut" + */ + easing?: AnimationEasing; + /** + * The delay prop specifies a delay in milliseconds before the animation begins. + * If multiple values are in the animation queue, it is the delay between each animation. + * @default 0 + */ + delay?: number; + /** + * The onEnd prop specifies a function to run when the animation ends. If multiple animations are in the queue, it is called after the last animation. + */ + onEnd?: () => void; + /** + * The data prop specifies the latest set of values to tween to. + * When this prop changes, VictoryAnimation will begin animating from the current value to the new value. + * When given an array of values, VictoryAnimation will use it as an animation queue. + * @default {} + */ + data?: AnimationData; } - + /** * VictoryAnimation animates prop changes for any React component. * Just use a child function inside VictoryAnimation that accepts an object of tweened values and returns a component to render. */ - export class VictoryAnimation extends React.Component<VictoryAnimationProps, any> {} - + export class VictoryAnimation extends React.Component<VictoryAnimationProps, any> {} + /** * Text anchor type */ type TextAnchorType = "start" | "middle" | "end" | "inherit"; - + /** * Vertical anchor type */ type VerticalAnchorType = "start" | "middle" | "end"; - + export interface VictoryLabelProps { - /** - * Specifies the angle to rotate the text by. - */ - angle?: string | number; - /** - * The capHeight prop defines a text metric for the font being used: the expected height of capital letters. - * This is necessary because of SVG, which (a) positions the *bottom* of the text at `y`, and (b) has no notion of line height. - * The value should ideally use the same units as `lineHeight` and `dy`, preferably ems. If given a unitless number, it is assumed to be ems. - * @default "0.71em" - */ - capHeight?: StringOrNumberOrCallback; - /** - * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine child text - */ - datum?: {}; - /** - * Labels that apply to an entire data series will recieve the entire series as `data` instead of an individual datum prop. - */ - data?: any[]; - /** - * The events prop attaches arbitrary event handlers to the label component. - * Event handlers are currently only called with their corresponding events. - */ - events?: React.DOMAttributes<any>; - /** - * The children of this component define the content of the label. - * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. - */ - children?: StringOrNumberOrCallback; - /** - * The labelPlacement prop is used to specify the placement of labels relative to the data point they represent. - * This prop may be given as “vertical”, “parallel” or “perpendicular”. This props is particularly useful in polar - * charts, where it may be desireable to position a label either parallel or perpendicular to its corresponding angle. - * When this prop is not set, perpendicular label placement will be used for polar charts, and vertical label - * placement will be used for cartesian charts. - */ - labelPlacement?: "parallel" | "perpendicular" | "vertical"; - /** - * The lineHeight prop defines how much space a single line of text should take up. - * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, - * but the result is similar: a roughly equal amount of extra space is distributed above and below the line of text. - * The value should ideally use the same units as `capHeight` and `dy`, preferably ems. - * If given a unitless number, it is assumed to be ems. - * @default 1 - */ - lineHeight?: StringOrNumberOrCallback; - /** - * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. - * **This prop should not be set manually.** - */ - origin?: { x: number, y: number }; - /** - * Victory components can pass a boolean polar prop to specify whether a label is part of a polar chart. - * **This prop should not be set manually.** - */ - polar?: boolean; - /** - * The renderInPortal prop specifies whether VictoryLabel should render text in place or within a VictoryPortal. - * Setting renderInPortal to true is equivalent to wrapping VictoryLabel in a VictoryPortal. This prop is false by default. - */ - renderInPortal?: boolean; - /** - * The style prop applies CSS properties to the rendered `<text>` element. - */ - style?: React.CSSProperties; - /** - * The text prop defines the text VictoryLabel will render. The text prop may be given as a string, number, a function of datum, - * or an array of any of these. Strings may include newline characters, which VictoryLabel will split into separate - * <tspan/> elements. When text is given as an array, separate <tspan/> elements will be created for each element in the array. - */ - text?: string[] | StringOrNumberOrCallback; - /** - * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. - */ - textAnchor?: TextAnchorType | { (): TextAnchorType }; - /** - * The verticalAnchor prop defines how the text is vertically positioned relative to the given `x` and `y` coordinates. - */ - verticalAnchor?: VerticalAnchorType | { (): VerticalAnchorType }; - /** - * The transform prop applies a transform to the rendered `<text>` element. - * In addition to being a string, it can be an object containing transform definitions for easier authoring. - */ - transform?: string | {} | { (): string | {} }; - /** - * The x prop defines the x coordinate to use as a basis for horizontal positioning. - */ - x?: number; - /** - * The y prop defines the y coordinate to use as a basis for vertical positioning. - */ - y?: number; - /** - * The dx prop defines a horizontal shift from the `x` coordinate. - */ - dx?: StringOrNumberOrCallback; - /** - * The dy prop defines a vertical shift from the `y` coordinate. - * Since this component already accounts for `capHeight`, `lineHeight`, and `verticalAnchor`, this will usually not be necessary. - */ - dy?: StringOrNumberOrCallback; + /** + * Specifies the angle to rotate the text by. + */ + angle?: string | number; + /** + * The capHeight prop defines a text metric for the font being used: the expected height of capital letters. + * This is necessary because of SVG, which (a) positions the *bottom* of the text at `y`, and (b) has no notion of line height. + * The value should ideally use the same units as `lineHeight` and `dy`, preferably ems. If given a unitless number, it is assumed to be ems. + * @default "0.71em" + */ + capHeight?: StringOrNumberOrCallback; + /** + * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine child text + */ + datum?: {}; + /** + * Labels that apply to an entire data series will recieve the entire series as `data` instead of an individual datum prop. + */ + data?: any[]; + /** + * The events prop attaches arbitrary event handlers to the label component. + * Event handlers are currently only called with their corresponding events. + */ + events?: React.DOMAttributes<any>; + /** + * The children of this component define the content of the label. + * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. + */ + children?: StringOrNumberOrCallback; + /** + * The labelPlacement prop is used to specify the placement of labels relative to the data point they represent. + * This prop may be given as “vertical”, “parallel” or “perpendicular”. This props is particularly useful in polar + * charts, where it may be desireable to position a label either parallel or perpendicular to its corresponding angle. + * When this prop is not set, perpendicular label placement will be used for polar charts, and vertical label + * placement will be used for cartesian charts. + */ + labelPlacement?: "parallel" | "perpendicular" | "vertical"; + /** + * The lineHeight prop defines how much space a single line of text should take up. + * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, + * but the result is similar: a roughly equal amount of extra space is distributed above and below the line of text. + * The value should ideally use the same units as `capHeight` and `dy`, preferably ems. + * If given a unitless number, it is assumed to be ems. + * @default 1 + */ + lineHeight?: StringOrNumberOrCallback; + /** + * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. + * **This prop should not be set manually.** + */ + origin?: { x: number, y: number }; + /** + * Victory components can pass a boolean polar prop to specify whether a label is part of a polar chart. + * **This prop should not be set manually.** + */ + polar?: boolean; + /** + * The renderInPortal prop specifies whether VictoryLabel should render text in place or within a VictoryPortal. + * Setting renderInPortal to true is equivalent to wrapping VictoryLabel in a VictoryPortal. This prop is false by default. + */ + renderInPortal?: boolean; + /** + * The style prop applies CSS properties to the rendered `<text>` element. + */ + style?: React.CSSProperties; + /** + * The text prop defines the text VictoryLabel will render. The text prop may be given as a string, number, a function of datum, + * or an array of any of these. Strings may include newline characters, which VictoryLabel will split into separate + * <tspan/> elements. When text is given as an array, separate <tspan/> elements will be created for each element in the array. + */ + text?: string[] | StringOrNumberOrCallback; + /** + * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. + */ + textAnchor?: TextAnchorType | { (): TextAnchorType }; + /** + * The verticalAnchor prop defines how the text is vertically positioned relative to the given `x` and `y` coordinates. + */ + verticalAnchor?: VerticalAnchorType | { (): VerticalAnchorType }; + /** + * The transform prop applies a transform to the rendered `<text>` element. + * In addition to being a string, it can be an object containing transform definitions for easier authoring. + */ + transform?: string | {} | { (): string | {} }; + /** + * The x prop defines the x coordinate to use as a basis for horizontal positioning. + */ + x?: number; + /** + * The y prop defines the y coordinate to use as a basis for vertical positioning. + */ + y?: number; + /** + * The dx prop defines a horizontal shift from the `x` coordinate. + */ + dx?: StringOrNumberOrCallback; + /** + * The dy prop defines a vertical shift from the `y` coordinate. + * Since this component already accounts for `capHeight`, `lineHeight`, and `verticalAnchor`, this will usually not be necessary. + */ + dy?: StringOrNumberOrCallback; } - + /** * VictoryLabel is a text component that provides several enhancements over SVG’s <text> element. */ export class VictoryLabel extends React.Component<VictoryLabelProps, any> {} - + export interface VictoryContainerProps { - /** - * The responsive prop specifies whether the rendered container should be a responsive container - * with a viewBox attribute, or a static container with absolute width and height. - * @default true - */ - responsive?: boolean; - /** - * The style prop specifies styles for your VictoryContainer. Any valid inline style properties - * will be applied. Height and width should be specified via the height - * and width props, as they are used to calculate the alignment of - * components within the container. Styles from the child component will - * also be passed, if any exist. - * @examples {border: 1px solid red} - */ - style?: React.CSSProperties; - /** - * The height props specifies the height the svg viewBox of the container. - * This value should be given as a number of pixels. If no height prop - * is given, the height prop from the child component passed will be used. - */ - height?: number; - /** - * The width props specifies the width of the svg viewBox of the container - * This value should be given as a number of pixels. If no width prop - * is given, the width prop from the child component passed will be used. - */ - width?: number; - /** - * The events prop attaches arbitrary event handlers to the container component. - * Event handlers passed from other Victory components are called with their - * corresponding events as well as scale, style, width, height, and data when - * applicable. Use the invert method to convert event coordinate information to - * data. `scale.x.invert(evt.offsetX)`. - * @examples {{ onClick: (evt) => alert(`x: ${evt.clientX}, y: ${evt.clientY}`)}} - */ - events?: React.DOMAttributes<any>; - /** - * The title prop specifies the title to be applied to the SVG to assist - * accessibility for screen readers. The more descriptive this title is, the more - * useful it will be. If no title prop is passed, it will default to Victory Chart. - * @example "Popularity of Dog Breeds by Percentage" - * @default "Victory Chart" - */ - title?: string; - /** - * The desc prop specifies the description of the chart/SVG to assist with - * accessibility for screen readers. The more info about the chart provided in - * the description, the more usable it will be for people using screen readers. - * This prop defaults to an empty string. - * @example "Golden retreivers make up 30%, Labs make up 25%, and other dog breeds are - * not represented above 5% each." - * @default "" - */ - desc?: string; + /** + * The responsive prop specifies whether the rendered container should be a responsive container + * with a viewBox attribute, or a static container with absolute width and height. + * @default true + */ + responsive?: boolean; + /** + * The style prop specifies styles for your VictoryContainer. Any valid inline style properties + * will be applied. Height and width should be specified via the height + * and width props, as they are used to calculate the alignment of + * components within the container. Styles from the child component will + * also be passed, if any exist. + * @examples {border: 1px solid red} + */ + style?: React.CSSProperties; + /** + * The height props specifies the height the svg viewBox of the container. + * This value should be given as a number of pixels. If no height prop + * is given, the height prop from the child component passed will be used. + */ + height?: number; + /** + * The width props specifies the width of the svg viewBox of the container + * This value should be given as a number of pixels. If no width prop + * is given, the width prop from the child component passed will be used. + */ + width?: number; + /** + * The events prop attaches arbitrary event handlers to the container component. + * Event handlers passed from other Victory components are called with their + * corresponding events as well as scale, style, width, height, and data when + * applicable. Use the invert method to convert event coordinate information to + * data. `scale.x.invert(evt.offsetX)`. + * @examples {{ onClick: (evt) => alert(`x: ${evt.clientX}, y: ${evt.clientY}`)}} + */ + events?: React.DOMAttributes<any>; + /** + * The title prop specifies the title to be applied to the SVG to assist + * accessibility for screen readers. The more descriptive this title is, the more + * useful it will be. If no title prop is passed, it will default to Victory Chart. + * @example "Popularity of Dog Breeds by Percentage" + * @default "Victory Chart" + */ + title?: string; + /** + * The desc prop specifies the description of the chart/SVG to assist with + * accessibility for screen readers. The more info about the chart provided in + * the description, the more usable it will be for people using screen readers. + * This prop defaults to an empty string. + * @example "Golden retreivers make up 30%, Labs make up 25%, and other dog breeds are + * not represented above 5% each." + * @default "" + */ + desc?: string; } - - export class VictoryContainer extends React.Component<VictoryContainerProps, any> {} - + + export class VictoryContainer extends React.Component<VictoryContainerProps, any> {} + type CursorData = { - x: number; - y: number; + x: number; + y: number; }; - + export interface VictoryCursorContainerProps extends VictoryContainerProps { - /** - * The cursorComponent prop takes a component instance which will be used to render a cursor element. - * The new element created will be supplied with x1, y1, x2 and y2 positioning props. - * If a cursorComponent is not supplied, a new Line component will be rendered. - * @default cursorComponent={<Line/>} - */ - cursorComponent?: React.ReactElement<any>; - /** - * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). - * When this prop is not specified, the cursor will be a 2-dimensional crosshair. - * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; - * the cursor will then be a vertical line that will inspect the time value of the current mouse position. - * @example cursorDimension="x" - */ - cursorDimension?: 'x' | 'y'; - /** - * The cursorLabel prop defines the label that will appear next to the cursor. - * A label will only appear if cursorLabel is set. This prop should be given as a - * function of a point (an Object with x and y properties). - * @example cursorLabel={(point) => point.x} - */ - cursorLabel?: (point: CursorData) => void; - /** - * The cursorLabelComponent prop takes a component instance which will be - * used to render a label for the cursor. The new element created from the passed - * cursorLabelComponent will be supplied with the following props: x, y, - * active, text. If cursorLabelComponent is omitted, a new VictoryLabel will be created with the props described above. - * @default cursorLabelComponent={<VictoryLabel/>} - */ - cursorLabelComponent?: React.ReactElement<any>; - /** - * The cursorLabelOffset prop determines the pixel offset of the cursor label - * from the cursor point. This prop should be an Object with x and y properties, or a - * number to be used for both dimensions. - * @default "{ x: 5, y: -10 }" - */ - cursorLabelOffset?: number | CursorData; - /** - * Whenever the mouse is not over the chart, the cursor will not be displayed. - * If instead you would like to keep it displayed, use the defaultCursorValue prop to set the default value. - * The prop should be a point (an Object with x and y properties) for 2-dimensional cursors, or a number for 1-dimensional cursors. - * @example defaultCursorValue={{x: 1, y: 1}}, defaultCursorValue={0}} - */ - defaultCursorValue?: number | CursorData; - /** - * When the disable prop is set to true, VictoryCursorContainer events will not fire. - */ - disable?: boolean; - /** - * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). - * When this prop is not specified, the cursor will be a 2-dimensional crosshair. - * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; - * the cursor will then be a vertical line that will inspect the time value of the current mouse position. - * @example onChange={(value, props) => this.setState({cursorValue: value})} - */ - onCursorChange?: (value: CursorData, props: VictoryCursorContainerProps) => void; + /** + * The cursorComponent prop takes a component instance which will be used to render a cursor element. + * The new element created will be supplied with x1, y1, x2 and y2 positioning props. + * If a cursorComponent is not supplied, a new Line component will be rendered. + * @default cursorComponent={<Line/>} + */ + cursorComponent?: React.ReactElement<any>; + /** + * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). + * When this prop is not specified, the cursor will be a 2-dimensional crosshair. + * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; + * the cursor will then be a vertical line that will inspect the time value of the current mouse position. + * @example cursorDimension="x" + */ + cursorDimension?: 'x' | 'y'; + /** + * The cursorLabel prop defines the label that will appear next to the cursor. + * A label will only appear if cursorLabel is set. This prop should be given as a + * function of a point (an Object with x and y properties). + * @example cursorLabel={(point) => point.x} + */ + cursorLabel?: (point: CursorData) => void; + /** + * The cursorLabelComponent prop takes a component instance which will be + * used to render a label for the cursor. The new element created from the passed + * cursorLabelComponent will be supplied with the following props: x, y, + * active, text. If cursorLabelComponent is omitted, a new VictoryLabel will be created with the props described above. + * @default cursorLabelComponent={<VictoryLabel/>} + */ + cursorLabelComponent?: React.ReactElement<any>; + /** + * The cursorLabelOffset prop determines the pixel offset of the cursor label + * from the cursor point. This prop should be an Object with x and y properties, or a + * number to be used for both dimensions. + * @default "{ x: 5, y: -10 }" + */ + cursorLabelOffset?: number | CursorData; + /** + * Whenever the mouse is not over the chart, the cursor will not be displayed. + * If instead you would like to keep it displayed, use the defaultCursorValue prop to set the default value. + * The prop should be a point (an Object with x and y properties) for 2-dimensional cursors, or a number for 1-dimensional cursors. + * @example defaultCursorValue={{x: 1, y: 1}}, defaultCursorValue={0}} + */ + defaultCursorValue?: number | CursorData; + /** + * When the disable prop is set to true, VictoryCursorContainer events will not fire. + */ + disable?: boolean; + /** + * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). + * When this prop is not specified, the cursor will be a 2-dimensional crosshair. + * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; + * the cursor will then be a vertical line that will inspect the time value of the current mouse position. + * @example onChange={(value, props) => this.setState({cursorValue: value})} + */ + onCursorChange?: (value: CursorData, props: VictoryCursorContainerProps) => void; } - - export class VictoryCursorContainer extends React.Component<VictoryCursorContainerProps, any> {} - + + export class VictoryCursorContainer extends React.Component<VictoryCursorContainerProps, any> {} + export interface VictoryBrushContainerProps extends VictoryContainerProps { - /** - * The optional allowDrag prop accepts a boolean that enables dragging behavior - * for the highlighted brush area. Resizing will still be enabled when the allowDrag - * prop is set to false. - * @default true - */ - allowDrag?: boolean; - /** - * The optional allowResize prop accepts a boolean that enables resizing the - * highlighted brush area. Dragging will still be enabled when the allowResize - * prop is set to false, but the dimensions of the brush area will be fixed. - * @default true - */ - allowResize?: boolean; - /** - * The brushComponent prop specifies the component to be rendered for the - * highlighted area. This component will be supplied with the following props: x, y, - * width, height, and style. When this prop is not specified, a <rect/> will be rendered. - * @default brushComponent={<rect/>} - */ - brushComponent?: React.ReactElement<any>; - /** - * When the brushDimension prop is set, brushing will only be specific to the to - * the given dimension (either "x" or "y"), and the entire domain of the other - * dimension will be highlighted. When this prop is not specified, highlighting will - * occur along both dimensions. - * @example brushDimension="x" - */ - brushDimension?: 'x' | 'y'; - /** - * The optional brushDomain prop describes the highlighted state. This prop is an - * object that specifies separate arrays for x and y. Each array is a tuple that - * describes the minimum and maximum values to render. If this prop is not provided - * initially, the chart will render with the entire domain highlighted. When this prop - * changes, the chart will render with a new highlighted domain. - * @example brushDomain={{ x: [50, 100], y: [0, 100] }} - */ - brushDomain?: DomainPropType; - /** - * The brushStyle adds custom styles to the brushComponent. This prop - * should be given as an object of SVG style attributes. - * @default "brushStyle={{ stroke: "transparent", fill: "black", fillOpacity: 0.1 }}" - */ - brushStyle?: React.CSSProperties; - /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the - * prop is set to "all", the entire domain will be selected. When the prop is set to "none", - * no new region will be selected, and any existing active brush will be cleared. When - * the prop is set to "disable" the new selected region will default to the current active brush. - */ - defaultBrushArea?: 'all' | 'none' | 'disable'; - /** - * When the disable prop is set to true, VictoryBrushContainer events will not fire. - */ - disable?: boolean; - /** - * The handleComponent prop specifies the component to be rendered for each - * handle for the highlighted area. This component will be supplied with the following - * props: x, y, width, height, cursor, and style. When this prop is not - * specified, a <rect/> will be rendered. - * @default handleComponent={<rect/>} - */ - handleComponent?: React.ReactElement<any>; - /** - * The handleStyle adds custom styles to the handleComponents. This prop should be given as an object of SVG style attributes. - * - * Handles refer to the region on each highlighted area where the area may be - * expanded. Only handles relevant to the given dimension will be rendered. For - * example, when brushDimension="x" only "left" and "right" handles will be - * rendered. Handles are automatically styled with cursors appropriate to their orientation. - * @default "handleStyle={{ stroke: 'transparent', fill: 'transparent' }}" - */ - handleStyle?: React.CSSProperties; - /** - * The optional onBrushDomainChange prop accepts an function to be called on - * each update to the highlighted domain. The function accepts the parameters of - * domain (the updated domain), and props (the props used by VictoryBrushContainer). - * @example onBrushDomainChange={(domain, props) => handleDomainChange(domain, props)} - */ - onBrushDomainChange?: (domain: DomainPropType, props: VictoryBrushContainerProps) => void; + /** + * The optional allowDrag prop accepts a boolean that enables dragging behavior + * for the highlighted brush area. Resizing will still be enabled when the allowDrag + * prop is set to false. + * @default true + */ + allowDrag?: boolean; + /** + * The optional allowResize prop accepts a boolean that enables resizing the + * highlighted brush area. Dragging will still be enabled when the allowResize + * prop is set to false, but the dimensions of the brush area will be fixed. + * @default true + */ + allowResize?: boolean; + /** + * The brushComponent prop specifies the component to be rendered for the + * highlighted area. This component will be supplied with the following props: x, y, + * width, height, and style. When this prop is not specified, a <rect/> will be rendered. + * @default brushComponent={<rect/>} + */ + brushComponent?: React.ReactElement<any>; + /** + * When the brushDimension prop is set, brushing will only be specific to the to + * the given dimension (either "x" or "y"), and the entire domain of the other + * dimension will be highlighted. When this prop is not specified, highlighting will + * occur along both dimensions. + * @example brushDimension="x" + */ + brushDimension?: 'x' | 'y'; + /** + * The optional brushDomain prop describes the highlighted state. This prop is an + * object that specifies separate arrays for x and y. Each array is a tuple that + * describes the minimum and maximum values to render. If this prop is not provided + * initially, the chart will render with the entire domain highlighted. When this prop + * changes, the chart will render with a new highlighted domain. + * @example brushDomain={{ x: [50, 100], y: [0, 100] }} + */ + brushDomain?: DomainPropType; + /** + * The brushStyle adds custom styles to the brushComponent. This prop + * should be given as an object of SVG style attributes. + * @default "brushStyle={{ stroke: "transparent", fill: "black", fillOpacity: 0.1 }}" + */ + brushStyle?: React.CSSProperties; + /** + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the + * prop is set to "all", the entire domain will be selected. When the prop is set to "none", + * no new region will be selected, and any existing active brush will be cleared. When + * the prop is set to "disable" the new selected region will default to the current active brush. + */ + defaultBrushArea?: 'all' | 'none' | 'disable'; + /** + * When the disable prop is set to true, VictoryBrushContainer events will not fire. + */ + disable?: boolean; + /** + * The handleComponent prop specifies the component to be rendered for each + * handle for the highlighted area. This component will be supplied with the following + * props: x, y, width, height, cursor, and style. When this prop is not + * specified, a <rect/> will be rendered. + * @default handleComponent={<rect/>} + */ + handleComponent?: React.ReactElement<any>; + /** + * The handleStyle adds custom styles to the handleComponents. This prop should be given as an object of SVG style attributes. + * + * Handles refer to the region on each highlighted area where the area may be + * expanded. Only handles relevant to the given dimension will be rendered. For + * example, when brushDimension="x" only "left" and "right" handles will be + * rendered. Handles are automatically styled with cursors appropriate to their orientation. + * @default "handleStyle={{ stroke: 'transparent', fill: 'transparent' }}" + */ + handleStyle?: React.CSSProperties; + /** + * The optional onBrushDomainChange prop accepts an function to be called on + * each update to the highlighted domain. The function accepts the parameters of + * domain (the updated domain), and props (the props used by VictoryBrushContainer). + * @example onBrushDomainChange={(domain, props) => handleDomainChange(domain, props)} + */ + onBrushDomainChange?: (domain: DomainPropType, props: VictoryBrushContainerProps) => void; } - - export class VictoryBrushContainer extends React.Component<VictoryBrushContainerProps, any> {} - + + export class VictoryBrushContainer extends React.Component<VictoryBrushContainerProps, any> {} + export interface VictoryZoomContainerProps extends VictoryContainerProps { - /** - * The optional allowPan prop accepts a boolean that enables the panning - * functionality. Zooming will still be enabled when the allowPan prop is set to false. - * @default true - */ - allowPan?: boolean; - /** - * The optional allowZoom prop accepts a boolean that enables the zoom - * functionality. Panning will still be enabled when the allowZoom prop is set to false. - * @default true - */ - allowZoom?: boolean; - /** - * VictoryZoomContainer works by clipping data outside of a given domain. - * VictoryZoomContainer uses VictoryClipContainer by default. - * This prop should not be replaced with a custom component, but you may want to set - * props on VictoryClipContainer, such as clipPadding. - * @example clipContainerComponent={<VictoryClipContainer clipPadding={{top: 10, right: 10}}}/>} - */ - clipContainerComponent?: React.ReactElement<any>; - /** - * When the zoomDimension prop is set, panning and zooming will be restricted to - * the given dimension (either x or y), and the domain of the other dimension will - * remain static. When this prop is not specified, both x and y dimensions will pan and zoom. - * @example zoomDimension="x" - */ - zoomDimension?: 'x' | 'y'; - /** - * The zoomDomain prop describes the zoomed state. This prop is an object that - * specifies separate arrays for x and y. Each array is a tuple that describes the - * minimum and maximum values to render. If this prop is not provided initially, the - * chart will render without an initial zoom, displaying the entire dataset. Updates to - * zoomDomain will trigger a re-render of the chart with the new domain. - * @example zoomDomain={{x: [0, 100]}} - */ - zoomDomain?: DomainPropType; - /** - * The brushStyle adds custom styles to the brushComponent. This prop - * should be given as an object of SVG style attributes. - * @default "brushStyle={{ stroke: 'transparent', fill: 'black', fillOpacity: 0.1 }}" - */ - brushStyle?: React.CSSProperties; - /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the - * prop is set to "all", the entire domain will be selected. When the prop is set to "none", - * no new region will be selected, and any existing active brush will be cleared. When - * the prop is set to "disable" the new selected region will default to the current active brush. - */ - defaultBrushArea?: 'all' | 'none' | 'disable'; - /** - * When the disable prop is set to true, VictoryBrushContainer events will not fire. - */ - disable?: boolean; - /** - * When the disable prop is set to true, VictoryZoomContainer events will not fire. - */ - downsample?: number | boolean; - /** - * The minimumZoom prop sets a minimum domain extent for the zoomed chart. - * When the difference between the maximum and minimum of a zoomed domain is equal to the minimumZoom - * in either dimension, the component will stop responding to events that would normally trigger zooming in. - * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum - * zoom will cover 1 / 1000th of the original domain. This prop should be given as an object - * with numeric values for x and y. - * @example minimumZoom={{x: 1, y: 0.01}} - */ - minimumZoom?: CursorData; - /** - * The optional onZoomDomainChange prop accepts an function to be called on each update to the visible domain. - * The function accepts the parameters domain (the updated domain) and props (the props used by VictoryZoomContainer). - * @example onZoomDomainChange={(domain, props) => handleDomainChange(domain, props)} - */ - onZoomDomainChange?: (domain: DomainPropType, props: VictoryZoomContainerProps) => void; + /** + * The optional allowPan prop accepts a boolean that enables the panning + * functionality. Zooming will still be enabled when the allowPan prop is set to false. + * @default true + */ + allowPan?: boolean; + /** + * The optional allowZoom prop accepts a boolean that enables the zoom + * functionality. Panning will still be enabled when the allowZoom prop is set to false. + * @default true + */ + allowZoom?: boolean; + /** + * VictoryZoomContainer works by clipping data outside of a given domain. + * VictoryZoomContainer uses VictoryClipContainer by default. + * This prop should not be replaced with a custom component, but you may want to set + * props on VictoryClipContainer, such as clipPadding. + * @example clipContainerComponent={<VictoryClipContainer clipPadding={{top: 10, right: 10}}}/>} + */ + clipContainerComponent?: React.ReactElement<any>; + /** + * When the zoomDimension prop is set, panning and zooming will be restricted to + * the given dimension (either x or y), and the domain of the other dimension will + * remain static. When this prop is not specified, both x and y dimensions will pan and zoom. + * @example zoomDimension="x" + */ + zoomDimension?: 'x' | 'y'; + /** + * The zoomDomain prop describes the zoomed state. This prop is an object that + * specifies separate arrays for x and y. Each array is a tuple that describes the + * minimum and maximum values to render. If this prop is not provided initially, the + * chart will render without an initial zoom, displaying the entire dataset. Updates to + * zoomDomain will trigger a re-render of the chart with the new domain. + * @example zoomDomain={{x: [0, 100]}} + */ + zoomDomain?: DomainPropType; + /** + * The brushStyle adds custom styles to the brushComponent. This prop + * should be given as an object of SVG style attributes. + * @default "brushStyle={{ stroke: 'transparent', fill: 'black', fillOpacity: 0.1 }}" + */ + brushStyle?: React.CSSProperties; + /** + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the + * prop is set to "all", the entire domain will be selected. When the prop is set to "none", + * no new region will be selected, and any existing active brush will be cleared. When + * the prop is set to "disable" the new selected region will default to the current active brush. + */ + defaultBrushArea?: 'all' | 'none' | 'disable'; + /** + * When the disable prop is set to true, VictoryBrushContainer events will not fire. + */ + disable?: boolean; + /** + * When the disable prop is set to true, VictoryZoomContainer events will not fire. + */ + downsample?: number | boolean; + /** + * The minimumZoom prop sets a minimum domain extent for the zoomed chart. + * When the difference between the maximum and minimum of a zoomed domain is equal to the minimumZoom + * in either dimension, the component will stop responding to events that would normally trigger zooming in. + * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum + * zoom will cover 1 / 1000th of the original domain. This prop should be given as an object + * with numeric values for x and y. + * @example minimumZoom={{x: 1, y: 0.01}} + */ + minimumZoom?: CursorData; + /** + * The optional onZoomDomainChange prop accepts an function to be called on each update to the visible domain. + * The function accepts the parameters domain (the updated domain) and props (the props used by VictoryZoomContainer). + * @example onZoomDomainChange={(domain, props) => handleDomainChange(domain, props)} + */ + onZoomDomainChange?: (domain: DomainPropType, props: VictoryZoomContainerProps) => void; } - - export class VictoryZoomContainer extends React.Component<VictoryZoomContainerProps, any> {} - + + export class VictoryZoomContainer extends React.Component<VictoryZoomContainerProps, any> {} + // Note: Many SVG attributes are missed in CSSProperties interface export interface VictoryThemeDefinition { - area?: VictoryStyleInterface; - axis?: { - axis: React.CSSProperties; - axisLabel: React.CSSProperties; - grid: React.CSSProperties; - ticks: React.CSSProperties; - tickLabels: React.CSSProperties; + area?: VictoryStyleInterface; + axis?: { + axis: React.CSSProperties; + axisLabel: React.CSSProperties; + grid: React.CSSProperties; + ticks: React.CSSProperties; + tickLabels: React.CSSProperties; + }; + bar?: VictoryStyleInterface; + candlestick?: VictoryStyleInterface & { + props: { + width: number; + height: number; + candleColors: { + positive: string; + negative: string; + }; }; - bar?: VictoryStyleInterface; - candlestick?: VictoryStyleInterface & { - props: { - width: number; - height: number; - candleColors: { - positive: string; - negative: string; - }; - }; - }; - line?: VictoryStyleInterface; - pie?: { - props: { - width: number; - height: number; - colorScale: string[]; - }; - style: VictoryStyleInterface; - }; - scatter?: VictoryStyleInterface; - props?: { - width: number; - height: number; - colorScale: string[]; + }; + line?: VictoryStyleInterface; + pie?: { + props: { + width: number; + height: number; + colorScale: string[]; }; + style: VictoryStyleInterface; + }; + scatter?: VictoryStyleInterface; + props?: { + width: number; + height: number; + colorScale: string[]; + }; } - + interface VictoryThemeInterface { - /** - * Default theme - */ - grayscale: VictoryThemeDefinition; - material: VictoryThemeDefinition; + /** + * Default theme + */ + grayscale: VictoryThemeDefinition; + material: VictoryThemeDefinition; } - + /** * Available themes */ export const VictoryTheme: VictoryThemeInterface; - + type OrientationTypes = "top" | "bottom" | "left" | "right"; - + export interface VictoryTooltipProps { - /** - * The active prop specifies whether the tooltip component should be displayed. - */ - active?: boolean; - /** - * When true, tooltip events will set the active prop on both data and label elements. - * @default false - */ - activateData?: boolean; - /** - * The angle prop specifies the angle to rotate the tooltip around its origin point. - */ - angle?: string | number; - /** - * The cornerRadius prop determines corner radius of the flyout container. This prop may be given as a positive number or a function of datum. - */ - cornerRadius?: NumberOrCallback; - /** - * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine text. - */ - datum?: {}; - /** - * Victory components can pass a data prop to their label component. This can be useful in custom components that need to make use of the entire dataset. - */ - data?: any[]; - /** - * The dx prop defines a horizontal shift from the x coordinate. - */ - dx?: StringOrNumberOrCallback; - /** - * The dy prop defines a vertical shift from the y coordinate. - */ - dy?: StringOrNumberOrCallback; - /** - * The events prop attaches arbitrary event handlers to the label component. This prop should be given as an object of event names and corresponding event handlers. - * When events are provided via Victory’s event system, event handlers will be called with the event, the props of the component is attached to, and an eventKey. - * Examples: events={{onClick: (evt) => alert("x: " + evt.clientX)}} - */ - events?: {}; - /** - * The style prop applies SVG style properties to the rendered flyout container. These props will be passed to the flyoutComponent. - */ - flyoutStyle?: VictoryStyleObject; - /** - * The flyoutComponent prop takes a component instance which will be used to create the flyout path for each tooltip. - * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, - * index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. - * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. - * If flyoutComponent is omitted, a default Flyout component will be created with props described above. - * Examples: flyoutComponent={<Flyout x={50} y={50}/>}, flyoutComponent={<MyCustomFlyout/>} - * @default <Flyout/> - */ - flyoutComponent?: React.ReactElement<any>; - /** - * The groupComponent prop takes a component instance which will be used to create group elements for use within container elements. This prop defaults to a <g> tag. - * @default groupComponent={<g/>} - */ - groupComponent?: React.ReactElement<any>; - /** - * The height prop defines the height of the tooltip flyout. This prop may be given as a positive number or a function of datum. - * If this prop is not set, height will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. - */ - height?: NumberOrCallback; - /** - * The horizontal prop determines whether to plot the flyouts to the left / right of the (x, y) coordinate rather than top / bottom. - * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. - * negative values result in a left orientation and positive values will result in a right orientation by default. - */ - horizontal?: boolean; - /** - * The index prop represents the index of the datum in the data array. - */ - index?: number | string; - /** - * The labelComponent prop takes a component instance which will be used to render each tooltip label. - * The new element created from the passed labelComponent will be supplied with the following properties: x, y, index, datum, verticalAnchor, textAnchor, style, text, and events. - * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. - * If labelComponent is omitted, a new VictoryLabel will be created with the props described above. - * Examples: labelComponent={<VictoryLabel dy={20}/>}, labelComponent={<MyCustomLabel/>} - * @default <VictoryLabel/> - */ - labelComponent?: React.ReactElement<any>; - /** - * The orientation prop determines which side of the (x, y) coordinate the tooltip should be rendered on. - * This prop can be given as “top”, “bottom”, “left”, “right”, or as a function of datum that returns one of these values. - * If this prop is not provided it will be determined from the sign of the datum, and the value of the horizontal prop. - */ - orientation?: OrientationTypes; - /** - * The pointerLength prop determines the length of the triangular pointer extending from the flyout. This prop may be given as a positive number or a function of datum. - */ - pointerLength?: NumberOrCallback; - /** - * The pointerWidth prop determines the width of the base of the triangular pointer extending from - * the flyout. This prop may be given as a positive number or a function of datum. - */ - pointerWidth?: NumberOrCallback; - /** - * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element - * within VictoryContainer. Note: This prop should not be set to true when using a custom container element. - */ - renderInPortal?: boolean; - /** - * The style prop applies CSS properties to the rendered `<text>` element. - */ - style?: React.CSSProperties; - /** - * The text prop defines the text VictoryTooltip will render. The text prop may be given as a string, number, or function of datum. - * When VictoryLabel is used as the labelComponent, strings may include newline characters, which VictoryLabel will split in to separate <tspan/> elements. - */ - text?: StringOrNumberOrCallback | string[] | number[]; - /** - * VictoryAxis uses the standard theme prop. Read about it here - * @default VictoryTheme.grayscale - */ - theme?: VictoryThemeDefinition; - /** - * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. - * If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. - */ - width?: NumberOrCallback; - /** - * The x prop defines the x coordinate to use as a basis for horizontal positioning. - */ - x?: number; - /** - * The y prop defines the y coordinate to use as a basis for vertical positioning. - */ - y?: number; + /** + * The active prop specifies whether the tooltip component should be displayed. + */ + active?: boolean; + /** + * When true, tooltip events will set the active prop on both data and label elements. + * @default false + */ + activateData?: boolean; + /** + * The angle prop specifies the angle to rotate the tooltip around its origin point. + */ + angle?: string | number; + /** + * The cornerRadius prop determines corner radius of the flyout container. This prop may be given as a positive number or a function of datum. + */ + cornerRadius?: NumberOrCallback; + /** + * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine text. + */ + datum?: {}; + /** + * Victory components can pass a data prop to their label component. This can be useful in custom components that need to make use of the entire dataset. + */ + data?: any[]; + /** + * The dx prop defines a horizontal shift from the x coordinate. + */ + dx?: StringOrNumberOrCallback; + /** + * The dy prop defines a vertical shift from the y coordinate. + */ + dy?: StringOrNumberOrCallback; + /** + * The events prop attaches arbitrary event handlers to the label component. This prop should be given as an object of event names and corresponding event handlers. + * When events are provided via Victory’s event system, event handlers will be called with the event, the props of the component is attached to, and an eventKey. + * Examples: events={{onClick: (evt) => alert("x: " + evt.clientX)}} + */ + events?: {}; + /** + * The style prop applies SVG style properties to the rendered flyout container. These props will be passed to the flyoutComponent. + */ + flyoutStyle?: VictoryStyleObject; + /** + * The flyoutComponent prop takes a component instance which will be used to create the flyout path for each tooltip. + * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, + * index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. + * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. + * If flyoutComponent is omitted, a default Flyout component will be created with props described above. + * Examples: flyoutComponent={<Flyout x={50} y={50}/>}, flyoutComponent={<MyCustomFlyout/>} + * @default <Flyout/> + */ + flyoutComponent?: React.ReactElement<any>; + /** + * The groupComponent prop takes a component instance which will be used to create group elements for use within container elements. This prop defaults to a <g> tag. + * @default groupComponent={<g/>} + */ + groupComponent?: React.ReactElement<any>; + /** + * The height prop defines the height of the tooltip flyout. This prop may be given as a positive number or a function of datum. + * If this prop is not set, height will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. + */ + height?: NumberOrCallback; + /** + * The horizontal prop determines whether to plot the flyouts to the left / right of the (x, y) coordinate rather than top / bottom. + * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. + * negative values result in a left orientation and positive values will result in a right orientation by default. + */ + horizontal?: boolean; + /** + * The index prop represents the index of the datum in the data array. + */ + index?: number | string; + /** + * The labelComponent prop takes a component instance which will be used to render each tooltip label. + * The new element created from the passed labelComponent will be supplied with the following properties: x, y, index, datum, verticalAnchor, textAnchor, style, text, and events. + * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. + * If labelComponent is omitted, a new VictoryLabel will be created with the props described above. + * Examples: labelComponent={<VictoryLabel dy={20}/>}, labelComponent={<MyCustomLabel/>} + * @default <VictoryLabel/> + */ + labelComponent?: React.ReactElement<any>; + /** + * The orientation prop determines which side of the (x, y) coordinate the tooltip should be rendered on. + * This prop can be given as “top”, “bottom”, “left”, “right”, or as a function of datum that returns one of these values. + * If this prop is not provided it will be determined from the sign of the datum, and the value of the horizontal prop. + */ + orientation?: OrientationTypes; + /** + * The pointerLength prop determines the length of the triangular pointer extending from the flyout. This prop may be given as a positive number or a function of datum. + */ + pointerLength?: NumberOrCallback; + /** + * The pointerWidth prop determines the width of the base of the triangular pointer extending from + * the flyout. This prop may be given as a positive number or a function of datum. + */ + pointerWidth?: NumberOrCallback; + /** + * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element + * within VictoryContainer. Note: This prop should not be set to true when using a custom container element. + */ + renderInPortal?: boolean; + /** + * The style prop applies CSS properties to the rendered `<text>` element. + */ + style?: React.CSSProperties; + /** + * The text prop defines the text VictoryTooltip will render. The text prop may be given as a string, number, or function of datum. + * When VictoryLabel is used as the labelComponent, strings may include newline characters, which VictoryLabel will split in to separate <tspan/> elements. + */ + text?: StringOrNumberOrCallback | string[] | number[]; + /** + * VictoryAxis uses the standard theme prop. Read about it here + * @default VictoryTheme.grayscale + */ + theme?: VictoryThemeDefinition; + /** + * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. + * If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. + */ + width?: NumberOrCallback; + /** + * The x prop defines the x coordinate to use as a basis for horizontal positioning. + */ + x?: number; + /** + * The y prop defines the y coordinate to use as a basis for vertical positioning. + */ + y?: number; } - + /** * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label * component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. * VictoryTooltip renders text as well as a configurable Flyout container. */ export class VictoryTooltip extends React.Component< - VictoryTooltipProps, - any - > {} - + VictoryTooltipProps, + any + > {} + /** * Animate object used in components */ export interface AnimatePropTypeInterface { - /** - * Animation duration - */ - duration: number; - /** - * Animation end callback - */ - onEnd?: () => void; - /** - * Animation exit transition configuration - */ - onExit?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - }; - /** - * Animation enter transition configuration - */ - onEnter?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - after?: (datum: any) => AnimationStyle; - }; - /** - * Animation load transition configuration - */ - onLoad?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - after?: (datum: any) => AnimationStyle; - }; - /** - * The easing prop specifies an easing function name to use for tweening. - * @default "quadInOut" - */ - easing?: AnimationEasing; + /** + * Animation duration + */ + duration: number; + /** + * Animation end callback + */ + onEnd?: () => void; + /** + * Animation exit transition configuration + */ + onExit?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + }; + /** + * Animation enter transition configuration + */ + onEnter?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + after?: (datum: any) => AnimationStyle; + }; + /** + * Animation load transition configuration + */ + onLoad?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + after?: (datum: any) => AnimationStyle; + }; + /** + * The easing prop specifies an easing function name to use for tweening. + * @default "quadInOut" + */ + easing?: AnimationEasing; } - + /** * Return value for eventHandlers values */ interface EventCallbackInterface<TTarget, TEventKey> { - /** - * Use only in: - * - VictoryChart - * - VictoryStack - */ - childName?: string; - target?: TTarget; - eventKey?: TEventKey; - /** - * Will be called with the calculated props for the individual selected element and result will override - * props of selected element via object assignment - * @param props - */ - mutation: (props: any) => any; + /** + * Use only in: + * - VictoryChart + * - VictoryStack + */ + childName?: string; + target?: TTarget; + eventKey?: TEventKey; + /** + * Will be called with the calculated props for the individual selected element and result will override + * props of selected element via object assignment + * @param props + */ + mutation: (props: any) => any; } - + export interface EventPropTypeInterface<TTarget, TEventKey> { - /** - * Use only in: - * - VictoryChart - * - VictoryStack - */ - childName?: string; - /** - * Targets may be any valid style namespace for a given component - */ - target: TTarget; - - eventKey?: TEventKey; - /** - * Event handlers map. Keys are standard event names (such as onClick) and values are event callbacks - */ - eventHandlers: { - [key: string]: { - (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey> } | - { (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey>[] - } - }; + /** + * Use only in: + * - VictoryChart + * - VictoryStack + */ + childName?: string; + /** + * Targets may be any valid style namespace for a given component + */ + target: TTarget; + + eventKey?: TEventKey; + /** + * Event handlers map. Keys are standard event names (such as onClick) and values are event callbacks + */ + eventHandlers: { + [key: string]: { + (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey> } | + { (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey>[] + } + }; } - + /** * Data domain type */ type DomainTuple = [number, number] | [Date, Date]; - - type DomainPropType = DomainTuple | { x?: DomainTuple; y: DomainTuple; } | { x: DomainTuple; y?: DomainTuple; }; - + + type DomainPropType = DomainTuple | { x?: DomainTuple; y: DomainTuple; } | { x: DomainTuple; y?: DomainTuple; }; + /** * Domain padding */ - type DomainPaddingPropType = number | { - x?: number | [ number, number]; - y?: number | [ number, number]; - }; - + type DomainPaddingPropType = number | { + x?: number | [ number, number]; + y?: number | [ number, number]; + }; + /** * D3 scale function shape. Don't want to introduce typing dependency to d3 */ interface D3Scale { - domain: () => any; - range: () => any; - copy: () => any; + domain: () => any; + range: () => any; + copy: () => any; } - + /** * Acceptable scale types */ type ScalePropType = "linear" | "time" | "log" | "sqrt"; - + /** * Category prop type */ - type CategoryPropType = string[] | { - x: string[] - y: string[] - }; - + type CategoryPropType = string[] | { + x: string[] + y: string[] + }; + /** * Data getter property type */ - type DataGetterPropType = number | string | string[] | { (data: any): number | string | string[] }; - - type InterpolationPropType = "basis" | "basisClosed" | "basisOpen" | "bundle" | - "cardinal" | "cardinalClosed" | "cardinalOpen" | - "catmullRom" | "catmullRomClosed" | "catmullRomOpen" | - "linear" | "linearClosed" | "monotoneX" | "monotoneY" | - "natural" | "radial" | "step" | "stepAfter" | "stepBefore"; - - type ColorScalePropType = "greyscale" | "qualitative" | "heatmap" | "warm" | "cool" | "red" | "green" | "blue" | string[]; - + type DataGetterPropType = number | string | string[] | { (data: any): number | string | string[] }; + + type InterpolationPropType = "basis" | "basisClosed" | "basisOpen" | "bundle" | + "cardinal" | "cardinalClosed" | "cardinalOpen" | + "catmullRom" | "catmullRomClosed" | "catmullRomOpen" | + "linear" | "linearClosed" | "monotoneX" | "monotoneY" | + "natural" | "radial" | "step" | "stepAfter" | "stepBefore"; + + type ColorScalePropType = "greyscale" | "qualitative" | "heatmap" | "warm" | "cool" | "red" | "green" | "blue" | string[]; + /** * Common properties */ interface VictoryCommonProps { - /** - * The animate prop specifies props for VictoryAnimation to use. - * The animate prop should also be used to specify enter and exit - * transition configurations with the `onExit` and `onEnter` namespaces respectively. - * @example - * {duration: 500, onExit: () => {}, onEnter: {duration: 500, before: () => ({y: 0})})} - */ - animate?: AnimatePropTypeInterface; - /** - * The name prop is used to reference a component instance when defining shared events. - */ - name?: string; - /** - * The height props specifies the height the svg viewBox of the chart container. - * This value should be given as a number of pixels - */ - height?: number; - /** - * The padding props specifies the amount of padding in number of pixels between - * the edge of the chart and any rendered child components. This prop can be given - * as a number or as an object with padding specified for top, bottom, left - * and right. - * @default 50 - */ - padding?: number | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - /** - * The scale prop determines which scales your chart should use. This prop can be - * given as a string specifying a supported scale ("linear", "time", "log", "sqrt"), - * as a d3 scale function, or as an object with scales specified for x and y - * @example d3Scale.time(), {x: "linear", y: "log"} - * @default "linear" - */ - scale?: ScalePropType | D3Scale | { - x?: ScalePropType | D3Scale; - y?: ScalePropType | D3Scale; - }; - /** - * The standalone prop determines whether the component will render a standalone svg - * or a <g> tag that will be included in an external svg. Set standalone to false to - * compose VictoryAxis with other components within an enclosing <svg> tag. - * @default true - */ - standalone?: boolean; - /** - * The width props specifies the width of the svg viewBox of the chart container - * This value should be given as a number of pixels - */ - width?: number; - /** - * The containerComponent prop takes an entire component which will be used to - * create a container element for standalone charts. - * The new element created from the passed containerComponent wil be provided with - * these props from VictoryArea: height, width, children - * (the chart itself) and style. Props that are not provided by the - * child chart component include title and desc, both of which - * are intended to add accessibility to Victory components. The more descriptive these props - * are, the more accessible your data will be for people using screen readers. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a dataComponent is - * not provided, VictoryArea will use the default VictoryContainer component. - * @example <VictoryContainer title="Chart of Dog Breeds" desc="This chart shows how popular each dog breed is by percentage in Seattle." /> - * @default <VictoryContainer/> - */ - containerComponent?: React.ReactElement<any>; - /** - * The theme prop takes a style object with nested data, labels, and parent objects. - * You can create this object yourself, or you can use a theme provided by Victory. - * When using VictoryArea as a solo component, implement the theme directly on - * VictoryArea. If you are wrapping VictoryArea in VictoryChart, VictoryStack, or - * VictoryGroup, please call the theme on the outermost wrapper component instead. - * @example theme={VictoryTheme.material} - * http://www.github.com/FormidableLabs/victory-core/tree/master/src/victory-theme/material.js - */ - theme?: VictoryThemeDefinition; - /** - * The groupComponent prop takes an entire component which will be used to - * create group elements for use within container elements. This prop defaults - * to a <g> tag on web, and a react-native-svg <G> tag on mobile - * @default <g/> - */ - groupComponent?: React.ReactElement<any>; + /** + * The animate prop specifies props for VictoryAnimation to use. + * The animate prop should also be used to specify enter and exit + * transition configurations with the `onExit` and `onEnter` namespaces respectively. + * @example + * {duration: 500, onExit: () => {}, onEnter: {duration: 500, before: () => ({y: 0})})} + */ + animate?: AnimatePropTypeInterface; + /** + * The name prop is used to reference a component instance when defining shared events. + */ + name?: string; + /** + * The height props specifies the height the svg viewBox of the chart container. + * This value should be given as a number of pixels + */ + height?: number; + /** + * The padding props specifies the amount of padding in number of pixels between + * the edge of the chart and any rendered child components. This prop can be given + * as a number or as an object with padding specified for top, bottom, left + * and right. + * @default 50 + */ + padding?: number | { + top?: number; + bottom?: number; + left?: number; + right?: number; + }; + /** + * The scale prop determines which scales your chart should use. This prop can be + * given as a string specifying a supported scale ("linear", "time", "log", "sqrt"), + * as a d3 scale function, or as an object with scales specified for x and y + * @example d3Scale.time(), {x: "linear", y: "log"} + * @default "linear" + */ + scale?: ScalePropType | D3Scale | { + x?: ScalePropType | D3Scale; + y?: ScalePropType | D3Scale; + }; + /** + * The standalone prop determines whether the component will render a standalone svg + * or a <g> tag that will be included in an external svg. Set standalone to false to + * compose VictoryAxis with other components within an enclosing <svg> tag. + * @default true + */ + standalone?: boolean; + /** + * The width props specifies the width of the svg viewBox of the chart container + * This value should be given as a number of pixels + */ + width?: number; + /** + * The containerComponent prop takes an entire component which will be used to + * create a container element for standalone charts. + * The new element created from the passed containerComponent wil be provided with + * these props from VictoryArea: height, width, children + * (the chart itself) and style. Props that are not provided by the + * child chart component include title and desc, both of which + * are intended to add accessibility to Victory components. The more descriptive these props + * are, the more accessible your data will be for people using screen readers. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a dataComponent is + * not provided, VictoryArea will use the default VictoryContainer component. + * @example <VictoryContainer title="Chart of Dog Breeds" desc="This chart shows how popular each dog breed is by percentage in Seattle." /> + * @default <VictoryContainer/> + */ + containerComponent?: React.ReactElement<any>; + /** + * The theme prop takes a style object with nested data, labels, and parent objects. + * You can create this object yourself, or you can use a theme provided by Victory. + * When using VictoryArea as a solo component, implement the theme directly on + * VictoryArea. If you are wrapping VictoryArea in VictoryChart, VictoryStack, or + * VictoryGroup, please call the theme on the outermost wrapper component instead. + * @example theme={VictoryTheme.material} + * http://www.github.com/FormidableLabs/victory-core/tree/master/src/victory-theme/material.js + */ + theme?: VictoryThemeDefinition; + /** + * The groupComponent prop takes an entire component which will be used to + * create group elements for use within container elements. This prop defaults + * to a <g> tag on web, and a react-native-svg <G> tag on mobile + * @default <g/> + */ + groupComponent?: React.ReactElement<any>; } - + /** * Common properties for all data components */ interface VictoryDatableProps { - /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these arrays of values specified for x and y. If this prop is not set, - * categorical data will be plotted in the order it was given in the data array - * @example ["dogs", "cats", "mice"] - */ - categories?: CategoryPropType; - /** - * The data prop specifies the data to be plotted. Data should be in the form of an array - * of data points, or an array of arrays of data points for multiple datasets. - * Each data point may be any format you wish (depending on the `x` and `y` accessor props), - * but by default, an object with x and y properties is expected. - * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], - * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] - */ - data?: any[]; - /** - * The dataComponent prop takes an entire component which will be used to create an area. - * The new element created from the passed dataComponent will be provided with the - * following properties calculated by VictoryArea: a scale, style, events, interpolation, - * and an array of modified data objects (including x, y, and calculated y0 and y1). - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a dataComponent is - * not provided, VictoryArea will use its default Area component. - * @default <Area/> - */ - dataComponent?: React.ReactElement<any>; - /** - * The domain prop describes the range of values your chart will cover. This prop can be - * given as a array of the minimum and maximum expected values for your bar chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The x prop specifies how to access the X value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) - * @default "x" - */ - x?: DataGetterPropType; - /** - * The y prop specifies how to access the Y value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) - * @default "y" - */ - y?: DataGetterPropType; + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these arrays of values specified for x and y. If this prop is not set, + * categorical data will be plotted in the order it was given in the data array + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The data prop specifies the data to be plotted. Data should be in the form of an array + * of data points, or an array of arrays of data points for multiple datasets. + * Each data point may be any format you wish (depending on the `x` and `y` accessor props), + * but by default, an object with x and y properties is expected. + * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], + * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] + */ + data?: any[]; + /** + * The dataComponent prop takes an entire component which will be used to create an area. + * The new element created from the passed dataComponent will be provided with the + * following properties calculated by VictoryArea: a scale, style, events, interpolation, + * and an array of modified data objects (including x, y, and calculated y0 and y1). + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a dataComponent is + * not provided, VictoryArea will use its default Area component. + * @default <Area/> + */ + dataComponent?: React.ReactElement<any>; + /** + * The domain prop describes the range of values your chart will cover. This prop can be + * given as a array of the minimum and maximum expected values for your bar chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The x prop specifies how to access the X value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) + * @default "x" + */ + x?: DataGetterPropType; + /** + * The y prop specifies how to access the Y value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) + * @default "y" + */ + y?: DataGetterPropType; } - + // Common labable interface interface VictoryLabableProps { - /** - * The labelComponent prop takes in an entire label component which will be used - * to create a label for the area. The new element created from the passed labelComponent - * will be supplied with the following properties: x, y, index, data, verticalAnchor, - * textAnchor, angle, style, text, and events. any of these props may be overridden - * by passing in props to the supplied component, or modified or ignored within - * the custom component itself. If labelComponent is omitted, a new VictoryLabel - * will be created with props described above. This labelComponent prop should be used to - * provide a series label for VictoryArea. If individual labels are required for each - * data point, they should be created by composing VictoryArea with VictoryScatter - * @default <VictoryLabel/> - */ - labelComponent?: React.ReactElement<any>; + /** + * The labelComponent prop takes in an entire label component which will be used + * to create a label for the area. The new element created from the passed labelComponent + * will be supplied with the following properties: x, y, index, data, verticalAnchor, + * textAnchor, angle, style, text, and events. any of these props may be overridden + * by passing in props to the supplied component, or modified or ignored within + * the custom component itself. If labelComponent is omitted, a new VictoryLabel + * will be created with props described above. This labelComponent prop should be used to + * provide a series label for VictoryArea. If individual labels are required for each + * data point, they should be created by composing VictoryArea with VictoryScatter + * @default <VictoryLabel/> + */ + labelComponent?: React.ReactElement<any>; } - + interface VictoryMultiLabeableProps extends VictoryLabableProps { - /** - * The labels prop defines labels that will appear above each bar in your chart. - * This prop should be given as an array of values or as a function of data. - * If given as an array, the number of elements in the array should be equal to - * the length of the data array. Labels may also be added directly to the data object - * like data={[{x: 1, y: 1, label: "first"}]}. - * @example ["spring", "summer", "fall", "winter"], (datum) => datum.title - */ - labels?: string[] | { (data: any): string }; + /** + * The labels prop defines labels that will appear above each bar in your chart. + * This prop should be given as an array of values or as a function of data. + * If given as an array, the number of elements in the array should be equal to + * the length of the data array. Labels may also be added directly to the data object + * like data={[{x: 1, y: 1, label: "first"}]}. + * @example ["spring", "summer", "fall", "winter"], (datum) => datum.title + */ + labels?: string[] | { (data: any): string }; } - + interface VictorySingleLabableProps extends VictoryLabableProps { - /** - * The label prop defines the label that will appear at the edge of the area. - * This prop should be given a string or as a function of data. If individual - * labels are required for each data point, they should be created by composing - * VictoryArea with VictoryScatter - * @example: "Series 1", (data) => `${data.length} points` - */ - label?: string | { (data: any): string }; + /** + * The label prop defines the label that will appear at the edge of the area. + * This prop should be given a string or as a function of data. If individual + * labels are required for each data point, they should be created by composing + * VictoryArea with VictoryScatter + * @example: "Series 1", (data) => `${data.length} points` + */ + label?: string | { (data: any): string }; } - + export interface VictoryAreaProps extends VictoryCommonProps, VictoryDatableProps, @@ -1091,571 +1091,571 @@ declare module "victory" { */ style?: VictoryStyleInterface; } - + /** * Draw area charts with React. VictoryArea is a composable component, so it doesn't include axes. * Add VictoryArea as a child of VictoryChart for a complete chart. */ export class VictoryArea extends React.Component<VictoryAreaProps, any> {} - + export interface VictoryAxisProps extends VictoryCommonProps { - /** - * The axisComponent prop takes in an entire component which will be used - * to create the axis line. The new element created from the passed axisComponent - * will be supplied with the following properties: x1, y1, x2, y2, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If an axisComponent - * is not supplied, VictoryAxis will render its default AxisLine component. - * @default <AxisLine/> - */ - axisComponent?: React.ReactElement<any>; - /** - * The axisLabelComponent prop takes in an entire component which will be used - * to create the axis label. The new element created from the passed axisLabelComponent - * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, - * angle, transform, style and events. Any of these props may be overridden by - * passing in props to the supplied component, or modified or ignored within - * the custom component itself. If an axisLabelComponent is not supplied, a new - * VictoryLabel will be created with props described above - * @default <VictoryLabel/> - */ - axisLabelComponent?: React.ReactElement<any>; - /** - * This prop specifies whether a given axis is intended to cross another axis. - */ - crossAxis?: boolean; - /** - * The dependentAxis prop specifies whether the axis corresponds to the - * dependent variable (usually y). This prop is useful when composing axis - * with other components to form a chart. - */ - dependentAxis?: boolean; - /** - * The domain prop describes the range of values your axis will include. This prop should be - * given as a array of the minimum and maximum expected values for your axis. - * If this value is not given it will be calculated based on the scale or tickValues. - * @examples [-1, 1] - */ - domain?: DomainPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "axis", "axisLabel", "ticks", "tickLabels", and "grid" are - * all valid targets for VictoryAxis events. The eventKey may optionally be used to select a - * single element by index rather than an entire set. The eventHandlers object - * should be given as an object whose keys are standard event names (i.e. onClick) - * and whose values are event callbacks. The return value of an event handler - * be used to modify other elemnts. The return value should be given as an object or - * an array of objects with optional target and eventKey keys, and a mutation - * key whose value is a function. The target and eventKey keys will default to those - * corresponding to the element the event handler was attached to. The mutation - * function will be called with the calculated props for the individual selected - * element (i.e. a single tick), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "grid", - * eventKey: 2, - * eventHandlers: { - * onClick: () => { - * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {stroke: "orange"})}; - * } - * }, { - * target: "tickLabels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"axis" | "axisLabel" | "grid" | "ticks" | "tickLabels" | "parent", number | string>[]; - /** - * When true, this prop reduces the number of tick labels to fit the length of the axis. - * Labels are removed at approximately even intervals from the original array of labels. - * This feature only works well for labels that are approximately evenly spaced. - * @default false - */ - fixLabelOverlap?: boolean; - /** - * The gridComponent prop takes in an entire component which will be used - * to create grid lines. The new element created from the passed gridComponent - * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a gridComponent - * is not supplied, VictoryAxis will render its default GridLine component. - * @default <GridLine/> - */ - gridComponent?: React.ReactElement<any>; - /** - * If true, this value will flip the domain of a given axis. - */ - invertAxis?: boolean; - /** - * The label prop defines the label that will appear along the axis. This - * prop should be given as a value or an entire, HTML-complete label - * component. If a label component is given, it will be cloned. The new - * element's properties x, y, textAnchor, verticalAnchor, and transform - * will have defaults provided by the axis; styles filled out with - * defaults provided by the axis, and overrides from the label component. - * If a value is given, a new VictoryLabel will be created with props and - * styles from the axis. - */ - label?: any; - /** - * This value describes how far from the "edge" of its permitted area each axis - * will be set back in the x-direction. If this prop is not given, - * the offset is calculated based on font size, axis orientation, and label padding. - */ - offsetX?: number; - /** - * This value describes how far from the "edge" of its permitted area each axis - * will be set back in the y-direction. If this prop is not given, - * the offset is calculated based on font size, axis orientation, and label padding. - */ - offsetY?: number; - /** - * The orientation prop specifies the position and orientation of your axis. - */ - orientation?: "top" | "bottom" | "left" | "right"; - /** - * The style prop defines the style of the component. The style prop should be given as an object - * with styles defined for parent, axis, axisLabel, grid, ticks, and tickLabels. Any valid svg - * styles are supported, but width, height, and padding should be specified via props as they - * determine relative layout for components in VictoryChart. Functional styles may be defined for - * grid, tick, and tickLabel style properties, and they will be evaluated with each tick. - * - * note: When a component is rendered as a child of another Victory component, or within a custom - * <svg> element with standalone={false} parent styles will be applied to the enclosing <g> tag. - * Many styles that can be applied to a parent <svg> will not be expressed when applied to a <g>. - * - * note: custom angle and verticalAnchor properties may be included in labels styles. - */ - style?: { - parent?: React.CSSProperties; - axis?: React.CSSProperties; - axisLabel?: React.CSSProperties; - grid?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - ticks?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - tickLabels?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; + /** + * The axisComponent prop takes in an entire component which will be used + * to create the axis line. The new element created from the passed axisComponent + * will be supplied with the following properties: x1, y1, x2, y2, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If an axisComponent + * is not supplied, VictoryAxis will render its default AxisLine component. + * @default <AxisLine/> + */ + axisComponent?: React.ReactElement<any>; + /** + * The axisLabelComponent prop takes in an entire component which will be used + * to create the axis label. The new element created from the passed axisLabelComponent + * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, + * angle, transform, style and events. Any of these props may be overridden by + * passing in props to the supplied component, or modified or ignored within + * the custom component itself. If an axisLabelComponent is not supplied, a new + * VictoryLabel will be created with props described above + * @default <VictoryLabel/> + */ + axisLabelComponent?: React.ReactElement<any>; + /** + * This prop specifies whether a given axis is intended to cross another axis. + */ + crossAxis?: boolean; + /** + * The dependentAxis prop specifies whether the axis corresponds to the + * dependent variable (usually y). This prop is useful when composing axis + * with other components to form a chart. + */ + dependentAxis?: boolean; + /** + * The domain prop describes the range of values your axis will include. This prop should be + * given as a array of the minimum and maximum expected values for your axis. + * If this value is not given it will be calculated based on the scale or tickValues. + * @examples [-1, 1] + */ + domain?: DomainPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "axis", "axisLabel", "ticks", "tickLabels", and "grid" are + * all valid targets for VictoryAxis events. The eventKey may optionally be used to select a + * single element by index rather than an entire set. The eventHandlers object + * should be given as an object whose keys are standard event names (i.e. onClick) + * and whose values are event callbacks. The return value of an event handler + * be used to modify other elemnts. The return value should be given as an object or + * an array of objects with optional target and eventKey keys, and a mutation + * key whose value is a function. The target and eventKey keys will default to those + * corresponding to the element the event handler was attached to. The mutation + * function will be called with the calculated props for the individual selected + * element (i.e. a single tick), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "grid", + * eventKey: 2, + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {stroke: "orange"})}; + * } + * }, { + * target: "tickLabels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"axis" | "axisLabel" | "grid" | "ticks" | "tickLabels" | "parent", number | string>[]; + /** + * When true, this prop reduces the number of tick labels to fit the length of the axis. + * Labels are removed at approximately even intervals from the original array of labels. + * This feature only works well for labels that are approximately evenly spaced. + * @default false + */ + fixLabelOverlap?: boolean; + /** + * The gridComponent prop takes in an entire component which will be used + * to create grid lines. The new element created from the passed gridComponent + * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a gridComponent + * is not supplied, VictoryAxis will render its default GridLine component. + * @default <GridLine/> + */ + gridComponent?: React.ReactElement<any>; + /** + * If true, this value will flip the domain of a given axis. + */ + invertAxis?: boolean; + /** + * The label prop defines the label that will appear along the axis. This + * prop should be given as a value or an entire, HTML-complete label + * component. If a label component is given, it will be cloned. The new + * element's properties x, y, textAnchor, verticalAnchor, and transform + * will have defaults provided by the axis; styles filled out with + * defaults provided by the axis, and overrides from the label component. + * If a value is given, a new VictoryLabel will be created with props and + * styles from the axis. + */ + label?: any; + /** + * This value describes how far from the "edge" of its permitted area each axis + * will be set back in the x-direction. If this prop is not given, + * the offset is calculated based on font size, axis orientation, and label padding. + */ + offsetX?: number; + /** + * This value describes how far from the "edge" of its permitted area each axis + * will be set back in the y-direction. If this prop is not given, + * the offset is calculated based on font size, axis orientation, and label padding. + */ + offsetY?: number; + /** + * The orientation prop specifies the position and orientation of your axis. + */ + orientation?: "top" | "bottom" | "left" | "right"; + /** + * The style prop defines the style of the component. The style prop should be given as an object + * with styles defined for parent, axis, axisLabel, grid, ticks, and tickLabels. Any valid svg + * styles are supported, but width, height, and padding should be specified via props as they + * determine relative layout for components in VictoryChart. Functional styles may be defined for + * grid, tick, and tickLabel style properties, and they will be evaluated with each tick. + * + * note: When a component is rendered as a child of another Victory component, or within a custom + * <svg> element with standalone={false} parent styles will be applied to the enclosing <g> tag. + * Many styles that can be applied to a parent <svg> will not be expressed when applied to a <g>. + * + * note: custom angle and verticalAnchor properties may be included in labels styles. + */ + style?: { + parent?: React.CSSProperties; + axis?: React.CSSProperties; + axisLabel?: React.CSSProperties; + grid?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) }; - /** - * The tickComponent prop takes in an entire component which will be used - * to create tick lines. The new element created from the passed tickComponent - * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a tickComponent - * is not supplied, VictoryAxis will render its default Tick component. - * @default <Tick/> - */ - tickComponent?: React.ReactElement<any>; - /** - * The tickCount prop specifies approximately how many ticks should be drawn on the axis if - * tickValues are not explicitly provided. This value is calculated by d3 scale and - * prioritizes returning "nice" values and evenly spaced ticks over an exact number of ticks. - * If you need an exact number of ticks, please specify them via the tickValues prop. - * This prop must have a value greater than zero. - * @default 5 - */ - tickCount?: number; - /** - * The tickLabelComponent prop takes in an entire component which will be used - * to create the tick labels. The new element created from the passed tickLabelComponent - * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, - * angle, tick, style and events. Any of these props may be overridden by - * passing in props to the supplied component, or modified or ignored within - * the custom component itself. If an tickLabelComponent is not supplied, a new - * VictoryLabel will be created with props described above - * @default <VictoryLabel/> - */ - tickLabelComponent?: React.ReactElement<any>; - /** - * The tickFormat prop specifies how tick values should be expressed visually. - * tickFormat can be given as a function to be applied to every tickValue, or as - * an array of display values for each tickValue. - * @example d3.time.format("%Y"), (x) => x.toPrecision(2), ["first", "second", "third"] - */ - tickFormat?: any[] | { (tick: any, index: number, ticks: any[]): string | number }; - /** - * The tickValues prop explicitly specifies which tick values to draw on the axis. - * @example ["apples", "bananas", "oranges"], [2, 4, 6, 8] - */ - tickValues?: any[]; + ticks?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + tickLabels?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + }; + /** + * The tickComponent prop takes in an entire component which will be used + * to create tick lines. The new element created from the passed tickComponent + * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a tickComponent + * is not supplied, VictoryAxis will render its default Tick component. + * @default <Tick/> + */ + tickComponent?: React.ReactElement<any>; + /** + * The tickCount prop specifies approximately how many ticks should be drawn on the axis if + * tickValues are not explicitly provided. This value is calculated by d3 scale and + * prioritizes returning "nice" values and evenly spaced ticks over an exact number of ticks. + * If you need an exact number of ticks, please specify them via the tickValues prop. + * This prop must have a value greater than zero. + * @default 5 + */ + tickCount?: number; + /** + * The tickLabelComponent prop takes in an entire component which will be used + * to create the tick labels. The new element created from the passed tickLabelComponent + * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, + * angle, tick, style and events. Any of these props may be overridden by + * passing in props to the supplied component, or modified or ignored within + * the custom component itself. If an tickLabelComponent is not supplied, a new + * VictoryLabel will be created with props described above + * @default <VictoryLabel/> + */ + tickLabelComponent?: React.ReactElement<any>; + /** + * The tickFormat prop specifies how tick values should be expressed visually. + * tickFormat can be given as a function to be applied to every tickValue, or as + * an array of display values for each tickValue. + * @example d3.time.format("%Y"), (x) => x.toPrecision(2), ["first", "second", "third"] + */ + tickFormat?: any[] | { (tick: any, index: number, ticks: any[]): string | number }; + /** + * The tickValues prop explicitly specifies which tick values to draw on the axis. + * @example ["apples", "bananas", "oranges"], [2, 4, 6, 8] + */ + tickValues?: any[]; } - + /** * VictoryAxis draws an SVG chart axis with React. * Styles and data can be customized by passing in your own values as properties to the component. * Data changes are animated with VictoryAnimation. */ export class VictoryAxis extends React.Component<VictoryAxisProps, any> {} - - export interface VictoryBarProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { - /** - * The alignment prop specifies how bars should be aligned relative to their data points. - * This prop may be given as “start”, “middle” or “end”. When this prop is not specified, - * bars will have “middle” alignment relative to their data points. - */ - alignment?: "start" | "middle" | "end"; - /** - * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. - * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will - * be used to calculate a default width for each bar given the total number of bars in the data series - * and the overall width of the chart. - */ - barRatio?: number; - /** - * The barWidth prop is used to specify the width of each bar. This prop may be given as - * a number of pixels or as a function that returns a number. When this prop is given as - * a function, it will be evaluated with the arguments datum, and active. When this value - * is not given, a default value will be calculated based on the overall dimensions of - * the chart, and the number of bars. - */ - barWidth?: NumberOrCallback; - /** - * The cornerRadius prop specifies a radius to apply to each bar. - * If this prop is given as a single number, the radius will only be applied to the top of each bar. - * When this prop is given as a function, it will be evaluated with the arguments datum, and active. - */ - cornerRadius?: NumberOrCallback - | { - top?: number | (NumberOrCallback), - topLeft?: number | (NumberOrCallback), - topRight?: number | (NumberOrCallback), - bottom?: number | (NumberOrCallback), - bottomLeft?: number | (NumberOrCallback), - bottomRight?: number | (NumberOrCallback) - }; - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryBar events. - * The eventKey may optionally be used to select a single element by index rather than an entire - * set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @example - * events={[ - * { - * target: "data", - * eventKey: "thisOne", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * eventKey: "theOtherOne", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * eventKey: "theOtherOne", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The style prop specifies styles for your VictoryBar. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. In addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; + + export interface VictoryBarProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { + /** + * The alignment prop specifies how bars should be aligned relative to their data points. + * This prop may be given as “start”, “middle” or “end”. When this prop is not specified, + * bars will have “middle” alignment relative to their data points. + */ + alignment?: "start" | "middle" | "end"; + /** + * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. + * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will + * be used to calculate a default width for each bar given the total number of bars in the data series + * and the overall width of the chart. + */ + barRatio?: number; + /** + * The barWidth prop is used to specify the width of each bar. This prop may be given as + * a number of pixels or as a function that returns a number. When this prop is given as + * a function, it will be evaluated with the arguments datum, and active. When this value + * is not given, a default value will be calculated based on the overall dimensions of + * the chart, and the number of bars. + */ + barWidth?: NumberOrCallback; + /** + * The cornerRadius prop specifies a radius to apply to each bar. + * If this prop is given as a single number, the radius will only be applied to the top of each bar. + * When this prop is given as a function, it will be evaluated with the arguments datum, and active. + */ + cornerRadius?: NumberOrCallback + | { + top?: number | (NumberOrCallback), + topLeft?: number | (NumberOrCallback), + topRight?: number | (NumberOrCallback), + bottom?: number | (NumberOrCallback), + bottomLeft?: number | (NumberOrCallback), + bottomRight?: number | (NumberOrCallback) + }; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryBar events. + * The eventKey may optionally be used to select a single element by index rather than an entire + * set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @example + * events={[ + * { + * target: "data", + * eventKey: "thisOne", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: "theOtherOne", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: "theOtherOne", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The style prop specifies styles for your VictoryBar. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. In addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; } - + /** * Draw SVG bar charts with React. VictoryBar is a composable component, so it doesn't include axes * Check out VictoryChart for complete bar charts and more. */ export class VictoryBar extends React.Component<VictoryBarProps, any> {} - - export interface VictoryBoxPlotStyleInterface - extends VictoryStyleInterface { - max?: VictoryStyleObject; - maxLabels?: VictoryStyleObject; - min?: VictoryStyleObject; - minLabels?: VictoryStyleObject; - median?: VictoryStyleObject; - medianLabels?: VictoryStyleObject; - q1?: VictoryStyleObject; - q1Labels?: VictoryStyleObject; - q3?: VictoryStyleObject; - q3Labels?: VictoryStyleObject; - } - - export interface VictoryBoxPlotProps - extends VictoryCommonProps, - VictoryDatableProps { - /** - * The boxWidth prop specifies how wide each box should be. If the whiskerWidth - * prop is not set, this prop will also determine the width of the whisker crosshair. - */ - boxWidth?: number; - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryChart, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The labelOrientation prop determines where labels are placed relative to their - * corresponding data. If this prop is not set, it will be set to “top” for - * horizontal charts, and “right” for vertical charts. - */ - labelOrientation?: "top" | "bottom" | "left" | "right"; - /** - * When the boolean labels prop is set to true, the values for min, max, median, - * q1, and q3 will be displayed for each box. For more granular label control, use - * the individual minLabels, maxLabels, medianLabels, q1Labels, and q3Labels props. - */ - labels?: boolean; - /** - * Use the max data accessor prop to define the max value of a box plot. - */ - max?: StringOrNumberOrCallback; - /** - * Use the median data accessor prop to define the median value of a box plot. - */ - median?: StringOrNumberOrCallback; - /** - * Use the min data accessor prop to define the min value of a box plot. - */ - min?: StringOrNumberOrCallback; - /** - * Use the q1 data accessor prop to define the q1 value of a box plot. - */ - q1?: StringOrNumberOrCallback; - /** - * Use the q3 data accessor prop to define the q1 value of a box plot. - */ - q3?: StringOrNumberOrCallback; - /** - * The style prop defines the style of the component. The style prop - * should be given as an object with styles defined for parent, max, - * maxLabels, min, minLabels,median, medianLabels,q1, q1Labels,q3, - * q3Labels. Any valid svg styles are supported, but width, height, a - * nd padding should be specified via props as they determine relative - * layout for components in VictoryChart. Functional styles may be - * defined for style properties, and they will be evaluated with each datum. - */ - style?: VictoryBoxPlotStyleInterface; - /** - * The whiskerWidth prop specifies how wide each whisker crosshair should be. If the - * whiskerWidth prop is not set, the width of the whisker crosshair will match - * the width of the box. - */ - whiskerWidth?: number; - } - - /** - * VictoryBoxPlot renders a box plot to describe the distribution of a set of data. Data for - * VictoryBoxPlot may be given with summary statistics pre-calculated (min, median, max, q1, q3), - * or as an array of raw data. VictoryBoxPlot can be composed with VictoryChart to create box plot charts. - */ - export class VictoryBoxPlot extends React.Component< - VictoryBoxPlotProps, - any - > {} - - export interface VictoryChartProps extends VictoryCommonProps { - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryChart, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The style prop specifies styles for your chart. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. - * @example {border: "1px solid #ccc", margin: "2%", maxWidth: "40%"} - */ - style?: Pick<VictoryStyleInterface, 'parent'>; - } - - /** - * A flexible charting component for React. - * VictoryChart composes other Victory components into reusable charts. - * Acting as a coordinator rather than a stand-alone component, VictoryChart reconciles props such as domain and scale for child components, - * and provides a set of sensible defaults. This component works with: - * - VictoryAxis - * - VictoryLine - * - VictoryScatter - * - VictoryBar - */ - export class VictoryChart extends React.Component<VictoryChartProps, any> {} - - export interface VictoryGroupProps extends VictoryCommonProps, VictoryMultiLabeableProps { + + export interface VictoryBoxPlotStyleInterface + extends VictoryStyleInterface { + max?: VictoryStyleObject; + maxLabels?: VictoryStyleObject; + min?: VictoryStyleObject; + minLabels?: VictoryStyleObject; + median?: VictoryStyleObject; + medianLabels?: VictoryStyleObject; + q1?: VictoryStyleObject; + q1Labels?: VictoryStyleObject; + q3?: VictoryStyleObject; + q3Labels?: VictoryStyleObject; + } + + export interface VictoryBoxPlotProps + extends VictoryCommonProps, + VictoryDatableProps { + /** + * The boxWidth prop specifies how wide each box should be. If the whiskerWidth + * prop is not set, this prop will also determine the width of the whisker crosshair. + */ + boxWidth?: number; + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryChart, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The labelOrientation prop determines where labels are placed relative to their + * corresponding data. If this prop is not set, it will be set to “top” for + * horizontal charts, and “right” for vertical charts. + */ + labelOrientation?: "top" | "bottom" | "left" | "right"; + /** + * When the boolean labels prop is set to true, the values for min, max, median, + * q1, and q3 will be displayed for each box. For more granular label control, use + * the individual minLabels, maxLabels, medianLabels, q1Labels, and q3Labels props. + */ + labels?: boolean; + /** + * Use the max data accessor prop to define the max value of a box plot. + */ + max?: StringOrNumberOrCallback; + /** + * Use the median data accessor prop to define the median value of a box plot. + */ + median?: StringOrNumberOrCallback; + /** + * Use the min data accessor prop to define the min value of a box plot. + */ + min?: StringOrNumberOrCallback; + /** + * Use the q1 data accessor prop to define the q1 value of a box plot. + */ + q1?: StringOrNumberOrCallback; + /** + * Use the q3 data accessor prop to define the q1 value of a box plot. + */ + q3?: StringOrNumberOrCallback; + /** + * The style prop defines the style of the component. The style prop + * should be given as an object with styles defined for parent, max, + * maxLabels, min, minLabels,median, medianLabels,q1, q1Labels,q3, + * q3Labels. Any valid svg styles are supported, but width, height, a + * nd padding should be specified via props as they determine relative + * layout for components in VictoryChart. Functional styles may be + * defined for style properties, and they will be evaluated with each datum. + */ + style?: VictoryBoxPlotStyleInterface; + /** + * The whiskerWidth prop specifies how wide each whisker crosshair should be. If the + * whiskerWidth prop is not set, the width of the whisker crosshair will match + * the width of the box. + */ + whiskerWidth?: number; + } + + /** + * VictoryBoxPlot renders a box plot to describe the distribution of a set of data. Data for + * VictoryBoxPlot may be given with summary statistics pre-calculated (min, median, max, q1, q3), + * or as an array of raw data. VictoryBoxPlot can be composed with VictoryChart to create box plot charts. + */ + export class VictoryBoxPlot extends React.Component< + VictoryBoxPlotProps, + any + > {} + + export interface VictoryChartProps extends VictoryCommonProps { + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryChart, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The style prop specifies styles for your chart. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. + * @example {border: "1px solid #ccc", margin: "2%", maxWidth: "40%"} + */ + style?: Pick<VictoryStyleInterface, 'parent'>; + } + + /** + * A flexible charting component for React. + * VictoryChart composes other Victory components into reusable charts. + * Acting as a coordinator rather than a stand-alone component, VictoryChart reconciles props such as domain and scale for child components, + * and provides a set of sensible defaults. This component works with: + * - VictoryAxis + * - VictoryLine + * - VictoryScatter + * - VictoryBar + */ + export class VictoryChart extends React.Component<VictoryChartProps, any> {} + + export interface VictoryGroupProps extends VictoryCommonProps, VictoryMultiLabeableProps { /** * The categories prop specifies how categorical data for a chart should be ordered. * This prop should be given as an array of string values, or an object with @@ -1731,7 +1731,7 @@ declare module "victory" { * } * ]} */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally * assign eventKeys to data @@ -1755,11 +1755,11 @@ declare module "victory" { * applied to all grouped children */ style?: VictoryStyleInterface; - } - - export class VictoryGroup extends React.Component<VictoryGroupProps, any> {} - - export interface VictoryLineProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { + } + + export class VictoryGroup extends React.Component<VictoryGroupProps, any> {} + + export interface VictoryLineProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { /** * The event prop take an array of event objects. Event objects are composed of * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace @@ -1797,7 +1797,7 @@ declare module "victory" { * } * ]} */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; + events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; /** * The interpolation prop determines how data points should be connected * when plotting a line @@ -1812,13 +1812,13 @@ declare module "victory" { * The labels prop defines the labels that will appear above each point. * This prop should be given as an array or as a function of data. */ - labels?: string[]|number[]|Function; + labels?: string[]|number[]|Function; /** * Use the sortKey prop to indicate how data should be sorted. This prop * is given directly to the lodash sortBy function to be executed on the * final dataset. */ - sortKey?: string|string[]|Function; + sortKey?: string|string[]|Function; /** * The style prop specifies styles for your VictoryLine. Any valid inline style properties * will be applied. Height, width, and padding should be specified via the height, @@ -1829,15 +1829,15 @@ declare module "victory" { * @examples{data: {stroke: "red"}, labels: {fontSize: 12}} */ style?: VictoryStyleInterface; - } - - /** - * VictoryLine creates a line based on data. VictoryLine is a composable component, so it does not include an axis. - * Check out VictoryChart for easy to use line charts and more. - */ - export class VictoryLine extends React.Component<VictoryLineProps, any> {} - - export interface VictoryLegendProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { + } + + /** + * VictoryLine creates a line based on data. VictoryLine is a composable component, so it does not include an axis. + * Check out VictoryChart for easy to use line charts and more. + */ + export class VictoryLine extends React.Component<VictoryLineProps, any> {} + + export interface VictoryLegendProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { /** * The colorScale prop defines a color scale to be applied to each data * symbol in VictoryLegend. This prop should be given as an array of CSS @@ -1883,11 +1883,11 @@ declare module "victory" { * The data prop must be given as an array. */ data?: Array<{ - name?: string; - symbol?: { - fill?: string; - type?: string; - }; + name?: string; + symbol?: { + fill?: string; + type?: string; + }; }>; /** * The itemsPerRow prop determines how many items to render in each row @@ -1942,7 +1942,7 @@ declare module "victory" { * displaying many series of data. * @default 'vertical' */ - orientation?: 'horizontal'|'vertical'; + orientation?: 'horizontal'|'vertical'; /** * The padding prop specifies the amount of padding in pixels between * the edge of the legend and any rendered child components. This prop @@ -1953,12 +1953,12 @@ declare module "victory" { * VictoryLegend, setting padding on the child component will have no * effect. */ - padding?: number | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; + padding?: number | { + top?: number; + bottom?: number; + left?: number; + right?: number; + }; /** * The standalone props specifies whether the component should be * rendered in an independent <svg> element or in a <g> tag. This prop @@ -1984,16 +1984,16 @@ declare module "victory" { */ x?: number; y?: number; - } - - /** - * VictoryLegend renders a chart legend component. - */ - export class VictoryLegend extends React.Component<VictoryLegendProps, any> {} - - type ScatterSymbolType = "circle" | "diamond" | "plus" | "square" | "star" | "triangleDown" | "triangleUp"; - - export interface VictoryScatterProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { + } + + /** + * VictoryLegend renders a chart legend component. + */ + export class VictoryLegend extends React.Component<VictoryLegendProps, any> {} + + type ScatterSymbolType = "circle" | "diamond" | "plus" | "square" | "star" | "triangleDown" | "triangleUp"; + + export interface VictoryScatterProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { /** * The bubbleProperty prop indicates which property of the data object should be used * to scale data points in a bubble chart @@ -2039,7 +2039,7 @@ declare module "victory" { * } * ]} */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally * assign eventKeys to data @@ -2072,15 +2072,15 @@ declare module "victory" { * The symbol prop determines which symbol should be drawn to represent data points. */ symbol?: ScatterSymbolType | { (data: any): ScatterSymbolType }; - } - - /** - * VictoryScatter creates a scatter of points from data. VictoryScatter is a composable component, so it does not include an axis. - * Check out VictoryChart for easy to use scatter plots and more. - */ - export class VictoryScatter extends React.Component<VictoryScatterProps, any> {} - - export interface VictoryStackProps extends VictoryCommonProps, VictoryMultiLabeableProps { + } + + /** + * VictoryScatter creates a scatter of points from data. VictoryScatter is a composable component, so it does not include an axis. + * Check out VictoryChart for easy to use scatter plots and more. + */ + export class VictoryScatter extends React.Component<VictoryScatterProps, any> {} + + export interface VictoryStackProps extends VictoryCommonProps, VictoryMultiLabeableProps { /** * The categories prop specifies how categorical data for a chart should be ordered. * This prop should be given as an array of string values, or an object with @@ -2156,7 +2156,7 @@ declare module "victory" { * } * ]} */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally * assign eventKeys to data @@ -2178,11 +2178,11 @@ declare module "victory" { * by the VictoryGroup component wrapper, or can be set manually. */ xOffset?: number; - } - - export class VictoryStack extends React.Component<VictoryStackProps, any> {} - - export interface VictoryPieProps extends VictoryCommonProps, VictoryMultiLabeableProps { + } + + export class VictoryStack extends React.Component<VictoryStackProps, any> {} + + export interface VictoryPieProps extends VictoryCommonProps, VictoryMultiLabeableProps { /** * The colorScale prop is an optional prop that defines the color scale the pie * will be created on. This prop should be given as an array of CSS colors, or as a string @@ -2262,7 +2262,7 @@ declare module "victory" { * } * ]} */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally * assign eventKeys to data @@ -2323,12 +2323,13 @@ declare module "victory" { * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) */ y?: DataGetterPropType; + } + + /** + * victory-pie draws an SVG pie or donut chart with React. + * Styles and data can be customized by passing in your own values as properties to the component. + * Data changes are animated with VictoryAnimation. + */ + export class VictoryPie extends React.Component<VictoryPieProps, any> {} } - - /** - * victory-pie draws an SVG pie or donut chart with React. - * Styles and data can be customized by passing in your own values as properties to the component. - * Data changes are animated with VictoryAnimation. - */ - export class VictoryPie extends React.Component<VictoryPieProps, any> {} -} + \ No newline at end of file From 54766514fa90919b8238abc6728a4edb66cf7b59 Mon Sep 17 00:00:00 2001 From: James Lismore <jlismore@gmail.com> Date: Wed, 6 Feb 2019 11:43:12 -0500 Subject: [PATCH 095/197] Second try and reverting bad whitespace fix --- types/victory/index.d.ts | 4313 +++++++++++++++++++------------------- 1 file changed, 2156 insertions(+), 2157 deletions(-) diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index c3468151ba..e2f1cb8111 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -11,1054 +11,1481 @@ /// <reference types="react"/> declare module "victory" { - import * as React from "react"; - + import * as React from "react"; + + /** + * Single animation object to interpolate + */ + export type AnimationStyle = { [key: string ]: string | number }; + + /** + * Animation styles to interpolate + */ + + export type AnimationData = AnimationStyle | AnimationStyle[]; + + export type AnimationEasing = + "back" | "backIn" | "backOut" | "backInOut" | "bounce" | "bounceIn" | "bounceOut" | + "bounceInOut" | "circle" | "circleIn" | "circleOut" | "circleInOut" | "linear" | + "linearIn" | "linearOut" | "linearInOut" | "cubic" | "cubicIn" | "cubicOut" | + "cubicInOut" | "elastic" | "elasticIn" | "elasticOut" | "elasticInOut" | "exp" | + "expIn" | "expOut" | "expInOut" | "poly" | "polyIn" | "polyOut" | "polyInOut" | + "quad" | "quadIn" | "quadOut" | "quadInOut" | "sin" | "sinIn" | "sinOut" | "sinInOut"; + + // Many victory components accept string or number or callback which returns string or number + type StringOrNumberOrCallback = + | string + | number + | ((datum: any, active: boolean) => string | number); + type NumberOrCallback = ((datum: any, active: boolean) => number) | number; + + type VictoryStyleObject = { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; + /** + * Style interface used in components/themeing + */ + export interface VictoryStyleInterface { + parent?: VictoryStyleObject; + data?: VictoryStyleObject; + labels?: VictoryStyleObject; + } + + export interface VictoryAnimationProps { /** - * Single animation object to interpolate + * The child of should be a function that takes an object of tweened values and returns a component to render. + * @param style */ - export type AnimationStyle = { [key: string ]: string | number }; - + children?: (style: AnimationStyle) => React.ReactElement<any>; /** - * Animation styles to interpolate + * The number of milliseconds the animation should take to complete. + * @default 1000 */ - - export type AnimationData = AnimationStyle | AnimationStyle[]; - - export type AnimationEasing = - "back" | "backIn" | "backOut" | "backInOut" | "bounce" | "bounceIn" | "bounceOut" | - "bounceInOut" | "circle" | "circleIn" | "circleOut" | "circleInOut" | "linear" | - "linearIn" | "linearOut" | "linearInOut" | "cubic" | "cubicIn" | "cubicOut" | - "cubicInOut" | "elastic" | "elasticIn" | "elasticOut" | "elasticInOut" | "exp" | - "expIn" | "expOut" | "expInOut" | "poly" | "polyIn" | "polyOut" | "polyInOut" | - "quad" | "quadIn" | "quadOut" | "quadInOut" | "sin" | "sinIn" | "sinOut" | "sinInOut"; - - // Many victory components accept string or number or callback which returns string or number - type StringOrNumberOrCallback = - | string - | number - | ((datum: any, active: boolean) => string | number); - type NumberOrCallback = ((datum: any, active: boolean) => number) | number; - - type VictoryStyleObject = { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; + duration?: number; /** - * Style interface used in components/themeing + * The easing prop specifies an easing function name to use for tweening. + * @default "quadInOut" */ - export interface VictoryStyleInterface { - parent?: VictoryStyleObject; - data?: VictoryStyleObject; - labels?: VictoryStyleObject; - } - - export interface VictoryAnimationProps { - /** - * The child of should be a function that takes an object of tweened values and returns a component to render. - * @param style - */ - children?: (style: AnimationStyle) => React.ReactElement<any>; - /** - * The number of milliseconds the animation should take to complete. - * @default 1000 - */ - duration?: number; - /** - * The easing prop specifies an easing function name to use for tweening. - * @default "quadInOut" - */ - easing?: AnimationEasing; - /** - * The delay prop specifies a delay in milliseconds before the animation begins. - * If multiple values are in the animation queue, it is the delay between each animation. - * @default 0 - */ - delay?: number; - /** - * The onEnd prop specifies a function to run when the animation ends. If multiple animations are in the queue, it is called after the last animation. - */ - onEnd?: () => void; - /** - * The data prop specifies the latest set of values to tween to. - * When this prop changes, VictoryAnimation will begin animating from the current value to the new value. - * When given an array of values, VictoryAnimation will use it as an animation queue. - * @default {} - */ - data?: AnimationData; - } - + easing?: AnimationEasing; /** - * VictoryAnimation animates prop changes for any React component. - * Just use a child function inside VictoryAnimation that accepts an object of tweened values and returns a component to render. + * The delay prop specifies a delay in milliseconds before the animation begins. + * If multiple values are in the animation queue, it is the delay between each animation. + * @default 0 */ - export class VictoryAnimation extends React.Component<VictoryAnimationProps, any> {} - + delay?: number; /** - * Text anchor type + * The onEnd prop specifies a function to run when the animation ends. If multiple animations are in the queue, it is called after the last animation. */ - type TextAnchorType = "start" | "middle" | "end" | "inherit"; - + onEnd?: () => void; /** - * Vertical anchor type + * The data prop specifies the latest set of values to tween to. + * When this prop changes, VictoryAnimation will begin animating from the current value to the new value. + * When given an array of values, VictoryAnimation will use it as an animation queue. + * @default {} */ - type VerticalAnchorType = "start" | "middle" | "end"; - - export interface VictoryLabelProps { - /** - * Specifies the angle to rotate the text by. - */ - angle?: string | number; - /** - * The capHeight prop defines a text metric for the font being used: the expected height of capital letters. - * This is necessary because of SVG, which (a) positions the *bottom* of the text at `y`, and (b) has no notion of line height. - * The value should ideally use the same units as `lineHeight` and `dy`, preferably ems. If given a unitless number, it is assumed to be ems. - * @default "0.71em" - */ - capHeight?: StringOrNumberOrCallback; - /** - * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine child text - */ - datum?: {}; - /** - * Labels that apply to an entire data series will recieve the entire series as `data` instead of an individual datum prop. - */ - data?: any[]; - /** - * The events prop attaches arbitrary event handlers to the label component. - * Event handlers are currently only called with their corresponding events. - */ - events?: React.DOMAttributes<any>; - /** - * The children of this component define the content of the label. - * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. - */ - children?: StringOrNumberOrCallback; - /** - * The labelPlacement prop is used to specify the placement of labels relative to the data point they represent. - * This prop may be given as “vertical”, “parallel” or “perpendicular”. This props is particularly useful in polar - * charts, where it may be desireable to position a label either parallel or perpendicular to its corresponding angle. - * When this prop is not set, perpendicular label placement will be used for polar charts, and vertical label - * placement will be used for cartesian charts. - */ - labelPlacement?: "parallel" | "perpendicular" | "vertical"; - /** - * The lineHeight prop defines how much space a single line of text should take up. - * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, - * but the result is similar: a roughly equal amount of extra space is distributed above and below the line of text. - * The value should ideally use the same units as `capHeight` and `dy`, preferably ems. - * If given a unitless number, it is assumed to be ems. - * @default 1 - */ - lineHeight?: StringOrNumberOrCallback; - /** - * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. - * **This prop should not be set manually.** - */ - origin?: { x: number, y: number }; - /** - * Victory components can pass a boolean polar prop to specify whether a label is part of a polar chart. - * **This prop should not be set manually.** - */ - polar?: boolean; - /** - * The renderInPortal prop specifies whether VictoryLabel should render text in place or within a VictoryPortal. - * Setting renderInPortal to true is equivalent to wrapping VictoryLabel in a VictoryPortal. This prop is false by default. - */ - renderInPortal?: boolean; - /** - * The style prop applies CSS properties to the rendered `<text>` element. - */ - style?: React.CSSProperties; - /** - * The text prop defines the text VictoryLabel will render. The text prop may be given as a string, number, a function of datum, - * or an array of any of these. Strings may include newline characters, which VictoryLabel will split into separate - * <tspan/> elements. When text is given as an array, separate <tspan/> elements will be created for each element in the array. - */ - text?: string[] | StringOrNumberOrCallback; - /** - * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. - */ - textAnchor?: TextAnchorType | { (): TextAnchorType }; - /** - * The verticalAnchor prop defines how the text is vertically positioned relative to the given `x` and `y` coordinates. - */ - verticalAnchor?: VerticalAnchorType | { (): VerticalAnchorType }; - /** - * The transform prop applies a transform to the rendered `<text>` element. - * In addition to being a string, it can be an object containing transform definitions for easier authoring. - */ - transform?: string | {} | { (): string | {} }; - /** - * The x prop defines the x coordinate to use as a basis for horizontal positioning. - */ - x?: number; - /** - * The y prop defines the y coordinate to use as a basis for vertical positioning. - */ - y?: number; - /** - * The dx prop defines a horizontal shift from the `x` coordinate. - */ - dx?: StringOrNumberOrCallback; - /** - * The dy prop defines a vertical shift from the `y` coordinate. - * Since this component already accounts for `capHeight`, `lineHeight`, and `verticalAnchor`, this will usually not be necessary. - */ - dy?: StringOrNumberOrCallback; - } - + data?: AnimationData; + } + + /** + * VictoryAnimation animates prop changes for any React component. + * Just use a child function inside VictoryAnimation that accepts an object of tweened values and returns a component to render. + */ + export class VictoryAnimation extends React.Component<VictoryAnimationProps, any> {} + + /** + * Text anchor type + */ + type TextAnchorType = "start" | "middle" | "end" | "inherit"; + + /** + * Vertical anchor type + */ + type VerticalAnchorType = "start" | "middle" | "end"; + + export interface VictoryLabelProps { /** - * VictoryLabel is a text component that provides several enhancements over SVG’s <text> element. + * Specifies the angle to rotate the text by. */ - export class VictoryLabel extends React.Component<VictoryLabelProps, any> {} - - export interface VictoryContainerProps { - /** - * The responsive prop specifies whether the rendered container should be a responsive container - * with a viewBox attribute, or a static container with absolute width and height. - * @default true - */ - responsive?: boolean; - /** - * The style prop specifies styles for your VictoryContainer. Any valid inline style properties - * will be applied. Height and width should be specified via the height - * and width props, as they are used to calculate the alignment of - * components within the container. Styles from the child component will - * also be passed, if any exist. - * @examples {border: 1px solid red} - */ - style?: React.CSSProperties; - /** - * The height props specifies the height the svg viewBox of the container. - * This value should be given as a number of pixels. If no height prop - * is given, the height prop from the child component passed will be used. - */ - height?: number; - /** - * The width props specifies the width of the svg viewBox of the container - * This value should be given as a number of pixels. If no width prop - * is given, the width prop from the child component passed will be used. - */ - width?: number; - /** - * The events prop attaches arbitrary event handlers to the container component. - * Event handlers passed from other Victory components are called with their - * corresponding events as well as scale, style, width, height, and data when - * applicable. Use the invert method to convert event coordinate information to - * data. `scale.x.invert(evt.offsetX)`. - * @examples {{ onClick: (evt) => alert(`x: ${evt.clientX}, y: ${evt.clientY}`)}} - */ - events?: React.DOMAttributes<any>; - /** - * The title prop specifies the title to be applied to the SVG to assist - * accessibility for screen readers. The more descriptive this title is, the more - * useful it will be. If no title prop is passed, it will default to Victory Chart. - * @example "Popularity of Dog Breeds by Percentage" - * @default "Victory Chart" - */ - title?: string; - /** - * The desc prop specifies the description of the chart/SVG to assist with - * accessibility for screen readers. The more info about the chart provided in - * the description, the more usable it will be for people using screen readers. - * This prop defaults to an empty string. - * @example "Golden retreivers make up 30%, Labs make up 25%, and other dog breeds are - * not represented above 5% each." - * @default "" - */ - desc?: string; - } - - export class VictoryContainer extends React.Component<VictoryContainerProps, any> {} - - type CursorData = { - x: number; - y: number; + angle?: string | number; + /** + * The capHeight prop defines a text metric for the font being used: the expected height of capital letters. + * This is necessary because of SVG, which (a) positions the *bottom* of the text at `y`, and (b) has no notion of line height. + * The value should ideally use the same units as `lineHeight` and `dy`, preferably ems. If given a unitless number, it is assumed to be ems. + * @default "0.71em" + */ + capHeight?: StringOrNumberOrCallback; + /** + * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine child text + */ + datum?: {}; + /** + * Labels that apply to an entire data series will recieve the entire series as `data` instead of an individual datum prop. + */ + data?: any[]; + /** + * The events prop attaches arbitrary event handlers to the label component. + * Event handlers are currently only called with their corresponding events. + */ + events?: React.DOMAttributes<any>; + /** + * The children of this component define the content of the label. + * This makes using the component similar to normal HTML spans or labels. strings, numbers, and functions of data / value are supported. + */ + children?: StringOrNumberOrCallback; + /** + * The labelPlacement prop is used to specify the placement of labels relative to the data point they represent. + * This prop may be given as “vertical”, “parallel” or “perpendicular”. This props is particularly useful in polar + * charts, where it may be desireable to position a label either parallel or perpendicular to its corresponding angle. + * When this prop is not set, perpendicular label placement will be used for polar charts, and vertical label + * placement will be used for cartesian charts. + */ + labelPlacement?: "parallel" | "perpendicular" | "vertical"; + /** + * The lineHeight prop defines how much space a single line of text should take up. + * Note that SVG has no notion of line-height, so the positioning may differ slightly from what you would expect with CSS, + * but the result is similar: a roughly equal amount of extra space is distributed above and below the line of text. + * The value should ideally use the same units as `capHeight` and `dy`, preferably ems. + * If given a unitless number, it is assumed to be ems. + * @default 1 + */ + lineHeight?: StringOrNumberOrCallback; + /** + * Victory components will pass an origin prop is to define the center point in svg coordinates for polar charts. + * **This prop should not be set manually.** + */ + origin?: { x: number, y: number }; + /** + * Victory components can pass a boolean polar prop to specify whether a label is part of a polar chart. + * **This prop should not be set manually.** + */ + polar?: boolean; + /** + * The renderInPortal prop specifies whether VictoryLabel should render text in place or within a VictoryPortal. + * Setting renderInPortal to true is equivalent to wrapping VictoryLabel in a VictoryPortal. This prop is false by default. + */ + renderInPortal?: boolean; + /** + * The style prop applies CSS properties to the rendered `<text>` element. + */ + style?: React.CSSProperties; + /** + * The text prop defines the text VictoryLabel will render. The text prop may be given as a string, number, a function of datum, + * or an array of any of these. Strings may include newline characters, which VictoryLabel will split into separate + * <tspan/> elements. When text is given as an array, separate <tspan/> elements will be created for each element in the array. + */ + text?: string[] | StringOrNumberOrCallback; + /** + * The textAnchor prop defines how the text is horizontally positioned relative to the given `x` and `y` coordinates. + */ + textAnchor?: TextAnchorType | { (): TextAnchorType }; + /** + * The verticalAnchor prop defines how the text is vertically positioned relative to the given `x` and `y` coordinates. + */ + verticalAnchor?: VerticalAnchorType | { (): VerticalAnchorType }; + /** + * The transform prop applies a transform to the rendered `<text>` element. + * In addition to being a string, it can be an object containing transform definitions for easier authoring. + */ + transform?: string | {} | { (): string | {} }; + /** + * The x prop defines the x coordinate to use as a basis for horizontal positioning. + */ + x?: number; + /** + * The y prop defines the y coordinate to use as a basis for vertical positioning. + */ + y?: number; + /** + * The dx prop defines a horizontal shift from the `x` coordinate. + */ + dx?: StringOrNumberOrCallback; + /** + * The dy prop defines a vertical shift from the `y` coordinate. + * Since this component already accounts for `capHeight`, `lineHeight`, and `verticalAnchor`, this will usually not be necessary. + */ + dy?: StringOrNumberOrCallback; + } + + /** + * VictoryLabel is a text component that provides several enhancements over SVG’s <text> element. + */ + export class VictoryLabel extends React.Component<VictoryLabelProps, any> {} + + export interface VictoryContainerProps { + /** + * The responsive prop specifies whether the rendered container should be a responsive container + * with a viewBox attribute, or a static container with absolute width and height. + * @default true + */ + responsive?: boolean; + /** + * The style prop specifies styles for your VictoryContainer. Any valid inline style properties + * will be applied. Height and width should be specified via the height + * and width props, as they are used to calculate the alignment of + * components within the container. Styles from the child component will + * also be passed, if any exist. + * @examples {border: 1px solid red} + */ + style?: React.CSSProperties; + /** + * The height props specifies the height the svg viewBox of the container. + * This value should be given as a number of pixels. If no height prop + * is given, the height prop from the child component passed will be used. + */ + height?: number; + /** + * The width props specifies the width of the svg viewBox of the container + * This value should be given as a number of pixels. If no width prop + * is given, the width prop from the child component passed will be used. + */ + width?: number; + /** + * The events prop attaches arbitrary event handlers to the container component. + * Event handlers passed from other Victory components are called with their + * corresponding events as well as scale, style, width, height, and data when + * applicable. Use the invert method to convert event coordinate information to + * data. `scale.x.invert(evt.offsetX)`. + * @examples {{ onClick: (evt) => alert(`x: ${evt.clientX}, y: ${evt.clientY}`)}} + */ + events?: React.DOMAttributes<any>; + /** + * The title prop specifies the title to be applied to the SVG to assist + * accessibility for screen readers. The more descriptive this title is, the more + * useful it will be. If no title prop is passed, it will default to Victory Chart. + * @example "Popularity of Dog Breeds by Percentage" + * @default "Victory Chart" + */ + title?: string; + /** + * The desc prop specifies the description of the chart/SVG to assist with + * accessibility for screen readers. The more info about the chart provided in + * the description, the more usable it will be for people using screen readers. + * This prop defaults to an empty string. + * @example "Golden retreivers make up 30%, Labs make up 25%, and other dog breeds are + * not represented above 5% each." + * @default "" + */ + desc?: string; + } + + export class VictoryContainer extends React.Component<VictoryContainerProps, any> {} + + type CursorData = { + x: number; + y: number; + }; + + export interface VictoryCursorContainerProps extends VictoryContainerProps { + /** + * The cursorComponent prop takes a component instance which will be used to render a cursor element. + * The new element created will be supplied with x1, y1, x2 and y2 positioning props. + * If a cursorComponent is not supplied, a new Line component will be rendered. + * @default cursorComponent={<Line/>} + */ + cursorComponent?: React.ReactElement<any>; + /** + * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). + * When this prop is not specified, the cursor will be a 2-dimensional crosshair. + * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; + * the cursor will then be a vertical line that will inspect the time value of the current mouse position. + * @example cursorDimension="x" + */ + cursorDimension?: 'x' | 'y'; + /** + * The cursorLabel prop defines the label that will appear next to the cursor. + * A label will only appear if cursorLabel is set. This prop should be given as a + * function of a point (an Object with x and y properties). + * @example cursorLabel={(point) => point.x} + */ + cursorLabel?: (point: CursorData) => void; + /** + * The cursorLabelComponent prop takes a component instance which will be + * used to render a label for the cursor. The new element created from the passed + * cursorLabelComponent will be supplied with the following props: x, y, + * active, text. If cursorLabelComponent is omitted, a new VictoryLabel will be created with the props described above. + * @default cursorLabelComponent={<VictoryLabel/>} + */ + cursorLabelComponent?: React.ReactElement<any>; + /** + * The cursorLabelOffset prop determines the pixel offset of the cursor label + * from the cursor point. This prop should be an Object with x and y properties, or a + * number to be used for both dimensions. + * @default "{ x: 5, y: -10 }" + */ + cursorLabelOffset?: number | CursorData; + /** + * Whenever the mouse is not over the chart, the cursor will not be displayed. + * If instead you would like to keep it displayed, use the defaultCursorValue prop to set the default value. + * The prop should be a point (an Object with x and y properties) for 2-dimensional cursors, or a number for 1-dimensional cursors. + * @example defaultCursorValue={{x: 1, y: 1}}, defaultCursorValue={0}} + */ + defaultCursorValue?: number | CursorData; + /** + * When the disable prop is set to true, VictoryCursorContainer events will not fire. + */ + disable?: boolean; + /** + * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). + * When this prop is not specified, the cursor will be a 2-dimensional crosshair. + * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; + * the cursor will then be a vertical line that will inspect the time value of the current mouse position. + * @example onChange={(value, props) => this.setState({cursorValue: value})} + */ + onCursorChange?: (value: CursorData, props: VictoryCursorContainerProps) => void; + } + + export class VictoryCursorContainer extends React.Component<VictoryCursorContainerProps, any> {} + + export interface VictoryBrushContainerProps extends VictoryContainerProps { + /** + * The optional allowDrag prop accepts a boolean that enables dragging behavior + * for the highlighted brush area. Resizing will still be enabled when the allowDrag + * prop is set to false. + * @default true + */ + allowDrag?: boolean; + /** + * The optional allowResize prop accepts a boolean that enables resizing the + * highlighted brush area. Dragging will still be enabled when the allowResize + * prop is set to false, but the dimensions of the brush area will be fixed. + * @default true + */ + allowResize?: boolean; + /** + * The brushComponent prop specifies the component to be rendered for the + * highlighted area. This component will be supplied with the following props: x, y, + * width, height, and style. When this prop is not specified, a <rect/> will be rendered. + * @default brushComponent={<rect/>} + */ + brushComponent?: React.ReactElement<any>; + /** + * When the brushDimension prop is set, brushing will only be specific to the to + * the given dimension (either "x" or "y"), and the entire domain of the other + * dimension will be highlighted. When this prop is not specified, highlighting will + * occur along both dimensions. + * @example brushDimension="x" + */ + brushDimension?: 'x' | 'y'; + /** + * The optional brushDomain prop describes the highlighted state. This prop is an + * object that specifies separate arrays for x and y. Each array is a tuple that + * describes the minimum and maximum values to render. If this prop is not provided + * initially, the chart will render with the entire domain highlighted. When this prop + * changes, the chart will render with a new highlighted domain. + * @example brushDomain={{ x: [50, 100], y: [0, 100] }} + */ + brushDomain?: DomainPropType; + /** + * The brushStyle adds custom styles to the brushComponent. This prop + * should be given as an object of SVG style attributes. + * @default "brushStyle={{ stroke: "transparent", fill: "black", fillOpacity: 0.1 }}" + */ + brushStyle?: React.CSSProperties; + /** + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the + * prop is set to "all", the entire domain will be selected. When the prop is set to "none", + * no new region will be selected, and any existing active brush will be cleared. When + * the prop is set to "disable" the new selected region will default to the current active brush. + */ + defaultBrushArea?: 'all' | 'none' | 'disable'; + /** + * When the disable prop is set to true, VictoryBrushContainer events will not fire. + */ + disable?: boolean; + /** + * The handleComponent prop specifies the component to be rendered for each + * handle for the highlighted area. This component will be supplied with the following + * props: x, y, width, height, cursor, and style. When this prop is not + * specified, a <rect/> will be rendered. + * @default handleComponent={<rect/>} + */ + handleComponent?: React.ReactElement<any>; + /** + * The handleStyle adds custom styles to the handleComponents. This prop should be given as an object of SVG style attributes. + * + * Handles refer to the region on each highlighted area where the area may be + * expanded. Only handles relevant to the given dimension will be rendered. For + * example, when brushDimension="x" only "left" and "right" handles will be + * rendered. Handles are automatically styled with cursors appropriate to their orientation. + * @default "handleStyle={{ stroke: 'transparent', fill: 'transparent' }}" + */ + handleStyle?: React.CSSProperties; + /** + * The optional onBrushDomainChange prop accepts an function to be called on + * each update to the highlighted domain. The function accepts the parameters of + * domain (the updated domain), and props (the props used by VictoryBrushContainer). + * @example onBrushDomainChange={(domain, props) => handleDomainChange(domain, props)} + */ + onBrushDomainChange?: (domain: DomainPropType, props: VictoryBrushContainerProps) => void; + } + + export class VictoryBrushContainer extends React.Component<VictoryBrushContainerProps, any> {} + + export interface VictoryZoomContainerProps extends VictoryContainerProps { + /** + * The optional allowPan prop accepts a boolean that enables the panning + * functionality. Zooming will still be enabled when the allowPan prop is set to false. + * @default true + */ + allowPan?: boolean; + /** + * The optional allowZoom prop accepts a boolean that enables the zoom + * functionality. Panning will still be enabled when the allowZoom prop is set to false. + * @default true + */ + allowZoom?: boolean; + /** + * VictoryZoomContainer works by clipping data outside of a given domain. + * VictoryZoomContainer uses VictoryClipContainer by default. + * This prop should not be replaced with a custom component, but you may want to set + * props on VictoryClipContainer, such as clipPadding. + * @example clipContainerComponent={<VictoryClipContainer clipPadding={{top: 10, right: 10}}}/>} + */ + clipContainerComponent?: React.ReactElement<any>; + /** + * When the zoomDimension prop is set, panning and zooming will be restricted to + * the given dimension (either x or y), and the domain of the other dimension will + * remain static. When this prop is not specified, both x and y dimensions will pan and zoom. + * @example zoomDimension="x" + */ + zoomDimension?: 'x' | 'y'; + /** + * The zoomDomain prop describes the zoomed state. This prop is an object that + * specifies separate arrays for x and y. Each array is a tuple that describes the + * minimum and maximum values to render. If this prop is not provided initially, the + * chart will render without an initial zoom, displaying the entire dataset. Updates to + * zoomDomain will trigger a re-render of the chart with the new domain. + * @example zoomDomain={{x: [0, 100]}} + */ + zoomDomain?: DomainPropType; + /** + * The brushStyle adds custom styles to the brushComponent. This prop + * should be given as an object of SVG style attributes. + * @default "brushStyle={{ stroke: 'transparent', fill: 'black', fillOpacity: 0.1 }}" + */ + brushStyle?: React.CSSProperties; + /** + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the + * prop is set to "all", the entire domain will be selected. When the prop is set to "none", + * no new region will be selected, and any existing active brush will be cleared. When + * the prop is set to "disable" the new selected region will default to the current active brush. + */ + defaultBrushArea?: 'all' | 'none' | 'disable'; + /** + * When the disable prop is set to true, VictoryBrushContainer events will not fire. + */ + disable?: boolean; + /** + * When the disable prop is set to true, VictoryZoomContainer events will not fire. + */ + downsample?: number | boolean; + /** + * The minimumZoom prop sets a minimum domain extent for the zoomed chart. + * When the difference between the maximum and minimum of a zoomed domain is equal to the minimumZoom + * in either dimension, the component will stop responding to events that would normally trigger zooming in. + * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum + * zoom will cover 1 / 1000th of the original domain. This prop should be given as an object + * with numeric values for x and y. + * @example minimumZoom={{x: 1, y: 0.01}} + */ + minimumZoom?: CursorData; + /** + * The optional onZoomDomainChange prop accepts an function to be called on each update to the visible domain. + * The function accepts the parameters domain (the updated domain) and props (the props used by VictoryZoomContainer). + * @example onZoomDomainChange={(domain, props) => handleDomainChange(domain, props)} + */ + onZoomDomainChange?: (domain: DomainPropType, props: VictoryZoomContainerProps) => void; + } + + export class VictoryZoomContainer extends React.Component<VictoryZoomContainerProps, any> {} + + // Note: Many SVG attributes are missed in CSSProperties interface + export interface VictoryThemeDefinition { + area?: VictoryStyleInterface; + axis?: { + axis: React.CSSProperties; + axisLabel: React.CSSProperties; + grid: React.CSSProperties; + ticks: React.CSSProperties; + tickLabels: React.CSSProperties; }; - - export interface VictoryCursorContainerProps extends VictoryContainerProps { - /** - * The cursorComponent prop takes a component instance which will be used to render a cursor element. - * The new element created will be supplied with x1, y1, x2 and y2 positioning props. - * If a cursorComponent is not supplied, a new Line component will be rendered. - * @default cursorComponent={<Line/>} - */ - cursorComponent?: React.ReactElement<any>; - /** - * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). - * When this prop is not specified, the cursor will be a 2-dimensional crosshair. - * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; - * the cursor will then be a vertical line that will inspect the time value of the current mouse position. - * @example cursorDimension="x" - */ - cursorDimension?: 'x' | 'y'; - /** - * The cursorLabel prop defines the label that will appear next to the cursor. - * A label will only appear if cursorLabel is set. This prop should be given as a - * function of a point (an Object with x and y properties). - * @example cursorLabel={(point) => point.x} - */ - cursorLabel?: (point: CursorData) => void; - /** - * The cursorLabelComponent prop takes a component instance which will be - * used to render a label for the cursor. The new element created from the passed - * cursorLabelComponent will be supplied with the following props: x, y, - * active, text. If cursorLabelComponent is omitted, a new VictoryLabel will be created with the props described above. - * @default cursorLabelComponent={<VictoryLabel/>} - */ - cursorLabelComponent?: React.ReactElement<any>; - /** - * The cursorLabelOffset prop determines the pixel offset of the cursor label - * from the cursor point. This prop should be an Object with x and y properties, or a - * number to be used for both dimensions. - * @default "{ x: 5, y: -10 }" - */ - cursorLabelOffset?: number | CursorData; - /** - * Whenever the mouse is not over the chart, the cursor will not be displayed. - * If instead you would like to keep it displayed, use the defaultCursorValue prop to set the default value. - * The prop should be a point (an Object with x and y properties) for 2-dimensional cursors, or a number for 1-dimensional cursors. - * @example defaultCursorValue={{x: 1, y: 1}}, defaultCursorValue={0}} - */ - defaultCursorValue?: number | CursorData; - /** - * When the disable prop is set to true, VictoryCursorContainer events will not fire. - */ - disable?: boolean; - /** - * When the cursorDimension prop is set, the cursor will be a line to inspect the given dimension (either "x" or "y"). - * When this prop is not specified, the cursor will be a 2-dimensional crosshair. - * For example, if you would like to inspect the time of time-series data, set dimension={"x"}; - * the cursor will then be a vertical line that will inspect the time value of the current mouse position. - * @example onChange={(value, props) => this.setState({cursorValue: value})} - */ - onCursorChange?: (value: CursorData, props: VictoryCursorContainerProps) => void; - } - - export class VictoryCursorContainer extends React.Component<VictoryCursorContainerProps, any> {} - - export interface VictoryBrushContainerProps extends VictoryContainerProps { - /** - * The optional allowDrag prop accepts a boolean that enables dragging behavior - * for the highlighted brush area. Resizing will still be enabled when the allowDrag - * prop is set to false. - * @default true - */ - allowDrag?: boolean; - /** - * The optional allowResize prop accepts a boolean that enables resizing the - * highlighted brush area. Dragging will still be enabled when the allowResize - * prop is set to false, but the dimensions of the brush area will be fixed. - * @default true - */ - allowResize?: boolean; - /** - * The brushComponent prop specifies the component to be rendered for the - * highlighted area. This component will be supplied with the following props: x, y, - * width, height, and style. When this prop is not specified, a <rect/> will be rendered. - * @default brushComponent={<rect/>} - */ - brushComponent?: React.ReactElement<any>; - /** - * When the brushDimension prop is set, brushing will only be specific to the to - * the given dimension (either "x" or "y"), and the entire domain of the other - * dimension will be highlighted. When this prop is not specified, highlighting will - * occur along both dimensions. - * @example brushDimension="x" - */ - brushDimension?: 'x' | 'y'; - /** - * The optional brushDomain prop describes the highlighted state. This prop is an - * object that specifies separate arrays for x and y. Each array is a tuple that - * describes the minimum and maximum values to render. If this prop is not provided - * initially, the chart will render with the entire domain highlighted. When this prop - * changes, the chart will render with a new highlighted domain. - * @example brushDomain={{ x: [50, 100], y: [0, 100] }} - */ - brushDomain?: DomainPropType; - /** - * The brushStyle adds custom styles to the brushComponent. This prop - * should be given as an object of SVG style attributes. - * @default "brushStyle={{ stroke: "transparent", fill: "black", fillOpacity: 0.1 }}" - */ - brushStyle?: React.CSSProperties; - /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the - * prop is set to "all", the entire domain will be selected. When the prop is set to "none", - * no new region will be selected, and any existing active brush will be cleared. When - * the prop is set to "disable" the new selected region will default to the current active brush. - */ - defaultBrushArea?: 'all' | 'none' | 'disable'; - /** - * When the disable prop is set to true, VictoryBrushContainer events will not fire. - */ - disable?: boolean; - /** - * The handleComponent prop specifies the component to be rendered for each - * handle for the highlighted area. This component will be supplied with the following - * props: x, y, width, height, cursor, and style. When this prop is not - * specified, a <rect/> will be rendered. - * @default handleComponent={<rect/>} - */ - handleComponent?: React.ReactElement<any>; - /** - * The handleStyle adds custom styles to the handleComponents. This prop should be given as an object of SVG style attributes. - * - * Handles refer to the region on each highlighted area where the area may be - * expanded. Only handles relevant to the given dimension will be rendered. For - * example, when brushDimension="x" only "left" and "right" handles will be - * rendered. Handles are automatically styled with cursors appropriate to their orientation. - * @default "handleStyle={{ stroke: 'transparent', fill: 'transparent' }}" - */ - handleStyle?: React.CSSProperties; - /** - * The optional onBrushDomainChange prop accepts an function to be called on - * each update to the highlighted domain. The function accepts the parameters of - * domain (the updated domain), and props (the props used by VictoryBrushContainer). - * @example onBrushDomainChange={(domain, props) => handleDomainChange(domain, props)} - */ - onBrushDomainChange?: (domain: DomainPropType, props: VictoryBrushContainerProps) => void; - } - - export class VictoryBrushContainer extends React.Component<VictoryBrushContainerProps, any> {} - - export interface VictoryZoomContainerProps extends VictoryContainerProps { - /** - * The optional allowPan prop accepts a boolean that enables the panning - * functionality. Zooming will still be enabled when the allowPan prop is set to false. - * @default true - */ - allowPan?: boolean; - /** - * The optional allowZoom prop accepts a boolean that enables the zoom - * functionality. Panning will still be enabled when the allowZoom prop is set to false. - * @default true - */ - allowZoom?: boolean; - /** - * VictoryZoomContainer works by clipping data outside of a given domain. - * VictoryZoomContainer uses VictoryClipContainer by default. - * This prop should not be replaced with a custom component, but you may want to set - * props on VictoryClipContainer, such as clipPadding. - * @example clipContainerComponent={<VictoryClipContainer clipPadding={{top: 10, right: 10}}}/>} - */ - clipContainerComponent?: React.ReactElement<any>; - /** - * When the zoomDimension prop is set, panning and zooming will be restricted to - * the given dimension (either x or y), and the domain of the other dimension will - * remain static. When this prop is not specified, both x and y dimensions will pan and zoom. - * @example zoomDimension="x" - */ - zoomDimension?: 'x' | 'y'; - /** - * The zoomDomain prop describes the zoomed state. This prop is an object that - * specifies separate arrays for x and y. Each array is a tuple that describes the - * minimum and maximum values to render. If this prop is not provided initially, the - * chart will render without an initial zoom, displaying the entire dataset. Updates to - * zoomDomain will trigger a re-render of the chart with the new domain. - * @example zoomDomain={{x: [0, 100]}} - */ - zoomDomain?: DomainPropType; - /** - * The brushStyle adds custom styles to the brushComponent. This prop - * should be given as an object of SVG style attributes. - * @default "brushStyle={{ stroke: 'transparent', fill: 'black', fillOpacity: 0.1 }}" - */ - brushStyle?: React.CSSProperties; - /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the - * prop is set to "all", the entire domain will be selected. When the prop is set to "none", - * no new region will be selected, and any existing active brush will be cleared. When - * the prop is set to "disable" the new selected region will default to the current active brush. - */ - defaultBrushArea?: 'all' | 'none' | 'disable'; - /** - * When the disable prop is set to true, VictoryBrushContainer events will not fire. - */ - disable?: boolean; - /** - * When the disable prop is set to true, VictoryZoomContainer events will not fire. - */ - downsample?: number | boolean; - /** - * The minimumZoom prop sets a minimum domain extent for the zoomed chart. - * When the difference between the maximum and minimum of a zoomed domain is equal to the minimumZoom - * in either dimension, the component will stop responding to events that would normally trigger zooming in. - * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum - * zoom will cover 1 / 1000th of the original domain. This prop should be given as an object - * with numeric values for x and y. - * @example minimumZoom={{x: 1, y: 0.01}} - */ - minimumZoom?: CursorData; - /** - * The optional onZoomDomainChange prop accepts an function to be called on each update to the visible domain. - * The function accepts the parameters domain (the updated domain) and props (the props used by VictoryZoomContainer). - * @example onZoomDomainChange={(domain, props) => handleDomainChange(domain, props)} - */ - onZoomDomainChange?: (domain: DomainPropType, props: VictoryZoomContainerProps) => void; - } - - export class VictoryZoomContainer extends React.Component<VictoryZoomContainerProps, any> {} - - // Note: Many SVG attributes are missed in CSSProperties interface - export interface VictoryThemeDefinition { - area?: VictoryStyleInterface; - axis?: { - axis: React.CSSProperties; - axisLabel: React.CSSProperties; - grid: React.CSSProperties; - ticks: React.CSSProperties; - tickLabels: React.CSSProperties; - }; - bar?: VictoryStyleInterface; - candlestick?: VictoryStyleInterface & { - props: { - width: number; - height: number; - candleColors: { - positive: string; - negative: string; - }; + bar?: VictoryStyleInterface; + candlestick?: VictoryStyleInterface & { + props: { + width: number; + height: number; + candleColors: { + positive: string; + negative: string; }; }; - line?: VictoryStyleInterface; - pie?: { - props: { - width: number; - height: number; - colorScale: string[]; - }; - style: VictoryStyleInterface; - }; - scatter?: VictoryStyleInterface; - props?: { + }; + line?: VictoryStyleInterface; + pie?: { + props: { width: number; height: number; colorScale: string[]; }; - } - - interface VictoryThemeInterface { - /** - * Default theme - */ - grayscale: VictoryThemeDefinition; - material: VictoryThemeDefinition; - } - - /** - * Available themes - */ - export const VictoryTheme: VictoryThemeInterface; - - type OrientationTypes = "top" | "bottom" | "left" | "right"; - - export interface VictoryTooltipProps { - /** - * The active prop specifies whether the tooltip component should be displayed. - */ - active?: boolean; - /** - * When true, tooltip events will set the active prop on both data and label elements. - * @default false - */ - activateData?: boolean; - /** - * The angle prop specifies the angle to rotate the tooltip around its origin point. - */ - angle?: string | number; - /** - * The cornerRadius prop determines corner radius of the flyout container. This prop may be given as a positive number or a function of datum. - */ - cornerRadius?: NumberOrCallback; - /** - * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine text. - */ - datum?: {}; - /** - * Victory components can pass a data prop to their label component. This can be useful in custom components that need to make use of the entire dataset. - */ - data?: any[]; - /** - * The dx prop defines a horizontal shift from the x coordinate. - */ - dx?: StringOrNumberOrCallback; - /** - * The dy prop defines a vertical shift from the y coordinate. - */ - dy?: StringOrNumberOrCallback; - /** - * The events prop attaches arbitrary event handlers to the label component. This prop should be given as an object of event names and corresponding event handlers. - * When events are provided via Victory’s event system, event handlers will be called with the event, the props of the component is attached to, and an eventKey. - * Examples: events={{onClick: (evt) => alert("x: " + evt.clientX)}} - */ - events?: {}; - /** - * The style prop applies SVG style properties to the rendered flyout container. These props will be passed to the flyoutComponent. - */ - flyoutStyle?: VictoryStyleObject; - /** - * The flyoutComponent prop takes a component instance which will be used to create the flyout path for each tooltip. - * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, - * index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. - * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. - * If flyoutComponent is omitted, a default Flyout component will be created with props described above. - * Examples: flyoutComponent={<Flyout x={50} y={50}/>}, flyoutComponent={<MyCustomFlyout/>} - * @default <Flyout/> - */ - flyoutComponent?: React.ReactElement<any>; - /** - * The groupComponent prop takes a component instance which will be used to create group elements for use within container elements. This prop defaults to a <g> tag. - * @default groupComponent={<g/>} - */ - groupComponent?: React.ReactElement<any>; - /** - * The height prop defines the height of the tooltip flyout. This prop may be given as a positive number or a function of datum. - * If this prop is not set, height will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. - */ - height?: NumberOrCallback; - /** - * The horizontal prop determines whether to plot the flyouts to the left / right of the (x, y) coordinate rather than top / bottom. - * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. - * negative values result in a left orientation and positive values will result in a right orientation by default. - */ - horizontal?: boolean; - /** - * The index prop represents the index of the datum in the data array. - */ - index?: number | string; - /** - * The labelComponent prop takes a component instance which will be used to render each tooltip label. - * The new element created from the passed labelComponent will be supplied with the following properties: x, y, index, datum, verticalAnchor, textAnchor, style, text, and events. - * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. - * If labelComponent is omitted, a new VictoryLabel will be created with the props described above. - * Examples: labelComponent={<VictoryLabel dy={20}/>}, labelComponent={<MyCustomLabel/>} - * @default <VictoryLabel/> - */ - labelComponent?: React.ReactElement<any>; - /** - * The orientation prop determines which side of the (x, y) coordinate the tooltip should be rendered on. - * This prop can be given as “top”, “bottom”, “left”, “right”, or as a function of datum that returns one of these values. - * If this prop is not provided it will be determined from the sign of the datum, and the value of the horizontal prop. - */ - orientation?: OrientationTypes; - /** - * The pointerLength prop determines the length of the triangular pointer extending from the flyout. This prop may be given as a positive number or a function of datum. - */ - pointerLength?: NumberOrCallback; - /** - * The pointerWidth prop determines the width of the base of the triangular pointer extending from - * the flyout. This prop may be given as a positive number or a function of datum. - */ - pointerWidth?: NumberOrCallback; - /** - * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element - * within VictoryContainer. Note: This prop should not be set to true when using a custom container element. - */ - renderInPortal?: boolean; - /** - * The style prop applies CSS properties to the rendered `<text>` element. - */ - style?: React.CSSProperties; - /** - * The text prop defines the text VictoryTooltip will render. The text prop may be given as a string, number, or function of datum. - * When VictoryLabel is used as the labelComponent, strings may include newline characters, which VictoryLabel will split in to separate <tspan/> elements. - */ - text?: StringOrNumberOrCallback | string[] | number[]; - /** - * VictoryAxis uses the standard theme prop. Read about it here - * @default VictoryTheme.grayscale - */ - theme?: VictoryThemeDefinition; - /** - * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. - * If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. - */ - width?: NumberOrCallback; - /** - * The x prop defines the x coordinate to use as a basis for horizontal positioning. - */ - x?: number; - /** - * The y prop defines the y coordinate to use as a basis for vertical positioning. - */ - y?: number; - } - - /** - * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label - * component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. - * VictoryTooltip renders text as well as a configurable Flyout container. - */ - export class VictoryTooltip extends React.Component< - VictoryTooltipProps, - any - > {} - - /** - * Animate object used in components - */ - export interface AnimatePropTypeInterface { - /** - * Animation duration - */ - duration: number; - /** - * Animation end callback - */ - onEnd?: () => void; - /** - * Animation exit transition configuration - */ - onExit?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - }; - /** - * Animation enter transition configuration - */ - onEnter?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - after?: (datum: any) => AnimationStyle; - }; - /** - * Animation load transition configuration - */ - onLoad?: { - duration?: number; - before?: (datum: any) => AnimationStyle; - after?: (datum: any) => AnimationStyle; - }; - /** - * The easing prop specifies an easing function name to use for tweening. - * @default "quadInOut" - */ - easing?: AnimationEasing; - } - - /** - * Return value for eventHandlers values - */ - interface EventCallbackInterface<TTarget, TEventKey> { - /** - * Use only in: - * - VictoryChart - * - VictoryStack - */ - childName?: string; - target?: TTarget; - eventKey?: TEventKey; - /** - * Will be called with the calculated props for the individual selected element and result will override - * props of selected element via object assignment - * @param props - */ - mutation: (props: any) => any; - } - - export interface EventPropTypeInterface<TTarget, TEventKey> { - /** - * Use only in: - * - VictoryChart - * - VictoryStack - */ - childName?: string; - /** - * Targets may be any valid style namespace for a given component - */ - target: TTarget; - - eventKey?: TEventKey; - /** - * Event handlers map. Keys are standard event names (such as onClick) and values are event callbacks - */ - eventHandlers: { - [key: string]: { - (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey> } | - { (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey>[] - } - }; - } - - /** - * Data domain type - */ - type DomainTuple = [number, number] | [Date, Date]; - - type DomainPropType = DomainTuple | { x?: DomainTuple; y: DomainTuple; } | { x: DomainTuple; y?: DomainTuple; }; - - /** - * Domain padding - */ - type DomainPaddingPropType = number | { - x?: number | [ number, number]; - y?: number | [ number, number]; + style: VictoryStyleInterface; }; - - /** - * D3 scale function shape. Don't want to introduce typing dependency to d3 - */ - interface D3Scale { - domain: () => any; - range: () => any; - copy: () => any; - } - - /** - * Acceptable scale types - */ - type ScalePropType = "linear" | "time" | "log" | "sqrt"; - - /** - * Category prop type - */ - type CategoryPropType = string[] | { - x: string[] - y: string[] + scatter?: VictoryStyleInterface; + props?: { + width: number; + height: number; + colorScale: string[]; }; - + } + + interface VictoryThemeInterface { /** - * Data getter property type + * Default theme */ - type DataGetterPropType = number | string | string[] | { (data: any): number | string | string[] }; - - type InterpolationPropType = "basis" | "basisClosed" | "basisOpen" | "bundle" | - "cardinal" | "cardinalClosed" | "cardinalOpen" | - "catmullRom" | "catmullRomClosed" | "catmullRomOpen" | - "linear" | "linearClosed" | "monotoneX" | "monotoneY" | - "natural" | "radial" | "step" | "stepAfter" | "stepBefore"; - - type ColorScalePropType = "greyscale" | "qualitative" | "heatmap" | "warm" | "cool" | "red" | "green" | "blue" | string[]; - + grayscale: VictoryThemeDefinition; + material: VictoryThemeDefinition; + } + + /** + * Available themes + */ + export const VictoryTheme: VictoryThemeInterface; + + type OrientationTypes = "top" | "bottom" | "left" | "right"; + + export interface VictoryTooltipProps { /** - * Common properties + * The active prop specifies whether the tooltip component should be displayed. */ - interface VictoryCommonProps { + active?: boolean; + /** + * When true, tooltip events will set the active prop on both data and label elements. + * @default false + */ + activateData?: boolean; + /** + * The angle prop specifies the angle to rotate the tooltip around its origin point. + */ + angle?: string | number; + /** + * The cornerRadius prop determines corner radius of the flyout container. This prop may be given as a positive number or a function of datum. + */ + cornerRadius?: NumberOrCallback; + /** + * Victory components can pass a datum prop to their label component. This can be used to calculate functional styles, and determine text. + */ + datum?: {}; + /** + * Victory components can pass a data prop to their label component. This can be useful in custom components that need to make use of the entire dataset. + */ + data?: any[]; + /** + * The dx prop defines a horizontal shift from the x coordinate. + */ + dx?: StringOrNumberOrCallback; + /** + * The dy prop defines a vertical shift from the y coordinate. + */ + dy?: StringOrNumberOrCallback; + /** + * The events prop attaches arbitrary event handlers to the label component. This prop should be given as an object of event names and corresponding event handlers. + * When events are provided via Victory’s event system, event handlers will be called with the event, the props of the component is attached to, and an eventKey. + * Examples: events={{onClick: (evt) => alert("x: " + evt.clientX)}} + */ + events?: {}; + /** + * The style prop applies SVG style properties to the rendered flyout container. These props will be passed to the flyoutComponent. + */ + flyoutStyle?: VictoryStyleObject; + /** + * The flyoutComponent prop takes a component instance which will be used to create the flyout path for each tooltip. + * The new element created from the passed flyoutComponent will be supplied with the following properties: x, y, dx, dy, + * index, datum, cornerRadius, pointerLength, pointerWidth, width, height, orientation, style, and events. + * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. + * If flyoutComponent is omitted, a default Flyout component will be created with props described above. + * Examples: flyoutComponent={<Flyout x={50} y={50}/>}, flyoutComponent={<MyCustomFlyout/>} + * @default <Flyout/> + */ + flyoutComponent?: React.ReactElement<any>; + /** + * The groupComponent prop takes a component instance which will be used to create group elements for use within container elements. This prop defaults to a <g> tag. + * @default groupComponent={<g/>} + */ + groupComponent?: React.ReactElement<any>; + /** + * The height prop defines the height of the tooltip flyout. This prop may be given as a positive number or a function of datum. + * If this prop is not set, height will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. + */ + height?: NumberOrCallback; + /** + * The horizontal prop determines whether to plot the flyouts to the left / right of the (x, y) coordinate rather than top / bottom. + * This is useful when an orientation prop is not provided, and data will determine the default orientation. i.e. + * negative values result in a left orientation and positive values will result in a right orientation by default. + */ + horizontal?: boolean; + /** + * The index prop represents the index of the datum in the data array. + */ + index?: number | string; + /** + * The labelComponent prop takes a component instance which will be used to render each tooltip label. + * The new element created from the passed labelComponent will be supplied with the following properties: x, y, index, datum, verticalAnchor, textAnchor, style, text, and events. + * Any of these props may be overridden by passing in props to the supplied component, or modified or ignored within the custom component itself. + * If labelComponent is omitted, a new VictoryLabel will be created with the props described above. + * Examples: labelComponent={<VictoryLabel dy={20}/>}, labelComponent={<MyCustomLabel/>} + * @default <VictoryLabel/> + */ + labelComponent?: React.ReactElement<any>; + /** + * The orientation prop determines which side of the (x, y) coordinate the tooltip should be rendered on. + * This prop can be given as “top”, “bottom”, “left”, “right”, or as a function of datum that returns one of these values. + * If this prop is not provided it will be determined from the sign of the datum, and the value of the horizontal prop. + */ + orientation?: OrientationTypes; + /** + * The pointerLength prop determines the length of the triangular pointer extending from the flyout. This prop may be given as a positive number or a function of datum. + */ + pointerLength?: NumberOrCallback; + /** + * The pointerWidth prop determines the width of the base of the triangular pointer extending from + * the flyout. This prop may be given as a positive number or a function of datum. + */ + pointerWidth?: NumberOrCallback; + /** + * When renderInPortal is true, rendered tooltips will be wrapped in VictoryPortal and rendered within the Portal element + * within VictoryContainer. Note: This prop should not be set to true when using a custom container element. + */ + renderInPortal?: boolean; + /** + * The style prop applies CSS properties to the rendered `<text>` element. + */ + style?: React.CSSProperties; + /** + * The text prop defines the text VictoryTooltip will render. The text prop may be given as a string, number, or function of datum. + * When VictoryLabel is used as the labelComponent, strings may include newline characters, which VictoryLabel will split in to separate <tspan/> elements. + */ + text?: StringOrNumberOrCallback | string[] | number[]; + /** + * VictoryAxis uses the standard theme prop. Read about it here + * @default VictoryTheme.grayscale + */ + theme?: VictoryThemeDefinition; + /** + * The width prop defines the width of the tooltip flyout. This prop may be given as a positive number or a function of datum. + * If this prop is not set, width will be determined based on an approximate text size calculated from the text and style props provided to VictoryTooltip. + */ + width?: NumberOrCallback; + /** + * The x prop defines the x coordinate to use as a basis for horizontal positioning. + */ + x?: number; + /** + * The y prop defines the y coordinate to use as a basis for vertical positioning. + */ + y?: number; + } + + /** + * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label + * component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. + * VictoryTooltip renders text as well as a configurable Flyout container. + */ + export class VictoryTooltip extends React.Component< + VictoryTooltipProps, + any + > {} + + /** + * Animate object used in components + */ + export interface AnimatePropTypeInterface { + /** + * Animation duration + */ + duration: number; + /** + * Animation end callback + */ + onEnd?: () => void; + /** + * Animation exit transition configuration + */ + onExit?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + }; + /** + * Animation enter transition configuration + */ + onEnter?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + after?: (datum: any) => AnimationStyle; + }; + /** + * Animation load transition configuration + */ + onLoad?: { + duration?: number; + before?: (datum: any) => AnimationStyle; + after?: (datum: any) => AnimationStyle; + }; + /** + * The easing prop specifies an easing function name to use for tweening. + * @default "quadInOut" + */ + easing?: AnimationEasing; + } + + /** + * Return value for eventHandlers values + */ + interface EventCallbackInterface<TTarget, TEventKey> { + /** + * Use only in: + * - VictoryChart + * - VictoryStack + */ + childName?: string; + target?: TTarget; + eventKey?: TEventKey; + /** + * Will be called with the calculated props for the individual selected element and result will override + * props of selected element via object assignment + * @param props + */ + mutation: (props: any) => any; + } + + export interface EventPropTypeInterface<TTarget, TEventKey> { + /** + * Use only in: + * - VictoryChart + * - VictoryStack + */ + childName?: string; + /** + * Targets may be any valid style namespace for a given component + */ + target: TTarget; + + eventKey?: TEventKey; + /** + * Event handlers map. Keys are standard event names (such as onClick) and values are event callbacks + */ + eventHandlers: { + [key: string]: { + (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey> } | + { (event: React.SyntheticEvent<any>): EventCallbackInterface<TTarget, TEventKey>[] + } + }; + } + + /** + * Data domain type + */ + type DomainTuple = [number, number] | [Date, Date]; + + type DomainPropType = DomainTuple | { x?: DomainTuple; y: DomainTuple; } | { x: DomainTuple; y?: DomainTuple; }; + + /** + * Domain padding + */ + type DomainPaddingPropType = number | { + x?: number | [ number, number]; + y?: number | [ number, number]; + }; + + /** + * D3 scale function shape. Don't want to introduce typing dependency to d3 + */ + interface D3Scale { + domain: () => any; + range: () => any; + copy: () => any; + } + + /** + * Acceptable scale types + */ + type ScalePropType = "linear" | "time" | "log" | "sqrt"; + + /** + * Category prop type + */ + type CategoryPropType = string[] | { + x: string[] + y: string[] + }; + + /** + * Data getter property type + */ + type DataGetterPropType = number | string | string[] | { (data: any): number | string | string[] }; + + type InterpolationPropType = "basis" | "basisClosed" | "basisOpen" | "bundle" | + "cardinal" | "cardinalClosed" | "cardinalOpen" | + "catmullRom" | "catmullRomClosed" | "catmullRomOpen" | + "linear" | "linearClosed" | "monotoneX" | "monotoneY" | + "natural" | "radial" | "step" | "stepAfter" | "stepBefore"; + + type ColorScalePropType = "greyscale" | "qualitative" | "heatmap" | "warm" | "cool" | "red" | "green" | "blue" | string[]; + + /** + * Common properties + */ + interface VictoryCommonProps { + /** + * The animate prop specifies props for VictoryAnimation to use. + * The animate prop should also be used to specify enter and exit + * transition configurations with the `onExit` and `onEnter` namespaces respectively. + * @example + * {duration: 500, onExit: () => {}, onEnter: {duration: 500, before: () => ({y: 0})})} + */ + animate?: AnimatePropTypeInterface; + /** + * The name prop is used to reference a component instance when defining shared events. + */ + name?: string; + /** + * The height props specifies the height the svg viewBox of the chart container. + * This value should be given as a number of pixels + */ + height?: number; + /** + * The padding props specifies the amount of padding in number of pixels between + * the edge of the chart and any rendered child components. This prop can be given + * as a number or as an object with padding specified for top, bottom, left + * and right. + * @default 50 + */ + padding?: number | { + top?: number; + bottom?: number; + left?: number; + right?: number; + }; + /** + * The scale prop determines which scales your chart should use. This prop can be + * given as a string specifying a supported scale ("linear", "time", "log", "sqrt"), + * as a d3 scale function, or as an object with scales specified for x and y + * @example d3Scale.time(), {x: "linear", y: "log"} + * @default "linear" + */ + scale?: ScalePropType | D3Scale | { + x?: ScalePropType | D3Scale; + y?: ScalePropType | D3Scale; + }; + /** + * The standalone prop determines whether the component will render a standalone svg + * or a <g> tag that will be included in an external svg. Set standalone to false to + * compose VictoryAxis with other components within an enclosing <svg> tag. + * @default true + */ + standalone?: boolean; + /** + * The width props specifies the width of the svg viewBox of the chart container + * This value should be given as a number of pixels + */ + width?: number; + /** + * The containerComponent prop takes an entire component which will be used to + * create a container element for standalone charts. + * The new element created from the passed containerComponent wil be provided with + * these props from VictoryArea: height, width, children + * (the chart itself) and style. Props that are not provided by the + * child chart component include title and desc, both of which + * are intended to add accessibility to Victory components. The more descriptive these props + * are, the more accessible your data will be for people using screen readers. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a dataComponent is + * not provided, VictoryArea will use the default VictoryContainer component. + * @example <VictoryContainer title="Chart of Dog Breeds" desc="This chart shows how popular each dog breed is by percentage in Seattle." /> + * @default <VictoryContainer/> + */ + containerComponent?: React.ReactElement<any>; + /** + * The theme prop takes a style object with nested data, labels, and parent objects. + * You can create this object yourself, or you can use a theme provided by Victory. + * When using VictoryArea as a solo component, implement the theme directly on + * VictoryArea. If you are wrapping VictoryArea in VictoryChart, VictoryStack, or + * VictoryGroup, please call the theme on the outermost wrapper component instead. + * @example theme={VictoryTheme.material} + * http://www.github.com/FormidableLabs/victory-core/tree/master/src/victory-theme/material.js + */ + theme?: VictoryThemeDefinition; + /** + * The groupComponent prop takes an entire component which will be used to + * create group elements for use within container elements. This prop defaults + * to a <g> tag on web, and a react-native-svg <G> tag on mobile + * @default <g/> + */ + groupComponent?: React.ReactElement<any>; + } + + /** + * Common properties for all data components + */ + interface VictoryDatableProps { + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these arrays of values specified for x and y. If this prop is not set, + * categorical data will be plotted in the order it was given in the data array + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The data prop specifies the data to be plotted. Data should be in the form of an array + * of data points, or an array of arrays of data points for multiple datasets. + * Each data point may be any format you wish (depending on the `x` and `y` accessor props), + * but by default, an object with x and y properties is expected. + * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], + * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] + */ + data?: any[]; + /** + * The dataComponent prop takes an entire component which will be used to create an area. + * The new element created from the passed dataComponent will be provided with the + * following properties calculated by VictoryArea: a scale, style, events, interpolation, + * and an array of modified data objects (including x, y, and calculated y0 and y1). + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a dataComponent is + * not provided, VictoryArea will use its default Area component. + * @default <Area/> + */ + dataComponent?: React.ReactElement<any>; + /** + * The domain prop describes the range of values your chart will cover. This prop can be + * given as a array of the minimum and maximum expected values for your bar chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The x prop specifies how to access the X value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) + * @default "x" + */ + x?: DataGetterPropType; + /** + * The y prop specifies how to access the Y value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) + * @default "y" + */ + y?: DataGetterPropType; + } + + // Common labable interface + interface VictoryLabableProps { + /** + * The labelComponent prop takes in an entire label component which will be used + * to create a label for the area. The new element created from the passed labelComponent + * will be supplied with the following properties: x, y, index, data, verticalAnchor, + * textAnchor, angle, style, text, and events. any of these props may be overridden + * by passing in props to the supplied component, or modified or ignored within + * the custom component itself. If labelComponent is omitted, a new VictoryLabel + * will be created with props described above. This labelComponent prop should be used to + * provide a series label for VictoryArea. If individual labels are required for each + * data point, they should be created by composing VictoryArea with VictoryScatter + * @default <VictoryLabel/> + */ + labelComponent?: React.ReactElement<any>; + } + + interface VictoryMultiLabeableProps extends VictoryLabableProps { + /** + * The labels prop defines labels that will appear above each bar in your chart. + * This prop should be given as an array of values or as a function of data. + * If given as an array, the number of elements in the array should be equal to + * the length of the data array. Labels may also be added directly to the data object + * like data={[{x: 1, y: 1, label: "first"}]}. + * @example ["spring", "summer", "fall", "winter"], (datum) => datum.title + */ + labels?: string[] | { (data: any): string }; + } + + interface VictorySingleLabableProps extends VictoryLabableProps { + /** + * The label prop defines the label that will appear at the edge of the area. + * This prop should be given a string or as a function of data. If individual + * labels are required for each data point, they should be created by composing + * VictoryArea with VictoryScatter + * @example: "Series 1", (data) => `${data.length} points` + */ + label?: string | { (data: any): string }; + } + + export interface VictoryAreaProps + extends VictoryCommonProps, + VictoryDatableProps, + VictorySingleLabableProps { /** - * The animate prop specifies props for VictoryAnimation to use. - * The animate prop should also be used to specify enter and exit - * transition configurations with the `onExit` and `onEnter` namespaces respectively. + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryArea events. + * Since VictoryArea only renders a single element, the eventKey property is not used. + * The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. an area), and the object returned from the mutation function + * will override the props of the selected element via object assignment. * @example - * {duration: 500, onExit: () => {}, onEnter: {duration: 500, before: () => ({y: 0})})} + * events={[ + * { + * target: "data", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} */ - animate?: AnimatePropTypeInterface; + events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; /** - * The name prop is used to reference a component instance when defining shared events. - */ - name?: string; - /** - * The height props specifies the height the svg viewBox of the chart container. - * This value should be given as a number of pixels - */ - height?: number; - /** - * The padding props specifies the amount of padding in number of pixels between - * the edge of the chart and any rendered child components. This prop can be given - * as a number or as an object with padding specified for top, bottom, left - * and right. - * @default 50 - */ - padding?: number | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - /** - * The scale prop determines which scales your chart should use. This prop can be - * given as a string specifying a supported scale ("linear", "time", "log", "sqrt"), - * as a d3 scale function, or as an object with scales specified for x and y - * @example d3Scale.time(), {x: "linear", y: "log"} + * The interpolation prop determines how data points should be connected when plotting a line * @default "linear" */ - scale?: ScalePropType | D3Scale | { - x?: ScalePropType | D3Scale; - y?: ScalePropType | D3Scale; - }; + interpolation?: InterpolationPropType; /** - * The standalone prop determines whether the component will render a standalone svg - * or a <g> tag that will be included in an external svg. Set standalone to false to - * compose VictoryAxis with other components within an enclosing <svg> tag. - * @default true + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + * @default 50 */ - standalone?: boolean; + samples?: number; /** - * The width props specifies the width of the svg viewBox of the chart container - * This value should be given as a number of pixels + * The style prop specifies styles for your VictoryArea. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. + * @example {data: {fill: "red"}, labels: {fontSize: 12}} */ - width?: number; - /** - * The containerComponent prop takes an entire component which will be used to - * create a container element for standalone charts. - * The new element created from the passed containerComponent wil be provided with - * these props from VictoryArea: height, width, children - * (the chart itself) and style. Props that are not provided by the - * child chart component include title and desc, both of which - * are intended to add accessibility to Victory components. The more descriptive these props - * are, the more accessible your data will be for people using screen readers. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a dataComponent is - * not provided, VictoryArea will use the default VictoryContainer component. - * @example <VictoryContainer title="Chart of Dog Breeds" desc="This chart shows how popular each dog breed is by percentage in Seattle." /> - * @default <VictoryContainer/> - */ - containerComponent?: React.ReactElement<any>; - /** - * The theme prop takes a style object with nested data, labels, and parent objects. - * You can create this object yourself, or you can use a theme provided by Victory. - * When using VictoryArea as a solo component, implement the theme directly on - * VictoryArea. If you are wrapping VictoryArea in VictoryChart, VictoryStack, or - * VictoryGroup, please call the theme on the outermost wrapper component instead. - * @example theme={VictoryTheme.material} - * http://www.github.com/FormidableLabs/victory-core/tree/master/src/victory-theme/material.js - */ - theme?: VictoryThemeDefinition; - /** - * The groupComponent prop takes an entire component which will be used to - * create group elements for use within container elements. This prop defaults - * to a <g> tag on web, and a react-native-svg <G> tag on mobile - * @default <g/> - */ - groupComponent?: React.ReactElement<any>; - } - + style?: VictoryStyleInterface; + } + + /** + * Draw area charts with React. VictoryArea is a composable component, so it doesn't include axes. + * Add VictoryArea as a child of VictoryChart for a complete chart. + */ + export class VictoryArea extends React.Component<VictoryAreaProps, any> {} + + export interface VictoryAxisProps extends VictoryCommonProps { /** - * Common properties for all data components + * The axisComponent prop takes in an entire component which will be used + * to create the axis line. The new element created from the passed axisComponent + * will be supplied with the following properties: x1, y1, x2, y2, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If an axisComponent + * is not supplied, VictoryAxis will render its default AxisLine component. + * @default <AxisLine/> */ - interface VictoryDatableProps { - /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these arrays of values specified for x and y. If this prop is not set, - * categorical data will be plotted in the order it was given in the data array - * @example ["dogs", "cats", "mice"] - */ - categories?: CategoryPropType; - /** - * The data prop specifies the data to be plotted. Data should be in the form of an array - * of data points, or an array of arrays of data points for multiple datasets. - * Each data point may be any format you wish (depending on the `x` and `y` accessor props), - * but by default, an object with x and y properties is expected. - * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], - * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] - */ - data?: any[]; - /** - * The dataComponent prop takes an entire component which will be used to create an area. - * The new element created from the passed dataComponent will be provided with the - * following properties calculated by VictoryArea: a scale, style, events, interpolation, - * and an array of modified data objects (including x, y, and calculated y0 and y1). - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a dataComponent is - * not provided, VictoryArea will use its default Area component. - * @default <Area/> - */ - dataComponent?: React.ReactElement<any>; - /** - * The domain prop describes the range of values your chart will cover. This prop can be - * given as a array of the minimum and maximum expected values for your bar chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The x prop specifies how to access the X value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) - * @default "x" - */ - x?: DataGetterPropType; - /** - * The y prop specifies how to access the Y value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) - * @default "y" - */ - y?: DataGetterPropType; + axisComponent?: React.ReactElement<any>; + /** + * The axisLabelComponent prop takes in an entire component which will be used + * to create the axis label. The new element created from the passed axisLabelComponent + * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, + * angle, transform, style and events. Any of these props may be overridden by + * passing in props to the supplied component, or modified or ignored within + * the custom component itself. If an axisLabelComponent is not supplied, a new + * VictoryLabel will be created with props described above + * @default <VictoryLabel/> + */ + axisLabelComponent?: React.ReactElement<any>; + /** + * This prop specifies whether a given axis is intended to cross another axis. + */ + crossAxis?: boolean; + /** + * The dependentAxis prop specifies whether the axis corresponds to the + * dependent variable (usually y). This prop is useful when composing axis + * with other components to form a chart. + */ + dependentAxis?: boolean; + /** + * The domain prop describes the range of values your axis will include. This prop should be + * given as a array of the minimum and maximum expected values for your axis. + * If this value is not given it will be calculated based on the scale or tickValues. + * @examples [-1, 1] + */ + domain?: DomainPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "axis", "axisLabel", "ticks", "tickLabels", and "grid" are + * all valid targets for VictoryAxis events. The eventKey may optionally be used to select a + * single element by index rather than an entire set. The eventHandlers object + * should be given as an object whose keys are standard event names (i.e. onClick) + * and whose values are event callbacks. The return value of an event handler + * be used to modify other elemnts. The return value should be given as an object or + * an array of objects with optional target and eventKey keys, and a mutation + * key whose value is a function. The target and eventKey keys will default to those + * corresponding to the element the event handler was attached to. The mutation + * function will be called with the calculated props for the individual selected + * element (i.e. a single tick), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "grid", + * eventKey: 2, + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {stroke: "orange"})}; + * } + * }, { + * target: "tickLabels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"axis" | "axisLabel" | "grid" | "ticks" | "tickLabels" | "parent", number | string>[]; + /** + * When true, this prop reduces the number of tick labels to fit the length of the axis. + * Labels are removed at approximately even intervals from the original array of labels. + * This feature only works well for labels that are approximately evenly spaced. + * @default false + */ + fixLabelOverlap?: boolean; + /** + * The gridComponent prop takes in an entire component which will be used + * to create grid lines. The new element created from the passed gridComponent + * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a gridComponent + * is not supplied, VictoryAxis will render its default GridLine component. + * @default <GridLine/> + */ + gridComponent?: React.ReactElement<any>; + /** + * If true, this value will flip the domain of a given axis. + */ + invertAxis?: boolean; + /** + * The label prop defines the label that will appear along the axis. This + * prop should be given as a value or an entire, HTML-complete label + * component. If a label component is given, it will be cloned. The new + * element's properties x, y, textAnchor, verticalAnchor, and transform + * will have defaults provided by the axis; styles filled out with + * defaults provided by the axis, and overrides from the label component. + * If a value is given, a new VictoryLabel will be created with props and + * styles from the axis. + */ + label?: any; + /** + * This value describes how far from the "edge" of its permitted area each axis + * will be set back in the x-direction. If this prop is not given, + * the offset is calculated based on font size, axis orientation, and label padding. + */ + offsetX?: number; + /** + * This value describes how far from the "edge" of its permitted area each axis + * will be set back in the y-direction. If this prop is not given, + * the offset is calculated based on font size, axis orientation, and label padding. + */ + offsetY?: number; + /** + * The orientation prop specifies the position and orientation of your axis. + */ + orientation?: "top" | "bottom" | "left" | "right"; + /** + * The style prop defines the style of the component. The style prop should be given as an object + * with styles defined for parent, axis, axisLabel, grid, ticks, and tickLabels. Any valid svg + * styles are supported, but width, height, and padding should be specified via props as they + * determine relative layout for components in VictoryChart. Functional styles may be defined for + * grid, tick, and tickLabel style properties, and they will be evaluated with each tick. + * + * note: When a component is rendered as a child of another Victory component, or within a custom + * <svg> element with standalone={false} parent styles will be applied to the enclosing <g> tag. + * Many styles that can be applied to a parent <svg> will not be expressed when applied to a <g>. + * + * note: custom angle and verticalAnchor properties may be included in labels styles. + */ + style?: { + parent?: React.CSSProperties; + axis?: React.CSSProperties; + axisLabel?: React.CSSProperties; + grid?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + ticks?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + tickLabels?: { + [K in keyof React.CSSProperties]: + | string + | number + | ((tick?: any) => string | number) + }; + }; + /** + * The tickComponent prop takes in an entire component which will be used + * to create tick lines. The new element created from the passed tickComponent + * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. + * Any of these props may be overridden by passing in props to the supplied component, + * or modified or ignored within the custom component itself. If a tickComponent + * is not supplied, VictoryAxis will render its default Tick component. + * @default <Tick/> + */ + tickComponent?: React.ReactElement<any>; + /** + * The tickCount prop specifies approximately how many ticks should be drawn on the axis if + * tickValues are not explicitly provided. This value is calculated by d3 scale and + * prioritizes returning "nice" values and evenly spaced ticks over an exact number of ticks. + * If you need an exact number of ticks, please specify them via the tickValues prop. + * This prop must have a value greater than zero. + * @default 5 + */ + tickCount?: number; + /** + * The tickLabelComponent prop takes in an entire component which will be used + * to create the tick labels. The new element created from the passed tickLabelComponent + * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, + * angle, tick, style and events. Any of these props may be overridden by + * passing in props to the supplied component, or modified or ignored within + * the custom component itself. If an tickLabelComponent is not supplied, a new + * VictoryLabel will be created with props described above + * @default <VictoryLabel/> + */ + tickLabelComponent?: React.ReactElement<any>; + /** + * The tickFormat prop specifies how tick values should be expressed visually. + * tickFormat can be given as a function to be applied to every tickValue, or as + * an array of display values for each tickValue. + * @example d3.time.format("%Y"), (x) => x.toPrecision(2), ["first", "second", "third"] + */ + tickFormat?: any[] | { (tick: any, index: number, ticks: any[]): string | number }; + /** + * The tickValues prop explicitly specifies which tick values to draw on the axis. + * @example ["apples", "bananas", "oranges"], [2, 4, 6, 8] + */ + tickValues?: any[]; + } + + /** + * VictoryAxis draws an SVG chart axis with React. + * Styles and data can be customized by passing in your own values as properties to the component. + * Data changes are animated with VictoryAnimation. + */ + export class VictoryAxis extends React.Component<VictoryAxisProps, any> {} + + export interface VictoryBarProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { + /** + * The alignment prop specifies how bars should be aligned relative to their data points. + * This prop may be given as “start”, “middle” or “end”. When this prop is not specified, + * bars will have “middle” alignment relative to their data points. + */ + alignment?: "start" | "middle" | "end"; + /** + * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. + * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will + * be used to calculate a default width for each bar given the total number of bars in the data series + * and the overall width of the chart. + */ + barRatio?: number; + /** + * The barWidth prop is used to specify the width of each bar. This prop may be given as + * a number of pixels or as a function that returns a number. When this prop is given as + * a function, it will be evaluated with the arguments datum, and active. When this value + * is not given, a default value will be calculated based on the overall dimensions of + * the chart, and the number of bars. + */ + barWidth?: NumberOrCallback; + /** + * The cornerRadius prop specifies a radius to apply to each bar. + * If this prop is given as a single number, the radius will only be applied to the top of each bar. + * When this prop is given as a function, it will be evaluated with the arguments datum, and active. + */ + cornerRadius?: NumberOrCallback + | { + top?: number | (NumberOrCallback), + topLeft?: number | (NumberOrCallback), + topRight?: number | (NumberOrCallback), + bottom?: number | (NumberOrCallback), + bottomLeft?: number | (NumberOrCallback), + bottomRight?: number | (NumberOrCallback) + }; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryBar events. + * The eventKey may optionally be used to select a single element by index rather than an entire + * set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @example + * events={[ + * { + * target: "data", + * eventKey: "thisOne", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: "theOtherOne", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: "theOtherOne", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. + */ + horizontal?: boolean; + /** + * The style prop specifies styles for your VictoryBar. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. In addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + } + + /** + * Draw SVG bar charts with React. VictoryBar is a composable component, so it doesn't include axes + * Check out VictoryChart for complete bar charts and more. + */ + export class VictoryBar extends React.Component<VictoryBarProps, any> {} + + export interface VictoryBoxPlotStyleInterface + extends VictoryStyleInterface { + max?: VictoryStyleObject; + maxLabels?: VictoryStyleObject; + min?: VictoryStyleObject; + minLabels?: VictoryStyleObject; + median?: VictoryStyleObject; + medianLabels?: VictoryStyleObject; + q1?: VictoryStyleObject; + q1Labels?: VictoryStyleObject; + q3?: VictoryStyleObject; + q3Labels?: VictoryStyleObject; } - - // Common labable interface - interface VictoryLabableProps { - /** - * The labelComponent prop takes in an entire label component which will be used - * to create a label for the area. The new element created from the passed labelComponent - * will be supplied with the following properties: x, y, index, data, verticalAnchor, - * textAnchor, angle, style, text, and events. any of these props may be overridden - * by passing in props to the supplied component, or modified or ignored within - * the custom component itself. If labelComponent is omitted, a new VictoryLabel - * will be created with props described above. This labelComponent prop should be used to - * provide a series label for VictoryArea. If individual labels are required for each - * data point, they should be created by composing VictoryArea with VictoryScatter - * @default <VictoryLabel/> - */ - labelComponent?: React.ReactElement<any>; - } - - interface VictoryMultiLabeableProps extends VictoryLabableProps { - /** - * The labels prop defines labels that will appear above each bar in your chart. - * This prop should be given as an array of values or as a function of data. - * If given as an array, the number of elements in the array should be equal to - * the length of the data array. Labels may also be added directly to the data object - * like data={[{x: 1, y: 1, label: "first"}]}. - * @example ["spring", "summer", "fall", "winter"], (datum) => datum.title - */ - labels?: string[] | { (data: any): string }; - } - - interface VictorySingleLabableProps extends VictoryLabableProps { - /** - * The label prop defines the label that will appear at the edge of the area. - * This prop should be given a string or as a function of data. If individual - * labels are required for each data point, they should be created by composing - * VictoryArea with VictoryScatter - * @example: "Series 1", (data) => `${data.length} points` - */ - label?: string | { (data: any): string }; - } - - export interface VictoryAreaProps + + export interface VictoryBoxPlotProps extends VictoryCommonProps, - VictoryDatableProps, - VictorySingleLabableProps { + VictoryDatableProps { + /** + * The boxWidth prop specifies how wide each box should be. If the whiskerWidth + * prop is not set, this prop will also determine the width of the whisker crosshair. + */ + boxWidth?: number; + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; /** * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryArea events. - * Since VictoryArea only renders a single element, the eventKey property is not used. - * The eventHandlers object should be given as an object whose keys are standard + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryChart, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard * event names (i.e. onClick) and whose values are event callbacks. The return value * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys * will default to those corresponding to the element the event handler was attached to. * The mutation function will be called with the calculated props for the individual selected - * element (i.e. an area), and the object returned from the mutation function + * element (i.e. a single bar), and the object returned from the mutation function * will override the props of the selected element via object assignment. - * @example + * @examples * events={[ * { * target: "data", + * childName: "firstBar", * eventHandlers: { * onClick: () => { * return [ * { + * childName: "secondBar", * mutation: (props) => { * return {style: merge({}, props.style, {fill: "orange"})}; * } * }, { + * childName: "secondBar", * target: "labels", * mutation: () => { * return {text: "hey"}; @@ -1070,290 +1497,514 @@ declare module "victory" { * } * ]} */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", "all">[]; + events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; /** - * The interpolation prop determines how data points should be connected when plotting a line - * @default "linear" + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data */ - interpolation?: InterpolationPropType; + eventKey?: StringOrNumberOrCallback; /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - * @default 50 + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. */ - samples?: number; + horizontal?: boolean; /** - * The style prop specifies styles for your VictoryArea. Any valid inline style properties + * The labelOrientation prop determines where labels are placed relative to their + * corresponding data. If this prop is not set, it will be set to “top” for + * horizontal charts, and “right” for vertical charts. + */ + labelOrientation?: "top" | "bottom" | "left" | "right"; + /** + * When the boolean labels prop is set to true, the values for min, max, median, + * q1, and q3 will be displayed for each box. For more granular label control, use + * the individual minLabels, maxLabels, medianLabels, q1Labels, and q3Labels props. + */ + labels?: boolean; + /** + * Use the max data accessor prop to define the max value of a box plot. + */ + max?: StringOrNumberOrCallback; + /** + * Use the median data accessor prop to define the median value of a box plot. + */ + median?: StringOrNumberOrCallback; + /** + * Use the min data accessor prop to define the min value of a box plot. + */ + min?: StringOrNumberOrCallback; + /** + * Use the q1 data accessor prop to define the q1 value of a box plot. + */ + q1?: StringOrNumberOrCallback; + /** + * Use the q3 data accessor prop to define the q1 value of a box plot. + */ + q3?: StringOrNumberOrCallback; + /** + * The style prop defines the style of the component. The style prop + * should be given as an object with styles defined for parent, max, + * maxLabels, min, minLabels,median, medianLabels,q1, q1Labels,q3, + * q3Labels. Any valid svg styles are supported, but width, height, a + * nd padding should be specified via props as they determine relative + * layout for components in VictoryChart. Functional styles may be + * defined for style properties, and they will be evaluated with each datum. + */ + style?: VictoryBoxPlotStyleInterface; + /** + * The whiskerWidth prop specifies how wide each whisker crosshair should be. If the + * whiskerWidth prop is not set, the width of the whisker crosshair will match + * the width of the box. + */ + whiskerWidth?: number; + } + + /** + * VictoryBoxPlot renders a box plot to describe the distribution of a set of data. Data for + * VictoryBoxPlot may be given with summary statistics pre-calculated (min, median, max, q1, q3), + * or as an array of raw data. VictoryBoxPlot can be composed with VictoryChart to create box plot charts. + */ + export class VictoryBoxPlot extends React.Component< + VictoryBoxPlotProps, + any + > {} + + export interface VictoryChartProps extends VictoryCommonProps { + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryChart, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The style prop specifies styles for your chart. Any valid inline style properties * will be applied. Height, width, and padding should be specified via the height, * width, and padding props, as they are used to calculate the alignment of * components within chart. - * @example {data: {fill: "red"}, labels: {fontSize: 12}} + * @example {border: "1px solid #ccc", margin: "2%", maxWidth: "40%"} */ - style?: VictoryStyleInterface; + style?: Pick<VictoryStyleInterface, 'parent'>; } - + /** - * Draw area charts with React. VictoryArea is a composable component, so it doesn't include axes. - * Add VictoryArea as a child of VictoryChart for a complete chart. + * A flexible charting component for React. + * VictoryChart composes other Victory components into reusable charts. + * Acting as a coordinator rather than a stand-alone component, VictoryChart reconciles props such as domain and scale for child components, + * and provides a set of sensible defaults. This component works with: + * - VictoryAxis + * - VictoryLine + * - VictoryScatter + * - VictoryBar */ - export class VictoryArea extends React.Component<VictoryAreaProps, any> {} - - export interface VictoryAxisProps extends VictoryCommonProps { + export class VictoryChart extends React.Component<VictoryChartProps, any> {} + + export interface VictoryGroupProps extends VictoryCommonProps, VictoryMultiLabeableProps { /** - * The axisComponent prop takes in an entire component which will be used - * to create the axis line. The new element created from the passed axisComponent - * will be supplied with the following properties: x1, y1, x2, y2, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If an axisComponent - * is not supplied, VictoryAxis will render its default AxisLine component. - * @default <AxisLine/> + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these values for x and y. When categories are not given as an object + * When this prop is set on a wrapper component, it will dictate the categories of + * its the children. If this prop is not set, any categories on child component + * or categorical data, will be merged to create a shared set of categories. + * @example ["dogs", "cats", "mice"] */ - axisComponent?: React.ReactElement<any>; + categories?: CategoryPropType; /** - * The axisLabelComponent prop takes in an entire component which will be used - * to create the axis label. The new element created from the passed axisLabelComponent - * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, - * angle, transform, style and events. Any of these props may be overridden by - * passing in props to the supplied component, or modified or ignored within - * the custom component itself. If an axisLabelComponent is not supplied, a new - * VictoryLabel will be created with props described above - * @default <VictoryLabel/> + * The colorScale prop is an optional prop that defines the color scale the chart's bars + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryBar will automatically assign + * values from this color scale to the bars unless colors are explicitly provided in the + * `dataAttributes` prop. */ - axisLabelComponent?: React.ReactElement<any>; + colorScale?: ColorScalePropType; /** - * This prop specifies whether a given axis is intended to cross another axis. - */ - crossAxis?: boolean; - /** - * The dependentAxis prop specifies whether the axis corresponds to the - * dependent variable (usually y). This prop is useful when composing axis - * with other components to form a chart. - */ - dependentAxis?: boolean; - /** - * The domain prop describes the range of values your axis will include. This prop should be - * given as a array of the minimum and maximum expected values for your axis. - * If this value is not given it will be calculated based on the scale or tickValues. - * @examples [-1, 1] + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @examples: [-1, 1], {x: [0, 100], y: [0, 1]} */ domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; /** * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "axis", "axisLabel", "ticks", "tickLabels", and "grid" are - * all valid targets for VictoryAxis events. The eventKey may optionally be used to select a - * single element by index rather than an entire set. The eventHandlers object - * should be given as an object whose keys are standard event names (i.e. onClick) - * and whose values are event callbacks. The return value of an event handler - * be used to modify other elemnts. The return value should be given as an object or - * an array of objects with optional target and eventKey keys, and a mutation - * key whose value is a function. The target and eventKey keys will default to those - * corresponding to the element the event handler was attached to. The mutation - * function will be called with the calculated props for the individual selected - * element (i.e. a single tick), and the object returned from the mutation function + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryGroup, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function * will override the props of the selected element via object assignment. * @examples * events={[ * { - * target: "grid", - * eventKey: 2, + * target: "data", + * childName: "firstBar", * eventHandlers: { * onClick: () => { * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {stroke: "orange"})}; - * } - * }, { - * target: "tickLabels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; * } * } * } * ]} */ - events?: EventPropTypeInterface<"axis" | "axisLabel" | "grid" | "ticks" | "tickLabels" | "parent", number | string>[]; + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** - * When true, this prop reduces the number of tick labels to fit the length of the axis. - * Labels are removed at approximately even intervals from the original array of labels. - * This feature only works well for labels that are approximately evenly spaced. - * @default false + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data */ - fixLabelOverlap?: boolean; + eventKey?: StringOrNumberOrCallback; /** - * The gridComponent prop takes in an entire component which will be used - * to create grid lines. The new element created from the passed gridComponent - * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a gridComponent - * is not supplied, VictoryAxis will render its default GridLine component. - * @default <GridLine/> + * The horizontal prop determines whether the bars will be laid vertically or + * horizontally. The bars will be vertical if this prop is false or unspecified, + * or horizontal if the prop is set to true. */ - gridComponent?: React.ReactElement<any>; + horizontal?: boolean; /** - * If true, this value will flip the domain of a given axis. + * The offset prop determines the number of pixels each element in a group should + * be offset from its original position of the on the independent axis. In the + * case of groups of bars, this number should be equal to the width of the bar + * plus the desired spacing between bars. */ - invertAxis?: boolean; + offset?: number; /** - * The label prop defines the label that will appear along the axis. This - * prop should be given as a value or an entire, HTML-complete label - * component. If a label component is given, it will be cloned. The new - * element's properties x, y, textAnchor, verticalAnchor, and transform - * will have defaults provided by the axis; styles filled out with - * defaults provided by the axis, and overrides from the label component. - * If a value is given, a new VictoryLabel will be created with props and - * styles from the axis. + * The style prop specifies styles for your grouped chart. These styles will be + * applied to all grouped children */ - label?: any; - /** - * This value describes how far from the "edge" of its permitted area each axis - * will be set back in the x-direction. If this prop is not given, - * the offset is calculated based on font size, axis orientation, and label padding. - */ - offsetX?: number; - /** - * This value describes how far from the "edge" of its permitted area each axis - * will be set back in the y-direction. If this prop is not given, - * the offset is calculated based on font size, axis orientation, and label padding. - */ - offsetY?: number; - /** - * The orientation prop specifies the position and orientation of your axis. - */ - orientation?: "top" | "bottom" | "left" | "right"; - /** - * The style prop defines the style of the component. The style prop should be given as an object - * with styles defined for parent, axis, axisLabel, grid, ticks, and tickLabels. Any valid svg - * styles are supported, but width, height, and padding should be specified via props as they - * determine relative layout for components in VictoryChart. Functional styles may be defined for - * grid, tick, and tickLabel style properties, and they will be evaluated with each tick. - * - * note: When a component is rendered as a child of another Victory component, or within a custom - * <svg> element with standalone={false} parent styles will be applied to the enclosing <g> tag. - * Many styles that can be applied to a parent <svg> will not be expressed when applied to a <g>. - * - * note: custom angle and verticalAnchor properties may be included in labels styles. - */ - style?: { - parent?: React.CSSProperties; - axis?: React.CSSProperties; - axisLabel?: React.CSSProperties; - grid?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - ticks?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - tickLabels?: { - [K in keyof React.CSSProperties]: - | string - | number - | ((tick?: any) => string | number) - }; - }; - /** - * The tickComponent prop takes in an entire component which will be used - * to create tick lines. The new element created from the passed tickComponent - * will be supplied with the following properties: x1, y1, x2, y2, tick, style and events. - * Any of these props may be overridden by passing in props to the supplied component, - * or modified or ignored within the custom component itself. If a tickComponent - * is not supplied, VictoryAxis will render its default Tick component. - * @default <Tick/> - */ - tickComponent?: React.ReactElement<any>; - /** - * The tickCount prop specifies approximately how many ticks should be drawn on the axis if - * tickValues are not explicitly provided. This value is calculated by d3 scale and - * prioritizes returning "nice" values and evenly spaced ticks over an exact number of ticks. - * If you need an exact number of ticks, please specify them via the tickValues prop. - * This prop must have a value greater than zero. - * @default 5 - */ - tickCount?: number; - /** - * The tickLabelComponent prop takes in an entire component which will be used - * to create the tick labels. The new element created from the passed tickLabelComponent - * will be supplied with the following properties: x, y, verticalAnchor, textAnchor, - * angle, tick, style and events. Any of these props may be overridden by - * passing in props to the supplied component, or modified or ignored within - * the custom component itself. If an tickLabelComponent is not supplied, a new - * VictoryLabel will be created with props described above - * @default <VictoryLabel/> - */ - tickLabelComponent?: React.ReactElement<any>; - /** - * The tickFormat prop specifies how tick values should be expressed visually. - * tickFormat can be given as a function to be applied to every tickValue, or as - * an array of display values for each tickValue. - * @example d3.time.format("%Y"), (x) => x.toPrecision(2), ["first", "second", "third"] - */ - tickFormat?: any[] | { (tick: any, index: number, ticks: any[]): string | number }; - /** - * The tickValues prop explicitly specifies which tick values to draw on the axis. - * @example ["apples", "bananas", "oranges"], [2, 4, 6, 8] - */ - tickValues?: any[]; + style?: VictoryStyleInterface; } - - /** - * VictoryAxis draws an SVG chart axis with React. - * Styles and data can be customized by passing in your own values as properties to the component. - * Data changes are animated with VictoryAnimation. - */ - export class VictoryAxis extends React.Component<VictoryAxisProps, any> {} - - export interface VictoryBarProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { - /** - * The alignment prop specifies how bars should be aligned relative to their data points. - * This prop may be given as “start”, “middle” or “end”. When this prop is not specified, - * bars will have “middle” alignment relative to their data points. - */ - alignment?: "start" | "middle" | "end"; - /** - * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. - * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will - * be used to calculate a default width for each bar given the total number of bars in the data series - * and the overall width of the chart. - */ - barRatio?: number; - /** - * The barWidth prop is used to specify the width of each bar. This prop may be given as - * a number of pixels or as a function that returns a number. When this prop is given as - * a function, it will be evaluated with the arguments datum, and active. When this value - * is not given, a default value will be calculated based on the overall dimensions of - * the chart, and the number of bars. - */ - barWidth?: NumberOrCallback; - /** - * The cornerRadius prop specifies a radius to apply to each bar. - * If this prop is given as a single number, the radius will only be applied to the top of each bar. - * When this prop is given as a function, it will be evaluated with the arguments datum, and active. - */ - cornerRadius?: NumberOrCallback - | { - top?: number | (NumberOrCallback), - topLeft?: number | (NumberOrCallback), - topRight?: number | (NumberOrCallback), - bottom?: number | (NumberOrCallback), - bottomLeft?: number | (NumberOrCallback), - bottomRight?: number | (NumberOrCallback) - }; + + export class VictoryGroup extends React.Component<VictoryGroupProps, any> {} + + export interface VictoryLineProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { /** * The event prop take an array of event objects. Event objects are composed of * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryBar events. - * The eventKey may optionally be used to select a single element by index rather than an entire - * set. The eventHandlers object should be given as an object whose keys are standard + * for a given component, so "data" and "labels" are all valid targets for VictoryLine events. + * Since VictoryLine only renders a single element, the eventKey property is not used. + * The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a line), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * mutation: (props) => { + * return {style: merge({}, props.style, {stroke: "orange"})}; + * } + * }, { + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; + /** + * The interpolation prop determines how data points should be connected + * when plotting a line + */ + interpolation?: InterpolationPropType; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + */ + samples?: number; + /** + * The labels prop defines the labels that will appear above each point. + * This prop should be given as an array or as a function of data. + */ + labels?: string[]|number[]|Function; + /** + * Use the sortKey prop to indicate how data should be sorted. This prop + * is given directly to the lodash sortBy function to be executed on the + * final dataset. + */ + sortKey?: string|string[]|Function; + /** + * The style prop specifies styles for your VictoryLine. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. in addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @examples{data: {stroke: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + } + + /** + * VictoryLine creates a line based on data. VictoryLine is a composable component, so it does not include an axis. + * Check out VictoryChart for easy to use line charts and more. + */ + export class VictoryLine extends React.Component<VictoryLineProps, any> {} + + export interface VictoryLegendProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { + /** + * The colorScale prop defines a color scale to be applied to each data + * symbol in VictoryLegend. This prop should be given as an array of CSS + * colors, or as a string corresponding to one of the built in color + * scales: "grayscale", "qualitative", "heatmap", "warm", "cool", "red", + * "green", "blue". VictoryLegend will assign a color to each symbol by + * index, unless they are explicitly specified in the data object. + * Colors will repeat when there are more symbols than colors in the + * provided colorScale. + */ + colorScale?: ColorScalePropType; + /** + * The style prop defines the style of the VictoryLegend component. + * The style prop should be given as an object with styles defined for data, labels and + * parent. Any valid svg styles are supported, but width, height, and + * padding should be specified via props as they determine relative + * layout for components in VictoryLegend. + */ + style?: VictoryStyleInterface; + /** + * The containerComponent prop takes a component instance which will be + * used to create a container element for standalone legends. The new + * element created from the passed containerComponent will be provided + * with the following props: height, width, children (the legend itself) + * and style. If a containerComponent is not provided, the default + * VictoryContainer component will be used. VictoryContainer supports + * title and desc props, which are intended to add accessibility to + * Victory components. The more descriptive these props are, the more + * accessible your data will be for people using screen readers. These + * props may be set by passing them directly to the supplied component. + * By default, VictoryContainer renders a responsive svg using the + * viewBox attribute. To render a static container, set + * responsive={false} directly on the instance of VictoryContainer + * supplied via the containerComponent prop. VictoryContainer also + * renders a Portal element that may be used in conjunction with + * VictoryPortal to force components to render above other children. + * @default <VictoryContainer/> + */ + containerComponent?: React.ReactElement<any>; + /** + * Specify data via the data prop. VictoryLegend expects data as an + * array of objects with name (required), symbol, and labels properties. + * The data prop must be given as an array. + */ + data?: Array<{ + name?: string; + symbol?: { + fill?: string; + type?: string; + }; + }>; + /** + * The itemsPerRow prop determines how many items to render in each row + * of a horizontal legend, or in each column of a vertical legend. This + * prop should be given as an integer. When this prop is not given, + * legend items will be rendered in a single row or column. + */ + itemsPerRow?: number; + /** + * The dataComponent prop takes a component instance which will be + * responsible for rendering a data element used to associate a symbol + * or color with each data series. The new element created from the + * passed dataComponent will be provided with the following properties + * calculated by VictoryLegend: x, y, size, style, and symbol. Any of + * these props may be overridden by passing in props to the supplied + * component, or modified or ignored within the custom component itself. + * If a dataComponent is not provided, VictoryLegend will use its + * default Point component. + */ + dataComponent?: React.ReactElement<any>; + /** + * The groupComponent prop takes an entire component which will be used to + * create group elements for use within container elements. This prop defaults + * to a <g> tag on web, and a react-native-svg <G> tag on mobile + * @default <g/> + */ + groupComponent?: React.ReactElement<any>; + /** + * The gutter prop defines the number of pixels between legend rows or + * columns, depending on orientation. When orientation is horizontal, + * gutters are between columns. When orientation is vertical, gutters + * are the space between rows. + */ + gutter?: number; + /** + * The labelComponent prop takes a component instance which will be used + * to render each legend label. The new element created from the passed + * labelComponent will be supplied with the following properties: x, y, + * style, and text. Any of these props may be overridden by passing in + * props to the supplied component, or modified or ignored within the + * custom component itself. If labelComponent is omitted, a new + * VictoryLabel will be created with the props described above. + */ + labelComponent?: React.ReactElement<any>; + /** + * The orientation prop takes a string that defines whether legend data + * are displayed in a row or column. When orientation is "horizontal", + * legend items will be displayed in a single row. When orientation is + * "vertical", legend items will be displayed in a single column. Line + * and text-wrapping is not currently supported, so "vertical" + * orientation is both the default setting and recommended for + * displaying many series of data. + * @default 'vertical' + */ + orientation?: 'horizontal'|'vertical'; + /** + * The padding prop specifies the amount of padding in pixels between + * the edge of the legend and any rendered child components. This prop + * can be given as a number or as an object with padding specified for + * top, bottom, left and right. As with width and height, the absolute + * padding will depend on whether the component is rendered in a + * responsive container. When a component is nested within + * VictoryLegend, setting padding on the child component will have no + * effect. + */ + padding?: number | { + top?: number; + bottom?: number; + left?: number; + right?: number; + }; + /** + * The standalone props specifies whether the component should be + * rendered in an independent <svg> element or in a <g> tag. This prop + * defaults to true, and renders an svg. + */ + standalone?: boolean; + /** + * The symbolSpacer prop defines the number of pixels between data + * components and label components. + */ + symbolSpacer?: number; + /** + * The width and height props define the width and height of the legend. + * These props may be given as positive numbers or functions of data. If + * these props are not set, width and height will be determined based on + * an approximate text size calculated from the text and style props + * provided to VictoryLegend. + */ + width?: number; + height?: number; + /** + * The x and y props define the base position of the legend element. + */ + x?: number; + y?: number; + } + + /** + * VictoryLegend renders a chart legend component. + */ + export class VictoryLegend extends React.Component<VictoryLegendProps, any> {} + + type ScatterSymbolType = "circle" | "diamond" | "plus" | "square" | "star" | "triangleDown" | "triangleUp"; + + export interface VictoryScatterProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { + /** + * The bubbleProperty prop indicates which property of the data object should be used + * to scale data points in a bubble chart + */ + bubbleProperty?: string; + /** + * The event prop take an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryScatter + * events. The eventKey may optionally be used to select a single element by index rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard * event names (i.e. onClick) and whose values are event callbacks. The return value * of an event handler is used to modify elemnts. The return value should be given * as an object or an array of objects with optional target and eventKey keys, @@ -1362,7 +2013,7 @@ declare module "victory" { * The mutation function will be called with the calculated props for the individual selected * element (i.e. a single bar), and the object returned from the mutation function * will override the props of the selected element via object assignment. - * @example + * @examples * events={[ * { * target: "data", @@ -1388,7 +2039,124 @@ declare module "victory" { * } * ]} */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * The maxBubbleSize prop sets an upper limit for scaling data points in a bubble chart + */ + maxBubbleSize?: number; + /** + * The samples prop specifies how many individual points to plot when plotting + * y as a function of x. Samples is ignored if x props are provided instead. + */ + samples?: number; + /** + * The size prop determines how to scale each data point + */ + size?: number | { (data: any): number }; + /** + * The style prop specifies styles for your VictoryScatter. Any valid inline style properties + * will be applied. Height, width, and padding should be specified via the height, + * width, and padding props, as they are used to calculate the alignment of + * components within chart. In addition to normal style properties, angle and verticalAnchor + * may also be specified via the labels object, and they will be passed as props to + * VictoryLabel, or any custom labelComponent. + * @example {data: {fill: "red"}, labels: {fontSize: 12}} + */ + style?: VictoryStyleInterface; + /** + * The symbol prop determines which symbol should be drawn to represent data points. + */ + symbol?: ScatterSymbolType | { (data: any): ScatterSymbolType }; + } + + /** + * VictoryScatter creates a scatter of points from data. VictoryScatter is a composable component, so it does not include an axis. + * Check out VictoryChart for easy to use scatter plots and more. + */ + export class VictoryScatter extends React.Component<VictoryScatterProps, any> {} + + export interface VictoryStackProps extends VictoryCommonProps, VictoryMultiLabeableProps { + /** + * The categories prop specifies how categorical data for a chart should be ordered. + * This prop should be given as an array of string values, or an object with + * these values for x and y. When categories are not given as an object + * When this prop is set on a wrapper component, it will dictate the categories of + * its the children. If this prop is not set, any categories on child component + * or catigorical data, will be merged to create a shared set of categories. + * @example ["dogs", "cats", "mice"] + */ + categories?: CategoryPropType; + /** + * The colorScale prop is an optional prop that defines the color scale the chart's bars + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryBar will automatically assign + * values from this color scale to the bars unless colors are explicitly provided in the + * `dataAttributes` prop. + */ + colorScale?: ColorScalePropType; + /** + * The domain prop describes the range of values your chart will include. This prop can be + * given as a array of the minimum and maximum expected values for your chart, + * or as an object that specifies separate arrays for x and y. + * If this prop is not provided, a domain will be calculated from data, or other + * available information. + * @example: [-1, 1], {x: [0, 100], y: [0, 1]} + */ + domain?: DomainPropType; + /** + * The domainPadding prop specifies a number of pixels of padding to add to the + * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther + * from the origin to prevent crowding. This prop should be given as an object with + * numbers specified for x and y. + */ + domainPadding?: DomainPaddingPropType; + /** + * The event prop take an array of event objects. Event objects are composed of + * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, (i.e. "data" and "labels"). The childName will refer to an + * individual child of VictoryStack, either by its name prop, or by index. The eventKey + * may optionally be used to select a single element by index or eventKey rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey and childName keys, + * and a mutation key whose value is a function. The target and eventKey and childName keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * childName: "firstBar", + * eventHandlers: { + * onClick: () => { + * return [ + * { + * childName: "secondBar", + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * childName: "secondBar", + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** * Similar to data accessor props `x` and `y`, this prop may be used to functionally * assign eventKeys to data @@ -1401,935 +2169,166 @@ declare module "victory" { */ horizontal?: boolean; /** - * The style prop specifies styles for your VictoryBar. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. In addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} + * The style prop specifies styles for your grouped chart. These styles will be + * applied to all grouped children */ style?: VictoryStyleInterface; + /** + * The xOffset prop is used for grouping stacks of bars. This prop will be set + * by the VictoryGroup component wrapper, or can be set manually. + */ + xOffset?: number; } - + + export class VictoryStack extends React.Component<VictoryStackProps, any> {} + + export interface VictoryPieProps extends VictoryCommonProps, VictoryMultiLabeableProps { + /** + * The colorScale prop is an optional prop that defines the color scale the pie + * will be created on. This prop should be given as an array of CSS colors, or as a string + * corresponding to one of the built in color scales. VictoryPie will automatically assign + * values from this color scale to the pie slices unless colors are explicitly provided in the + * data object + */ + colorScale?: ColorScalePropType; + /** + * The data prop specifies the data to be plotted, + * where data X-value is the slice label (string or number), + * and Y-value is the corresponding number value represented by the slice + * Data should be in the form of an array of data points. + * Each data point may be any format you wish (depending on the `x` and `y` accessor props), + * but by default, an object with x and y properties is expected. + * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], + * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] + */ + data?: any[]; + /** + * The dataComponent prop takes an entire, HTML-complete data component which will be used to + * create slices for each datum in the pie chart. The new element created from the passed + * dataComponent will have the property datum set by the pie chart for the point it renders; + * properties style and pathFunction calculated by VictoryPie; an index property set + * corresponding to the location of the datum in the data provided to the pie; events bound to + * the VictoryPie; and the d3 compatible slice object. + * If a dataComponent is not provided, VictoryPie's Slice component will be used. + */ + dataComponent?: React.ReactElement<any>; + /** + * The labelRadius prop defines the radius of the arc that will be used for positioning each slice label. + * If this prop is not set, the label radius will default to the radius of the pie + label padding. + */ + labelRadius?: number; + /** + * The overall end angle of the pie in degrees. This prop is used in conjunction with + * startAngle to create a pie that spans only a segment of a circle. + */ + endAngle?: number; + /** + * The event prop takes an array of event objects. Event objects are composed of + * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace + * for a given component, so "data" and "labels" are all valid targets for VictoryPie + * events. The eventKey may optionally be used to select a single element by index rather than + * an entire set. The eventHandlers object should be given as an object whose keys are standard + * event names (i.e. onClick) and whose values are event callbacks. The return value + * of an event handler is used to modify elemnts. The return value should be given + * as an object or an array of objects with optional target and eventKey keys, + * and a mutation key whose value is a function. The target and eventKey keys + * will default to those corresponding to the element the event handler was attached to. + * The mutation function will be called with the calculated props for the individual selected + * element (i.e. a single bar), and the object returned from the mutation function + * will override the props of the selected element via object assignment. + * @examples + * events={[ + * { + * target: "data", + * eventKey: 1, + * eventHandlers: { + * onClick: () => { + * return [ + * { + * eventKey: 2, + * mutation: (props) => { + * return {style: merge({}, props.style, {fill: "orange"})}; + * } + * }, { + * eventKey: 2, + * target: "labels", + * mutation: () => { + * return {text: "hey"}; + * } + * } + * ]; + * } + * } + * } + * ]} + */ + events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; + /** + * Similar to data accessor props `x` and `y`, this prop may be used to functionally + * assign eventKeys to data + */ + eventKey?: StringOrNumberOrCallback; + /** + * Specifies the radius of the chart. If this property is not provided it is computed + * from width, height, and padding props + * + */ + radius?: number; + /** + * When creating a donut chart, this prop determines the number of pixels between + * the center of the chart and the inner edge of a donut. When this prop is set to zero + * a regular pie chart is rendered. + */ + innerRadius?: number; + /** + * Set the cornerRadius for every dataComponent (Slice by default) within VictoryPie + */ + cornerRadius?: number; + /** + * The padAngle prop determines the amount of separation between adjacent data slices + * in number of degrees + */ + padAngle?: number; + /** + * The overall start angle of the pie in degrees. This prop is used in conjunction with + * endAngle to create a pie that spans only a segment of a circle. + */ + startAngle?: number; + /** + * The style prop specifies styles for your pie. VictoryPie relies on Radium, + * so valid Radium style objects should work for this prop. Height, width, and + * padding should be specified via the height, width, and padding props. + * @example {data: {stroke: "black"}, label: {fontSize: 10}} + */ + style?: VictoryStyleInterface; + /** + * The x prop specifies how to access the X value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) + */ + x?: DataGetterPropType; + /** + * The y prop specifies how to access the Y value of each data point. + * If given as a function, it will be run on each data point, and returned value will be used. + * If given as an integer, it will be used as an array index for array-type data points. + * If given as a string, it will be used as a property key for object-type data points. + * If given as an array of strings, or a string containing dots or brackets, + * it will be used as a nested object property path (for details see Lodash docs for _.get). + * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). + * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) + */ + y?: DataGetterPropType; + } + /** - * Draw SVG bar charts with React. VictoryBar is a composable component, so it doesn't include axes - * Check out VictoryChart for complete bar charts and more. + * victory-pie draws an SVG pie or donut chart with React. + * Styles and data can be customized by passing in your own values as properties to the component. + * Data changes are animated with VictoryAnimation. */ - export class VictoryBar extends React.Component<VictoryBarProps, any> {} - - export interface VictoryBoxPlotStyleInterface - extends VictoryStyleInterface { - max?: VictoryStyleObject; - maxLabels?: VictoryStyleObject; - min?: VictoryStyleObject; - minLabels?: VictoryStyleObject; - median?: VictoryStyleObject; - medianLabels?: VictoryStyleObject; - q1?: VictoryStyleObject; - q1Labels?: VictoryStyleObject; - q3?: VictoryStyleObject; - q3Labels?: VictoryStyleObject; - } - - export interface VictoryBoxPlotProps - extends VictoryCommonProps, - VictoryDatableProps { - /** - * The boxWidth prop specifies how wide each box should be. If the whiskerWidth - * prop is not set, this prop will also determine the width of the whisker crosshair. - */ - boxWidth?: number; - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryChart, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The labelOrientation prop determines where labels are placed relative to their - * corresponding data. If this prop is not set, it will be set to “top” for - * horizontal charts, and “right” for vertical charts. - */ - labelOrientation?: "top" | "bottom" | "left" | "right"; - /** - * When the boolean labels prop is set to true, the values for min, max, median, - * q1, and q3 will be displayed for each box. For more granular label control, use - * the individual minLabels, maxLabels, medianLabels, q1Labels, and q3Labels props. - */ - labels?: boolean; - /** - * Use the max data accessor prop to define the max value of a box plot. - */ - max?: StringOrNumberOrCallback; - /** - * Use the median data accessor prop to define the median value of a box plot. - */ - median?: StringOrNumberOrCallback; - /** - * Use the min data accessor prop to define the min value of a box plot. - */ - min?: StringOrNumberOrCallback; - /** - * Use the q1 data accessor prop to define the q1 value of a box plot. - */ - q1?: StringOrNumberOrCallback; - /** - * Use the q3 data accessor prop to define the q1 value of a box plot. - */ - q3?: StringOrNumberOrCallback; - /** - * The style prop defines the style of the component. The style prop - * should be given as an object with styles defined for parent, max, - * maxLabels, min, minLabels,median, medianLabels,q1, q1Labels,q3, - * q3Labels. Any valid svg styles are supported, but width, height, a - * nd padding should be specified via props as they determine relative - * layout for components in VictoryChart. Functional styles may be - * defined for style properties, and they will be evaluated with each datum. - */ - style?: VictoryBoxPlotStyleInterface; - /** - * The whiskerWidth prop specifies how wide each whisker crosshair should be. If the - * whiskerWidth prop is not set, the width of the whisker crosshair will match - * the width of the box. - */ - whiskerWidth?: number; - } - - /** - * VictoryBoxPlot renders a box plot to describe the distribution of a set of data. Data for - * VictoryBoxPlot may be given with summary statistics pre-calculated (min, median, max, q1, q3), - * or as an array of raw data. VictoryBoxPlot can be composed with VictoryChart to create box plot charts. - */ - export class VictoryBoxPlot extends React.Component< - VictoryBoxPlotProps, - any - > {} - - export interface VictoryChartProps extends VictoryCommonProps { - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryChart, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<string, StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The style prop specifies styles for your chart. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. - * @example {border: "1px solid #ccc", margin: "2%", maxWidth: "40%"} - */ - style?: Pick<VictoryStyleInterface, 'parent'>; - } - - /** - * A flexible charting component for React. - * VictoryChart composes other Victory components into reusable charts. - * Acting as a coordinator rather than a stand-alone component, VictoryChart reconciles props such as domain and scale for child components, - * and provides a set of sensible defaults. This component works with: - * - VictoryAxis - * - VictoryLine - * - VictoryScatter - * - VictoryBar - */ - export class VictoryChart extends React.Component<VictoryChartProps, any> {} - - export interface VictoryGroupProps extends VictoryCommonProps, VictoryMultiLabeableProps { - /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these values for x and y. When categories are not given as an object - * When this prop is set on a wrapper component, it will dictate the categories of - * its the children. If this prop is not set, any categories on child component - * or categorical data, will be merged to create a shared set of categories. - * @example ["dogs", "cats", "mice"] - */ - categories?: CategoryPropType; - /** - * The colorScale prop is an optional prop that defines the color scale the chart's bars - * will be created on. This prop should be given as an array of CSS colors, or as a string - * corresponding to one of the built in color scales. VictoryBar will automatically assign - * values from this color scale to the bars unless colors are explicitly provided in the - * `dataAttributes` prop. - */ - colorScale?: ColorScalePropType; - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @examples: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryGroup, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The offset prop determines the number of pixels each element in a group should - * be offset from its original position of the on the independent axis. In the - * case of groups of bars, this number should be equal to the width of the bar - * plus the desired spacing between bars. - */ - offset?: number; - /** - * The style prop specifies styles for your grouped chart. These styles will be - * applied to all grouped children - */ - style?: VictoryStyleInterface; - } - - export class VictoryGroup extends React.Component<VictoryGroupProps, any> {} - - export interface VictoryLineProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryLine events. - * Since VictoryLine only renders a single element, the eventKey property is not used. - * The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a line), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * mutation: (props) => { - * return {style: merge({}, props.style, {stroke: "orange"})}; - * } - * }, { - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; - /** - * The interpolation prop determines how data points should be connected - * when plotting a line - */ - interpolation?: InterpolationPropType; - /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - */ - samples?: number; - /** - * The labels prop defines the labels that will appear above each point. - * This prop should be given as an array or as a function of data. - */ - labels?: string[]|number[]|Function; - /** - * Use the sortKey prop to indicate how data should be sorted. This prop - * is given directly to the lodash sortBy function to be executed on the - * final dataset. - */ - sortKey?: string|string[]|Function; - /** - * The style prop specifies styles for your VictoryLine. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. in addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @examples{data: {stroke: "red"}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; - } - - /** - * VictoryLine creates a line based on data. VictoryLine is a composable component, so it does not include an axis. - * Check out VictoryChart for easy to use line charts and more. - */ - export class VictoryLine extends React.Component<VictoryLineProps, any> {} - - export interface VictoryLegendProps extends VictoryCommonProps, VictoryDatableProps, VictorySingleLabableProps { - /** - * The colorScale prop defines a color scale to be applied to each data - * symbol in VictoryLegend. This prop should be given as an array of CSS - * colors, or as a string corresponding to one of the built in color - * scales: "grayscale", "qualitative", "heatmap", "warm", "cool", "red", - * "green", "blue". VictoryLegend will assign a color to each symbol by - * index, unless they are explicitly specified in the data object. - * Colors will repeat when there are more symbols than colors in the - * provided colorScale. - */ - colorScale?: ColorScalePropType; - /** - * The style prop defines the style of the VictoryLegend component. - * The style prop should be given as an object with styles defined for data, labels and - * parent. Any valid svg styles are supported, but width, height, and - * padding should be specified via props as they determine relative - * layout for components in VictoryLegend. - */ - style?: VictoryStyleInterface; - /** - * The containerComponent prop takes a component instance which will be - * used to create a container element for standalone legends. The new - * element created from the passed containerComponent will be provided - * with the following props: height, width, children (the legend itself) - * and style. If a containerComponent is not provided, the default - * VictoryContainer component will be used. VictoryContainer supports - * title and desc props, which are intended to add accessibility to - * Victory components. The more descriptive these props are, the more - * accessible your data will be for people using screen readers. These - * props may be set by passing them directly to the supplied component. - * By default, VictoryContainer renders a responsive svg using the - * viewBox attribute. To render a static container, set - * responsive={false} directly on the instance of VictoryContainer - * supplied via the containerComponent prop. VictoryContainer also - * renders a Portal element that may be used in conjunction with - * VictoryPortal to force components to render above other children. - * @default <VictoryContainer/> - */ - containerComponent?: React.ReactElement<any>; - /** - * Specify data via the data prop. VictoryLegend expects data as an - * array of objects with name (required), symbol, and labels properties. - * The data prop must be given as an array. - */ - data?: Array<{ - name?: string; - symbol?: { - fill?: string; - type?: string; - }; - }>; - /** - * The itemsPerRow prop determines how many items to render in each row - * of a horizontal legend, or in each column of a vertical legend. This - * prop should be given as an integer. When this prop is not given, - * legend items will be rendered in a single row or column. - */ - itemsPerRow?: number; - /** - * The dataComponent prop takes a component instance which will be - * responsible for rendering a data element used to associate a symbol - * or color with each data series. The new element created from the - * passed dataComponent will be provided with the following properties - * calculated by VictoryLegend: x, y, size, style, and symbol. Any of - * these props may be overridden by passing in props to the supplied - * component, or modified or ignored within the custom component itself. - * If a dataComponent is not provided, VictoryLegend will use its - * default Point component. - */ - dataComponent?: React.ReactElement<any>; - /** - * The groupComponent prop takes an entire component which will be used to - * create group elements for use within container elements. This prop defaults - * to a <g> tag on web, and a react-native-svg <G> tag on mobile - * @default <g/> - */ - groupComponent?: React.ReactElement<any>; - /** - * The gutter prop defines the number of pixels between legend rows or - * columns, depending on orientation. When orientation is horizontal, - * gutters are between columns. When orientation is vertical, gutters - * are the space between rows. - */ - gutter?: number; - /** - * The labelComponent prop takes a component instance which will be used - * to render each legend label. The new element created from the passed - * labelComponent will be supplied with the following properties: x, y, - * style, and text. Any of these props may be overridden by passing in - * props to the supplied component, or modified or ignored within the - * custom component itself. If labelComponent is omitted, a new - * VictoryLabel will be created with the props described above. - */ - labelComponent?: React.ReactElement<any>; - /** - * The orientation prop takes a string that defines whether legend data - * are displayed in a row or column. When orientation is "horizontal", - * legend items will be displayed in a single row. When orientation is - * "vertical", legend items will be displayed in a single column. Line - * and text-wrapping is not currently supported, so "vertical" - * orientation is both the default setting and recommended for - * displaying many series of data. - * @default 'vertical' - */ - orientation?: 'horizontal'|'vertical'; - /** - * The padding prop specifies the amount of padding in pixels between - * the edge of the legend and any rendered child components. This prop - * can be given as a number or as an object with padding specified for - * top, bottom, left and right. As with width and height, the absolute - * padding will depend on whether the component is rendered in a - * responsive container. When a component is nested within - * VictoryLegend, setting padding on the child component will have no - * effect. - */ - padding?: number | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - /** - * The standalone props specifies whether the component should be - * rendered in an independent <svg> element or in a <g> tag. This prop - * defaults to true, and renders an svg. - */ - standalone?: boolean; - /** - * The symbolSpacer prop defines the number of pixels between data - * components and label components. - */ - symbolSpacer?: number; - /** - * The width and height props define the width and height of the legend. - * These props may be given as positive numbers or functions of data. If - * these props are not set, width and height will be determined based on - * an approximate text size calculated from the text and style props - * provided to VictoryLegend. - */ - width?: number; - height?: number; - /** - * The x and y props define the base position of the legend element. - */ - x?: number; - y?: number; - } - - /** - * VictoryLegend renders a chart legend component. - */ - export class VictoryLegend extends React.Component<VictoryLegendProps, any> {} - - type ScatterSymbolType = "circle" | "diamond" | "plus" | "square" | "star" | "triangleDown" | "triangleUp"; - - export interface VictoryScatterProps extends VictoryCommonProps, VictoryDatableProps, VictoryMultiLabeableProps { - /** - * The bubbleProperty prop indicates which property of the data object should be used - * to scale data points in a bubble chart - */ - bubbleProperty?: string; - /** - * The event prop take an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryScatter - * events. The eventKey may optionally be used to select a single element by index rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * eventKey: "thisOne", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * eventKey: "theOtherOne", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * eventKey: "theOtherOne", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The maxBubbleSize prop sets an upper limit for scaling data points in a bubble chart - */ - maxBubbleSize?: number; - /** - * The samples prop specifies how many individual points to plot when plotting - * y as a function of x. Samples is ignored if x props are provided instead. - */ - samples?: number; - /** - * The size prop determines how to scale each data point - */ - size?: number | { (data: any): number }; - /** - * The style prop specifies styles for your VictoryScatter. Any valid inline style properties - * will be applied. Height, width, and padding should be specified via the height, - * width, and padding props, as they are used to calculate the alignment of - * components within chart. In addition to normal style properties, angle and verticalAnchor - * may also be specified via the labels object, and they will be passed as props to - * VictoryLabel, or any custom labelComponent. - * @example {data: {fill: "red"}, labels: {fontSize: 12}} - */ - style?: VictoryStyleInterface; - /** - * The symbol prop determines which symbol should be drawn to represent data points. - */ - symbol?: ScatterSymbolType | { (data: any): ScatterSymbolType }; - } - - /** - * VictoryScatter creates a scatter of points from data. VictoryScatter is a composable component, so it does not include an axis. - * Check out VictoryChart for easy to use scatter plots and more. - */ - export class VictoryScatter extends React.Component<VictoryScatterProps, any> {} - - export interface VictoryStackProps extends VictoryCommonProps, VictoryMultiLabeableProps { - /** - * The categories prop specifies how categorical data for a chart should be ordered. - * This prop should be given as an array of string values, or an object with - * these values for x and y. When categories are not given as an object - * When this prop is set on a wrapper component, it will dictate the categories of - * its the children. If this prop is not set, any categories on child component - * or catigorical data, will be merged to create a shared set of categories. - * @example ["dogs", "cats", "mice"] - */ - categories?: CategoryPropType; - /** - * The colorScale prop is an optional prop that defines the color scale the chart's bars - * will be created on. This prop should be given as an array of CSS colors, or as a string - * corresponding to one of the built in color scales. VictoryBar will automatically assign - * values from this color scale to the bars unless colors are explicitly provided in the - * `dataAttributes` prop. - */ - colorScale?: ColorScalePropType; - /** - * The domain prop describes the range of values your chart will include. This prop can be - * given as a array of the minimum and maximum expected values for your chart, - * or as an object that specifies separate arrays for x and y. - * If this prop is not provided, a domain will be calculated from data, or other - * available information. - * @example: [-1, 1], {x: [0, 100], y: [0, 1]} - */ - domain?: DomainPropType; - /** - * The domainPadding prop specifies a number of pixels of padding to add to the - * beginning and end of a domain. This prop is useful for explicitly spacing ticks farther - * from the origin to prevent crowding. This prop should be given as an object with - * numbers specified for x and y. - */ - domainPadding?: DomainPaddingPropType; - /** - * The event prop take an array of event objects. Event objects are composed of - * a childName, target, eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, (i.e. "data" and "labels"). The childName will refer to an - * individual child of VictoryStack, either by its name prop, or by index. The eventKey - * may optionally be used to select a single element by index or eventKey rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey and childName keys, - * and a mutation key whose value is a function. The target and eventKey and childName keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * childName: "firstBar", - * eventHandlers: { - * onClick: () => { - * return [ - * { - * childName: "secondBar", - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * childName: "secondBar", - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * The horizontal prop determines whether the bars will be laid vertically or - * horizontally. The bars will be vertical if this prop is false or unspecified, - * or horizontal if the prop is set to true. - */ - horizontal?: boolean; - /** - * The style prop specifies styles for your grouped chart. These styles will be - * applied to all grouped children - */ - style?: VictoryStyleInterface; - /** - * The xOffset prop is used for grouping stacks of bars. This prop will be set - * by the VictoryGroup component wrapper, or can be set manually. - */ - xOffset?: number; - } - - export class VictoryStack extends React.Component<VictoryStackProps, any> {} - - export interface VictoryPieProps extends VictoryCommonProps, VictoryMultiLabeableProps { - /** - * The colorScale prop is an optional prop that defines the color scale the pie - * will be created on. This prop should be given as an array of CSS colors, or as a string - * corresponding to one of the built in color scales. VictoryPie will automatically assign - * values from this color scale to the pie slices unless colors are explicitly provided in the - * data object - */ - colorScale?: ColorScalePropType; - /** - * The data prop specifies the data to be plotted, - * where data X-value is the slice label (string or number), - * and Y-value is the corresponding number value represented by the slice - * Data should be in the form of an array of data points. - * Each data point may be any format you wish (depending on the `x` and `y` accessor props), - * but by default, an object with x and y properties is expected. - * @example [{x: 1, y: 2}, {x: 2, y: 3}], [[1, 2], [2, 3]], - * [[{x: "a", y: 1}, {x: "b", y: 2}], [{x: "a", y: 2}, {x: "b", y: 3}]] - */ - data?: any[]; - /** - * The dataComponent prop takes an entire, HTML-complete data component which will be used to - * create slices for each datum in the pie chart. The new element created from the passed - * dataComponent will have the property datum set by the pie chart for the point it renders; - * properties style and pathFunction calculated by VictoryPie; an index property set - * corresponding to the location of the datum in the data provided to the pie; events bound to - * the VictoryPie; and the d3 compatible slice object. - * If a dataComponent is not provided, VictoryPie's Slice component will be used. - */ - dataComponent?: React.ReactElement<any>; - /** - * The labelRadius prop defines the radius of the arc that will be used for positioning each slice label. - * If this prop is not set, the label radius will default to the radius of the pie + label padding. - */ - labelRadius?: number; - /** - * The overall end angle of the pie in degrees. This prop is used in conjunction with - * startAngle to create a pie that spans only a segment of a circle. - */ - endAngle?: number; - /** - * The event prop takes an array of event objects. Event objects are composed of - * a target, an eventKey, and eventHandlers. Targets may be any valid style namespace - * for a given component, so "data" and "labels" are all valid targets for VictoryPie - * events. The eventKey may optionally be used to select a single element by index rather than - * an entire set. The eventHandlers object should be given as an object whose keys are standard - * event names (i.e. onClick) and whose values are event callbacks. The return value - * of an event handler is used to modify elemnts. The return value should be given - * as an object or an array of objects with optional target and eventKey keys, - * and a mutation key whose value is a function. The target and eventKey keys - * will default to those corresponding to the element the event handler was attached to. - * The mutation function will be called with the calculated props for the individual selected - * element (i.e. a single bar), and the object returned from the mutation function - * will override the props of the selected element via object assignment. - * @examples - * events={[ - * { - * target: "data", - * eventKey: 1, - * eventHandlers: { - * onClick: () => { - * return [ - * { - * eventKey: 2, - * mutation: (props) => { - * return {style: merge({}, props.style, {fill: "orange"})}; - * } - * }, { - * eventKey: 2, - * target: "labels", - * mutation: () => { - * return {text: "hey"}; - * } - * } - * ]; - * } - * } - * } - * ]} - */ - events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback | string[] | number[]>[]; - /** - * Similar to data accessor props `x` and `y`, this prop may be used to functionally - * assign eventKeys to data - */ - eventKey?: StringOrNumberOrCallback; - /** - * Specifies the radius of the chart. If this property is not provided it is computed - * from width, height, and padding props - * - */ - radius?: number; - /** - * When creating a donut chart, this prop determines the number of pixels between - * the center of the chart and the inner edge of a donut. When this prop is set to zero - * a regular pie chart is rendered. - */ - innerRadius?: number; - /** - * Set the cornerRadius for every dataComponent (Slice by default) within VictoryPie - */ - cornerRadius?: number; - /** - * The padAngle prop determines the amount of separation between adjacent data slices - * in number of degrees - */ - padAngle?: number; - /** - * The overall start angle of the pie in degrees. This prop is used in conjunction with - * endAngle to create a pie that spans only a segment of a circle. - */ - startAngle?: number; - /** - * The style prop specifies styles for your pie. VictoryPie relies on Radium, - * so valid Radium style objects should work for this prop. Height, width, and - * padding should be specified via the height, width, and padding props. - * @example {data: {stroke: "black"}, label: {fontSize: 10}} - */ - style?: VictoryStyleInterface; - /** - * The x prop specifies how to access the X value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'x', 'x.value.nested.1.thing', 'x[2].also.nested', null, d => Math.sin(d) - */ - x?: DataGetterPropType; - /** - * The y prop specifies how to access the Y value of each data point. - * If given as a function, it will be run on each data point, and returned value will be used. - * If given as an integer, it will be used as an array index for array-type data points. - * If given as a string, it will be used as a property key for object-type data points. - * If given as an array of strings, or a string containing dots or brackets, - * it will be used as a nested object property path (for details see Lodash docs for _.get). - * If `null` or `undefined`, the data value will be used as is (identity function/pass-through). - * @example 0, 'y', 'y.value.nested.1.thing', 'y[2].also.nested', null, d => Math.sin(d) - */ - y?: DataGetterPropType; - } - - /** - * victory-pie draws an SVG pie or donut chart with React. - * Styles and data can be customized by passing in your own values as properties to the component. - * Data changes are animated with VictoryAnimation. - */ - export class VictoryPie extends React.Component<VictoryPieProps, any> {} - } - \ No newline at end of file + export class VictoryPie extends React.Component<VictoryPieProps, any> {} + } From 1e389cf9770e25872ff933aec5fc8f331d8d88ce Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Wed, 6 Feb 2019 11:02:02 -0600 Subject: [PATCH 096/197] Add types for @carbon/colors and update paths --- types/carbon__colors/carbon__colors-tests.ts | 3 + types/carbon__colors/index.d.ts | 491 +++++++++++++++++++ types/carbon__colors/tsconfig.json | 19 + types/carbon__colors/tslint.json | 1 + 4 files changed, 514 insertions(+) create mode 100644 types/carbon__colors/carbon__colors-tests.ts create mode 100644 types/carbon__colors/index.d.ts create mode 100644 types/carbon__colors/tsconfig.json create mode 100644 types/carbon__colors/tslint.json diff --git a/types/carbon__colors/carbon__colors-tests.ts b/types/carbon__colors/carbon__colors-tests.ts new file mode 100644 index 0000000000..1df2cea931 --- /dev/null +++ b/types/carbon__colors/carbon__colors-tests.ts @@ -0,0 +1,3 @@ +import { rgba } from "@carbon/colors"; + +rgba("TOTORO", 0.4); // $ExpectType string diff --git a/types/carbon__colors/index.d.ts b/types/carbon__colors/index.d.ts new file mode 100644 index 0000000000..33438d7c66 --- /dev/null +++ b/types/carbon__colors/index.d.ts @@ -0,0 +1,491 @@ +// Type definitions for @carbon/colors 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/colors +// Definitions by: Vince Picone <https://github.com/vpicone> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const black: string; + +export const black100: string; + +export const blue: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const blue10: string; + +export const blue100: string; + +export const blue20: string; + +export const blue30: string; + +export const blue40: string; + +export const blue50: string; + +export const blue60: string; + +export const blue70: string; + +export const blue80: string; + +export const blue90: string; + +export const colors: { + black: { + "100": string; + }; + blue: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + coolGray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + cyan: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + gray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + green: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + magenta: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + orange: { + "40": string; + }; + purple: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + red: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + teal: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + warmGray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; + }; + white: { + "0": string; + }; + yellow: { + "20": string; + }; +}; + +export const coolGray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const coolGray10: string; + +export const coolGray100: string; + +export const coolGray20: string; + +export const coolGray30: string; + +export const coolGray40: string; + +export const coolGray50: string; + +export const coolGray60: string; + +export const coolGray70: string; + +export const coolGray80: string; + +export const coolGray90: string; + +export const cyan: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const cyan10: string; + +export const cyan100: string; + +export const cyan20: string; + +export const cyan30: string; + +export const cyan40: string; + +export const cyan50: string; + +export const cyan60: string; + +export const cyan70: string; + +export const cyan80: string; + +export const cyan90: string; + +export const gray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const gray10: string; + +export const gray100: string; + +export const gray20: string; + +export const gray30: string; + +export const gray40: string; + +export const gray50: string; + +export const gray60: string; + +export const gray70: string; + +export const gray80: string; + +export const gray90: string; + +export const green: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const green10: string; + +export const green100: string; + +export const green20: string; + +export const green30: string; + +export const green40: string; + +export const green50: string; + +export const green60: string; + +export const green70: string; + +export const green80: string; + +export const green90: string; + +export const magenta: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const magenta10: string; + +export const magenta100: string; + +export const magenta20: string; + +export const magenta30: string; + +export const magenta40: string; + +export const magenta50: string; + +export const magenta60: string; + +export const magenta70: string; + +export const magenta80: string; + +export const magenta90: string; + +export const orange: string; + +export const orange40: string; + +export const purple: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const purple10: string; + +export const purple100: string; + +export const purple20: string; + +export const purple30: string; + +export const purple40: string; + +export const purple50: string; + +export const purple60: string; + +export const purple70: string; + +export const purple80: string; + +export const purple90: string; + +export const red: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const red10: string; + +export const red100: string; + +export const red20: string; + +export const red30: string; + +export const red40: string; + +export const red50: string; + +export const red60: string; + +export const red70: string; + +export const red80: string; + +export const red90: string; + +export const teal: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const teal10: string; + +export const teal100: string; + +export const teal20: string; + +export const teal30: string; + +export const teal40: string; + +export const teal50: string; + +export const teal60: string; + +export const teal70: string; + +export const teal80: string; + +export const teal90: string; + +export const warmGray: { + "10": string; + "100": string; + "20": string; + "30": string; + "40": string; + "50": string; + "60": string; + "70": string; + "80": string; + "90": string; +}; + +export const warmGray10: string; + +export const warmGray100: string; + +export const warmGray20: string; + +export const warmGray30: string; + +export const warmGray40: string; + +export const warmGray50: string; + +export const warmGray60: string; + +export const warmGray70: string; + +export const warmGray80: string; + +export const warmGray90: string; + +export const white: string; + +export const white0: string; + +export const yellow: string; + +export const yellow20: string; + +export function rgba(hexcode: string, opacity: number): string; + +export namespace rgba { + const prototype: {}; +} diff --git a/types/carbon__colors/tsconfig.json b/types/carbon__colors/tsconfig.json new file mode 100644 index 0000000000..3b03be1aae --- /dev/null +++ b/types/carbon__colors/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true, + "paths": { + "@carbon/colors": ["carbon__colors"] + } + }, + "files": ["index.d.ts", "carbon__colors-tests.ts"] +} diff --git a/types/carbon__colors/tslint.json b/types/carbon__colors/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/carbon__colors/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From f86b9137fb1b01fb07e1d08eb454cd53e804d0b6 Mon Sep 17 00:00:00 2001 From: Anton Evzhakov <anton@evz.name> Date: Wed, 6 Feb 2019 16:57:30 +0200 Subject: [PATCH 097/197] Add definition for `isSchema()` method signature --- types/yup/index.d.ts | 1 + types/yup/yup-tests.ts | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 9f3cb687a2..88c4890b82 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -26,6 +26,7 @@ export function addMethod<T extends Schema<any>>( export function ref(path: string, options?: { contextPrefix: string }): Ref; export function lazy<T>(fn: (value: T) => Schema<T>): Lazy; export function setLocale(customLocale: LocaleObject): void; +export function isSchema(obj: any): obj is Schema<any>; export const mixed: MixedSchemaConstructor; export const string: StringSchemaConstructor; diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index a90a7df25d..f0404cf8bd 100644 --- a/types/yup/yup-tests.ts +++ b/types/yup/yup-tests.ts @@ -3,6 +3,7 @@ import * as yup from "yup"; // tslint:disable-next-line:no-duplicate-imports import { reach, + isSchema, date, Schema, ObjectSchema, @@ -24,6 +25,10 @@ const schema1 = yup.object().shape({ reach(schema1, "nested.arr.num"); reach(schema1, "nested.arr[].num"); +// isSchema function +const isSchemaResult1: boolean = isSchema(schema1); +const isSchemaResult2: boolean = isSchema({}); + // addMethod function yup.addMethod<NumberSchema>(yup.number, "minimum", function( this, From cfdcd0cb154f1abf23cf9b83c8feea1742596f05 Mon Sep 17 00:00:00 2001 From: racerhere <a0283001@lc02v23l3hv2r.dhcp.ti.com> Date: Wed, 6 Feb 2019 11:17:26 -0600 Subject: [PATCH 098/197] [kissfft-js]: add type declarations for kissfft-js --- types/kissfft-js/index.d.ts | 17 +++++++++++++++++ types/kissfft-js/kissfft-js-tests.ts | 12 ++++++++++++ types/kissfft-js/tsconfig.json | 22 ++++++++++++++++++++++ types/kissfft-js/tslint.json | 1 + 4 files changed, 52 insertions(+) create mode 100644 types/kissfft-js/index.d.ts create mode 100644 types/kissfft-js/kissfft-js-tests.ts create mode 100644 types/kissfft-js/tsconfig.json create mode 100644 types/kissfft-js/tslint.json diff --git a/types/kissfft-js/index.d.ts b/types/kissfft-js/index.d.ts new file mode 100644 index 0000000000..11f41a3505 --- /dev/null +++ b/types/kissfft-js/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for kissfft-js 0.1 +// Project: https://github.com/j-funk/kissfft-js#readme +// Definitions by: racerhere <https://github.com/racerhere> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/types/kissfft-js + +declare abstract class AbstractKissFFT { + constructor(size: number); + forward(input: number[]): number[]; + inverse(input: number[]): number[]; + dispose(): void; +} + +export class FFT extends AbstractKissFFT { +} + +export class FFTR extends AbstractKissFFT { +} diff --git a/types/kissfft-js/kissfft-js-tests.ts b/types/kissfft-js/kissfft-js-tests.ts new file mode 100644 index 0000000000..76c0da2001 --- /dev/null +++ b/types/kissfft-js/kissfft-js-tests.ts @@ -0,0 +1,12 @@ +import {FFT} from "kissfft-js"; +import {FFTR} from "kissfft-js"; + +const fft = new FFT(0); // $ExpectType FFT +fft.forward([1, 2, 3]); // $ExpectType number[] +fft.inverse([1, 2, 3]); // $ExpectType number[] +fft.dispose(); // $ExpectType void + +const fftr = new FFTR(0); // $ExpectType FFTR +fftr.forward([1, 2, 3]); // $ExpectType number[] +fftr.inverse([1, 2, 3]); // $ExpectType number[] +fftr.dispose(); // $ExpectType void diff --git a/types/kissfft-js/tsconfig.json b/types/kissfft-js/tsconfig.json new file mode 100644 index 0000000000..5dfeddfade --- /dev/null +++ b/types/kissfft-js/tsconfig.json @@ -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", + "kissfft-js-tests.ts" + ] +} diff --git a/types/kissfft-js/tslint.json b/types/kissfft-js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/kissfft-js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 24e05c755b45b7e2ba2ec60a37dd00c327ada8e5 Mon Sep 17 00:00:00 2001 From: Deadly0 <xdeadlyx@ya.ru> Date: Wed, 6 Feb 2019 20:27:24 +0300 Subject: [PATCH 099/197] More detailed typing for Meteor.methods(), fixed User model. --- types/meteor/globals/meteor.d.ts | 12 ++++++++++-- types/meteor/meteor.d.ts | 12 ++++++++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/types/meteor/globals/meteor.d.ts b/types/meteor/globals/meteor.d.ts index 7a90b0611e..63f60df310 100644 --- a/types/meteor/globals/meteor.d.ts +++ b/types/meteor/globals/meteor.d.ts @@ -25,7 +25,7 @@ declare module Meteor { _id?: string; username?: string; emails?: UserEmail[]; - createdAt?: number; + createdAt?: Date; profile?: any; services?: any; } @@ -49,7 +49,15 @@ declare module Meteor { /** Error **/ /** Method **/ - function methods(methods: Object): void; + interface MethodThisType { + isSimulation: boolean; + userId: string | null; + connection: Connection | null; + setUserId(userId: string): void; + unblock(): void; + } + + function methods(methods: {[key: string]: (this: MethodThisType, ...args: any[]) => any}): void; function call(name: string, ...args: any[]): any; diff --git a/types/meteor/meteor.d.ts b/types/meteor/meteor.d.ts index ca08c31c98..141b1f7e61 100644 --- a/types/meteor/meteor.d.ts +++ b/types/meteor/meteor.d.ts @@ -26,7 +26,7 @@ declare module "meteor/meteor" { _id?: string; username?: string; emails?: UserEmail[]; - createdAt?: number; + createdAt?: Date; profile?: any; services?: any; } @@ -50,7 +50,15 @@ declare module "meteor/meteor" { /** Error **/ /** Method **/ - function methods(methods: Object): void; + interface MethodThisType { + isSimulation: boolean; + userId: string | null; + connection: Connection | null; + setUserId(userId: string): void; + unblock(): void; + } + + function methods(methods: {[key: string]: (this: MethodThisType, ...args: any[]) => any}): void; function call(name: string, ...args: any[]): any; From 14e3e2b16793f34e0e0525494a192a532ca5e540 Mon Sep 17 00:00:00 2001 From: racerhere <a0283001@lc02v23l3hv2r.dhcp.ti.com> Date: Wed, 6 Feb 2019 11:28:01 -0600 Subject: [PATCH 100/197] [kissfft-js] update tests --- types/kissfft-js/kissfft-js-tests.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/types/kissfft-js/kissfft-js-tests.ts b/types/kissfft-js/kissfft-js-tests.ts index 76c0da2001..7de3255660 100644 --- a/types/kissfft-js/kissfft-js-tests.ts +++ b/types/kissfft-js/kissfft-js-tests.ts @@ -1,12 +1,11 @@ -import {FFT} from "kissfft-js"; -import {FFTR} from "kissfft-js"; +import * as kissFFT from "kissfft-js"; -const fft = new FFT(0); // $ExpectType FFT +const fft = new kissFFT.FFT(0); // $ExpectType FFT fft.forward([1, 2, 3]); // $ExpectType number[] fft.inverse([1, 2, 3]); // $ExpectType number[] fft.dispose(); // $ExpectType void -const fftr = new FFTR(0); // $ExpectType FFTR +const fftr = new kissFFT.FFTR(0); // $ExpectType FFTR fftr.forward([1, 2, 3]); // $ExpectType number[] fftr.inverse([1, 2, 3]); // $ExpectType number[] fftr.dispose(); // $ExpectType void From 67d97feb29fa0dfbe86c7b831837997c385bf917 Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Wed, 6 Feb 2019 12:02:07 -0600 Subject: [PATCH 101/197] Add types for @carbon/themes --- types/carbon__themes/carbon__themes-tests.ts | 59 ++++++++++++++++ types/carbon__themes/index.d.ts | 74 ++++++++++++++++++++ types/carbon__themes/tsconfig.json | 19 +++++ types/carbon__themes/tslint.json | 1 + 4 files changed, 153 insertions(+) create mode 100644 types/carbon__themes/carbon__themes-tests.ts create mode 100644 types/carbon__themes/index.d.ts create mode 100644 types/carbon__themes/tsconfig.json create mode 100644 types/carbon__themes/tslint.json diff --git a/types/carbon__themes/carbon__themes-tests.ts b/types/carbon__themes/carbon__themes-tests.ts new file mode 100644 index 0000000000..7515742031 --- /dev/null +++ b/types/carbon__themes/carbon__themes-tests.ts @@ -0,0 +1,59 @@ +import ThemePackage from "@carbon/themes"; + +interface Theme { + active01: string; + activeDanger: string; + activePrimary: string; + activeSecondary: string; + activeTertiary: string; + activeUI: string; + brand01: string; + brand02: string; + brand03: string; + disabled01: string; + disabled02: string; + disabled03: string; + field01: string; + field02: string; + focus: string; + highlight: string; + hoverDanger: string; + hoverField: string; + hoverPrimary: string; + hoverPrimaryText: string; + hoverRow: string; + hoverSecondary: string; + hoverSelectedUI: string; + hoverTertiary: string; + hoverUI: string; + icon01: string; + icon02: string; + interactive01: string; + interactive02: string; + interactive03: string; + inverse01: string; + inverse02: string; + overlay01: string; + selectedUI: string; + support01: string; + support02: string; + support03: string; + support04: string; + text01: string; + text02: string; + text03: string; + text04: string; + ui01: string; + ui02: string; + ui03: string; + ui04: string; + ui05: string; + uiBackground: string; + visitedLink: string; +} + +const getDefaultTheme = (): Theme => { + return ThemePackage.white; +}; + +getDefaultTheme(); diff --git a/types/carbon__themes/index.d.ts b/types/carbon__themes/index.d.ts new file mode 100644 index 0000000000..e10f17f35c --- /dev/null +++ b/types/carbon__themes/index.d.ts @@ -0,0 +1,74 @@ +// Type definitions for @carbon/themes 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/themes +// Definitions by: Vince Picone <https://github.com/vpicone> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default carbon__themes; + +interface Theme { + active01: string; + activeDanger: string; + activePrimary: string; + activeSecondary: string; + activeTertiary: string; + activeUI: string; + brand01: string; + brand02: string; + brand03: string; + disabled01: string; + disabled02: string; + disabled03: string; + field01: string; + field02: string; + focus: string; + highlight: string; + hoverDanger: string; + hoverField: string; + hoverPrimary: string; + hoverPrimaryText: string; + hoverRow: string; + hoverSecondary: string; + hoverSelectedUI: string; + hoverTertiary: string; + hoverUI: string; + icon01: string; + icon02: string; + interactive01: string; + interactive02: string; + interactive03: string; + inverse01: string; + inverse02: string; + overlay01: string; + selectedUI: string; + support01: string; + support02: string; + support03: string; + support04: string; + text01: string; + text02: string; + text03: string; + text04: string; + ui01: string; + ui02: string; + ui03: string; + ui04: string; + ui05: string; + uiBackground: string; + visitedLink: string; +} + +// The default theme is included as a top level export +type ThemePackage = { + white: Theme; + g10: Theme; + g100: Theme; + g90: Theme; + themes: { + g10: Theme; + g100: Theme; + g90: Theme; + white: Theme; + }; +} & Theme; + +declare const carbon__themes: ThemePackage; diff --git a/types/carbon__themes/tsconfig.json b/types/carbon__themes/tsconfig.json new file mode 100644 index 0000000000..490b17648e --- /dev/null +++ b/types/carbon__themes/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@carbon/themes": ["carbon__themes"] + } + }, + "files": ["index.d.ts", "carbon__themes-tests.ts"] +} diff --git a/types/carbon__themes/tslint.json b/types/carbon__themes/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/carbon__themes/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 97515160efdb573a8e76ae4c73d49b17d817727c Mon Sep 17 00:00:00 2001 From: racerhere <a0283001@lc02v23l3hv2r.dhcp.ti.com> Date: Wed, 6 Feb 2019 12:46:54 -0600 Subject: [PATCH 102/197] [kissfft-js] enable strictFunctionTypes check --- types/kissfft-js/tsconfig.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/kissfft-js/tsconfig.json b/types/kissfft-js/tsconfig.json index 5dfeddfade..5164a8f4bd 100644 --- a/types/kissfft-js/tsconfig.json +++ b/types/kissfft-js/tsconfig.json @@ -13,7 +13,8 @@ ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true }, "files": [ "index.d.ts", From ff0e1f5aa0ddac9c1ae12797bcbcf0ab1fae98aa Mon Sep 17 00:00:00 2001 From: racerhere <a0283001@lc02v23l3hv2r.dhcp.ti.com> Date: Wed, 6 Feb 2019 12:50:22 -0600 Subject: [PATCH 103/197] [kissfft-js] fix lint rule strict-export-declare-modifiers --- types/kissfft-js/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/kissfft-js/index.d.ts b/types/kissfft-js/index.d.ts index 11f41a3505..14977f7aaa 100644 --- a/types/kissfft-js/index.d.ts +++ b/types/kissfft-js/index.d.ts @@ -15,3 +15,5 @@ export class FFT extends AbstractKissFFT { export class FFTR extends AbstractKissFFT { } + +export {} From fd72fae91ed6e896dbcf9802504aab3507dd02d8 Mon Sep 17 00:00:00 2001 From: racerhere <a0283001@lc02v23l3hv2r.dhcp.ti.com> Date: Wed, 6 Feb 2019 12:53:03 -0600 Subject: [PATCH 104/197] [kissfft-js] comply to strict-export-declare-modifiers lint rule --- types/kissfft-js/index.d.ts | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/types/kissfft-js/index.d.ts b/types/kissfft-js/index.d.ts index 14977f7aaa..f03119e4f5 100644 --- a/types/kissfft-js/index.d.ts +++ b/types/kissfft-js/index.d.ts @@ -3,17 +3,16 @@ // Definitions by: racerhere <https://github.com/racerhere> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/types/kissfft-js -declare abstract class AbstractKissFFT { +export class FFT { constructor(size: number); forward(input: number[]): number[]; inverse(input: number[]): number[]; dispose(): void; } -export class FFT extends AbstractKissFFT { -} - -export class FFTR extends AbstractKissFFT { -} - -export {} +export class FFTR { + constructor(size: number); + forward(input: number[]): number[]; + inverse(input: number[]): number[]; + dispose(): void; +} \ No newline at end of file From b27226fdf1f5f87594d113ad695057a88eae1376 Mon Sep 17 00:00:00 2001 From: racerhere <a0283001@lc02v23l3hv2r.dhcp.ti.com> Date: Wed, 6 Feb 2019 12:54:31 -0600 Subject: [PATCH 105/197] [kissfft-js] comply to eofline lint rule --- types/kissfft-js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/kissfft-js/index.d.ts b/types/kissfft-js/index.d.ts index f03119e4f5..dc745354ec 100644 --- a/types/kissfft-js/index.d.ts +++ b/types/kissfft-js/index.d.ts @@ -15,4 +15,4 @@ export class FFTR { forward(input: number[]): number[]; inverse(input: number[]): number[]; dispose(): void; -} \ No newline at end of file +} From 98149d72de09d1e5af3661a8c4b3f1fff8d9de5b Mon Sep 17 00:00:00 2001 From: John Slemmer <john.slemmer@gmail.com> Date: Wed, 6 Feb 2019 11:09:14 -0800 Subject: [PATCH 106/197] createError path and message optional from the documentation at https://github.com/jquense/yup#mixedtestname-string-message-string--function-test-function-schema > this.createError(Object: { path: String, message: String }): create and return a validation error. Useful for dynamically setting the path, or more likely, the error message. *If either option is omitted it will use the current path, or default message*. --- types/yup/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 9f3cb687a2..8fc9461e85 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -227,7 +227,7 @@ export interface TestContext { parent: any; schema: Schema<any>; resolve: (value: any) => any; - createError: (params: { path: string; message: string }) => ValidationError; + createError: (params: { path?: string; message?: string }) => ValidationError; } export interface ValidateOptions { From 6783579dd5789957135d92fe2c9e2c1c8d8ac872 Mon Sep 17 00:00:00 2001 From: John Slemmer <john.slemmer@gmail.com> Date: Wed, 6 Feb 2019 11:16:47 -0800 Subject: [PATCH 107/197] Update yup-tests.ts --- types/yup/yup-tests.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index a90a7df25d..9e63952cc4 100644 --- a/types/yup/yup-tests.ts +++ b/types/yup/yup-tests.ts @@ -199,6 +199,12 @@ const testContext = function(this: TestContext) { this.resolve; // $ExpectType ValidationError this.createError({ path: "1", message: "1" }); + // $ExpectType ValidationError + this.createError({ message: "1" }); + // $ExpectType ValidationError + this.createError({ path: "1"}); + // $ExpectType ValidationError + this.createError(); return true; }; mixed.test("with-context", "it uses function context", testContext); From 9a5a7d1f4ac6cdb6e99ab41e2b6d321fb78be5f3 Mon Sep 17 00:00:00 2001 From: John Slemmer <john.slemmer@gmail.com> Date: Wed, 6 Feb 2019 11:42:46 -0800 Subject: [PATCH 108/197] make createError params optional entirely --- types/yup/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 8fc9461e85..b4a953410f 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -227,7 +227,7 @@ export interface TestContext { parent: any; schema: Schema<any>; resolve: (value: any) => any; - createError: (params: { path?: string; message?: string }) => ValidationError; + createError: (params?: { path?: string; message?: string }) => ValidationError; } export interface ValidateOptions { From 58203a3042527af4163fa34408e87eb19e7c1e39 Mon Sep 17 00:00:00 2001 From: Mischa MacLeod <mischa@singlesource.io> Date: Tue, 5 Feb 2019 12:04:59 +1300 Subject: [PATCH 109/197] keyFromPublic takes an object containing both x and y strings encoded as Hex --- types/elliptic/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/elliptic/index.d.ts b/types/elliptic/index.d.ts index fa8e19a2cf..722568a6f6 100644 --- a/types/elliptic/index.d.ts +++ b/types/elliptic/index.d.ts @@ -176,7 +176,7 @@ export class ec { keyPair(options: ec.KeyPairOptions): ec.KeyPair; keyFromPrivate(priv: Buffer | string | ec.KeyPair, enc?: string): ec.KeyPair; - keyFromPublic(pub: Buffer | string | ec.KeyPair, enc?: string): ec.KeyPair; + keyFromPublic(pub: Buffer | string | {x: string, y: string} | ec.KeyPair, enc?: string): ec.KeyPair; genKeyPair(options?: ec.GenKeyPairOptions): ec.KeyPair; sign(msg: BNInput, key: Buffer | ec.KeyPair, enc: string, options?: ec.SignOptions): ec.Signature; sign(msg: BNInput, key: Buffer | ec.KeyPair, options?: ec.SignOptions): ec.Signature; @@ -201,7 +201,7 @@ export namespace ec { } class KeyPair { - static fromPublic(ec: ec, pub: Buffer | string | KeyPair, enc?: string): KeyPair; + static fromPublic(ec: ec, pub: Buffer | string | {x: string, y: string} | KeyPair, enc?: string): KeyPair; static fromPrivate(ec: ec, priv: Buffer | string | KeyPair, enc?: string): KeyPair; ec: ec; From 5d016cee8f01b5307da196a6feca3583ec5a939c Mon Sep 17 00:00:00 2001 From: Kristoffer <hello@kristoffer.is> Date: Wed, 6 Feb 2019 22:18:13 +0100 Subject: [PATCH 110/197] libxmljs: Type all options --- types/libxmljs/index.d.ts | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/types/libxmljs/index.d.ts b/types/libxmljs/index.d.ts index 5ba3fc294f..6540561a07 100644 --- a/types/libxmljs/index.d.ts +++ b/types/libxmljs/index.d.ts @@ -15,7 +15,40 @@ export const libxml_parser_version: string; interface StringMap { [key: string]: string; } // tslint:disable-next-line:strict-export-declare-modifiers -interface ParserOptions { [key: string]: boolean | string; } +interface ParserOptions { + recover?: boolean; + noent?: boolean; + dtdload?: boolean; + doctype?: boolean; + dtdattr?: any; + dtdvalid?: boolean; + noerror?: boolean; + errors?: boolean; + nowarning?: boolean; + warnings?: boolean; + pedantic?: boolean; + noblanks?: boolean; + blanks?: boolean; + sax1?: boolean; + xinclude?: boolean; + nonet?: boolean; + net?: boolean; + nodict?: boolean; + dict?: boolean; + nsclean?: boolean; + implied?: boolean; + nocdata?: boolean; + cdata?: boolean; + noxincnode?: boolean; + compact?: boolean; + old?: boolean; + nobasefix?: boolean; + basefix?: boolean; + huge?: boolean; + oldsax?: boolean; + ignore_enc?: boolean; + big_lines?: boolean; +} export function parseXml(source: string, options?: ParserOptions): Document; export function parseXmlString(source: string, options?: ParserOptions): Document; From 536174e4b335b716cd68c781cec2bf5e820109f3 Mon Sep 17 00:00:00 2001 From: Jonathan Viney <jonathan.viney@gmail.com> Date: Wed, 6 Feb 2019 12:16:29 +1300 Subject: [PATCH 111/197] [video.js]: add player networkState --- types/video.js/index.d.ts | 14 ++++++++++++++ types/video.js/video.js-tests.ts | 2 ++ 2 files changed, 16 insertions(+) diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index 9bcc8e858e..2c2457e3ea 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -3721,6 +3721,13 @@ declare namespace videojs { HaveEnoughData = 4 } + enum NetworkState { + Empty = 0, + Idle = 1, + Loading = 2, + NoSource = 3 + } + /** * An instance of the `Player` class is created when any of the Video.js setup methods * are used to initialize a video. @@ -4257,6 +4264,13 @@ declare namespace videojs { muted(): boolean; + /** + * Returns the current state of network activity for the element + * + * @return The current network state + */ + networkState(): NetworkState; + /** * Pause the video playback * @check diff --git a/types/video.js/video.js-tests.ts b/types/video.js/video.js-tests.ts index 910085557a..e21d7fe581 100644 --- a/types/video.js/video.js-tests.ts +++ b/types/video.js/video.js-tests.ts @@ -61,6 +61,8 @@ videojs("example_video_1").ready(function() { this.requestFullscreen(); + const networkState: videojs.NetworkState = this.networkState(); + testEvents(this); testComponents(this); From 9e0b1db4347a4357e7e3f11e06e744c93cf32219 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 6 Feb 2019 13:35:10 -0800 Subject: [PATCH 112/197] [jscodeshift] Use 'export =' and 'require' to be consistent with JS implementation --- types/jscodeshift/index.d.ts | 99 +---- types/jscodeshift/src/Collection.d.ts | 32 +- .../src/collections/JSXElement.d.ts | 19 +- types/jscodeshift/src/collections/Node.d.ts | 28 +- .../src/collections/VariableDeclarator.d.ts | 14 +- types/jscodeshift/src/core.d.ts | 363 ++++++++++++++++++ types/jscodeshift/src/template.d.ts | 28 +- .../bind-this-to-bind-expression.ts | 8 +- .../js-transforms/props-to-destructuring.ts | 2 +- types/jscodeshift/tsconfig.json | 1 + 10 files changed, 439 insertions(+), 155 deletions(-) create mode 100644 types/jscodeshift/src/core.d.ts diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts index f4cee2db55..e19423d928 100644 --- a/types/jscodeshift/index.d.ts +++ b/types/jscodeshift/index.d.ts @@ -4,101 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 -import { ASTNode } from "ast-types/gen/nodes"; -import recast, { Builders, NamedTypes, NodePath, Options, Parser } from "recast"; -import { Collection, registerMethods } from "./src/Collection"; -import * as JSXElement from "./src/collections/JSXElement"; -import * as VariableDeclarator from "./src/collections/VariableDeclarator"; -import { Template } from "./src/template"; +import core = require("./src/core"); -export type ASTPath<N = ASTNode> = NodePath<N, N>; - -export interface Filters { - JSXElement: JSXElement.FilterMethods; - VariableDeclarator: VariableDeclarator.FilterMethods; -} - -export interface Mappings { - JSXElement: JSXElement.MappingMethods; -} - -export interface Plugin { - (core: Core): void; -} - -export interface FileInfo { - /** The absolute path to the current file. */ - path: string; - /** The source code of the current file. */ - source: string; -} - -export interface Stats { - /** - * Helper function to collect data during --dry runs. - * This function keeps a counter for how often it was called with a specific argument. - * The result is shown in the console. Useful for finding out how many files match a criterion. - */ - (name: string, quantity?: number): void; -} - -interface Core { - (source: string, options?: Options): Collection<any>; - (source: ASTNode | ASTNode[] | ASTPath | ASTPath[]): Collection<any>; - - registerMethods: typeof registerMethods; - - types: typeof recast.types; - - match(path: ASTNode | ASTPath, filter: ((path: ASTNode) => boolean) | ASTNode): boolean; - - /** template, bound to default parser */ - template: Template; - - filters: Filters; - - mappings: Mappings; - - /** - * Utility function for registering plugins. - * - * Plugins are simple functions that are passed the core jscodeshift instance. - * They should extend jscodeshift by calling `registerMethods`, etc. - * This method guards against repeated registrations (the plugin callback will only be called once). - */ - use(plugin: Plugin): void; - - /** - * Returns a version of the core jscodeshift function "bound" to a specific - * parser. - */ - withParser(parser: string | Parser): JSCodeshift; -} - -type JSCodeshift = Core & NamedTypes & Builders; - -declare const core: JSCodeshift; -export default core; - -export interface API { - j: JSCodeshift; - jscodeshift: JSCodeshift; - stats: Stats; - report: (msg: string) => void; -} - -export interface Options { - [option: string]: any; -} - -export interface Transform { - /** - * If a string is returned and it is different from passed source, the transform is considered to be successful. - * If a string is returned but it's the same as the source, the transform is considered to be unsuccessful. - * If nothing is returned, the file is not supposed to be transformed (which is ok). - */ - (file: FileInfo, api: API, options: Options): string | null | undefined | void; -} - -export * from "ast-types/gen/nodes"; -export { Collection, Parser }; +export = core; diff --git a/types/jscodeshift/src/Collection.d.ts b/types/jscodeshift/src/Collection.d.ts index 5ddf7b2bdc..2cab87b153 100644 --- a/types/jscodeshift/src/Collection.d.ts +++ b/types/jscodeshift/src/Collection.d.ts @@ -1,9 +1,9 @@ -import { ASTNode, NodePath, Options, Type } from "recast"; -import * as JSXElement from "./collections/JSXElement"; -import * as NodeCollection from "./collections/Node"; -import * as VariableDeclarator from "./collections/VariableDeclarator"; +import recast = require("recast"); +import JSXElement = require("./collections/JSXElement"); +import NodeCollection = require("./collections/Node"); +import VariableDeclarator = require("./collections/VariableDeclarator"); -type ASTPath<N> = NodePath<N, N>; +type ASTPath<N> = recast.NodePath<N, N>; export interface Collection<N> extends NodeCollection.TraversalMethods, @@ -18,7 +18,7 @@ export interface Collection<N> * @param types An array of types all the paths in the collection * have in common. If not passed, it will be inferred from the paths. */ - new (paths: Array<ASTPath<N>>, parent: Collection<any>, types?: Array<Type<any>>): this; + new (paths: Array<ASTPath<N>>, parent: Collection<any>, types?: Array<recast.Type<any>>): this; /** * Returns a new collection containing the nodes for which the callback returns true. @@ -58,13 +58,13 @@ export interface Collection<N> * @param callback * @param type Force the new collection to be of a specific type */ - map<T = ASTNode>( + map<T = recast.ASTNode>( callback: ( path: ASTPath<N>, i: number, paths: Array<ASTPath<N>> ) => ASTPath<T> | Array<ASTPath<T>> | null | undefined, - type: Type<any> + type: recast.Type<any> ): Collection<T>; /** Returns the number of elements in this collection. */ @@ -85,7 +85,7 @@ export interface Collection<N> * Converts the AST back to a string, using recast. * @param options directly passed to recast's printer */ - toSource(options?: Options): string; + toSource(options?: recast.Options): string; /** * Returns a new collection containing only the element at position index. @@ -107,9 +107,13 @@ export interface Collection<N> /** * Returns true if this collection has the type 'type'. */ - isOfType(type: Type<any>): boolean; + isOfType(type: recast.Type<any>): boolean; } +export function fromPaths(...args: any[]): any; + +export function fromNodes(...args: any[]): any; + /** * This function adds the provided methods to the prototype of the corresponding * typed collection. If no type is passed, the methods are added to @@ -118,6 +122,10 @@ export interface Collection<N> * @param methods Methods to add to the prototype * @param type Optional type to add the methods to */ -export function registerMethods(methods: object, type?: Type<any>): void; +export function registerMethods(methods: object, type?: recast.Type<any>): void; -export { }; // to shut off automatic exporting +export function hasConflictingRegistration(...args: any[]): any; + +export function setDefaultCollectionType(...args: any[]): any; + +export {}; // shut off automatic exporting diff --git a/types/jscodeshift/src/collections/JSXElement.d.ts b/types/jscodeshift/src/collections/JSXElement.d.ts index 730c33ad90..0490e40f76 100644 --- a/types/jscodeshift/src/collections/JSXElement.d.ts +++ b/types/jscodeshift/src/collections/JSXElement.d.ts @@ -1,14 +1,15 @@ -import { JSXElement } from "ast-types/gen/nodes"; -import { NodePath } from "recast"; -import { Collection } from "../Collection"; +import nodes = require("ast-types/gen/nodes"); +import recast = require("recast"); +import Collection = require("../Collection"); -type ASTPath<N> = NodePath<N, N>; +type ASTPath<N> = recast.NodePath<N, N>; +type JSXElement = nodes.JSXElement; export interface GlobalMethods { /** * Finds all JSXElements optionally filtered by name */ - findJSXElements(name?: string): Collection<JSXElement>; + findJSXElements(name?: string): Collection.Collection<JSXElement>; /** * Finds all JSXElements by module name. Given @@ -19,7 +20,7 @@ export interface GlobalMethods { * findJSXElementsByModuleName('Foo') will find <Bar />, without having to * know the variable name. */ - findJSXElementsByModuleName(moduleName: string): Collection<JSXElement>; + findJSXElementsByModuleName(moduleName: string): Collection.Collection<JSXElement>; } type Defined<T> = T extends undefined ? never : T; @@ -30,13 +31,13 @@ export interface TraversalMethods { * Returns all child nodes, including literals and expressions. * This method only applies to JSXElement typed collections. */ - childNodes(): Collection<JSXElementChild>; + childNodes(): Collection.Collection<JSXElementChild>; /** * Returns all children that are JSXElements. * This method only applies to JSXElement typed collections. */ - childElements(): Collection<JSXElement>; + childElements(): Collection.Collection<JSXElement>; } interface Filter { @@ -67,4 +68,4 @@ export function register(): void; export const filters: FilterMethods; export const mappings: MappingMethods; -export { }; // to shut off automatic exporting +export {}; // shut off automatic exporting diff --git a/types/jscodeshift/src/collections/Node.d.ts b/types/jscodeshift/src/collections/Node.d.ts index e596c8a8ab..d1e74f314d 100644 --- a/types/jscodeshift/src/collections/Node.d.ts +++ b/types/jscodeshift/src/collections/Node.d.ts @@ -1,34 +1,34 @@ -import { VariableDeclarator } from "ast-types/gen/nodes"; -import { ASTNode, NodePath, Type } from "recast"; -import { Collection } from "../Collection"; +import nodes = require("ast-types/gen/nodes"); +import recast = require("recast"); +import Collection = require("../Collection"); -type ASTPath<N> = NodePath<N, N>; +type ASTPath<N> = recast.NodePath<N, N>; export interface TraversalMethods { /** * Find nodes of a specific type within the nodes of this collection. */ - find<T>(type: Type<T>, filter?: ((value: any) => boolean) | object): Collection<T>; + find<T>(type: recast.Type<T>, filter?: ((value: any) => boolean) | object): Collection.Collection<T>; /** * Returns a collection containing the paths that create the scope of the * currently selected paths. Dedupes the paths. */ - closestScope(): Collection<ASTNode>; + closestScope(): Collection.Collection<nodes.ASTNode>; /** * Traverse the AST up and finds the closest node of the provided type. */ - closest<T>(type: Type<T>, filter?: any): Collection<T>; + closest<T>(type: recast.Type<T>, filter?: any): Collection.Collection<T>; /** * Finds the declaration for each selected path. Useful for member expressions * or JSXElements. Expects a callback function that maps each path to the name * to look for. * - * If the callback returns a falsey value, the element is skipped. + * If the callback returns a falsy value, the element is skipped. */ - getVariableDeclarators(nameGetter: (...args: any[]) => any): Collection<VariableDeclarator>; + getVariableDeclarators(nameGetter: (...args: any[]) => any): Collection.Collection<nodes.VariableDeclarator>; } export interface MutationMethods<N> { @@ -37,21 +37,21 @@ export interface MutationMethods<N> { * is provided it is executed for every node and the node is replaced with the * functions return value. */ - replaceWith<T>(nodes: T | T[] | ((path: ASTPath<N>, i: number) => T)): Collection<T>; + replaceWith<T>(nodes: T | T[] | ((path: ASTPath<N>, i: number) => T)): Collection.Collection<T>; /** * Inserts a new node before the current one. */ - insertBefore(insert: any): Collection<N>; + insertBefore(insert: any): Collection.Collection<N>; /** * Inserts a new node after the current one. */ - insertAfter(insert: any): Collection<N>; + insertAfter(insert: any): Collection.Collection<N>; - remove(): Collection<N>; + remove(): Collection.Collection<N>; } export function register(): void; -export { }; // to shut off automatic exporting +export {}; // shut off automatic exporting diff --git a/types/jscodeshift/src/collections/VariableDeclarator.d.ts b/types/jscodeshift/src/collections/VariableDeclarator.d.ts index 8627b316db..eb7c8bcdfd 100644 --- a/types/jscodeshift/src/collections/VariableDeclarator.d.ts +++ b/types/jscodeshift/src/collections/VariableDeclarator.d.ts @@ -1,14 +1,14 @@ -import { VariableDeclarator } from "ast-types/gen/nodes"; -import { NodePath } from "recast"; -import { Collection } from "../Collection"; +import nodes = require("ast-types/gen/nodes"); +import recast = require("recast"); +import Collection = require("../Collection"); -type ASTPath<N> = NodePath<N, N>; +type ASTPath<N> = recast.NodePath<N, N>; export interface GlobalMethods { /** * Finds all variable declarators, optionally filtered by name. */ - findVariableDeclarators(name?: string): Collection<VariableDeclarator>; + findVariableDeclarators(name?: string): Collection.Collection<nodes.VariableDeclarator>; } export interface TransformMethods<N> { @@ -16,7 +16,7 @@ export interface TransformMethods<N> { * Renames a variable and all its occurrences. * This method only applies to VariableDeclarator typed collections. */ - renameTo(newName: string): Collection<N>; + renameTo(newName: string): Collection.Collection<N>; } interface Filter { @@ -36,4 +36,4 @@ export interface FilterMethods { export function register(): void; export const filters: FilterMethods; -export { }; // to shut off automatic exporting +export {}; // shut off automatic exporting diff --git a/types/jscodeshift/src/core.d.ts b/types/jscodeshift/src/core.d.ts new file mode 100644 index 0000000000..9b9f48305d --- /dev/null +++ b/types/jscodeshift/src/core.d.ts @@ -0,0 +1,363 @@ +import nodes = require("ast-types/gen/nodes"); +import recast = require("recast"); +import Collection = require("./Collection"); +import template = require("./template"); +import VariableDeclarator = require("./collections/VariableDeclarator"); +import JSXElement = require("./collections/JSXElement"); + +declare namespace core { + type Parser = recast.Parser; + + interface Filters { + JSXElement: JSXElement.FilterMethods; + VariableDeclarator: VariableDeclarator.FilterMethods; + } + + interface Mappings { + JSXElement: JSXElement.MappingMethods; + } + + interface Plugin { + (core: Core): void; + } + + interface FileInfo { + /** The absolute path to the current file. */ + path: string; + /** The source code of the current file. */ + source: string; + } + + interface Stats { + /** + * Helper function to collect data during --dry runs. + * This function keeps a counter for how often it was called with a specific argument. + * The result is shown in the console. Useful for finding out how many files match a criterion. + */ + (name: string, quantity?: number): void; + } + + type ASTPath<N = ASTNode> = recast.NodePath<N, N>; + + interface Core { + (source: string, options?: Options): Collection.Collection<any>; + (source: ASTNode | ASTNode[] | ASTPath | ASTPath[]): Collection.Collection<any>; + + registerMethods: typeof Collection.registerMethods; + + types: typeof recast.default.types; + + match( + path: ASTNode | ASTPath, + filter: ((path: ASTNode) => boolean) | ASTNode + ): boolean; + + /** template, bound to default parser */ + template: template.Template; + + filters: Filters; + + mappings: Mappings; + + /** + * Utility function for registering plugins. + * + * Plugins are simple functions that are passed the core jscodeshift instance. + * They should extend jscodeshift by calling `registerMethods`, etc. + * This method guards against repeated registrations (the plugin callback will only be called once). + */ + use(plugin: Plugin): void; + + /** + * Returns a version of the core jscodeshift function "bound" to a specific + * parser. + */ + withParser(parser: string | Parser): JSCodeshift; + } + + type JSCodeshift = Core & recast.NamedTypes & recast.Builders; + + interface API { + j: JSCodeshift; + jscodeshift: JSCodeshift; + stats: Stats; + report: (msg: string) => void; + } + + interface Options { + [option: string]: any; + } + + interface Transform { + /** + * If a string is returned and it is different from passed source, the transform is considered to be successful. + * If a string is returned but it's the same as the source, the transform is considered to be unsuccessful. + * If nothing is returned, the file is not supposed to be transformed (which is ok). + */ + (file: FileInfo, api: API, options: Options): string | null | undefined | void; + } + + type ASTNode = nodes.ASTNode; + + type AnyTypeAnnotation = nodes.AnyTypeAnnotation; + type ArrayExpression = nodes.ArrayExpression; + type ArrayPattern = nodes.ArrayPattern; + type ArrayTypeAnnotation = nodes.ArrayTypeAnnotation; + type ArrowFunctionExpression = nodes.ArrowFunctionExpression; + type AssignmentExpression = nodes.AssignmentExpression; + type AssignmentPattern = nodes.AssignmentPattern; + type AwaitExpression = nodes.AwaitExpression; + type BigIntLiteral = nodes.BigIntLiteral; + type BinaryExpression = nodes.BinaryExpression; + type BindExpression = nodes.BindExpression; + type Block = nodes.Block; + type BlockStatement = nodes.BlockStatement; + type BooleanLiteral = nodes.BooleanLiteral; + type BooleanLiteralTypeAnnotation = nodes.BooleanLiteralTypeAnnotation; + type BooleanTypeAnnotation = nodes.BooleanTypeAnnotation; + type BreakStatement = nodes.BreakStatement; + type CallExpression = nodes.CallExpression; + type CatchClause = nodes.CatchClause; + type ClassBody = nodes.ClassBody; + type ClassDeclaration = nodes.ClassDeclaration; + type ClassExpression = nodes.ClassExpression; + type ClassImplements = nodes.ClassImplements; + type ClassMethod = nodes.ClassMethod; + type ClassPrivateMethod = nodes.ClassPrivateMethod; + type ClassPrivateProperty = nodes.ClassPrivateProperty; + type ClassProperty = nodes.ClassProperty; + type ClassPropertyDefinition = nodes.ClassPropertyDefinition; + type Comment = nodes.Comment; + type CommentBlock = nodes.CommentBlock; + type CommentLine = nodes.CommentLine; + type ComprehensionBlock = nodes.ComprehensionBlock; + type ComprehensionExpression = nodes.ComprehensionExpression; + type ConditionalExpression = nodes.ConditionalExpression; + type ContinueStatement = nodes.ContinueStatement; + type DebuggerStatement = nodes.DebuggerStatement; + type Declaration = nodes.Declaration; + type DeclareClass = nodes.DeclareClass; + type DeclaredPredicate = nodes.DeclaredPredicate; + type DeclareExportAllDeclaration = nodes.DeclareExportAllDeclaration; + type DeclareExportDeclaration = nodes.DeclareExportDeclaration; + type DeclareFunction = nodes.DeclareFunction; + type DeclareInterface = nodes.DeclareInterface; + type DeclareModule = nodes.DeclareModule; + type DeclareModuleExports = nodes.DeclareModuleExports; + type DeclareOpaqueType = nodes.DeclareOpaqueType; + type DeclareTypeAlias = nodes.DeclareTypeAlias; + type DeclareVariable = nodes.DeclareVariable; + type Decorator = nodes.Decorator; + type Directive = nodes.Directive; + type DirectiveLiteral = nodes.DirectiveLiteral; + type DoExpression = nodes.DoExpression; + type DoWhileStatement = nodes.DoWhileStatement; + type EmptyStatement = nodes.EmptyStatement; + type EmptyTypeAnnotation = nodes.EmptyTypeAnnotation; + type ExistentialTypeParam = nodes.ExistentialTypeParam; + type ExistsTypeAnnotation = nodes.ExistsTypeAnnotation; + type ExportAllDeclaration = nodes.ExportAllDeclaration; + type ExportBatchSpecifier = nodes.ExportBatchSpecifier; + type ExportDeclaration = nodes.ExportDeclaration; + type ExportDefaultDeclaration = nodes.ExportDefaultDeclaration; + type ExportDefaultSpecifier = nodes.ExportDefaultSpecifier; + type ExportNamedDeclaration = nodes.ExportNamedDeclaration; + type ExportNamespaceSpecifier = nodes.ExportNamespaceSpecifier; + type ExportSpecifier = nodes.ExportSpecifier; + type Expression = nodes.Expression; + type ExpressionStatement = nodes.ExpressionStatement; + type File = nodes.File; + type Flow = nodes.Flow; + type FlowPredicate = nodes.FlowPredicate; + type FlowType = nodes.FlowType; + type ForAwaitStatement = nodes.ForAwaitStatement; + type ForInStatement = nodes.ForInStatement; + type ForOfStatement = nodes.ForOfStatement; + type ForStatement = nodes.ForStatement; + type Function = nodes.Function; + type FunctionDeclaration = nodes.FunctionDeclaration; + type FunctionExpression = nodes.FunctionExpression; + type FunctionTypeAnnotation = nodes.FunctionTypeAnnotation; + type FunctionTypeParam = nodes.FunctionTypeParam; + type GeneratorExpression = nodes.GeneratorExpression; + type GenericTypeAnnotation = nodes.GenericTypeAnnotation; + type Identifier = nodes.Identifier; + type IfStatement = nodes.IfStatement; + type Import = nodes.Import; + type ImportDeclaration = nodes.ImportDeclaration; + type ImportDefaultSpecifier = nodes.ImportDefaultSpecifier; + type ImportNamespaceSpecifier = nodes.ImportNamespaceSpecifier; + type ImportSpecifier = nodes.ImportSpecifier; + type InferredPredicate = nodes.InferredPredicate; + type InterfaceDeclaration = nodes.InterfaceDeclaration; + type InterfaceExtends = nodes.InterfaceExtends; + type InterfaceTypeAnnotation = nodes.InterfaceTypeAnnotation; + type InterpreterDirective = nodes.InterpreterDirective; + type IntersectionTypeAnnotation = nodes.IntersectionTypeAnnotation; + type JSXAttribute = nodes.JSXAttribute; + type JSXClosingElement = nodes.JSXClosingElement; + type JSXClosingFragment = nodes.JSXClosingFragment; + type JSXElement = nodes.JSXElement; + type JSXEmptyExpression = nodes.JSXEmptyExpression; + type JSXExpressionContainer = nodes.JSXExpressionContainer; + type JSXFragment = nodes.JSXFragment; + type JSXIdentifier = nodes.JSXIdentifier; + type JSXMemberExpression = nodes.JSXMemberExpression; + type JSXNamespacedName = nodes.JSXNamespacedName; + type JSXOpeningElement = nodes.JSXOpeningElement; + type JSXOpeningFragment = nodes.JSXOpeningFragment; + type JSXSpreadAttribute = nodes.JSXSpreadAttribute; + type JSXSpreadChild = nodes.JSXSpreadChild; + type JSXText = nodes.JSXText; + type LabeledStatement = nodes.LabeledStatement; + type Line = nodes.Line; + type Literal = nodes.Literal; + type LogicalExpression = nodes.LogicalExpression; + type MemberExpression = nodes.MemberExpression; + type MemberTypeAnnotation = nodes.MemberTypeAnnotation; + type MetaProperty = nodes.MetaProperty; + type MethodDefinition = nodes.MethodDefinition; + type MixedTypeAnnotation = nodes.MixedTypeAnnotation; + type ModuleSpecifier = nodes.ModuleSpecifier; + type NewExpression = nodes.NewExpression; + type Node = nodes.Node; + type Noop = nodes.Noop; + type NullableTypeAnnotation = nodes.NullableTypeAnnotation; + type NullLiteral = nodes.NullLiteral; + type NullLiteralTypeAnnotation = nodes.NullLiteralTypeAnnotation; + type NullTypeAnnotation = nodes.NullTypeAnnotation; + type NumberLiteralTypeAnnotation = nodes.NumberLiteralTypeAnnotation; + type NumberTypeAnnotation = nodes.NumberTypeAnnotation; + type NumericLiteral = nodes.NumericLiteral; + type NumericLiteralTypeAnnotation = nodes.NumericLiteralTypeAnnotation; + type ObjectExpression = nodes.ObjectExpression; + type ObjectMethod = nodes.ObjectMethod; + type ObjectPattern = nodes.ObjectPattern; + type ObjectProperty = nodes.ObjectProperty; + type ObjectTypeAnnotation = nodes.ObjectTypeAnnotation; + type ObjectTypeCallProperty = nodes.ObjectTypeCallProperty; + type ObjectTypeIndexer = nodes.ObjectTypeIndexer; + type ObjectTypeInternalSlot = nodes.ObjectTypeInternalSlot; + type ObjectTypeProperty = nodes.ObjectTypeProperty; + type ObjectTypeSpreadProperty = nodes.ObjectTypeSpreadProperty; + type OpaqueType = nodes.OpaqueType; + type OptionalCallExpression = nodes.OptionalCallExpression; + type OptionalMemberExpression = nodes.OptionalMemberExpression; + type ParenthesizedExpression = nodes.ParenthesizedExpression; + type Pattern = nodes.Pattern; + type Position = nodes.Position; + type Printable = nodes.Printable; + type PrivateName = nodes.PrivateName; + type Program = nodes.Program; + type Property = nodes.Property; + type PropertyPattern = nodes.PropertyPattern; + type QualifiedTypeIdentifier = nodes.QualifiedTypeIdentifier; + type RegExpLiteral = nodes.RegExpLiteral; + type RestElement = nodes.RestElement; + type RestProperty = nodes.RestProperty; + type ReturnStatement = nodes.ReturnStatement; + type SequenceExpression = nodes.SequenceExpression; + type SourceLocation = nodes.SourceLocation; + type Specifier = nodes.Specifier; + type SpreadElement = nodes.SpreadElement; + type SpreadElementPattern = nodes.SpreadElementPattern; + type SpreadProperty = nodes.SpreadProperty; + type SpreadPropertyPattern = nodes.SpreadPropertyPattern; + type Statement = nodes.Statement; + type StringLiteral = nodes.StringLiteral; + type StringLiteralTypeAnnotation = nodes.StringLiteralTypeAnnotation; + type StringTypeAnnotation = nodes.StringTypeAnnotation; + type Super = nodes.Super; + type SwitchCase = nodes.SwitchCase; + type SwitchStatement = nodes.SwitchStatement; + type TaggedTemplateExpression = nodes.TaggedTemplateExpression; + type TemplateElement = nodes.TemplateElement; + type TemplateLiteral = nodes.TemplateLiteral; + type ThisExpression = nodes.ThisExpression; + type ThisTypeAnnotation = nodes.ThisTypeAnnotation; + type ThrowStatement = nodes.ThrowStatement; + type TryStatement = nodes.TryStatement; + type TSAnyKeyword = nodes.TSAnyKeyword; + type TSArrayType = nodes.TSArrayType; + type TSAsExpression = nodes.TSAsExpression; + type TSBooleanKeyword = nodes.TSBooleanKeyword; + type TSCallSignatureDeclaration = nodes.TSCallSignatureDeclaration; + type TSConditionalType = nodes.TSConditionalType; + type TSConstructorType = nodes.TSConstructorType; + type TSConstructSignatureDeclaration = nodes.TSConstructSignatureDeclaration; + type TSDeclareFunction = nodes.TSDeclareFunction; + type TSDeclareMethod = nodes.TSDeclareMethod; + type TSEnumDeclaration = nodes.TSEnumDeclaration; + type TSEnumMember = nodes.TSEnumMember; + type TSExportAssignment = nodes.TSExportAssignment; + type TSExpressionWithTypeArguments = nodes.TSExpressionWithTypeArguments; + type TSExternalModuleReference = nodes.TSExternalModuleReference; + type TSFunctionType = nodes.TSFunctionType; + type TSHasOptionalTypeAnnotation = nodes.TSHasOptionalTypeAnnotation; + type TSHasOptionalTypeParameters = nodes.TSHasOptionalTypeParameters; + type TSImportEqualsDeclaration = nodes.TSImportEqualsDeclaration; + type TSIndexedAccessType = nodes.TSIndexedAccessType; + type TSIndexSignature = nodes.TSIndexSignature; + type TSInferType = nodes.TSInferType; + type TSInterfaceBody = nodes.TSInterfaceBody; + type TSInterfaceDeclaration = nodes.TSInterfaceDeclaration; + type TSIntersectionType = nodes.TSIntersectionType; + type TSLiteralType = nodes.TSLiteralType; + type TSMappedType = nodes.TSMappedType; + type TSMethodSignature = nodes.TSMethodSignature; + type TSModuleBlock = nodes.TSModuleBlock; + type TSModuleDeclaration = nodes.TSModuleDeclaration; + type TSNamespaceExportDeclaration = nodes.TSNamespaceExportDeclaration; + type TSNeverKeyword = nodes.TSNeverKeyword; + type TSNonNullExpression = nodes.TSNonNullExpression; + type TSNullKeyword = nodes.TSNullKeyword; + type TSNumberKeyword = nodes.TSNumberKeyword; + type TSObjectKeyword = nodes.TSObjectKeyword; + type TSOptionalType = nodes.TSOptionalType; + type TSParameterProperty = nodes.TSParameterProperty; + type TSParenthesizedType = nodes.TSParenthesizedType; + type TSPropertySignature = nodes.TSPropertySignature; + type TSQualifiedName = nodes.TSQualifiedName; + type TSRestType = nodes.TSRestType; + type TSStringKeyword = nodes.TSStringKeyword; + type TSSymbolKeyword = nodes.TSSymbolKeyword; + type TSThisType = nodes.TSThisType; + type TSTupleType = nodes.TSTupleType; + type TSType = nodes.TSType; + type TSTypeAliasDeclaration = nodes.TSTypeAliasDeclaration; + type TSTypeAnnotation = nodes.TSTypeAnnotation; + type TSTypeAssertion = nodes.TSTypeAssertion; + type TSTypeLiteral = nodes.TSTypeLiteral; + type TSTypeOperator = nodes.TSTypeOperator; + type TSTypeParameter = nodes.TSTypeParameter; + type TSTypeParameterDeclaration = nodes.TSTypeParameterDeclaration; + type TSTypeParameterInstantiation = nodes.TSTypeParameterInstantiation; + type TSTypePredicate = nodes.TSTypePredicate; + type TSTypeQuery = nodes.TSTypeQuery; + type TSTypeReference = nodes.TSTypeReference; + type TSUndefinedKeyword = nodes.TSUndefinedKeyword; + type TSUnionType = nodes.TSUnionType; + type TSUnknownKeyword = nodes.TSUnknownKeyword; + type TSVoidKeyword = nodes.TSVoidKeyword; + type TupleTypeAnnotation = nodes.TupleTypeAnnotation; + type TypeAlias = nodes.TypeAlias; + type TypeAnnotation = nodes.TypeAnnotation; + type TypeCastExpression = nodes.TypeCastExpression; + type TypeofTypeAnnotation = nodes.TypeofTypeAnnotation; + type TypeParameter = nodes.TypeParameter; + type TypeParameterDeclaration = nodes.TypeParameterDeclaration; + type TypeParameterInstantiation = nodes.TypeParameterInstantiation; + type UnaryExpression = nodes.UnaryExpression; + type UnionTypeAnnotation = nodes.UnionTypeAnnotation; + type UpdateExpression = nodes.UpdateExpression; + type VariableDeclaration = nodes.VariableDeclaration; + type VariableDeclarator = nodes.VariableDeclarator; + type Variance = nodes.Variance; + type VoidTypeAnnotation = nodes.VoidTypeAnnotation; + type WhileStatement = nodes.WhileStatement; + type WithStatement = nodes.WithStatement; + type YieldExpression = nodes.YieldExpression; +} + +declare const core: core.JSCodeshift; +export = core; diff --git a/types/jscodeshift/src/template.d.ts b/types/jscodeshift/src/template.d.ts index 44bfab9be3..cfc0a3c543 100644 --- a/types/jscodeshift/src/template.d.ts +++ b/types/jscodeshift/src/template.d.ts @@ -1,14 +1,18 @@ -import { Parser } from "recast"; +import recast = require("recast"); -export interface Template { - /** Tagged template function. Parses the string as source and returns an array of Statement AST nodes. */ - statements(...args: any[]): any; - /** Tagged template function. Parses the string as source and returns an Statement AST node. */ - statement(...args: any[]): any; - /** Tagged template function. Parses the string as source and returns an Expression AST node. */ - expression(...args: any[]): any; +export = template; + +declare const template: typeof withParser; + +declare function withParser(parser: recast.Parser): template.Template; + +declare namespace template { + interface Template { + /** Tagged template function. Parses the string as source and returns an array of Statement AST nodes. */ + statements(...args: any[]): any; + /** Tagged template function. Parses the string as source and returns an Statement AST node. */ + statement(...args: any[]): any; + /** Tagged template function. Parses the string as source and returns an Expression AST node. */ + expression(...args: any[]): any; + } } - -export default function withParser(parser: Parser): Template; - -export { }; // to shut off automatic exporting diff --git a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts index 6bd9be1fc8..1c6d8cda56 100644 --- a/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts +++ b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts @@ -8,9 +8,9 @@ * let x = ::this.foo; * */ -import { Transform, MemberExpression } from "jscodeshift"; +import j = require("jscodeshift"); -const transform: Transform = (file, api) => { +const transform: j.Transform = (file, api) => { const j = api.jscodeshift; return j(file.source) // Find stuff that looks like this.xyz.bind(this) @@ -18,6 +18,8 @@ const transform: Transform = (file, api) => { // Ensure that .bind() is being called with only one argument, and that argument is "this". .filter(p => p.value.arguments.length === 1 && p.value.arguments[0].type === "ThisExpression") // We can now replace it with ::this.xyz - .replaceWith(p => j.bindExpression(null, (p.value.callee as MemberExpression).object)) + .replaceWith(p => j.bindExpression(null, (p.value.callee as j.MemberExpression).object)) .toSource(); }; + +export = transform; diff --git a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts index 138d61a620..db4caff58c 100644 --- a/types/jscodeshift/test/js-transforms/props-to-destructuring.ts +++ b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts @@ -20,7 +20,7 @@ * } * */ -import { Transform, VariableDeclarator, ObjectPattern, Identifier, BlockStatement } from "jscodeshift"; +import { Transform, VariableDeclarator, ObjectPattern, Identifier } from "jscodeshift"; // tslint:disable-next-line max-line-length const keywordsStr = 'this function if return var else for new in typeof while case break try catch delete throw switch continue default instanceof do void finally with debugger implements interface package private protected public static class enum export extends import super true false null abstract boolean byte char const double final float goto int long native short synchronized throws transient volatile'; diff --git a/types/jscodeshift/tsconfig.json b/types/jscodeshift/tsconfig.json index a2c90ce266..5937bd483a 100644 --- a/types/jscodeshift/tsconfig.json +++ b/types/jscodeshift/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", + "src/core.d.ts", "src/Collection.d.ts", "src/collections/JSXElement.d.ts", "src/collections/Node.d.ts", From 47ffe1a4ba623bc5c363aee2ddb725ecadbfb361 Mon Sep 17 00:00:00 2001 From: Brie <723547+brieb@users.noreply.github.com> Date: Wed, 6 Feb 2019 13:41:12 -0800 Subject: [PATCH 113/197] [jscodeshift] Pin ast-types and recast --- types/jscodeshift/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/jscodeshift/package.json b/types/jscodeshift/package.json index 6fd3d8b70f..a501c0f28d 100644 --- a/types/jscodeshift/package.json +++ b/types/jscodeshift/package.json @@ -1,7 +1,7 @@ { "private": true, "dependencies": { - "ast-types": "^0.12.1", - "recast": "^0.17.2" + "ast-types": "0.12.1", + "recast": "0.17.2" } } From 48bd3be95c1664a96cda70f0ce405932ba8f71d1 Mon Sep 17 00:00:00 2001 From: Faizan Virani <fvirani@lyft.com> Date: Wed, 6 Feb 2019 15:42:16 -0800 Subject: [PATCH 114/197] Fixed typo in configure description --- types/enzyme/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 58e5938a8f..d9f858d2a7 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -619,7 +619,7 @@ export class EnzymeAdapter { } /** - * Configure enzyme to use the correct adapter for the react verstion + * Configure enzyme to use the correct adapter for the react version * This is enabling the Enzyme configuration with adapters in TS */ export function configure(options: { From 77a6c2a9706e17d83a3623f2b1686aafa383e27b Mon Sep 17 00:00:00 2001 From: Ron Buckton <ron.buckton@microsoft.com> Date: Thu, 31 Jan 2019 18:03:21 -0800 Subject: [PATCH 115/197] Adds 'typesVersions' support to NodeJS definitions --- types/node/base.d.ts | 41 ++++++++++++++++ types/node/globals.d.ts | 26 ---------- types/node/index.d.ts | 88 ++++++++++++++++++---------------- types/node/node-tests.ts | 6 +-- types/node/package.json | 11 +++++ types/node/ts3.1/index.d.ts | 18 +++++++ types/node/ts3.1/node-tests.ts | 2 + types/node/ts3.1/tsconfig.json | 25 ++++++++++ types/node/ts3.1/tslint.json | 10 ++++ types/node/ts3.1/util.d.ts | 10 ++++ types/node/tsconfig.json | 1 + types/node/util.d.ts | 22 ++++----- 12 files changed, 176 insertions(+), 84 deletions(-) create mode 100644 types/node/base.d.ts create mode 100644 types/node/package.json create mode 100644 types/node/ts3.1/index.d.ts create mode 100644 types/node/ts3.1/node-tests.ts create mode 100644 types/node/ts3.1/tsconfig.json create mode 100644 types/node/ts3.1/tslint.json create mode 100644 types/node/ts3.1/util.d.ts diff --git a/types/node/base.d.ts b/types/node/base.d.ts new file mode 100644 index 0000000000..70983d9515 --- /dev/null +++ b/types/node/base.d.ts @@ -0,0 +1,41 @@ +// base definnitions for all NodeJS modules that are not specific to any version of TypeScript +/// <reference path="globals.d.ts" /> +/// <reference path="assert.d.ts" /> +/// <reference path="async_hooks.d.ts" /> +/// <reference path="buffer.d.ts" /> +/// <reference path="child_process.d.ts" /> +/// <reference path="cluster.d.ts" /> +/// <reference path="console.d.ts" /> +/// <reference path="constants.d.ts" /> +/// <reference path="crypto.d.ts" /> +/// <reference path="dgram.d.ts" /> +/// <reference path="dns.d.ts" /> +/// <reference path="domain.d.ts" /> +/// <reference path="events.d.ts" /> +/// <reference path="fs.d.ts" /> +/// <reference path="http.d.ts" /> +/// <reference path="http2.d.ts" /> +/// <reference path="https.d.ts" /> +/// <reference path="inspector.d.ts" /> +/// <reference path="module.d.ts" /> +/// <reference path="net.d.ts" /> +/// <reference path="os.d.ts" /> +/// <reference path="path.d.ts" /> +/// <reference path="perf_hooks.d.ts" /> +/// <reference path="process.d.ts" /> +/// <reference path="punycode.d.ts" /> +/// <reference path="querystring.d.ts" /> +/// <reference path="readline.d.ts" /> +/// <reference path="repl.d.ts" /> +/// <reference path="stream.d.ts" /> +/// <reference path="string_decoder.d.ts" /> +/// <reference path="timers.d.ts" /> +/// <reference path="tls.d.ts" /> +/// <reference path="trace_events.d.ts" /> +/// <reference path="tty.d.ts" /> +/// <reference path="url.d.ts" /> +/// <reference path="util.d.ts" /> +/// <reference path="v8.d.ts" /> +/// <reference path="vm.d.ts" /> +/// <reference path="worker_threads.d.ts" /> +/// <reference path="zlib.d.ts" /> diff --git a/types/node/globals.d.ts b/types/node/globals.d.ts index e4f6f40fd1..0c4215fe7b 100644 --- a/types/node/globals.d.ts +++ b/types/node/globals.d.ts @@ -142,34 +142,8 @@ interface ErrorConstructor { stackTraceLimit: number; } -// compat for TypeScript 1.8 and default es5 target -// if you use with --target es3 or --target es5 and use below definitions, -// use the lib.es6.d.ts that is bundled with TypeScript 1.8. -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } - -interface Set<T> {} -interface ReadonlySet<T> {} - -// Forward-declare needed types from lib.es2015.d.ts (in case users are using `--lib es5`) -interface Iterable<T> { } -interface Iterator<T> { - next(value?: any): IteratorResult<T>; -} -interface IteratorResult<T> { } -interface IterableIterator<T> { } -interface AsyncIterableIterator<T> {} interface SymbolConstructor { readonly observable: symbol; - readonly iterator: symbol; - readonly asyncIterator: symbol; -} -declare var Symbol: SymbolConstructor; -interface SharedArrayBuffer { - readonly byteLength: number; - slice(begin?: number, end?: number): SharedArrayBuffer; } // Node.js ESNEXT support diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 9126f5504b..a237502039 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -35,43 +35,51 @@ // Kyle Uehlein <https://github.com/kuehlein> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// <reference path="globals.d.ts" /> -/// <reference path="assert.d.ts" /> -/// <reference path="async_hooks.d.ts" /> -/// <reference path="buffer.d.ts" /> -/// <reference path="child_process.d.ts" /> -/// <reference path="cluster.d.ts" /> -/// <reference path="console.d.ts" /> -/// <reference path="constants.d.ts" /> -/// <reference path="crypto.d.ts" /> -/// <reference path="dgram.d.ts" /> -/// <reference path="dns.d.ts" /> -/// <reference path="domain.d.ts" /> -/// <reference path="events.d.ts" /> -/// <reference path="fs.d.ts" /> -/// <reference path="http.d.ts" /> -/// <reference path="http2.d.ts" /> -/// <reference path="https.d.ts" /> -/// <reference path="inspector.d.ts" /> -/// <reference path="module.d.ts" /> -/// <reference path="net.d.ts" /> -/// <reference path="os.d.ts" /> -/// <reference path="path.d.ts" /> -/// <reference path="perf_hooks.d.ts" /> -/// <reference path="process.d.ts" /> -/// <reference path="punycode.d.ts" /> -/// <reference path="querystring.d.ts" /> -/// <reference path="readline.d.ts" /> -/// <reference path="repl.d.ts" /> -/// <reference path="stream.d.ts" /> -/// <reference path="string_decoder.d.ts" /> -/// <reference path="timers.d.ts" /> -/// <reference path="tls.d.ts" /> -/// <reference path="trace_events.d.ts" /> -/// <reference path="tty.d.ts" /> -/// <reference path="url.d.ts" /> -/// <reference path="util.d.ts" /> -/// <reference path="v8.d.ts" /> -/// <reference path="vm.d.ts" /> -/// <reference path="worker_threads.d.ts" /> -/// <reference path="zlib.d.ts" /> +// NOTE: These definitions support NodeJS and TypeScript 3.1. + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 2.1 +// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 + +// NOTE: Augmentations for TypeScript 3.1 and later should use individual files for overrides +// within the respective ~/ts3.1 (or later) folder. However, this is disallowed for versions +// prior to TypeScript 3.1, so the older definitions will be found here. + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// <reference path="base.d.ts" /> + +// TypeScript 2.1-specific augmentations: + +// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } +interface Set<T> {} +interface ReadonlySet<T> {} +interface IteratorResult<T> { } +interface Iterable<T> { } +interface Iterator<T> { + next(value?: any): IteratorResult<T>; +} +interface IterableIterator<T> { } +interface AsyncIterableIterator<T> {} +interface SymbolConstructor { + readonly iterator: symbol; + readonly asyncIterator: symbol; +} +declare var Symbol: SymbolConstructor; +interface SharedArrayBuffer { + readonly byteLength: number; + slice(begin?: number, end?: number): SharedArrayBuffer; +} + +declare module "util" { + namespace inspect { + const custom: symbol; + } + namespace promisify { + const custom: symbol; + } +} diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 3a8622802a..220de8ca8a 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -473,11 +473,7 @@ function bufferTests() { const arrUint8: Uint8Array = new Uint8Array(2); const buf5: Buffer = Buffer.from(arrUint8); const buf6: Buffer = Buffer.from(buf1); - const sharedArrayBuffer: SharedArrayBuffer = { - byteLength: 10, - slice: (begin?: number, end?: number) => sharedArrayBuffer - }; - const buf7: Buffer = Buffer.from(sharedArrayBuffer); + const buf7: Buffer = Buffer.from(undefined as SharedArrayBuffer); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) diff --git a/types/node/package.json b/types/node/package.json new file mode 100644 index 0000000000..c1f0c68752 --- /dev/null +++ b/types/node/package.json @@ -0,0 +1,11 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { + "*": [ + "ts3.1/*" + ] + } + } +} \ No newline at end of file diff --git a/types/node/ts3.1/index.d.ts b/types/node/ts3.1/index.d.ts new file mode 100644 index 0000000000..be36602300 --- /dev/null +++ b/types/node/ts3.1/index.d.ts @@ -0,0 +1,18 @@ +// NOTE: These definitions support NodeJS and TypeScript 3.1. + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 2.1 +// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 + +// Reference required types from the default lib: +/// <reference lib="es2018" /> +/// <reference lib="esnext.asyncIterable" /> +/// <reference lib="esnext.intl" /> + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +// tslint:disable-next-line:no-bad-reference +/// <reference path="../base.d.ts" /> + +// TypeScript 3.1-specific augmentations: +/// <reference path="util.d.ts" /> diff --git a/types/node/ts3.1/node-tests.ts b/types/node/ts3.1/node-tests.ts new file mode 100644 index 0000000000..18db498871 --- /dev/null +++ b/types/node/ts3.1/node-tests.ts @@ -0,0 +1,2 @@ +// tslint:disable-next-line:no-bad-reference +import "../node-tests"; diff --git a/types/node/ts3.1/tsconfig.json b/types/node/ts3.1/tsconfig.json new file mode 100644 index 0000000000..e1a9ddb149 --- /dev/null +++ b/types/node/ts3.1/tsconfig.json @@ -0,0 +1,25 @@ +{ + "files": [ + "index.d.ts", + "node-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/node/ts3.1/tslint.json b/types/node/ts3.1/tslint.json new file mode 100644 index 0000000000..1a8ddd9863 --- /dev/null +++ b/types/node/ts3.1/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "unified-signatures": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "strict-export-declare-modifiers": false // http2 needs this + } +} diff --git a/types/node/ts3.1/util.d.ts b/types/node/ts3.1/util.d.ts new file mode 100644 index 0000000000..e35ef8d0f1 --- /dev/null +++ b/types/node/ts3.1/util.d.ts @@ -0,0 +1,10 @@ +// tslint:disable-next-line:no-bad-reference +/// <reference path="../util.d.ts" /> +declare module "util" { + namespace inspect { + const custom: unique symbol; + } + namespace promisify { + const custom: unique symbol; + } +} diff --git a/types/node/tsconfig.json b/types/node/tsconfig.json index 9675935b6a..37cfa4baed 100644 --- a/types/node/tsconfig.json +++ b/types/node/tsconfig.json @@ -1,6 +1,7 @@ { "files": [ "index.d.ts", + "base.d.ts", "globals.d.ts", "assert.d.ts", "async_hooks.d.ts", diff --git a/types/node/util.d.ts b/types/node/util.d.ts index f918286559..9da88fe9cb 100644 --- a/types/node/util.d.ts +++ b/types/node/util.d.ts @@ -12,18 +12,17 @@ declare module "util" { function print(...param: any[]): void; /** @deprecated since v0.11.3 - use a third party module instead. */ function log(string: string): void; - const inspect: { - (object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; - (object: any, options: InspectOptions): string; - colors: { + function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + function inspect(object: any, options: InspectOptions): string; + namespace inspect { + let colors: { [color: string]: [number, number] | undefined - } - styles: { + }; + let styles: { [style: string]: string | undefined - } - defaultOptions: InspectOptions; - custom: symbol; - }; + }; + let defaultOptions: InspectOptions; + } /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ function isArray(object: any): object is any[]; /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ @@ -108,9 +107,6 @@ declare module "util" { fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: Error | null) => void) => void, ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>; function promisify(fn: Function): Function; - namespace promisify { - const custom: symbol; - } namespace types { function isAnyArrayBuffer(object: any): boolean; From 0f1a0a5d6e20dbab8bbe4ee1eac23e7503908b66 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser <DanielRosenwasser@users.noreply.github.com> Date: Wed, 6 Feb 2019 18:38:21 -0800 Subject: [PATCH 116/197] Update README.md --- README.md | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 650cecd1d5..faee7a4ee0 100644 --- a/README.md +++ b/README.md @@ -261,10 +261,10 @@ When it graduates draft mode, we may remove it from DefinitelyTyped and deprecat _NOTE: The discussion in this section assumes familiarity with [Semantic versioning](https://semver.org/)_ Each DefinitelyTyped package is versioned when published to NPM. -The [automated tools](https://github.com/Microsoft/types-publisher) that publish type declaration packages to NPM will set the type declaration package's version using the version number listed in the first line of its `index.d.ts` file. -For example, below are the first few lines of the latest (as of late 2018) [node.js type declarations](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts) for node.js library versions `10.12.x`. +The [types-publisher](https://github.com/Microsoft/types-publisher) (the tool that publishes `@types` packages to npm) will set the declaration package's version by using the `major.minor` version number listed in the first line of its `index.d.ts` file. +For example, here are the first few lines of [Node's type declarations](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1253faabf5e0d2c5470db6ea87795d7f96fef7e2/types/node/index.d.ts) for version `10.12.x` at the time of writing: -```javascript +```js // Type definitions for Node.js 10.12 // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript <https://github.com/Microsoft> @@ -272,21 +272,24 @@ For example, below are the first few lines of the latest (as of late 2018) [node // Alberto Schiabel <https://github.com/jkomyno> ``` -Because `10.12` is at the end the first line, the NPM version of the `@types/node` package will also be `10.12.x`. -Note that the first-line comment in the `index.d.ts` file should only contain major/minor versions (e.g. `10.12`) and should not contain a patch version (e.g. `10.12.4`). +Because `10.12` is at the end the first line, the npm version of the `@types/node` package will also be `10.12.x`. +Note that the first-line comment in the `index.d.ts` file should only contain the `major.minor` version (e.g. `10.12`) and should not contain a patch version (e.g. `10.12.4`). This is because only the major and minor release numbers are aligned between library packages and type declaration packages. The patch release number of the type declaration package (e.g. `.0` in `10.12.0`) is initialized to zero by DefinitelyTyped and is incremented each time a new `@types/node` package is published to NPM for the same major/minor version of the corresponding library. -Sometimes type declaration package versions and library package versions can get out of sync. -Below are a few common reasons why, in order of how much they inconvenience users of a library. +Sometimes type declaration package versions and library package versions can get out of sync. +Below are a few common reasons why, in order of how much they inconvenience users of a library. Only the last case is typically problematic. -* As noted above, the patch version of the type declaration package is unrelated to the library patch version. This allows DefinitelyTyped to safely update type declarations for the same major/minor version of a library. -* If a minor release adds new features that don't impact the type system, then there's no need to publish updated type declarations. In cases like this, updates are often skipped to the type declaration package. For example, imagine a contrived example of a library that formats only integers in its `2.0` release. If a `2.1` release of the library adds the capability to format floating point numbers too without changing API type signatures, then the type declaration package version might remain `2.0.3` even as the library goes to `2.1.0`. -* Users who are updating type declarations for a library sometimes forget to increment the type declaration package's version to match the library version. This doesn't usually result in any problems because `npm update` will usually pick the latest type declaration package version, although it may be confusing for users because they might assume that a library update is missing types that are really present. It will also cause problems when libraries are (see below) updated to a new major release with breaking changes, because users won't know which type declaration package version is the right one to use for older versions of the library. -* It's common for type declaration package updates to lag behind library updates because it's often library users, not maintainers, who update DefinitelyTyped when new library features are released. So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the type declaration package for a new library release. +* As noted above, the patch version of the type declaration package is unrelated to the library patch version. + This allows DefinitelyTyped to safely update type declarations for the same major/minor version of a library. +* If updating a package for new functionality, don't forget to update the version number to line up with that version of the library. + If users make sure versions correspond between JavaScript packages and their respective `@types` packages, then `npm update` should typically just work. +* It's common for type declaration package updates to lag behind library updates because it's often library users, not maintainers, who update DefinitelyTyped when new library features are released. + So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the type declaration package for a new library release. + If you're impacted by this, you can be the change you want to see in the world and you can be that helpful community member! -:exclamation:If you're updating type declarations for a library, always set the major/minor version in the first line of `index.d.ts` to match the library version that you're documenting!:exclamation: +:exclamation: If you're updating type declarations for a library, always set the `major.minor` version in the first line of `index.d.ts` to match the library version that you're documenting! :exclamation: #### If a library is updated to a new major version with breaking changes, how should I update its type declaration package? @@ -305,9 +308,8 @@ Because the root folder should always contain the type declarations for the late 2. Add path mapping rules to ensure that tests are running against the intended version. For example, the [`history`](https://github.com/ReactTraining/history/) library introduced breaking changes between version `2.x` and `3.x`. -Many developers waited a while to update their `package.json` to depend on version `3.x` of `history`. -Therefore, a maintainer of the type declarations for this library added a `v2` folder inside the history repository that contains type declarations for the older version. -The [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like: +Because many users still consumed the older `2.x` version, a maintainer who wanted to update the type declarations for this library to `3.x` added a `v2` folder inside the history repository that contains type declarations for the older version. +At the time of writing, the [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1253faabf5e0d2c5470db6ea87795d7f96fef7e2/types/history/v2/tsconfig.json) looks roughly like: ```json { From dda77e9c2af13607e6fa7be792d40a956c7c6be6 Mon Sep 17 00:00:00 2001 From: Joao Peixoto <joao.hartimer@gmail.com> Date: Wed, 6 Feb 2019 20:15:22 -0800 Subject: [PATCH 117/197] Make userHandle nullable instead of optional --- .../index.d.ts | 2 +- .../webappsec-credential-management-tests.ts | 45 ++++++++++--------- 2 files changed, 25 insertions(+), 22 deletions(-) diff --git a/types/webappsec-credential-management/index.d.ts b/types/webappsec-credential-management/index.d.ts index c8fbf8ec60..ce3e7ef26c 100644 --- a/types/webappsec-credential-management/index.d.ts +++ b/types/webappsec-credential-management/index.d.ts @@ -494,7 +494,7 @@ interface AuthenticatorAttestationResponse extends AuthenticatorResponse { interface AuthenticatorAssertionResponse extends AuthenticatorResponse { readonly authenticatorData: ArrayBuffer; readonly signature: ArrayBuffer; - readonly userHandle?: ArrayBuffer; + readonly userHandle: ArrayBuffer | null; } /** diff --git a/types/webappsec-credential-management/webappsec-credential-management-tests.ts b/types/webappsec-credential-management/webappsec-credential-management-tests.ts index 1e0500dfce..15ae1c6b9e 100644 --- a/types/webappsec-credential-management/webappsec-credential-management-tests.ts +++ b/types/webappsec-credential-management/webappsec-credential-management-tests.ts @@ -5,7 +5,7 @@ function passwordBasedSignInDeprecated() { return; } - navigator.credentials.get({password: true}).then((credential) => { + navigator.credentials.get({ password: true }).then((credential) => { if (!credential) { return; } @@ -117,7 +117,7 @@ function federatedSignIn() { navigator.credentials .get({ password: true, - federated: {providers: ['https://federation.com']} + federated: { providers: ['https://federation.com'] } }) .then((credential) => { if (!credential) return; @@ -141,7 +141,7 @@ function federatedSignIn() { const pwCred = credential as PasswordCredential; fetch( 'https://example.com/loginEndpoint', - {credentials: pwCred, method: 'POST'}); + { credentials: pwCred, method: 'POST' }); } }); } @@ -159,7 +159,7 @@ function passwordPostSignInConfirmation() { const formElem = (e.target as HTMLFormElement); const c = new PasswordCredential(formElem); - fetch(formElem.action, {method: 'POST', credentials: c}).then(r => { + fetch(formElem.action, { method: 'POST', credentials: c }).then(r => { if (r.status === 200) { navigator.credentials!.store(c); } @@ -172,7 +172,7 @@ function passwordPostSignInConfirmation() { function federationPostSignInConfirmation() { if (navigator.credentials) { navigator.credentials.store(new FederatedCredential( - {id: 'username', provider: 'https://federation.com'})); + { id: 'username', provider: 'https://federation.com' })); } } @@ -188,7 +188,7 @@ function existingFormPost(credential: PasswordCredential) { credential.passwordName = 'p'; fetch( 'https://example.com/loginEndpoint', - {credentials: credential, method: 'POST'}); + { credentials: credential, method: 'POST' }); } function additionalDataPost(credential: PasswordCredential, token: string) { @@ -196,14 +196,14 @@ function additionalDataPost(credential: PasswordCredential, token: string) { credential.additionalData.append('csrf', token); fetch( 'https://example.com/loginEndpoint', - {credentials: credential, method: 'POST'}); + { credentials: credential, method: 'POST' }); } function formEncodedPost(credential: PasswordCredential, token: string) { credential.additionalData = new URLSearchParams(); fetch( 'https://example.com/loginEndpoint', - {credentials: credential, method: 'POST'}); + { credentials: credential, method: 'POST' }); } // requireUserMediation example: not included in the spec, but included here @@ -236,7 +236,7 @@ function createPasswordCredential() { } navigator.credentials.create({ - password: {id: 'username', password: 'password'} + password: { id: 'username', password: 'password' } }).then((credential) => { // Credential created! }); @@ -266,7 +266,7 @@ function createFederatedCredential() { } navigator.credentials.create({ - federated: {id: 'username', provider: 'provider'} + federated: { id: 'username', provider: 'provider' } }).then((credential) => { // Credential created! }); @@ -293,7 +293,7 @@ function webauthnRegister() { }, challenge, pubKeyCredParams: [ - {type: 'public-key', alg: -7}, + { type: 'public-key', alg: -7 }, ], excludeCredentials: [ { @@ -329,16 +329,18 @@ function webauthnAuthenticate() { const challenge = new Uint8Array(32); window.crypto.getRandomValues(challenge); - const authPromise = navigator.credentials.get({publicKey: { - challenge, - timeout: 5000, - rpId: document.domain, - allowCredentials: [{ - type: "public-key", - id: credentialID, - transports: ['internal', 'ble', 'nfc', 'usb'] - }], - }}); + const authPromise = navigator.credentials.get({ + publicKey: { + challenge, + timeout: 5000, + rpId: document.domain, + allowCredentials: [{ + type: "public-key", + id: credentialID, + transports: ['internal', 'ble', 'nfc', 'usb'] + }], + } + }); authPromise.then((cred) => { if (cred === null) { @@ -362,6 +364,7 @@ function mockAuthenticatorAssertionResponse() { clientDataJSON: new ArrayBuffer(0), authenticatorData: new ArrayBuffer(0), signature: new ArrayBuffer(0), + userHandle: null, }; sampleResponse.userHandle === undefined; } From bc1eb3b28e41b2ed54865aecf134eae6c0b23add Mon Sep 17 00:00:00 2001 From: Mitchell Grice <mitchell.grice@polymathian.com> Date: Thu, 7 Feb 2019 15:11:18 +1000 Subject: [PATCH 118/197] Add moment-precise-range-plugin --- types/moment-precise-range-plugin/index.d.ts | 28 +++++++++++++++++++ .../moment-precise-range-plugin-tests.ts | 14 ++++++++++ .../moment-precise-range-plugin/package.json | 6 ++++ .../moment-precise-range-plugin/tsconfig.json | 23 +++++++++++++++ types/moment-precise-range-plugin/tslint.json | 1 + 5 files changed, 72 insertions(+) create mode 100644 types/moment-precise-range-plugin/index.d.ts create mode 100644 types/moment-precise-range-plugin/moment-precise-range-plugin-tests.ts create mode 100644 types/moment-precise-range-plugin/package.json create mode 100644 types/moment-precise-range-plugin/tsconfig.json create mode 100644 types/moment-precise-range-plugin/tslint.json diff --git a/types/moment-precise-range-plugin/index.d.ts b/types/moment-precise-range-plugin/index.d.ts new file mode 100644 index 0000000000..ad28b3d009 --- /dev/null +++ b/types/moment-precise-range-plugin/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for moment-precise-range 0.2 +// Project: https://github.com/codebox/moment-precise-range +// Definitions by: Mitchell Grice <https://github.com/gricey432> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import moment = require('moment'); + +export = moment; + +declare module "moment" { + interface PreciseRangeValueObject { + years: number; + months: number; + days: number; + hours: number; + minutes: number; + seconds: number; + firstDateWasLater: boolean; + } + + interface Moment { + preciseDiff(d2: Moment, returnValueObject?: false): string; + preciseDiff(d2: Moment, returnValueObject: true): PreciseRangeValueObject; + } + + function preciseDiff(d1: Moment, d2: Moment, returnValueObject?: false): string; + function preciseDiff(d1: Moment, d2: Moment, returnValueObject: true): PreciseRangeValueObject; +} diff --git a/types/moment-precise-range-plugin/moment-precise-range-plugin-tests.ts b/types/moment-precise-range-plugin/moment-precise-range-plugin-tests.ts new file mode 100644 index 0000000000..427d513fb9 --- /dev/null +++ b/types/moment-precise-range-plugin/moment-precise-range-plugin-tests.ts @@ -0,0 +1,14 @@ +import moment = require("moment"); +import * as momentPreciseRange from "moment-precise-range-plugin"; + +// Static methods +const m1 = moment.utc(); +const m2 = moment.utc(); +moment.preciseDiff(m1, m2); +moment.preciseDiff(m1, m2, true); +moment.preciseDiff(m1, m2, false); + +// Instance methods +m1.preciseDiff(m2); +m1.preciseDiff(m2, true); +m1.preciseDiff(m2, false); diff --git a/types/moment-precise-range-plugin/package.json b/types/moment-precise-range-plugin/package.json new file mode 100644 index 0000000000..19e5fb0d14 --- /dev/null +++ b/types/moment-precise-range-plugin/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "moment": ">=2.14.0" + } +} diff --git a/types/moment-precise-range-plugin/tsconfig.json b/types/moment-precise-range-plugin/tsconfig.json new file mode 100644 index 0000000000..cfb6dcbd4d --- /dev/null +++ b/types/moment-precise-range-plugin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "moment-precise-range-plugin-tests.ts" + ] +} diff --git a/types/moment-precise-range-plugin/tslint.json b/types/moment-precise-range-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/moment-precise-range-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From af9d8f543526e27f7d0eaeb8c8646cd28fbce8ee Mon Sep 17 00:00:00 2001 From: Ray Booysen <ray@sumatro.co.uk> Date: Thu, 7 Feb 2019 14:39:11 +0800 Subject: [PATCH 119/197] Add bunyan-seq typings --- types/bunyan-seq/bunyan-seq-tests.ts | 2 ++ types/bunyan-seq/index.d.ts | 21 +++++++++++++++++++++ types/bunyan-seq/tsconfig.json | 23 +++++++++++++++++++++++ types/bunyan-seq/tslint.json | 1 + 4 files changed, 47 insertions(+) create mode 100644 types/bunyan-seq/bunyan-seq-tests.ts create mode 100644 types/bunyan-seq/index.d.ts create mode 100644 types/bunyan-seq/tsconfig.json create mode 100644 types/bunyan-seq/tslint.json diff --git a/types/bunyan-seq/bunyan-seq-tests.ts b/types/bunyan-seq/bunyan-seq-tests.ts new file mode 100644 index 0000000000..beeeb9d8ee --- /dev/null +++ b/types/bunyan-seq/bunyan-seq-tests.ts @@ -0,0 +1,2 @@ +import bunyanSeq = require("bunyan-seq"); +bunyanSeq.createStream({name: 'LoggerComponent', serverUrl: 'http://seq.com'}); diff --git a/types/bunyan-seq/index.d.ts b/types/bunyan-seq/index.d.ts new file mode 100644 index 0000000000..2520c93339 --- /dev/null +++ b/types/bunyan-seq/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for bunyan-blackhole 0.2 +// Project: https://github.com/datalust/bunyan-seq +// Definitions by: Ray Booysen <https://github.com/raybooysen> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// <reference types="node" /> +import * as Logger from "bunyan"; +export interface Configuration { + apiKey?: string; + batchSizeLimit?: number; + eventSizeLimit?: number; + level?: string; + maxBatchingTime?: number; + name?: string; + onError?: (e: Error) => void; + reemitErrorEvents?: boolean; + serverUrl?: string; +} + +export function createStream(config: Configuration): Logger.Stream; diff --git a/types/bunyan-seq/tsconfig.json b/types/bunyan-seq/tsconfig.json new file mode 100644 index 0000000000..bd77368148 --- /dev/null +++ b/types/bunyan-seq/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bunyan-seq-tests.ts" + ] +} diff --git a/types/bunyan-seq/tslint.json b/types/bunyan-seq/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bunyan-seq/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From add287a1d6eedf8d8ad9ccfac159ff5265970b1e Mon Sep 17 00:00:00 2001 From: Haroen Viaene <hello@haroen.me> Date: Thu, 7 Feb 2019 09:22:57 +0100 Subject: [PATCH 120/197] algoliasearch: add missing type for removeStopWords closes https://github.com/algolia/algoliasearch-client-javascript/issues/741 --- types/algoliasearch/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index 04291996ba..633b681432 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -1687,7 +1687,7 @@ declare namespace algoliasearch { * a list of language ISO codes (as a comma-separated string) for which stop words should be enable * https://github.com/algolia/algoliasearch-client-js#removestopwords */ - removeStopWords?: string[]; + removeStopWords?: boolean | string[]; /** * List of attributes on which you want to apply word-splitting ("decompounding") for * each of the languages supported (German, Dutch, and Finnish as of 05/2018) From 7203a2a86763485d1b6152a1dcac381ddc495bfe Mon Sep 17 00:00:00 2001 From: Razvan Muscalu <34776591+RazzM13@users.noreply.github.com> Date: Thu, 7 Feb 2019 10:59:41 +0200 Subject: [PATCH 121/197] [@types/feathersjs__errors] Bumped version to 3.3. --- types/feathersjs__errors/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/feathersjs__errors/index.d.ts b/types/feathersjs__errors/index.d.ts index 01969de8a3..3a94e4cd50 100644 --- a/types/feathersjs__errors/index.d.ts +++ b/types/feathersjs__errors/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @feathersjs/errors 3.2 +// Type definitions for @feathersjs/errors 3.3 // Project: http://feathersjs.com/ // Definitions by: Jan Lohage <https://github.com/j2L4e> // RazzM13 <https://github.com/RazzM13> From a9259ab52140a3c0d35799d1c8072a86c34a7b78 Mon Sep 17 00:00:00 2001 From: Razvan Muscalu <34776591+RazzM13@users.noreply.github.com> Date: Thu, 7 Feb 2019 11:04:29 +0200 Subject: [PATCH 122/197] [@types/feathersjs__errors] Made "FeathersError" specific properties readonly. --- types/feathersjs__errors/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/feathersjs__errors/index.d.ts b/types/feathersjs__errors/index.d.ts index 3a94e4cd50..ab7b1eae34 100644 --- a/types/feathersjs__errors/index.d.ts +++ b/types/feathersjs__errors/index.d.ts @@ -6,10 +6,10 @@ // TypeScript Version: 2.2 export class FeathersError extends Error { - code: number; - className: string; - data: any; - errors: any; + readonly code: number; + readonly className: string; + readonly data: any; + readonly errors: any; constructor(msg: string | Error, name: string, code: number, className: string, data: any); } From 12738483e6597664a21ab33ecb5ba3ac109bb433 Mon Sep 17 00:00:00 2001 From: Razvan Muscalu <34776591+RazzM13@users.noreply.github.com> Date: Thu, 7 Feb 2019 11:09:17 +0200 Subject: [PATCH 123/197] [@types/feathersjs__errors] Added the missing "toJSON" function of the "FeathersError" base class that returns an object suitable for serialization. --- types/feathersjs__errors/index.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/types/feathersjs__errors/index.d.ts b/types/feathersjs__errors/index.d.ts index ab7b1eae34..3994e2056c 100644 --- a/types/feathersjs__errors/index.d.ts +++ b/types/feathersjs__errors/index.d.ts @@ -5,12 +5,22 @@ // Definitions: https://github.com/feathersjs-ecosystem/feathers-typescript // TypeScript Version: 2.2 +export interface FeathersErrorJSON { + readonly name: string; + readonly message: string; + readonly code: number; + readonly className: string; + readonly data: any; + readonly errors: any; +} + export class FeathersError extends Error { readonly code: number; readonly className: string; readonly data: any; readonly errors: any; constructor(msg: string | Error, name: string, code: number, className: string, data: any); + toJSON(): FeathersErrorJSON; } export class BadRequest extends FeathersError { From 18e80f42e7429f8a5dc74b95c008699babbe73a7 Mon Sep 17 00:00:00 2001 From: Christian Rackerseder <git@echooff.de> Date: Thu, 7 Feb 2019 10:26:54 +0100 Subject: [PATCH 124/197] [giphy-api] Add types --- types/giphy-api/giphy-api-tests.ts | 34 ++++++ types/giphy-api/index.d.ts | 189 +++++++++++++++++++++++++++++ types/giphy-api/tsconfig.json | 23 ++++ types/giphy-api/tslint.json | 1 + 4 files changed, 247 insertions(+) create mode 100644 types/giphy-api/giphy-api-tests.ts create mode 100644 types/giphy-api/index.d.ts create mode 100644 types/giphy-api/tsconfig.json create mode 100644 types/giphy-api/tslint.json diff --git a/types/giphy-api/giphy-api-tests.ts b/types/giphy-api/giphy-api-tests.ts new file mode 100644 index 0000000000..6168ece7ac --- /dev/null +++ b/types/giphy-api/giphy-api-tests.ts @@ -0,0 +1,34 @@ +import giphyApi = require('giphy-api'); + +const cb = (err: Error, res: any) => {}; + +giphyApi('API KEY HERE'); +giphyApi({ https: true }); +giphyApi({ timeout: 60 }); +giphyApi({ apiKey: 'API KEY' }); + +const giphy = giphyApi(); +giphy.search('pokemon', cb); +giphy.search('pokemon').then(res => {}); +giphy.search({ q: 'pokemon', rating: 'g' }, cb); +giphy.search({ q: 'pokemon', rating: 'g' }).then(res => {}); + +giphy.id('feqkVgjJpYtjy', cb); +giphy.id('feqkVgjJpYtjy').then(res => {}); +giphy.id(['feqkVgjJpYtjy'], cb); +giphy.id(['feqkVgjJpYtjy']).then(res => {}); + +giphy.translate('superman', cb); +giphy.translate('superman').then(res => {}); +giphy.translate({ s: 'superman', rating: 'g', fmt: 'html' }, cb); +giphy.translate({ s: 'superman', rating: 'g' }).then(res => {}); + +giphy.random('superman', cb); +giphy.random('superman').then(res => {}); +giphy.random({ tag: 'superman', rating: 'g' }, cb); +giphy.random({ tag: 'superman', rating: 'g' }).then(res => {}); + +giphy.trending(cb); +giphy.trending().then(res => {}); +giphy.trending({ limit: 2, rating: 'g' }); +giphy.trending({ limit: 2, rating: 'g' }).then(res => {}); diff --git a/types/giphy-api/index.d.ts b/types/giphy-api/index.d.ts new file mode 100644 index 0000000000..e179e2b99b --- /dev/null +++ b/types/giphy-api/index.d.ts @@ -0,0 +1,189 @@ +// Type definitions for giphy-api 2.0 +// Project: https://github.com/austinkelleher/giphy-api +// Definitions by: Christian Rackerseder <https://github.com/screendriver> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +type Rating = "y" | "g" | "pg" | "pg-13" | "r"; +type Format = "html" | "json"; + +interface GiphyOptions { + https?: boolean; + timeout?: number; + apiKey?: string; +} + +interface BaseOptions { + rating: Rating; + fmt?: Format; +} + +interface SearchOptions extends BaseOptions { + q: string; + limit?: number; + offset?: number; +} + +interface TranslateOptions extends BaseOptions { + s: string; +} + +interface RandomOptions extends BaseOptions { + tag: string; +} + +interface TrendingOptions extends BaseOptions { + limit?: number; +} + +interface BaseImage { + url: string; + width: string; + height: string; +} + +interface Result { + data: [ + { + type: "gif"; + id: string; + slug: string; + url: string; + bitly_gif_url: string; + bitly_url: string; + embed_url: string; + username: string; + source: string; + rating: Rating; + content_url: string; + source_tld: string; + source_post_url: string; + is_sticker: number; + import_datetime: string; + trending_datetime: string; + images: { + fixed_height_still: BaseImage; + original_still: BaseImage; + fixed_width: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + fixed_height_small_still: BaseImage; + fixed_height_downsampled: BaseImage & { + size: string; + webp: string; + webp_size: string; + }; + preview: { + width: string; + height: string; + mp4: string; + mp4_size: string; + }; + fixed_height_small: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + downsized_still: BaseImage & { + size: string; + }; + downsized: BaseImage & { + size: string; + }; + downsized_large: BaseImage & { + size: string; + }; + fixed_width_small_still: BaseImage; + preview_webp: BaseImage & { + size: string; + }; + fixed_width_still: BaseImage; + fixed_width_small: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + downsized_small: { + width: string; + height: string; + mp4: string; + mp4_size: string; + }; + fixed_width_downsampled: BaseImage & { + size: string; + webp: string; + webp_size: string; + }; + downsized_medium: BaseImage & { + size: string; + }; + original: BaseImage & { + size: string; + frames: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + fixed_height: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + looping: { mp4: string; mp4_size: string }; + original_mp4: { + width: string; + height: string; + mp4: string; + mp4_size: string; + }; + preview_gif: BaseImage & { + size: string; + }; + title: string; + _score: number; + analytics: { + onload: { url: string }; + onclick: { url: string }; + onsent: { url: string }; + }; + }; + } + ]; + pagination: { total_count: number; count: number; offset: number }; + meta: { + status: number; + msg: string; + response_id: string; + }; +} + +type Callback = (err: Error, res: Result) => void; + +interface Giphy { + search(queryOrOptions: string | SearchOptions, cb: Callback): void; + search(queryOrOptions: string | SearchOptions): Promise<Result>; + id(ids: string | string[], cb: Callback): void; + id(ids: string | string[]): Promise<Result>; + translate(termOrOptions: string | TranslateOptions, cb: Callback): void; + translate(termOrOptions: string | TranslateOptions): Promise<Result>; + random(tagOrOptions: string | RandomOptions, cb: Callback): void; + random(tagOrOptions: string | RandomOptions): Promise<Result>; + trending(options: TrendingOptions, cb: Callback): void; + trending(cb: Callback): void; + trending(options?: TrendingOptions): Promise<Result>; +} + +declare function giphyApi(apiKeyOrOptions?: string | GiphyOptions): Giphy; + +export = giphyApi; diff --git a/types/giphy-api/tsconfig.json b/types/giphy-api/tsconfig.json new file mode 100644 index 0000000000..e8d707c5fb --- /dev/null +++ b/types/giphy-api/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "giphy-api-tests.ts" + ] +} diff --git a/types/giphy-api/tslint.json b/types/giphy-api/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/giphy-api/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 209ac2ff355b0e97b65ae29838c3d898322bab20 Mon Sep 17 00:00:00 2001 From: Loik Gaonach <dev.loikg@gmail.com> Date: Thu, 7 Feb 2019 10:52:54 +0100 Subject: [PATCH 125/197] add websocket integration props to APIGatewayEventRequestContext messageId is nullable on connection events --- types/aws-lambda/aws-lambda-tests.ts | 11 +++++++++++ types/aws-lambda/index.d.ts | 10 ++++++++++ 2 files changed, 21 insertions(+) diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index ba6ebdc5ac..ad063c20b6 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -1,12 +1,14 @@ declare let str: string; declare let strOrNull: string | null; declare let strOrUndefined: string | undefined; +declare let strOrUndefinedOrNull: string | undefined | null; declare let date: Date; declare let anyObj: any; declare let num: number; declare let error: Error; declare let bool: boolean; declare let boolOrUndefined: boolean | undefined; +declare let numOrUndefined: number | undefined; declare let apiGwEvtReqCtx: AWSLambda.APIGatewayEventRequestContext; declare let apiGwEvtReqCtxOpt: AWSLambda.APIGatewayEventRequestContext | null | undefined; declare let apiGwEvt: AWSLambda.APIGatewayEvent; @@ -80,6 +82,11 @@ declare const scheduledEvent: AWSLambda.ScheduledEvent; str = apiGwEvtReqCtx.accountId; str = apiGwEvtReqCtx.apiId; authResponseContextOpt = apiGwEvtReqCtx.authorizer; +numOrUndefined = apiGwEvtReqCtx.connectedAt; +strOrUndefined = apiGwEvtReqCtx.connectionId; +strOrUndefined = apiGwEvtReqCtx.domainName; +strOrUndefined = apiGwEvtReqCtx.eventType; +strOrUndefined = apiGwEvtReqCtx.extendedRequestId; str = apiGwEvtReqCtx.httpMethod; strOrNull = apiGwEvtReqCtx.identity.accessKey; strOrNull = apiGwEvtReqCtx.identity.accountId; @@ -94,11 +101,15 @@ str = apiGwEvtReqCtx.identity.sourceIp; strOrNull = apiGwEvtReqCtx.identity.user; strOrNull = apiGwEvtReqCtx.identity.userAgent; strOrNull = apiGwEvtReqCtx.identity.userArn; +strOrUndefined = apiGwEvtReqCtx.messageDirection; +strOrUndefinedOrNull = apiGwEvtReqCtx.messageId; str = apiGwEvtReqCtx.path; str = apiGwEvtReqCtx.stage; str = apiGwEvtReqCtx.requestId; +strOrUndefined = apiGwEvtReqCtx.requestTime; str = apiGwEvtReqCtx.resourceId; str = apiGwEvtReqCtx.resourcePath; +strOrUndefined = apiGwEvtReqCtx.routeKey; /* API Gateway Event */ strOrNull = apiGwEvt.body; diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index 52314529bc..3301feebb5 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -25,6 +25,7 @@ // Trevor Leach <https://github.com/trevor-leach> // James Gregory <https://github.com/jagregory> // Erik Dalén <https://github.com/dalen> +// Loïk Gaonac'h <https://github.com/loikg> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -33,6 +34,11 @@ export interface APIGatewayEventRequestContext { accountId: string; apiId: string; authorizer?: AuthResponseContext | null; + connectedAt: number; + connectionId?: string; + domainName?: string; + eventType?: string; + extendedRequestId?: string; httpMethod: string; identity: { accessKey: string | null; @@ -49,12 +55,16 @@ export interface APIGatewayEventRequestContext { userAgent: string | null; userArn: string | null; }; + messageDirection?: string; + messageId?: string | null; path: string; stage: string; requestId: string; + requestTime?: string; requestTimeEpoch: number; resourceId: string; resourcePath: string; + routeKey?: string; } // API Gateway "event" From d787437c0adac1fe12fe20af9b06859d6622656b Mon Sep 17 00:00:00 2001 From: Jason Gray <jason.gray@postcodelottery.co.uk> Date: Fri, 1 Feb 2019 14:45:40 +0000 Subject: [PATCH 126/197] add types for aws-param-store --- .../aws-param-store/aws-param-store-tests.ts | 78 +++++++++++++++++++ types/aws-param-store/index.d.ts | 48 ++++++++++++ types/aws-param-store/package.json | 6 ++ types/aws-param-store/tsconfig.json | 23 ++++++ types/aws-param-store/tslint.json | 1 + 5 files changed, 156 insertions(+) create mode 100644 types/aws-param-store/aws-param-store-tests.ts create mode 100644 types/aws-param-store/index.d.ts create mode 100644 types/aws-param-store/package.json create mode 100644 types/aws-param-store/tsconfig.json create mode 100644 types/aws-param-store/tslint.json diff --git a/types/aws-param-store/aws-param-store-tests.ts b/types/aws-param-store/aws-param-store-tests.ts new file mode 100644 index 0000000000..13ad6c0514 --- /dev/null +++ b/types/aws-param-store/aws-param-store-tests.ts @@ -0,0 +1,78 @@ +import { SSM } from 'aws-sdk'; +import { + ParameterQuery, + parameterQuery, + getParameter, + getParameters, + getParametersByPath, + getParameterSync, + getParametersSync, + getParametersByPathSync, +} from 'aws-param-store'; + +declare let bool: boolean; +declare let query: ParameterQuery; +declare let psName: SSM.Types.PSParameterName; +declare let psNames: SSM.Types.ParameterNameList; +declare let options: SSM.Types.ClientConfiguration; +declare let paramResult: SSM.Types.Parameter; +declare let paramsResult: SSM.Types.GetParametersResult; +declare let paramsByPathResult: SSM.Types.ParameterList; +declare let allParamResults: SSM.Types.Parameter | SSM.Types.GetParametersByPathResult | SSM.Types.ParameterList; +declare let promiseParamResult: Promise<SSM.Types.Parameter>; +declare let promiseParamsResult: Promise<SSM.Types.GetParametersResult>; +declare let promiseParamsByPathResult: Promise<SSM.Types.ParameterList>; +declare let promiseAllParamResults: Promise<typeof allParamResults>; + +query = parameterQuery(); + +query.path(psName); +query.named(psName); +query.named(psNames); +query.decryption(bool); +query.recursive(bool); + +promiseAllParamResults = query.execute(); +allParamResults = query.executeSync(); + +// test chaining +query = query +.path(psName) +.named(psName) +.named(psNames) +.decryption(bool) +.recursive(bool); + +promiseAllParamResults = query +.path(psName) +.named(psName) +.named(psNames) +.decryption(bool) +.recursive(bool) +.execute(); + +allParamResults = query +.path(psName) +.named(psName) +.named(psNames) +.decryption(bool) +.recursive(bool) +.executeSync(); + +promiseParamResult = getParameter(psName); +promiseParamResult = getParameter(psName, options); + +promiseParamsResult = getParameters(psNames); +promiseParamsResult = getParameters(psNames, options); + +promiseParamsByPathResult = getParametersByPath(psNames); +promiseParamsByPathResult = getParametersByPath(psNames, options); + +paramResult = getParameterSync(psName); +paramResult = getParameterSync(psName, options); + +paramsResult = getParametersSync(psNames); +paramsResult = getParametersSync(psNames, options); + +paramsByPathResult = getParametersByPathSync(psNames); +paramsByPathResult = getParametersByPathSync(psNames, options); diff --git a/types/aws-param-store/index.d.ts b/types/aws-param-store/index.d.ts new file mode 100644 index 0000000000..c35edef688 --- /dev/null +++ b/types/aws-param-store/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for aws-param-store 2.1 +// Project: https://github.com/vandium-io/aws-param-store#readme +// Definitions by: Jason Gray <https://github.com/jasonthomasgray> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// <reference types="node" /> +import { SSM } from 'aws-sdk'; + +export function getParameter( + name: SSM.Types.PSParameterName, + options?: SSM.Types.ClientConfiguration +): Promise<SSM.Types.Parameter>; + +export function getParameterSync( + name: SSM.Types.PSParameterName, + options?: SSM.Types.ClientConfiguration +): SSM.Types.Parameter; + +export function getParameters( + names: SSM.Types.ParameterNameList, + options?: SSM.Types.ClientConfiguration +): Promise<SSM.Types.GetParametersResult>; + +export function getParametersSync( + names: SSM.Types.ParameterNameList, + options?: SSM.Types.ClientConfiguration +): SSM.Types.GetParametersResult; + +export function getParametersByPath( + path: SSM.Types.ParameterNameList, + options?: SSM.Types.ClientConfiguration +): Promise<SSM.Types.ParameterList>; + +export function getParametersByPathSync( + path: SSM.Types.ParameterNameList, + options?: SSM.Types.ClientConfiguration +): SSM.Types.ParameterList; + +export interface ParameterQuery { + path(path: SSM.Types.PSParameterName): ParameterQuery; + named(nameOrNames: SSM.Types.PSParameterName | SSM.Types.ParameterNameList): ParameterQuery; + decryption(enabled: boolean): ParameterQuery; + recursive(enabled: boolean): ParameterQuery; + execute(): Promise<SSM.Types.ParameterList | SSM.Types.Parameter | SSM.Types.GetParametersResult>; + executeSync(): SSM.Types.ParameterList | SSM.Types.Parameter | SSM.Types.GetParametersResult; +} + +export function parameterQuery(options?: SSM.Types.ClientConfiguration): ParameterQuery; diff --git a/types/aws-param-store/package.json b/types/aws-param-store/package.json new file mode 100644 index 0000000000..abb680d4ac --- /dev/null +++ b/types/aws-param-store/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "aws-sdk": "^2.325.0" + } +} diff --git a/types/aws-param-store/tsconfig.json b/types/aws-param-store/tsconfig.json new file mode 100644 index 0000000000..2857e45680 --- /dev/null +++ b/types/aws-param-store/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "aws-param-store-tests.ts" + ] +} diff --git a/types/aws-param-store/tslint.json b/types/aws-param-store/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/aws-param-store/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From bfa57b661f5da696100751cb19cdac599213ad42 Mon Sep 17 00:00:00 2001 From: Jan Pesa <jan.pesa@gmail.com> Date: Thu, 7 Feb 2019 13:44:32 +0100 Subject: [PATCH 127/197] [utif] Add types --- types/utif/index.d.ts | 71 ++++++++++++++++++++++++++++++++++++++++ types/utif/tsconfig.json | 23 +++++++++++++ types/utif/tslint.json | 1 + types/utif/utif-tests.ts | 15 +++++++++ 4 files changed, 110 insertions(+) create mode 100644 types/utif/index.d.ts create mode 100644 types/utif/tsconfig.json create mode 100644 types/utif/tslint.json create mode 100644 types/utif/utif-tests.ts diff --git a/types/utif/index.d.ts b/types/utif/index.d.ts new file mode 100644 index 0000000000..569dfd949c --- /dev/null +++ b/types/utif/index.d.ts @@ -0,0 +1,71 @@ +// Type definitions for utif 2.0 +// Project: https://github.com/photopea/UTIF.js +// Definitions by: Jan Pesa <https://github.com/smajl> +// Naveen Kumar Sangi <https://github.com/nkprince007> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import 'node'; + +export as namespace UTIF; + +export type TiffTag = string[] | number[]; + +/** + * Each IFD is an object, keys are "tXYZ" (XYZ is a TIFF tag number), values are values of these tags. + * You can get the the dimension (and other properties, "metadata") of the image without decompressing pixel data. + * For more information on what each tag means, refer https://github.com/photopea/UTIF.js/blob/master/UTIF.js#L742 or TIFF 6 specification. + */ +// tslint:disable-next-line:interface-name +export interface IFD { + [property: string]: TiffTag | number | Uint8Array; + data: Uint8Array; + width: number; + height: number; +} + +/** + * Returns an array of "IFDs" (image file directories). + * + * @param buffer A Buffer or ArrayBuffer containing TIFF or EXIF data. + */ +export function decode(buffer: Buffer | ArrayBuffer): IFD[]; + +/** + * Loops through each IFD. If there is an image inside it, it is decoded and three new properties are added to the IFD: width, height and data. + * Note: TIFF files may have various number of channels and various color depth. The interpretation of data depends on many tags (see the TIFF 6 specification). + * + * @param buffer A Buffer or ArrayBuffer containing TIFF or EXIF data + * @param ifds An array of image file directories parsed via UTIF.decode() + */ +export function decodeImages(buffer: Buffer | ArrayBuffer, ifds: IFD[]): void; + +/** + * Returns Uint8Array of the image in RGBA format, 8 bits per channel (ready to use in context2d.putImageData() etc.) + * + * @param ifd An image file directory + */ +export function toRGBA8(ifd: IFD): Uint8Array; + +/** + * Returns an ArrayBuffer of the binary TIFF file. + * Note: No compression available right now. + * + * @param rgba A Uint8Array containing RGBA pixel data. + * @param w Width of the image. + * @param h Height of the image. + * @param metadata [optional] The image file directory which should be encoded. + */ +export function encodeImage(rgba: Uint8Array, w: number, h: number, metadata?: IFD): ArrayBuffer; + +/** + * Returns ArrayBuffer of binary data which can be used to encode EXIF data. + * + * @param ifds The array of IFDs (image file directories) to be encoded. + */ +export function encode(ifds: IFD[]): ArrayBuffer; + +/** + * Replaces all Image elements in the document with Canvas elements. + * The attributes "id", "class" and "style" will be copied from the original Image to the new Canvas. + */ +export function replaceIMG(): void; diff --git a/types/utif/tsconfig.json b/types/utif/tsconfig.json new file mode 100644 index 0000000000..cd4c8aa8fe --- /dev/null +++ b/types/utif/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "utif-tests.ts" + ] +} diff --git a/types/utif/tslint.json b/types/utif/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/utif/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/utif/utif-tests.ts b/types/utif/utif-tests.ts new file mode 100644 index 0000000000..66455e2f4a --- /dev/null +++ b/types/utif/utif-tests.ts @@ -0,0 +1,15 @@ +import * as UTIF from "utif"; + +// $ExpectType IFD[] +const IFDs = UTIF.decode(new ArrayBuffer(64)); +// $ExpectType Uint8Array +const rgba = UTIF.toRGBA8(IFDs[0]); + +// $ExpectType ArrayBuffer +UTIF.encodeImage(rgba, 8, 8); +// $ExpectType ArrayBuffer +UTIF.encode(IFDs); +// $ExpectType void +UTIF.decodeImages(new ArrayBuffer(64), IFDs); +// $ExpectType void +UTIF.replaceIMG(); From 8c819e3ff0ee063d24094de2226675f5d6dd8f9b Mon Sep 17 00:00:00 2001 From: "dominic.griesel" <d.griesel@gmx.net> Date: Thu, 7 Feb 2019 13:53:22 +0100 Subject: [PATCH 128/197] [ioBroker] Add `custom` property to ObjectCommon Fixes: ioBroker/adapter-core#3 --- types/iobroker/index.d.ts | 3 +++ types/iobroker/iobroker-tests.ts | 10 ++++++++++ 2 files changed, 13 insertions(+) diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index 6beeccb08f..fb5eb5661a 100644 --- a/types/iobroker/index.d.ts +++ b/types/iobroker/index.d.ts @@ -254,6 +254,9 @@ declare global { icon?: string; /** role of the object */ role?: string; + + /** Custom settings for this object */ + custom?: Record<string, any>; } interface StateCommon extends ObjectCommon { diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts index 01ab0c6fc4..40e48fe8e4 100644 --- a/types/iobroker/iobroker-tests.ts +++ b/types/iobroker/iobroker-tests.ts @@ -259,3 +259,13 @@ adapter.subscribeStatesAsync("*").catch(handleError); adapter.subscribeForeignStatesAsync("*").catch(handleError); adapter.unsubscribeStatesAsync("*").catch(handleError); adapter.unsubscribeForeignStatesAsync("*").catch(handleError); + +// Repro from https://github.com/ioBroker/adapter-core/issues/3 +const repro1: ioBroker.ObjectChangeHandler = (id, obj) => { + obj + && obj.common + && obj.common.custom + && obj.common.custom["adapter.0"] + && obj.common.custom["adapter.0"].enabled + ; +}; From 6b6bf4230bd3274486636a339b8cfe17f730023b Mon Sep 17 00:00:00 2001 From: "dominic.griesel" <d.griesel@gmx.net> Date: Thu, 7 Feb 2019 14:14:59 +0100 Subject: [PATCH 129/197] Add regression test for ioBroker/adapter-core#4 --- types/iobroker/iobroker-tests.ts | 39 +++++++++++++++++++++----------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts index 40e48fe8e4..57d00e284b 100644 --- a/types/iobroker/iobroker-tests.ts +++ b/types/iobroker/iobroker-tests.ts @@ -209,8 +209,8 @@ switch (adapter.log.level) { adapter.sendTo("foo.0", "command", "message"); adapter.sendTo("foo.0", "message"); -adapter.sendTo("foo.0", "command", {msg: "message"}); -adapter.sendTo("foo.0", {msg: "message"}); +adapter.sendTo("foo.0", "command", { msg: "message" }); +adapter.sendTo("foo.0", { msg: "message" }); function handleMessageResponse(response?: ioBroker.Message) { if (!response) return; @@ -226,28 +226,28 @@ function handleMessageResponse(response?: ioBroker.Message) { } adapter.sendTo("foo.0", "command", "message", handleMessageResponse); adapter.sendTo("foo.0", "message", handleMessageResponse); -adapter.sendTo("foo.0", "command", {msg: "message"}, handleMessageResponse); -adapter.sendTo("foo.0", {msg: "message"}, handleMessageResponse); +adapter.sendTo("foo.0", "command", { msg: "message" }, handleMessageResponse); +adapter.sendTo("foo.0", { msg: "message" }, handleMessageResponse); adapter.sendToAsync("foo.0", "command", "message").then(handleMessageResponse); adapter.sendToAsync("foo.0", "message").then(handleMessageResponse); -adapter.sendToAsync("foo.0", "command", {msg: "message"}).then(handleMessageResponse); -adapter.sendToAsync("foo.0", {msg: "message"}).then(handleMessageResponse); +adapter.sendToAsync("foo.0", "command", { msg: "message" }).then(handleMessageResponse); +adapter.sendToAsync("foo.0", { msg: "message" }).then(handleMessageResponse); adapter.sendToHost("host-foo", "command", "message"); adapter.sendToHost("host-foo", "message"); -adapter.sendToHost("host-foo", "command", {msg: "message"}); -adapter.sendToHost("host-foo", {msg: "message"}); +adapter.sendToHost("host-foo", "command", { msg: "message" }); +adapter.sendToHost("host-foo", { msg: "message" }); adapter.sendToHost("host-foo", "command", "message", handleMessageResponse); adapter.sendToHost("host-foo", "message", handleMessageResponse); -adapter.sendToHost("host-foo", "command", {msg: "message"}, handleMessageResponse); -adapter.sendToHost("host-foo", {msg: "message"}, handleMessageResponse); +adapter.sendToHost("host-foo", "command", { msg: "message" }, handleMessageResponse); +adapter.sendToHost("host-foo", { msg: "message" }, handleMessageResponse); adapter.sendToHostAsync("host-foo", "command", "message").then(handleMessageResponse); adapter.sendToHostAsync("host-foo", "message").then(handleMessageResponse); -adapter.sendToHostAsync("host-foo", "command", {msg: "message"}).then(handleMessageResponse); -adapter.sendToHostAsync("host-foo", {msg: "message"}).then(handleMessageResponse); +adapter.sendToHostAsync("host-foo", "command", { msg: "message" }).then(handleMessageResponse); +adapter.sendToHostAsync("host-foo", { msg: "message" }).then(handleMessageResponse); function handleError(err?: string) { } adapter.subscribeStates("*", handleError); @@ -267,5 +267,18 @@ const repro1: ioBroker.ObjectChangeHandler = (id, obj) => { && obj.common.custom && obj.common.custom["adapter.0"] && obj.common.custom["adapter.0"].enabled - ; + ; }; + +// Repro from https://github.com/ioBroker/adapter-core/issues/4 +function repro2() { + // Prepare custom object + const obj = { + common: { + custom: { + "adapter.namespace": { start_day: null as any } + } + } + }; + adapter.extendForeignObject("obj.id", obj, (err) => { }); +} From 07b0e25aa55d23fae0768792262d16100ed78426 Mon Sep 17 00:00:00 2001 From: "dominic.griesel" <d.griesel@gmx.net> Date: Thu, 7 Feb 2019 14:42:21 +0100 Subject: [PATCH 130/197] Only allow `custom` in `StateCommon`, not the other common types --- types/iobroker/index.d.ts | 41 ++++++++++++++++++++++---------- types/iobroker/iobroker-tests.ts | 4 ++++ 2 files changed, 32 insertions(+), 13 deletions(-) diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index fb5eb5661a..0075f8a273 100644 --- a/types/iobroker/index.d.ts +++ b/types/iobroker/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ioBroker/ioBroker // Definitions by: AlCalzone <https://github.com/AlCalzone> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 3.2 // Note: This is not the definition for the package `iobroker`, // which is just an installer, not a library. @@ -254,9 +254,6 @@ declare global { icon?: string; /** role of the object */ role?: string; - - /** Custom settings for this object */ - custom?: Record<string, any>; } interface StateCommon extends ObjectCommon { @@ -299,14 +296,28 @@ declare global { /** attached history information */ history?: any; + + /** Custom settings for this state */ + custom?: Record<string, any>; } interface ChannelCommon extends ObjectCommon { /** description of this channel */ desc?: string; + + // Only states can have common.custom + custom?: undefined; } - type OtherCommon = ObjectCommon & { + interface DeviceCommon extends ObjectCommon { + // Only states can have common.custom + custom?: undefined; + // TODO: any other definition for device? + } + interface OtherCommon extends ObjectCommon { [propName: string]: any; - }; + + // Only states can have common.custom + custom?: undefined; + } interface BaseObject { /** The ID of this object */ @@ -314,7 +325,7 @@ declare global { native: Record<string, any>; enums?: Record<string, string>; type: string; // specified in the derived interfaces - common: ObjectCommon; + common: StateCommon | ChannelCommon | DeviceCommon | OtherCommon; acl?: ObjectACL; } @@ -338,10 +349,10 @@ declare global { interface DeviceObject extends BaseObject { type: "device"; - common: ObjectCommon; // TODO: any definition for device? + common: DeviceCommon; } interface PartialDeviceObject extends Partial<Pick<DeviceObject, "_id" | "native" | "enums" | "type" | "acl">> { - common?: Partial<ObjectCommon>; + common?: Partial<DeviceCommon>; } interface OtherObject extends BaseObject { @@ -353,11 +364,15 @@ declare global { } type Object = StateObject | ChannelObject | DeviceObject | OtherObject; + + type SettableObjectWorker<T extends ioBroker.Object> = + Pick<T, Exclude<keyof T, "_id" | "acl">> & { + _id?: T["_id"]; + acl?: T["acl"]; + }; + // In set[Foreign]Object[NotExists] methods, the ID and acl of the object is optional - interface SettableObject extends Pick<ioBroker.Object, Exclude<keyof ioBroker.Object, "_id" | "acl">> { - _id?: ioBroker.Object["_id"]; - acl?: ioBroker.Object["acl"]; - } + type SettableObject = SettableObjectWorker<ioBroker.Object>; type PartialObject = PartialStateObject | PartialChannelObject | PartialDeviceObject | PartialOtherObject; /** Defines access rights for a single file */ diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts index 57d00e284b..a2c89cb893 100644 --- a/types/iobroker/iobroker-tests.ts +++ b/types/iobroker/iobroker-tests.ts @@ -262,6 +262,10 @@ adapter.unsubscribeForeignStatesAsync("*").catch(handleError); // Repro from https://github.com/ioBroker/adapter-core/issues/3 const repro1: ioBroker.ObjectChangeHandler = (id, obj) => { + if (!obj || !obj.common) return; + if (obj.common.custom) { + const test1: ioBroker.StateCommon = obj.common; + } obj && obj.common && obj.common.custom From ccb7c5dc16029909045607a02aee70da37ac5c03 Mon Sep 17 00:00:00 2001 From: Bradley Hill <brad.hill@jostens.com> Date: Thu, 7 Feb 2019 08:49:41 -0600 Subject: [PATCH 131/197] Fabricjs - missing color matrix definition (we only had matrix when charlie chaplin played Neo) --- types/fabric/fabric-impl.d.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 68c0a73efe..5cc59d0941 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -3774,7 +3774,18 @@ interface IAllFilters { */ fromObject(object: any): IBrightnessFilter }; - Convolute: { + ColorMatrix: { + new(options?: { + /** Filter matrix */ + matrix?: number[] + }): IColorMatrix; + /** + * Returns filter instance from an object representation + * @param object Object to create an instance from + */ + fromObject(object: any): IColorMatrix + }; + Convolute: { new(options?: { opaque?: boolean, /** Filter matrix */ @@ -3962,6 +3973,13 @@ interface IBrightnessFilter extends IBaseFilter { */ applyTo(canvasEl: HTMLCanvasElement): void; } +interface IColorMatrix extends IBaseFilter { + /** + * Applies filter to canvas element + * @param canvasEl Canvas element to apply filter to + */ + applyTo(canvasEl: HTMLCanvasElement): void; +} interface IConvoluteFilter extends IBaseFilter { /** * Applies filter to canvas element From 6823bf50b489163a0604f8f0b1957678f2a5503e Mon Sep 17 00:00:00 2001 From: Jannik Keye <jannik.keye@gmail.com> Date: Thu, 7 Feb 2019 16:28:28 +0100 Subject: [PATCH 132/197] fix: remove fastify-static --- notNeededPackages.json | 6 +++ types/fastify-static/fastify-static-tests.ts | 16 -------- types/fastify-static/index.d.ts | 41 -------------------- types/fastify-static/package.json | 6 --- types/fastify-static/tsconfig.json | 16 -------- types/fastify-static/tslint.json | 1 - 6 files changed, 6 insertions(+), 80 deletions(-) delete mode 100644 types/fastify-static/fastify-static-tests.ts delete mode 100644 types/fastify-static/index.d.ts delete mode 100644 types/fastify-static/package.json delete mode 100644 types/fastify-static/tsconfig.json delete mode 100644 types/fastify-static/tslint.json diff --git a/notNeededPackages.json b/notNeededPackages.json index 701978da24..db3d6b10d2 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -570,6 +570,12 @@ "sourceRepoURL": "https://github.com/fastify/fastify-jwt", "asOfVersion": "0.8.1" }, + { + "libraryName": "fastify-static", + "typingsPackageName": "fastify-static", + "sourceRepoURL": "https://github.com/fastify/fastify-static", + "asOfVersion": "2.2.0" + }, { "libraryName": "fecha", "typingsPackageName": "fecha", diff --git a/types/fastify-static/fastify-static-tests.ts b/types/fastify-static/fastify-static-tests.ts deleted file mode 100644 index 630fc0ef52..0000000000 --- a/types/fastify-static/fastify-static-tests.ts +++ /dev/null @@ -1,16 +0,0 @@ -import path = require("path"); -import fastify = require("fastify"); -import fastifyStatic = require("fastify-static"); - -const app = fastify(); - -app.register<fastifyStatic.FastifyStaticOptions>(fastifyStatic, { - root: path.join(__dirname, "public"), - prefix: "/public/", // optional: default '/' - immutable: true, - maxAge: 42 -}); - -app.get("/another/path", (req, reply) => { - reply.sendFile("myHtml.html"); // serving path.join(__dirname, 'public', 'myHtml.html') directly -}); diff --git a/types/fastify-static/index.d.ts b/types/fastify-static/index.d.ts deleted file mode 100644 index ef4eda1952..0000000000 --- a/types/fastify-static/index.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -// Type definitions for fastify-static 0.14 -// Project: https://github.com/fastify/fastify-static -// Definitions by: Leonhard Melzer <https://github.com/leomelzer> -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 - -import fastify = require("fastify"); - -import { Server, IncomingMessage, ServerResponse } from "http"; - -declare module "fastify" { - interface FastifyReply<HttpResponse> { - sendFile(filename: string): FastifyReply<HttpResponse>; - } -} - -declare function fastifyStatic(): void; - -declare namespace fastifyStatic { - interface FastifyStaticOptions { - root: string; - prefix?: string; - serve?: boolean; - decorateReply?: boolean; - schemaHide?: boolean; - setHeaders?: () => void; - - // Passed on to `send` - acceptRanges?: boolean; - cacheControl?: boolean; - dotfiles?: boolean; - etag?: boolean; - extensions?: string[]; - immutable?: boolean; - index?: string[]; - lastModified?: boolean; - maxAge?: string | number; - } -} - -export = fastifyStatic; diff --git a/types/fastify-static/package.json b/types/fastify-static/package.json deleted file mode 100644 index e8c68ab969..0000000000 --- a/types/fastify-static/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "private": true, - "dependencies": { - "fastify": "^1.11.2" - } -} diff --git a/types/fastify-static/tsconfig.json b/types/fastify-static/tsconfig.json deleted file mode 100644 index bdfa7d40c6..0000000000 --- a/types/fastify-static/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": ["es6"], - "noImplicitAny": true, - "noImplicitThis": true, - "strictFunctionTypes": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": ["../"], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": ["index.d.ts", "fastify-static-tests.ts"] -} diff --git a/types/fastify-static/tslint.json b/types/fastify-static/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/fastify-static/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } From a336ba83ae30b666f284dfd16c1b926f7ae03106 Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Thu, 7 Feb 2019 09:45:58 -0600 Subject: [PATCH 133/197] Add @carbon/layout --- types/carbon__layout/carbon__layout-tests.ts | 20 +++++ types/carbon__layout/index.d.ts | 80 ++++++++++++++++++++ types/carbon__layout/tsconfig.json | 19 +++++ types/carbon__layout/tslint.json | 1 + 4 files changed, 120 insertions(+) create mode 100644 types/carbon__layout/carbon__layout-tests.ts create mode 100644 types/carbon__layout/index.d.ts create mode 100644 types/carbon__layout/tsconfig.json create mode 100644 types/carbon__layout/tslint.json diff --git a/types/carbon__layout/carbon__layout-tests.ts b/types/carbon__layout/carbon__layout-tests.ts new file mode 100644 index 0000000000..ef002f50ae --- /dev/null +++ b/types/carbon__layout/carbon__layout-tests.ts @@ -0,0 +1,20 @@ +import { + rem, + em, + px, + breakpoint, + breakpoints, + breakpointDown, + breakpointUp, + baseFontSize +} from "@carbon/layout"; + +const firstBreakpoint = Object.keys(breakpoints)[0]; + +rem(baseFontSize); // $ExpectType string +em(baseFontSize); // $ExpectType string +px(baseFontSize); // $ExpectType string + +breakpoint(firstBreakpoint); // $ExpectType string +breakpointUp(firstBreakpoint); // $ExpectType string +breakpointDown(firstBreakpoint); // $ExpectType string diff --git a/types/carbon__layout/index.d.ts b/types/carbon__layout/index.d.ts new file mode 100644 index 0000000000..1d7c7b4630 --- /dev/null +++ b/types/carbon__layout/index.d.ts @@ -0,0 +1,80 @@ +// Type definitions for @carbon/layout 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/layout +// Definitions by: Vince Picone <https://github.com/vpicone> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const baseFontSize: number; + +export const breakpoints: { + lg: { + columns: number; + margin: string; + width: string; + }; + max: { + columns: number; + margin: string; + width: string; + }; + md: { + columns: number; + margin: string; + width: string; + }; + sm: { + columns: number; + margin: string; + width: string; + }; + xlg: { + columns: number; + margin: string; + width: string; + }; +}; + +export const miniUnit: number; + +export const spacing: number[]; + +export function breakpoint(...args: any[]): string; + +export function breakpointDown(name: string): string; + +export function breakpointUp(name: string): string; + +export function em(px: number): string; + +export function miniUnits(count: number): string; + +export function px(value: number): string; + +export function rem(px: number): string; + +export namespace breakpoint { + const prototype: {}; +} + +export namespace breakpointDown { + const prototype: {}; +} + +export namespace breakpointUp { + const prototype: {}; +} + +export namespace em { + const prototype: {}; +} + +export namespace miniUnits { + const prototype: {}; +} + +export namespace px { + const prototype: {}; +} + +export namespace rem { + const prototype: {}; +} diff --git a/types/carbon__layout/tsconfig.json b/types/carbon__layout/tsconfig.json new file mode 100644 index 0000000000..10f832a631 --- /dev/null +++ b/types/carbon__layout/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@carbon/layout": ["carbon__layout"] + } + }, + "files": ["index.d.ts", "carbon__layout-tests.ts"] +} diff --git a/types/carbon__layout/tslint.json b/types/carbon__layout/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/carbon__layout/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 12e28d0e287d0a2fe41700639cb6e2f891c0ac0a Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Thu, 7 Feb 2019 09:49:53 -0600 Subject: [PATCH 134/197] Add carbon motion --- types/carbon__motion/carbon__motion-tests.ts | 0 types/carbon__motion/index.d.ts | 28 ++++++++++++++++++++ types/carbon__motion/tsconfig.json | 19 +++++++++++++ types/carbon__motion/tslint.json | 1 + 4 files changed, 48 insertions(+) create mode 100644 types/carbon__motion/carbon__motion-tests.ts create mode 100644 types/carbon__motion/index.d.ts create mode 100644 types/carbon__motion/tsconfig.json create mode 100644 types/carbon__motion/tslint.json diff --git a/types/carbon__motion/carbon__motion-tests.ts b/types/carbon__motion/carbon__motion-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/carbon__motion/index.d.ts b/types/carbon__motion/index.d.ts new file mode 100644 index 0000000000..9570133327 --- /dev/null +++ b/types/carbon__motion/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for carbon__motion-ts 0.0 +// Project: https://github.com/baz/foo (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) +// Definitions by: My Self <https://github.com/me> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const easings: { + entrance: { + expressive: string; + productive: string; + }; + exit: { + expressive: string; + productive: string; + }; + standard: { + expressive: string; + productive: string; + }; +}; + +export function motion(name: any, mode: any): any; + +export namespace motion { + const prototype: { + }; + +} + diff --git a/types/carbon__motion/tsconfig.json b/types/carbon__motion/tsconfig.json new file mode 100644 index 0000000000..38245c7c9e --- /dev/null +++ b/types/carbon__motion/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@carbon/motion": ["carbon__motion"] + } + }, + "files": ["index.d.ts", "carbon__motion-tests.ts"] +} diff --git a/types/carbon__motion/tslint.json b/types/carbon__motion/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/carbon__motion/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 6eea5834fa91716914c604464c4fd4d2ba032ac8 Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Thu, 7 Feb 2019 09:56:03 -0600 Subject: [PATCH 135/197] add tests --- types/carbon__motion/carbon__motion-tests.ts | 8 ++++++++ types/carbon__motion/index.d.ts | 7 ++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/types/carbon__motion/carbon__motion-tests.ts b/types/carbon__motion/carbon__motion-tests.ts index e69de29bb2..6bcc820f5d 100644 --- a/types/carbon__motion/carbon__motion-tests.ts +++ b/types/carbon__motion/carbon__motion-tests.ts @@ -0,0 +1,8 @@ +import { easings, motion } from "@carbon/motion"; + +const easingNames = Object.keys(easings); + +const firstEasing = easingNames[0]; +const firstMode = Object.keys(firstEasing)[0]; + +motion(firstEasing, firstMode); diff --git a/types/carbon__motion/index.d.ts b/types/carbon__motion/index.d.ts index 9570133327..5027843174 100644 --- a/types/carbon__motion/index.d.ts +++ b/types/carbon__motion/index.d.ts @@ -18,11 +18,8 @@ export const easings: { }; }; -export function motion(name: any, mode: any): any; +export function motion(name: string, mode: string): string; export namespace motion { - const prototype: { - }; - + const prototype: {}; } - From c341f6378d8db86af3740a5f8c3b822e72184b29 Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Thu, 7 Feb 2019 10:05:13 -0600 Subject: [PATCH 136/197] Add @carbon/type --- types/carbon__type/carbon__type-tests.ts | 0 types/carbon__type/index.d.ts | 717 +++++++++++++++++++++++ types/carbon__type/tsconfig.json | 19 + types/carbon__type/tslint.json | 1 + 4 files changed, 737 insertions(+) create mode 100644 types/carbon__type/carbon__type-tests.ts create mode 100644 types/carbon__type/index.d.ts create mode 100644 types/carbon__type/tsconfig.json create mode 100644 types/carbon__type/tslint.json diff --git a/types/carbon__type/carbon__type-tests.ts b/types/carbon__type/carbon__type-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/types/carbon__type/index.d.ts b/types/carbon__type/index.d.ts new file mode 100644 index 0000000000..af79ee812b --- /dev/null +++ b/types/carbon__type/index.d.ts @@ -0,0 +1,717 @@ +// Type definitions for @carbon/type 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/type +// Definitions by: Vince Picone <https://github.com/vpicone> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const bodyLong01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const bodyLong02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const bodyShort01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const bodyShort02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const caption01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const code01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const code02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const display01: { + "@media (min-width: 42rem)": { + fontSize: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const display02: { + "@media (min-width: 42rem)": { + fontSize: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const display03: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const display04: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const expressiveHeading04: { + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const expressiveHeading05: { + "@media (min-width: 42rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const expressiveParagraph01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lg: { + fontSize: string; + lineHeight: string; + }; + lineHeight: string; + max: { + fontSize: string; + lineHeight: string; + }; +}; + +export const fontFamilies: { + mono: string; + sans: string; + sansCondensed: string; + sansHebrew: string; + serif: string; +}; + +export const fontWeights: { + light: number; + regular: number; + semibold: number; +}; + +export const heading01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const heading02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const heading03: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const helperText01: { + fontFamily: string; + fontSize: string; + fontStyle: string; + letterSpacing: string; + lineHeight: string; +}; + +export const label01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; +}; + +export const productiveHeading04: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const productiveHeading05: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const quotation01: { + "@media (min-width: 42rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + }; + "@media (min-width: 66rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const quotation02: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; +}; + +export const reset: { + body: { + "-moz-osx-font-smoothing": string; + "-webkit-font-smoothing": string; + fontFamily: string; + fontWeight: number; + textRendering: string; + }; + html: { + fontSize: string; + }; + strong: { + fontWeight: number; + }; +}; + +export const scale: number[]; + +export const spacing: { + layout01: string; + layout02: string; + layout03: string; + margin01: string; + margin02: string; + margin03: string; +}; + +export const styles: { + bodyLong01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + bodyLong02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + bodyShort01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + bodyShort02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + caption01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + code01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + code02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + display01: { + "@media (min-width: 42rem)": { + fontSize: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + display02: { + "@media (min-width: 42rem)": { + fontSize: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + display03: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + display04: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + letterSpacing: string; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + expressiveHeading04: { + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + expressiveHeading05: { + "@media (min-width: 42rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + expressiveParagraph01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lg: { + fontSize: string; + lineHeight: string; + }; + lineHeight: string; + max: { + fontSize: string; + lineHeight: string; + }; + }; + heading01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + heading02: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + heading03: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + helperText01: { + fontFamily: string; + fontSize: string; + fontStyle: string; + letterSpacing: string; + lineHeight: string; + }; + label01: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: string; + lineHeight: string; + }; + productiveHeading04: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + productiveHeading05: { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + quotation01: { + "@media (min-width: 42rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + }; + "@media (min-width: 66rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; + quotation02: { + "@media (min-width: 42rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 66rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 82rem)": { + fontSize: string; + lineHeight: string; + }; + "@media (min-width: 99rem)": { + fontSize: string; + }; + fontFamily: string; + fontSize: string; + fontWeight: number; + letterSpacing: number; + lineHeight: string; + }; +}; + +export function fontFamily(name: any): any; + +export function fontWeight(weight: any): any; + +export function getTypeSize(step: any): any; + +export function print(block: any): any; + +export namespace fontFamily { + const prototype: {}; +} + +export namespace fontWeight { + const prototype: {}; +} + +export namespace getTypeSize { + const prototype: {}; +} + +export namespace print { + const prototype: {}; +} diff --git a/types/carbon__type/tsconfig.json b/types/carbon__type/tsconfig.json new file mode 100644 index 0000000000..7949e7ab22 --- /dev/null +++ b/types/carbon__type/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@carbon/type": ["carbon__type"] + } + }, + "files": ["index.d.ts", "carbon__type-tests.ts"] +} diff --git a/types/carbon__type/tslint.json b/types/carbon__type/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/carbon__type/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From d69938c98f79fdf9f948e47fdd7f6ba68c42ccfe Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Thu, 7 Feb 2019 10:06:01 -0600 Subject: [PATCH 137/197] fix headers --- types/carbon__motion/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/carbon__motion/index.d.ts b/types/carbon__motion/index.d.ts index 5027843174..173687d04c 100644 --- a/types/carbon__motion/index.d.ts +++ b/types/carbon__motion/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for carbon__motion-ts 0.0 -// Project: https://github.com/baz/foo (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) -// Definitions by: My Self <https://github.com/me> +// Type definitions for @carbon/motion 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/motion +// Definitions by: Vince Picone <https://github.com/vpicone> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export const easings: { From d4c5675d00e52c4cf99dcc88a5c0fea838d241eb Mon Sep 17 00:00:00 2001 From: Vince Picone <Vincent.Patrick.Picone@ibm.com> Date: Thu, 7 Feb 2019 10:19:01 -0600 Subject: [PATCH 138/197] Add @carbon/type --- types/carbon__type/carbon__type-tests.ts | 6 ++++++ types/carbon__type/index.d.ts | 17 +++++++++++++---- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/types/carbon__type/carbon__type-tests.ts b/types/carbon__type/carbon__type-tests.ts index e69de29bb2..a5d4cf7b8b 100644 --- a/types/carbon__type/carbon__type-tests.ts +++ b/types/carbon__type/carbon__type-tests.ts @@ -0,0 +1,6 @@ +import { fontFamily, fontWeight, getTypeSize, print } from "@carbon/type"; + +fontFamily("mono"); // $ExpectType { fontFamily: string; } +fontWeight("light"); // $ExpectType { fontWeight: number; } +print(fontFamily("mono")); // $ExpectType string +getTypeSize(2); // $ExpectType number diff --git a/types/carbon__type/index.d.ts b/types/carbon__type/index.d.ts index af79ee812b..7933f2e358 100644 --- a/types/carbon__type/index.d.ts +++ b/types/carbon__type/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/IBM/carbon-elements/tree/master/packages/type // Definitions by: Vince Picone <https://github.com/vpicone> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 export const bodyLong01: { fontFamily: string; @@ -692,13 +693,21 @@ export const styles: { }; }; -export function fontFamily(name: any): any; +export function fontFamily( + name: string +): { + fontFamily: string; +}; -export function fontWeight(weight: any): any; +export function fontWeight( + weight: string +): { + fontWeight: number; +}; -export function getTypeSize(step: any): any; +export function getTypeSize(step: number): number; -export function print(block: any): any; +export function print(block: object): string; export namespace fontFamily { const prototype: {}; From 95ea7a5148af9b2a643fcc5da7f3e7d0ae014f1d Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel <elizs@microsoft.com> Date: Thu, 7 Feb 2019 09:19:21 -0800 Subject: [PATCH 139/197] [office-js] [office-js-preview] (Outlook) Remove inapplicable props --- types/office-js-preview/index.d.ts | 127 +---------------------------- types/office-js/index.d.ts | 127 +---------------------------- 2 files changed, 4 insertions(+), 250 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index ffb686b3d2..026701c4be 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -10541,7 +10541,7 @@ declare namespace Office { /** * Represents an attachment on an item from the server. Read mode only. * - * An array of AttachmentDetail objects is returned as the attachments property of an Appointment or Message object. + * An array of `AttachmentDetails` objects is returned as the attachments property of an appointment or message item. * * [Api set: Mailbox 1.0] * @@ -11765,32 +11765,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> */ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets or sets the date and time that the appointment is to end. * @@ -13622,32 +13596,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Compose or read</td></tr></table> */ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets the type of item that an instance represents. * @@ -13676,29 +13624,6 @@ declare namespace Office { */ notificationMessages: NotificationMessages; - /** - * Gets or sets the recurrence pattern of an appointment. Gets the recurrence pattern of a meeting request. - * Read and compose modes for appointment items. Read mode for meeting request items. - * - * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance - * in a series. `null` is returned for single appointments and meeting requests of single appointments. - * `undefined` is returned for messages that are not meeting requests. - * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. - * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment - * and NOT a part of a series. - * - * [Api set: Mailbox 1.7] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Compose or read</td></tr></table> - */ - recurrence: Recurrence; - /** * Gets the id of the series that an instance belongs to. * @@ -15234,32 +15159,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> */ conversationId: string; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets the email address of the sender of a message. * @@ -15320,28 +15219,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> */ notificationMessages: NotificationMessages; - /** - * Gets or sets the recurrence pattern of an appointment. Gets the recurrence pattern of a meeting request. - * Read and compose modes for appointment items. Read mode for meeting request items. - * - * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance - * in a series. `null` is returned for single appointments and meeting requests of single appointments. - * `undefined` is returned for messages that are not meeting requests. - * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. - * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment - * and NOT a part of a series. - * - * [Api set: Mailbox 1.7] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - */ - recurrence: Recurrence; /** * Gets the id of the series that an instance belongs to. * @@ -17779,7 +17656,7 @@ declare namespace Office { /** * Gets a string that was identified as a meeting suggestion. */ - meetingstring: string; + meetingString: string; /** * Gets the date and time that a suggested meeting is to begin. */ diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index d53bdedb79..b35620eeb1 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -10541,7 +10541,7 @@ declare namespace Office { /** * Represents an attachment on an item from the server. Read mode only. * - * An array of AttachmentDetail objects is returned as the attachments property of an Appointment or Message object. + * An array of `AttachmentDetails` objects is returned as the attachments property of an appointment or message item. * * [Api set: Mailbox 1.0] * @@ -11765,32 +11765,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> */ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Organizer</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets or sets the date and time that the appointment is to end. * @@ -13622,32 +13596,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Compose or read</td></tr></table> */ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets the type of item that an instance represents. * @@ -13676,29 +13624,6 @@ declare namespace Office { */ notificationMessages: NotificationMessages; - /** - * Gets or sets the recurrence pattern of an appointment. Gets the recurrence pattern of a meeting request. - * Read and compose modes for appointment items. Read mode for meeting request items. - * - * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance - * in a series. `null` is returned for single appointments and meeting requests of single appointments. - * `undefined` is returned for messages that are not meeting requests. - * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. - * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment - * and NOT a part of a series. - * - * [Api set: Mailbox 1.7] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Compose or read</td></tr></table> - */ - recurrence: Recurrence; - /** * Gets the id of the series that an instance belongs to. * @@ -15234,32 +15159,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> */ conversationId: string; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. - */ - dateTimeModified: Date; /** * Gets the email address of the sender of a message. * @@ -15320,28 +15219,6 @@ declare namespace Office { * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> */ notificationMessages: NotificationMessages; - /** - * Gets or sets the recurrence pattern of an appointment. Gets the recurrence pattern of a meeting request. - * Read and compose modes for appointment items. Read mode for meeting request items. - * - * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance - * in a series. `null` is returned for single appointments and meeting requests of single appointments. - * `undefined` is returned for messages that are not meeting requests. - * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. - * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment - * and NOT a part of a series. - * - * [Api set: Mailbox 1.7] - * - * @remarks - * - * <table><tr><td>{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}</td><td>ReadItem</td></tr> - * - * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Compose</td></tr></table> - */ - recurrence: Recurrence; /** * Gets the id of the series that an instance belongs to. * @@ -17779,7 +17656,7 @@ declare namespace Office { /** * Gets a string that was identified as a meeting suggestion. */ - meetingstring: string; + meetingString: string; /** * Gets the date and time that a suggested meeting is to begin. */ From 8d7c359191857e2f72ffbf813bd17dfb1eaa24f4 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel <elizs@microsoft.com> Date: Thu, 7 Feb 2019 09:24:47 -0800 Subject: [PATCH 140/197] Minor cleanup --- types/office-js-preview/index.d.ts | 8 ++++---- types/office-js/index.d.ts | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 026701c4be..14838b162e 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -12849,7 +12849,7 @@ declare namespace Office { */ body: Body; /** - * Gets the date and time that an item was created. Read mode only. + * Gets the date and time that an item was created. * * [Api set: Mailbox 1.0] * @@ -12861,7 +12861,7 @@ declare namespace Office { */ dateTimeCreated: Date; /** - * Gets the date and time that an item was last modified. Read mode only. + * Gets the date and time that an item was last modified. * * [Api set: Mailbox 1.0] * @@ -16205,7 +16205,7 @@ declare namespace Office { */ conversationId: string; /** - * Gets the date and time that an item was created. Read mode only. + * Gets the date and time that an item was created. * * [Api set: Mailbox 1.0] * @@ -16217,7 +16217,7 @@ declare namespace Office { */ dateTimeCreated: Date; /** - * Gets the date and time that an item was last modified. Read mode only. + * Gets the date and time that an item was last modified. * * [Api set: Mailbox 1.0] * diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index b35620eeb1..aa90caf5be 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -12849,7 +12849,7 @@ declare namespace Office { */ body: Body; /** - * Gets the date and time that an item was created. Read mode only. + * Gets the date and time that an item was created. * * [Api set: Mailbox 1.0] * @@ -12861,7 +12861,7 @@ declare namespace Office { */ dateTimeCreated: Date; /** - * Gets the date and time that an item was last modified. Read mode only. + * Gets the date and time that an item was last modified. * * [Api set: Mailbox 1.0] * @@ -16205,7 +16205,7 @@ declare namespace Office { */ conversationId: string; /** - * Gets the date and time that an item was created. Read mode only. + * Gets the date and time that an item was created. * * [Api set: Mailbox 1.0] * @@ -16217,7 +16217,7 @@ declare namespace Office { */ dateTimeCreated: Date; /** - * Gets the date and time that an item was last modified. Read mode only. + * Gets the date and time that an item was last modified. * * [Api set: Mailbox 1.0] * From 210e52da16ed7dbde6f6bda1a70f605f157cc4de Mon Sep 17 00:00:00 2001 From: Ethan Setnik <esetnik@gmail.com> Date: Thu, 7 Feb 2019 12:45:29 -0500 Subject: [PATCH 141/197] add startSubmit and stopSubmit --- types/redux-form/immutable/index.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/redux-form/immutable/index.d.ts b/types/redux-form/immutable/index.d.ts index 742027ccad..2ce6164232 100644 --- a/types/redux-form/immutable/index.d.ts +++ b/types/redux-form/immutable/index.d.ts @@ -24,5 +24,7 @@ export { isSubmitting, isAsyncValidating, isValid, - SubmissionError -} from "../"; + SubmissionError, + startSubmit, + stopSubmit, +} from '../'; From cc6741b1bf8c4e34d465fae748308f510dc40e41 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel <elizs@microsoft.com> Date: Thu, 7 Feb 2019 09:53:12 -0800 Subject: [PATCH 142/197] Add link to OM page --- types/office-js-preview/index.d.ts | 24 ++++++++++++++++-------- types/office-js/index.d.ts | 24 ++++++++++++++++-------- 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 14838b162e..e9586af4f1 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -11742,7 +11742,8 @@ declare namespace Office { * The subclass of {@link Office.Item} dealing with appointments. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of Office.context.mailbox.item. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface Appointment extends Item { } @@ -11750,7 +11751,8 @@ declare namespace Office { * The appointment organizer mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface AppointmentCompose extends Appointment, ItemCompose { /** @@ -12817,7 +12819,8 @@ declare namespace Office { * The appointment attendee mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of 'Office.context.mailbox.item'. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface AppointmentRead extends Appointment, ItemRead { /** @@ -13876,7 +13879,8 @@ declare namespace Office { * The compose mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface ItemCompose extends Item { /** @@ -14650,7 +14654,8 @@ declare namespace Office { * The read mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface ItemRead extends Item { /** @@ -15069,7 +15074,8 @@ declare namespace Office { * A subclass of {@link Office.Item} for messages. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface Message extends Item { /** @@ -15097,7 +15103,8 @@ declare namespace Office { * The message compose mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface MessageCompose extends Message, ItemCompose { /** @@ -16137,7 +16144,8 @@ declare namespace Office { * The message read mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of Office.context.mailbox.item. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface MessageRead extends Message, ItemRead { /** diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index aa90caf5be..5a98b250ae 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -11742,7 +11742,8 @@ declare namespace Office { * The subclass of {@link Office.Item} dealing with appointments. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of Office.context.mailbox.item. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface Appointment extends Item { } @@ -11750,7 +11751,8 @@ declare namespace Office { * The appointment organizer mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface AppointmentCompose extends Appointment, ItemCompose { /** @@ -12817,7 +12819,8 @@ declare namespace Office { * The appointment attendee mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of 'Office.context.mailbox.item'. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface AppointmentRead extends Appointment, ItemRead { /** @@ -13876,7 +13879,8 @@ declare namespace Office { * The compose mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface ItemCompose extends Item { /** @@ -14650,7 +14654,8 @@ declare namespace Office { * The read mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface ItemRead extends Item { /** @@ -15069,7 +15074,8 @@ declare namespace Office { * A subclass of {@link Office.Item} for messages. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface Message extends Item { /** @@ -15097,7 +15103,8 @@ declare namespace Office { * The message compose mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of `Office.context.mailbox.item`. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface MessageCompose extends Message, ItemCompose { /** @@ -16137,7 +16144,8 @@ declare namespace Office { * The message read mode of {@link Office.Item | Office.context.mailbox.item}. * * Important: This is an internal Outlook object, not directly exposed through existing interfaces. - * You should treat this as a mode of Office.context.mailbox.item. Refer to the Object Model pages for more information. + * You should treat this as a mode of Office.context.mailbox.item. Refer to the + * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ interface MessageRead extends Message, ItemRead { /** From ab8fc4f1508ed95007e858d7b5615bb928af3ff4 Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel <elizs@microsoft.com> Date: Thu, 7 Feb 2019 10:44:26 -0800 Subject: [PATCH 143/197] Bold Important and Note --- types/office-js-preview/index.d.ts | 286 ++++++++++++++--------------- types/office-js/index.d.ts | 286 ++++++++++++++--------------- 2 files changed, 286 insertions(+), 286 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index e9586af4f1..bbed11cdea 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -20,7 +20,7 @@ declare namespace Office { */ var Promise: IPromiseConstructor; - // Note: this is a copy of the PromiseConstructor object from + // **Note**: this is a copy of the PromiseConstructor object from // https://github.com/Microsoft/TypeScript/blob/master/lib/lib.es2015.promise.d.ts // It is necessary so that even with targeting "ES5" and not specifying any libs, // developers will still get IntelliSense for "Office.Promise" just as they would with a regular Promise. @@ -628,7 +628,7 @@ declare namespace Office { * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the * `getSelectedDataAsync` and `setSelectedDataAsync` methods of the {@link Office.Document | Document} object. * - * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. + * **Note**: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. * To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. * * **Support details** @@ -1446,7 +1446,7 @@ declare namespace Office { /** * Specifies a table of sample data displayed in the prompt UI as an example of the kinds of fields (columns) that can be bound by your add-in. * The headers provided in the TableData object specify the labels used in the field selection UI. - * Note: This parameter is used only in add-ins for Access. It is ignored if provided when calling the method in an add-in for Excel. + * **Note**: This parameter is used only in add-ins for Access. It is ignored if provided when calling the method in an add-in for Excel. */ sampleData?: Office.TableData /** @@ -1781,43 +1781,43 @@ declare namespace Office { * Return or set data as tabular data with no headers. Data is returned or set as an array of arrays containing one-dimensional runs of * characters. For example, three rows of string values in two columns would be: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. * - * Note: Only applies to data in Excel and Word. + * **Note**: Only applies to data in Excel and Word. */ Matrix, /** * Return or set data as tabular data with optional headers. Data is returned or set as an array of arrays with optional headers. * - * Note: Only applies to data in Access, Excel, and Word. + * **Note**: Only applies to data in Access, Excel, and Word. */ Table, /** * Return or set data as HTML. * - * Note: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). + * **Note**: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). */ Html, /** * Return or set data as Office Open XML. * - * Note: Only applies to data in Word. + * **Note**: Only applies to data in Word. */ Ooxml, /** * Return a JSON object that contains an array of the ids, titles, and indexes of the selected slides. For example, * `{"slides":[{"id":257,"title":"Slide 2","index":2},{"id":256,"title":"Slide 1","index":1}]}` for a selection of two slides. * - * Note: Only applies to data in PowerPoint when calling the {@link Office.Document | Document}.getSelectedData method to get the current + * **Note**: Only applies to data in PowerPoint when calling the {@link Office.Document | Document}.getSelectedData method to get the current * slide or selected range of slides. */ SlideRange, /** * Data is returned or set as an image stream. - * Note: Only applies to data in Excel, Word, and PowerPoint. + * **Note**: Only applies to data in Excel, Word, and PowerPoint. */ Image, /** * Data is returned or set as XML data containing an SVG image. - * Note: Only applies to data in Excel, Word, and PowerPoint. + * **Note**: Only applies to data in Excel, Word, and PowerPoint. */ XmlSvg } @@ -2523,7 +2523,7 @@ declare namespace Office { * </tr> * <tr> * <td>An {@link Office.TableData} object, and the shape of the table matches the bound table.</td> - * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. Note: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> + * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. **Note**: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> * </tr> * </table> * @@ -2654,7 +2654,7 @@ declare namespace Office { * </tr> * <tr> * <td>An {@link Office.TableData} object, and the shape of the table matches the bound table.</td> - * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. Note: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> + * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. **Note**: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> * </tr> * </table> * @@ -2825,7 +2825,7 @@ declare namespace Office { * By default, adding a table in Excel assigns the name "Table1" for the first table you add, "Table2" for the second table you add, and so on. * To assign a meaningful name for a table in the Excel UI, use the Table Name property on the Table Tools | Design tab of the ribbon. * - * Note: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of + * **Note**: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of * the table in this format: "Sheet1!Table1" * * For Word, the itemName parameter refers to the Title property of a Rich Text content control. (You can't bind to content controls other @@ -2835,7 +2835,7 @@ declare namespace Office { * control from the Controls group on the Developer tab of the ribbon, use the Properties command in the Controls group to display the Content * Control Properties dialog box. Then set the Title property of the content control to the name you want to reference from your code. * - * Note: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one + * **Note**: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one * these content controls with this method (by specifying its name as the itemName parameter), the operation will fail. * * **Support details** @@ -2871,7 +2871,7 @@ declare namespace Office { * By default, adding a table in Excel assigns the name "Table1" for the first table you add, "Table2" for the second table you add, and so on. * To assign a meaningful name for a table in the Excel UI, use the Table Name property on the Table Tools | Design tab of the ribbon. * - * Note: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of + * **Note**: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of * the table in this format: "Sheet1!Table1" * * For Word, the itemName parameter refers to the Title property of a Rich Text content control. (You can't bind to content controls other @@ -2881,7 +2881,7 @@ declare namespace Office { * control from the Controls group on the Developer tab of the ribbon, use the Properties command in the Controls group to display the Content * Control Properties dialog box. Then set the Title property of the content control to the name you want to reference from your code. * - * Note: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one + * **Note**: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one * these content controls with this method (by specifying its name as the itemName parameter), the operation will fail. * * **Support details** @@ -4542,7 +4542,7 @@ declare namespace Office { * <table> * <tr><td>Word</td><td>If there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion point</td><td>If `data` is a string, the specified text is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.</td></tr> - * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (Important: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> + * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (**Important**: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> * <tr><td></td><td></td><td>If `data` is Office Open XML, the specified XML is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is a base64 encoded image stream, the specified image is inserted.</td></tr></td></tr> * <tr><td></td><td>If there is a selection</td><td>It will be replaced with the specified `data` following the same rules as above.</td></tr> @@ -4659,7 +4659,7 @@ declare namespace Office { * <table> * <tr><td>Word</td><td>If there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion point</td><td>If `data` is a string, the specified text is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.</td></tr> - * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (Important: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> + * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (**Important**: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> * <tr><td></td><td></td><td>If `data` is Office Open XML, the specified XML is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is a base64 encoded image stream, the specified image is inserted.</td></tr></td></tr> * <tr><td></td><td>If there is a selection</td><td>It will be replaced with the specified `data` following the same rules as above.</td></tr> @@ -5151,7 +5151,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of resources in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5177,7 +5177,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of resources in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the highest index number in the current project's resource collection. @@ -5202,7 +5202,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of tasks in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5228,7 +5228,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of tasks in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the highest index number in the current project's task collection. @@ -5253,7 +5253,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceIndex The index of the resource in the collection of resources for the project. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -5280,7 +5280,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceIndex The index of the resource in the collection of resources for the project. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5306,7 +5306,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskIndex The index of the task in the collection of tasks for the project. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -5333,7 +5333,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskIndex The index of the task in the collection of tasks for the project. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5359,7 +5359,7 @@ declare namespace Office { /** * Project documents only. Set resource field for specified resource Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceId Either a string or value of the Resource Id. * @param fieldId Resource Fields. @@ -5387,7 +5387,7 @@ declare namespace Office { /** * Project documents only. Set resource field for specified resource Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceId Either a string or value of the Resource Id. * @param fieldId Resource Fields. @@ -5414,7 +5414,7 @@ declare namespace Office { /** * Project documents only. Set task field for specified task Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskId Either a string or value of the Task Id. * @param fieldId Task Fields. @@ -5442,7 +5442,7 @@ declare namespace Office { /** * Project documents only. Set task field for specified task Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskId Either a string or value of the Task Id. * @param fieldId Task Fields. @@ -5662,7 +5662,7 @@ declare namespace Office { /** * Adds an event handler for the settingsChanged event. * - * Important: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but * the event will fire only when the add-in is loaded with a spreadsheet that is opened in Excel Online, and more than one user is editing the * spreadsheet (co-authoring). Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. * @@ -5719,7 +5719,7 @@ declare namespace Office { /** * Adds an event handler for the settingsChanged event. * - * Important: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but * the event will fire only when the add-in is loaded with a spreadsheet that is opened in Excel Online, and more than one user is editing the * spreadsheet (co-authoring). Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. * @@ -5862,7 +5862,7 @@ declare namespace Office { /** * Removes the specified setting. * - * Important: Be aware that the Settings.remove method affects only the in-memory copy of the settings property bag. To persist the removal of + * **Important**: Be aware that the Settings.remove method affects only the in-memory copy of the settings property bag. To persist the removal of * the specified setting in the document, at some point after calling the Settings.remove method and before the add-in is closed, you must * call the Settings.saveAsync method. * @@ -5970,7 +5970,7 @@ declare namespace Office { * set and get methods to work with the in-memory copy of the settings property bag. When you want to persist the settings so that they are * available the next time the add-in is used, use the saveAsync method. * - * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file + * **Note**: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file * itself are saved only when the user (or AutoRecover setting) saves the document to the file system. The refreshAsync method is only useful * in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to * all instances. @@ -6027,7 +6027,7 @@ declare namespace Office { * set and get methods to work with the in-memory copy of the settings property bag. When you want to persist the settings so that they are * available the next time the add-in is used, use the saveAsync method. * - * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file + * **Note**: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file * itself are saved only when the user (or AutoRecover setting) saves the document to the file system. The refreshAsync method is only useful * in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to * all instances. @@ -6078,7 +6078,7 @@ declare namespace Office { /** * Sets or creates the specified setting. * - * Important: Be aware that the Settings.set method affects only the in-memory copy of the settings property bag. + * **Important**: Be aware that the Settings.set method affects only the in-memory copy of the settings property bag. * To make sure that additions or changes to settings will be available to your add-in the next time the document is opened, at some point * after calling the Settings.set method and before the add-in is closed, you must call the Settings.saveAsync method to persist settings in * the document. @@ -6128,7 +6128,7 @@ declare namespace Office { * The settingsChanged event was designed to let you to handle potential conflicts when two or more users are * attempting to save settings at the same time when your add-in is used in a shared (co-authored) document. * - * **Important:** Your add-in's code can register a handler for the settingsChanged event when the add-in + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in * is running with any Excel client, but the event will fire only when the add-in is loaded with a spreadsheet * that is opened in Excel Online, and more than one user is editing the spreadsheet (co-authoring). * Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. @@ -11741,7 +11741,7 @@ declare namespace Office { /** * The subclass of {@link Office.Item} dealing with appointments. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -11750,7 +11750,7 @@ declare namespace Office { /** * The appointment organizer mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -11880,9 +11880,9 @@ declare namespace Office { * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance * in a series. `null` is returned for single appointments and meeting requests of single appointments. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single * appointment and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -11914,7 +11914,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -12271,7 +12271,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -12306,7 +12306,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -12566,11 +12566,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12610,11 +12610,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12643,11 +12643,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12677,11 +12677,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12818,7 +12818,7 @@ declare namespace Office { /** * The appointment attendee mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -12834,7 +12834,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Attendee</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. For more information, see + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * */ @@ -12874,7 +12874,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Attendee</td></tr></table> * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ dateTimeModified: Date; /** @@ -12962,7 +12962,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -13064,9 +13064,9 @@ declare namespace Office { * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance * in a series. `null` is returned for single appointments and meeting requests of single appointments. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single * appointment and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -13114,7 +13114,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. Before making REST API calls using this value, it * should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -13209,7 +13209,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13234,7 +13234,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13252,7 +13252,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -13281,7 +13281,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -13303,7 +13303,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13317,7 +13317,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13385,7 +13385,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13415,7 +13415,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13441,7 +13441,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13460,7 +13460,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -13487,7 +13487,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -13633,7 +13633,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -13734,7 +13734,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -13878,7 +13878,7 @@ declare namespace Office { /** * The compose mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -14166,7 +14166,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -14201,7 +14201,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -14396,11 +14396,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14442,11 +14442,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14475,11 +14475,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14510,11 +14510,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14653,7 +14653,7 @@ declare namespace Office { /** * The read mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -14668,7 +14668,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. * For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * @@ -14718,7 +14718,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -14775,7 +14775,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14800,7 +14800,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14818,7 +14818,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -14847,7 +14847,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -14870,7 +14870,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14884,7 +14884,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14953,7 +14953,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14983,7 +14983,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15009,7 +15009,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15028,7 +15028,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -15053,7 +15053,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -15073,7 +15073,7 @@ declare namespace Office { /** * A subclass of {@link Office.Item} for messages. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -15102,7 +15102,7 @@ declare namespace Office { /** * The message compose mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -15232,7 +15232,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -15592,7 +15592,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -15627,7 +15627,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -15891,11 +15891,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -15936,11 +15936,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -15968,11 +15968,11 @@ declare namespace Office { * Since appointments have no draft state, if saveAsync is called on an appointment in compose mode, the item will be saved as a normal * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16003,11 +16003,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16143,7 +16143,7 @@ declare namespace Office { /** * The message read mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -16159,7 +16159,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Read</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. * For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * @@ -16235,7 +16235,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Read</td></tr></table> * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ dateTimeModified: Date; /** @@ -16244,7 +16244,7 @@ declare namespace Office { * The from and sender properties represent the same person unless the message is sent by a delegate. * In that case, the from property represents the delegator, and the sender property represents the delegate. * - * Note: The recipientType property of the EmailAddressDetails object in the from property is undefined. + * **Note**: The recipientType property of the EmailAddressDetails object in the from property is undefined. * * The from property returns an EmailAddressDetails object. * @@ -16329,7 +16329,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -16394,9 +16394,9 @@ declare namespace Office { * in a series. `null` is returned for single appointments and meeting requests of single appointments. * `undefined` is returned for messages that are not meeting requests. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment * and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -16414,7 +16414,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -16437,7 +16437,7 @@ declare namespace Office { * The from and sender properties represent the same person unless the message is sent by a delegate. * In that case, the from property represents the delegator, and the sender property represents the delegate. * - * Note: The recipientType property of the EmailAddressDetails object in the sender property is undefined. + * **Note**: The recipientType property of the EmailAddressDetails object in the sender property is undefined. * * [Api set: Mailbox 1.0] * @@ -16542,7 +16542,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16567,7 +16567,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16586,7 +16586,7 @@ declare namespace Office { * Gets initialization data passed when the add-in is * {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -16616,7 +16616,7 @@ declare namespace Office { * Gets initialization data passed when the add-in is * {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the * web for Office 365. * * [Api set: Mailbox Preview] @@ -16639,7 +16639,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16653,7 +16653,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16723,7 +16723,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16753,7 +16753,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16779,7 +16779,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16798,7 +16798,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -16825,7 +16825,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -17163,7 +17163,7 @@ declare namespace Office { * * The ewsUrl value can be used by a remote service to make EWS calls to the user's mailbox. For example, you can create a remote service to {@link https://docs.microsoft.com/outlook/add-ins/get-attachments-of-an-outlook-item | get attachments from the selected item}. * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ ewsUrl: string; /** @@ -17224,7 +17224,7 @@ declare namespace Office { * Item IDs retrieved via a REST API (such as the Outlook Mail API or the Microsoft Graph) use a different format than the format used by * Exchange Web Services (EWS). The convertToEwsId method converts a REST-formatted ID into the proper format for EWS. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.3] * @@ -17265,7 +17265,7 @@ declare namespace Office { /** * Converts an item ID formatted for EWS into REST format. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.3] * @@ -17316,7 +17316,7 @@ declare namespace Office { * If the specified item identifier does not identify an existing appointment, a blank pane opens on the client computer or device, and * no error message will be returned. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17342,7 +17342,7 @@ declare namespace Office { * Do not use the displayMessageForm with an itemId that represents an appointment. Use the displayAppointmentForm method to display * an existing appointment, and displayNewAppointmentForm to display a form to create a new appointment. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17371,7 +17371,7 @@ declare namespace Office { * * If any of the parameters exceed the specified size limits, or if an unknown parameter name is specified, an exception is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17453,7 +17453,7 @@ declare namespace Office { * * The add-in should use the ewsUrl property to determine the correct URL to use when making EWS calls. * - * Note: It is recommended that add-ins use the REST APIs instead of Exchange Web Services whenever possible. + * **Note**: It is recommended that add-ins use the REST APIs instead of Exchange Web Services whenever possible. * * [Api set: Mailbox 1.5] * @@ -17575,13 +17575,13 @@ declare namespace Office { * The XML result of the EWS call is provided as a string in the asyncResult.value property. * If the result exceeds 1 MB in size, an error message is returned instead. * - * Note: This method is not supported in the following scenarios: + * **Note**: This method is not supported in the following scenarios: * * - In Outlook for iOS or Outlook for Android. * * - When the add-in is loaded in a Gmail mailbox. * - * Note: The server administrator must set OAuthAuthentication to true on the Client Access Server EWS directory to enable the + * **Note**: The server administrator must set OAuthAuthentication to true on the Client Access Server EWS directory to enable the * makeEwsRequestAsync method to make EWS requests. * * *Version differences* @@ -18462,7 +18462,7 @@ declare namespace Office { /** * Sets the recurrence pattern of an appointment series. * - * Note: setAsync should only be available for series items and not instance items. + * **Note**: setAsync should only be available for series items and not instance items. * * [Api set: Mailbox 1.7] * @@ -18489,7 +18489,7 @@ declare namespace Office { /** * Sets the recurrence pattern of an appointment series. * - * Note: setAsync should only be available for series items and not instance items. + * **Note**: setAsync should only be available for series items and not instance items. * * [Api set: Mailbox 1.7] * @@ -18631,7 +18631,7 @@ declare namespace Office { * * The RoamingSettings object is accessible via the roamingSettings property in the Office.context namespace. * - * Important: The RoamingSettings object is initialized from the persisted storage only when the add-in is first loaded. + * **Important**: The RoamingSettings object is initialized from the persisted storage only when the add-in is first loaded. * For task panes, this means that it is only initialized when the task pane first opens. * If the task pane navigates to another page or reloads the current page, the in-memory object is reset to its initial values, even if * your add-in has persisted changes. The persisted changes will not be available until the task pane is closed and reopened. @@ -19271,7 +19271,7 @@ declare namespace Office { /** * Gets the account type of the user associated with the mailbox. * - * Note: This member is currently only supported in Outlook 2016 for Mac, build 16.9.1212 and greater. + * **Note**: This member is currently only supported in Outlook 2016 for Mac, build 16.9.1212 and greater. * * [Api set: Mailbox 1.6] * diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 5a98b250ae..027a90d0c2 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -20,7 +20,7 @@ declare namespace Office { */ var Promise: IPromiseConstructor; - // Note: this is a copy of the PromiseConstructor object from + // **Note**: this is a copy of the PromiseConstructor object from // https://github.com/Microsoft/TypeScript/blob/master/lib/lib.es2015.promise.d.ts // It is necessary so that even with targeting "ES5" and not specifying any libs, // developers will still get IntelliSense for "Office.Promise" just as they would with a regular Promise. @@ -628,7 +628,7 @@ declare namespace Office { * You access the AsyncResult object in the function passed as the argument to the callback parameter of an "Async" method, such as the * `getSelectedDataAsync` and `setSelectedDataAsync` methods of the {@link Office.Document | Document} object. * - * Note: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. + * **Note**: What the value property returns for a particular "Async" method varies depending on the purpose and context of that method. * To determine what is returned by the value property for an "Async" method, refer to the "Callback value" section of the method's topic. * * **Support details** @@ -1446,7 +1446,7 @@ declare namespace Office { /** * Specifies a table of sample data displayed in the prompt UI as an example of the kinds of fields (columns) that can be bound by your add-in. * The headers provided in the TableData object specify the labels used in the field selection UI. - * Note: This parameter is used only in add-ins for Access. It is ignored if provided when calling the method in an add-in for Excel. + * **Note**: This parameter is used only in add-ins for Access. It is ignored if provided when calling the method in an add-in for Excel. */ sampleData?: Office.TableData /** @@ -1781,43 +1781,43 @@ declare namespace Office { * Return or set data as tabular data with no headers. Data is returned or set as an array of arrays containing one-dimensional runs of * characters. For example, three rows of string values in two columns would be: [["R1C1", "R1C2"], ["R2C1", "R2C2"], ["R3C1", "R3C2"]]. * - * Note: Only applies to data in Excel and Word. + * **Note**: Only applies to data in Excel and Word. */ Matrix, /** * Return or set data as tabular data with optional headers. Data is returned or set as an array of arrays with optional headers. * - * Note: Only applies to data in Access, Excel, and Word. + * **Note**: Only applies to data in Access, Excel, and Word. */ Table, /** * Return or set data as HTML. * - * Note: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). + * **Note**: Only applies to data in add-ins for Word and Outlook add-ins for Outlook (compose mode). */ Html, /** * Return or set data as Office Open XML. * - * Note: Only applies to data in Word. + * **Note**: Only applies to data in Word. */ Ooxml, /** * Return a JSON object that contains an array of the ids, titles, and indexes of the selected slides. For example, * `{"slides":[{"id":257,"title":"Slide 2","index":2},{"id":256,"title":"Slide 1","index":1}]}` for a selection of two slides. * - * Note: Only applies to data in PowerPoint when calling the {@link Office.Document | Document}.getSelectedData method to get the current + * **Note**: Only applies to data in PowerPoint when calling the {@link Office.Document | Document}.getSelectedData method to get the current * slide or selected range of slides. */ SlideRange, /** * Data is returned or set as an image stream. - * Note: Only applies to data in Excel, Word, and PowerPoint. + * **Note**: Only applies to data in Excel, Word, and PowerPoint. */ Image, /** * Data is returned or set as XML data containing an SVG image. - * Note: Only applies to data in Excel, Word, and PowerPoint. + * **Note**: Only applies to data in Excel, Word, and PowerPoint. */ XmlSvg } @@ -2523,7 +2523,7 @@ declare namespace Office { * </tr> * <tr> * <td>An {@link Office.TableData} object, and the shape of the table matches the bound table.</td> - * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. Note: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> + * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. **Note**: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> * </tr> * </table> * @@ -2654,7 +2654,7 @@ declare namespace Office { * </tr> * <tr> * <td>An {@link Office.TableData} object, and the shape of the table matches the bound table.</td> - * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. Note: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> + * <td>The specified set of rows and/or headers are written, if no other data in surrounding cells will be overwritten. **Note**: If you specify formulas in the TableData object you pass for the *data* parameter, you might not get the results you expect due to the "calculated columns" feature of Excel, which automatically duplicates formulas within a column. To work around this when you want to write *data* that contains formulas to a bound table, try specifying the data as an array of arrays (instead of a TableData object), and specify the *coercionType* as Microsoft.Office.Matrix or "matrix".</td> * </tr> * </table> * @@ -2825,7 +2825,7 @@ declare namespace Office { * By default, adding a table in Excel assigns the name "Table1" for the first table you add, "Table2" for the second table you add, and so on. * To assign a meaningful name for a table in the Excel UI, use the Table Name property on the Table Tools | Design tab of the ribbon. * - * Note: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of + * **Note**: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of * the table in this format: "Sheet1!Table1" * * For Word, the itemName parameter refers to the Title property of a Rich Text content control. (You can't bind to content controls other @@ -2835,7 +2835,7 @@ declare namespace Office { * control from the Controls group on the Developer tab of the ribbon, use the Properties command in the Controls group to display the Content * Control Properties dialog box. Then set the Title property of the content control to the name you want to reference from your code. * - * Note: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one + * **Note**: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one * these content controls with this method (by specifying its name as the itemName parameter), the operation will fail. * * **Support details** @@ -2871,7 +2871,7 @@ declare namespace Office { * By default, adding a table in Excel assigns the name "Table1" for the first table you add, "Table2" for the second table you add, and so on. * To assign a meaningful name for a table in the Excel UI, use the Table Name property on the Table Tools | Design tab of the ribbon. * - * Note: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of + * **Note**: In Excel, when specifying a table as a named item, you must fully qualify the name to include the worksheet name in the name of * the table in this format: "Sheet1!Table1" * * For Word, the itemName parameter refers to the Title property of a Rich Text content control. (You can't bind to content controls other @@ -2881,7 +2881,7 @@ declare namespace Office { * control from the Controls group on the Developer tab of the ribbon, use the Properties command in the Controls group to display the Content * Control Properties dialog box. Then set the Title property of the content control to the name you want to reference from your code. * - * Note: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one + * **Note**: In Word, if there are multiple Rich Text content controls with the same Title property value (name), and you try to bind to one * these content controls with this method (by specifying its name as the itemName parameter), the operation will fail. * * **Support details** @@ -4542,7 +4542,7 @@ declare namespace Office { * <table> * <tr><td>Word</td><td>If there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion point</td><td>If `data` is a string, the specified text is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.</td></tr> - * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (Important: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> + * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (**Important**: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> * <tr><td></td><td></td><td>If `data` is Office Open XML, the specified XML is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is a base64 encoded image stream, the specified image is inserted.</td></tr></td></tr> * <tr><td></td><td>If there is a selection</td><td>It will be replaced with the specified `data` following the same rules as above.</td></tr> @@ -4659,7 +4659,7 @@ declare namespace Office { * <table> * <tr><td>Word</td><td>If there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion point</td><td>If `data` is a string, the specified text is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.</td></tr> - * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (Important: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> + * <tr><td></td><td></td><td>If `data` is HTML, the specified HTML is inserted. (**Important**: If any of the HTML you insert is invalid, Word won't raise an error. Word will insert as much of the HTML as it can and omits any invalid data).</td></tr> * <tr><td></td><td></td><td>If `data` is Office Open XML, the specified XML is inserted.</td></tr> * <tr><td></td><td></td><td>If `data` is a base64 encoded image stream, the specified image is inserted.</td></tr></td></tr> * <tr><td></td><td>If there is a selection</td><td>It will be replaced with the specified `data` following the same rules as above.</td></tr> @@ -5151,7 +5151,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of resources in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5177,7 +5177,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of resources in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the highest index number in the current project's resource collection. @@ -5202,7 +5202,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of tasks in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5228,7 +5228,7 @@ declare namespace Office { /** * Project documents only. Get the maximum index of the collection of tasks in the current project. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. * The `value` property of the result is the highest index number in the current project's task collection. @@ -5253,7 +5253,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceIndex The index of the resource in the collection of resources for the project. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -5280,7 +5280,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the resource that has the specified index in the resource collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceIndex The index of the resource in the collection of resources for the project. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5306,7 +5306,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskIndex The index of the task in the collection of tasks for the project. * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -5333,7 +5333,7 @@ declare namespace Office { /** * Project documents only. Get the GUID of the task that has the specified index in the task collection. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskIndex The index of the task in the collection of tasks for the project. * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -5359,7 +5359,7 @@ declare namespace Office { /** * Project documents only. Set resource field for specified resource Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceId Either a string or value of the Resource Id. * @param fieldId Resource Fields. @@ -5387,7 +5387,7 @@ declare namespace Office { /** * Project documents only. Set resource field for specified resource Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param resourceId Either a string or value of the Resource Id. * @param fieldId Resource Fields. @@ -5414,7 +5414,7 @@ declare namespace Office { /** * Project documents only. Set task field for specified task Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskId Either a string or value of the Task Id. * @param fieldId Task Fields. @@ -5442,7 +5442,7 @@ declare namespace Office { /** * Project documents only. Set task field for specified task Id. * - * Important: This API works only in Project 2016 on Windows desktop. + * **Important**: This API works only in Project 2016 on Windows desktop. * * @param taskId Either a string or value of the Task Id. * @param fieldId Task Fields. @@ -5662,7 +5662,7 @@ declare namespace Office { /** * Adds an event handler for the settingsChanged event. * - * Important: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but * the event will fire only when the add-in is loaded with a spreadsheet that is opened in Excel Online, and more than one user is editing the * spreadsheet (co-authoring). Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. * @@ -5719,7 +5719,7 @@ declare namespace Office { /** * Adds an event handler for the settingsChanged event. * - * Important: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in is running with any Excel client, but * the event will fire only when the add-in is loaded with a spreadsheet that is opened in Excel Online, and more than one user is editing the * spreadsheet (co-authoring). Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. * @@ -5862,7 +5862,7 @@ declare namespace Office { /** * Removes the specified setting. * - * Important: Be aware that the Settings.remove method affects only the in-memory copy of the settings property bag. To persist the removal of + * **Important**: Be aware that the Settings.remove method affects only the in-memory copy of the settings property bag. To persist the removal of * the specified setting in the document, at some point after calling the Settings.remove method and before the add-in is closed, you must * call the Settings.saveAsync method. * @@ -5970,7 +5970,7 @@ declare namespace Office { * set and get methods to work with the in-memory copy of the settings property bag. When you want to persist the settings so that they are * available the next time the add-in is used, use the saveAsync method. * - * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file + * **Note**: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file * itself are saved only when the user (or AutoRecover setting) saves the document to the file system. The refreshAsync method is only useful * in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to * all instances. @@ -6027,7 +6027,7 @@ declare namespace Office { * set and get methods to work with the in-memory copy of the settings property bag. When you want to persist the settings so that they are * available the next time the add-in is used, use the saveAsync method. * - * Note: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file + * **Note**: The saveAsync method persists the in-memory settings property bag into the document file. However, the changes to the document file * itself are saved only when the user (or AutoRecover setting) saves the document to the file system. The refreshAsync method is only useful * in coauthoring scenarios when other instances of the same add-in might change the settings and those changes should be made available to * all instances. @@ -6078,7 +6078,7 @@ declare namespace Office { /** * Sets or creates the specified setting. * - * Important: Be aware that the Settings.set method affects only the in-memory copy of the settings property bag. + * **Important**: Be aware that the Settings.set method affects only the in-memory copy of the settings property bag. * To make sure that additions or changes to settings will be available to your add-in the next time the document is opened, at some point * after calling the Settings.set method and before the add-in is closed, you must call the Settings.saveAsync method to persist settings in * the document. @@ -6128,7 +6128,7 @@ declare namespace Office { * The settingsChanged event was designed to let you to handle potential conflicts when two or more users are * attempting to save settings at the same time when your add-in is used in a shared (co-authored) document. * - * **Important:** Your add-in's code can register a handler for the settingsChanged event when the add-in + * **Important**: Your add-in's code can register a handler for the settingsChanged event when the add-in * is running with any Excel client, but the event will fire only when the add-in is loaded with a spreadsheet * that is opened in Excel Online, and more than one user is editing the spreadsheet (co-authoring). * Therefore, effectively the settingsChanged event is supported only in Excel Online in co-authoring scenarios. @@ -11741,7 +11741,7 @@ declare namespace Office { /** * The subclass of {@link Office.Item} dealing with appointments. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -11750,7 +11750,7 @@ declare namespace Office { /** * The appointment organizer mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -11880,9 +11880,9 @@ declare namespace Office { * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance * in a series. `null` is returned for single appointments and meeting requests of single appointments. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single * appointment and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -11914,7 +11914,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -12271,7 +12271,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -12306,7 +12306,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -12566,11 +12566,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12610,11 +12610,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12643,11 +12643,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12677,11 +12677,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -12818,7 +12818,7 @@ declare namespace Office { /** * The appointment attendee mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -12834,7 +12834,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Attendee</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. For more information, see + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * */ @@ -12874,7 +12874,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Appointment Attendee</td></tr></table> * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ dateTimeModified: Date; /** @@ -12962,7 +12962,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -13064,9 +13064,9 @@ declare namespace Office { * The recurrence property returns a recurrence object for recurring appointments or meetings requests if an item is a series or an instance * in a series. `null` is returned for single appointments and meeting requests of single appointments. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single * appointment and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -13114,7 +13114,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. Before making REST API calls using this value, it * should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -13209,7 +13209,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13234,7 +13234,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13252,7 +13252,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -13281,7 +13281,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -13303,7 +13303,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13317,7 +13317,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13385,7 +13385,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13415,7 +13415,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13441,7 +13441,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -13460,7 +13460,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -13487,7 +13487,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -13633,7 +13633,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -13734,7 +13734,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -13878,7 +13878,7 @@ declare namespace Office { /** * The compose mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -14166,7 +14166,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -14201,7 +14201,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web for Office 365. * * [Api set: Mailbox Preview] * @@ -14396,11 +14396,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14442,11 +14442,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14475,11 +14475,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14510,11 +14510,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -14653,7 +14653,7 @@ declare namespace Office { /** * The read mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -14668,7 +14668,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Read</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. * For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * @@ -14718,7 +14718,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -14775,7 +14775,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14800,7 +14800,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14818,7 +14818,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -14847,7 +14847,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -14870,7 +14870,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14884,7 +14884,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14953,7 +14953,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -14983,7 +14983,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15009,7 +15009,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -15028,7 +15028,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -15053,7 +15053,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -15073,7 +15073,7 @@ declare namespace Office { /** * A subclass of {@link Office.Item} for messages. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -15102,7 +15102,7 @@ declare namespace Office { /** * The message compose mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -15232,7 +15232,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -15592,7 +15592,7 @@ declare namespace Office { * * In the Outlook desktop client, if the message is an inline reply, the close method has no effect. * - * Note: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, + * **Note**: In Outlook on the web, if the item is an appointment and it has previously been saved using saveAsync, the user is prompted to save, * discard, or cancel even if no changes have occurred since the item was last saved. * * [Api set: Mailbox 1.3] @@ -15627,7 +15627,7 @@ declare namespace Office { /** * Gets initialization data passed when the add-in is activated by an actionable message. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -15891,11 +15891,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -15936,11 +15936,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -15968,11 +15968,11 @@ declare namespace Office { * Since appointments have no draft state, if saveAsync is called on an appointment in compose mode, the item will be saved as a normal * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16003,11 +16003,11 @@ declare namespace Office { * appointment on the user's calendar. For new appointments that have not been saved before, no invitation will be sent. * Saving an existing appointment will send an update to added or removed attendees. * - * Note: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that + * **Note**: If your add-in calls saveAsync on an item in compose mode in order to get an itemId to use with EWS or the REST API, be aware that * when Outlook is in cached mode, it may take some time before the item is actually synced to the server. * Until the item is synced, using the itemId will return an error. * - * Note: The following clients have different behavior for saveAsync on appointments in compose mode: + * **Note**: The following clients have different behavior for saveAsync on appointments in compose mode: * * - Mac Outlook does not support saveAsync on a meeting in compose mode. Calling saveAsync on a meeting in Mac Outlook will return an error. * @@ -16143,7 +16143,7 @@ declare namespace Office { /** * The message read mode of {@link Office.Item | Office.context.mailbox.item}. * - * Important: This is an internal Outlook object, not directly exposed through existing interfaces. + * **Important**: This is an internal Outlook object, not directly exposed through existing interfaces. * You should treat this as a mode of Office.context.mailbox.item. Refer to the * {@link https://docs.microsoft.com/office/dev/add-ins/reference/objectmodel/preview-requirement-set/office.context.mailbox.item | Object Model} page for more information. */ @@ -16159,7 +16159,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Read</td></tr></table> * - * Note: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. + * **Note**: Certain types of files are blocked by Outlook due to potential security issues and are therefore not returned. * For more information, see * {@link https://support.office.com/article/Blocked-attachments-in-Outlook-434752E1-02D3-4E90-9124-8B81E49A8519 | Blocked attachments in Outlook}. * @@ -16235,7 +16235,7 @@ declare namespace Office { * * <tr><td>{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}</td><td>Message Read</td></tr></table> * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ dateTimeModified: Date; /** @@ -16244,7 +16244,7 @@ declare namespace Office { * The from and sender properties represent the same person unless the message is sent by a delegate. * In that case, the from property represents the delegator, and the sender property represents the delegate. * - * Note: The recipientType property of the EmailAddressDetails object in the from property is undefined. + * **Note**: The recipientType property of the EmailAddressDetails object in the from property is undefined. * * The from property returns an EmailAddressDetails object. * @@ -16329,7 +16329,7 @@ declare namespace Office { * If an item identifier is required, the saveAsync method can be used to save the item to the store, which will return the item identifier * in the asyncResult.value parameter in the callback function. * - * Note: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the itemId property is the same as the Exchange Web Services item identifier. * The itemId property is not identical to the Outlook Entry ID or the ID used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api#get-the-item-id | Use the Outlook REST APIs from an Outlook add-in}. @@ -16394,9 +16394,9 @@ declare namespace Office { * in a series. `null` is returned for single appointments and meeting requests of single appointments. * `undefined` is returned for messages that are not meeting requests. * - * Note: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. + * **Note**: Meeting requests have an itemClass value of IPM.Schedule.Meeting.Request. * - * Note: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment + * **Note**: If the recurrence object is null, this indicates that the object is a single appointment or a meeting request of a single appointment * and NOT a part of a series. * * [Api set: Mailbox 1.7] @@ -16414,7 +16414,7 @@ declare namespace Office { * In OWA and Outlook, the seriesId returns the Exchange Web Services (EWS) ID of the parent (series) item that this item belongs to. * However, in iOS and Android, the seriesId returns the REST ID of the parent item. * - * Note: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. + * **Note**: The identifier returned by the seriesId property is the same as the Exchange Web Services item identifier. * The seriesId property is not identical to the Outlook IDs used by the Outlook REST API. * Before making REST API calls using this value, it should be converted using Office.context.mailbox.convertToRestId. * For more details, see {@link https://docs.microsoft.com/outlook/add-ins/use-rest-api | Use the Outlook REST APIs from an Outlook add-in}. @@ -16437,7 +16437,7 @@ declare namespace Office { * The from and sender properties represent the same person unless the message is sent by a delegate. * In that case, the from property represents the delegator, and the sender property represents the delegate. * - * Note: The recipientType property of the EmailAddressDetails object in the sender property is undefined. + * **Note**: The recipientType property of the EmailAddressDetails object in the sender property is undefined. * * [Api set: Mailbox 1.0] * @@ -16542,7 +16542,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16567,7 +16567,7 @@ declare namespace Office { * attach them to the reply form. If any attachments fail to be added, an error is shown in the form UI. * If this isn't possible, then no error message is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16586,7 +16586,7 @@ declare namespace Office { * Gets initialization data passed when the add-in is * {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the web * for Office 365. * * [Api set: Mailbox Preview] @@ -16616,7 +16616,7 @@ declare namespace Office { * Gets initialization data passed when the add-in is * {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. * - * Note: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the + * **Note**: This method is only supported by Outlook 2016 for Windows (Click-to-Run versions greater than 16.0.8413.1000) and Outlook on the * web for Office 365. * * [Api set: Mailbox Preview] @@ -16639,7 +16639,7 @@ declare namespace Office { /** * Gets the entities found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16653,7 +16653,7 @@ declare namespace Office { /** * Gets an array of all the entities of the specified entity type found in the selected item's body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16723,7 +16723,7 @@ declare namespace Office { * The getFilteredEntitiesByName method returns the entities that match the regular expression defined in the ItemHasKnownEntity rule element * in the manifest XML file with the specified FilterName element value. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16753,7 +16753,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16779,7 +16779,7 @@ declare namespace Office { * and should not attempt to return the entire body of the item. * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -16798,7 +16798,7 @@ declare namespace Office { /** * Gets the entities found in a highlighted match a user has selected. Highlighted matches apply to contextual add-ins. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -16825,7 +16825,7 @@ declare namespace Office { * Using a regular expression such as .* to obtain the entire body of an item does not always return the expected results. * Instead, use the Body.getAsync method to retrieve the entire body. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.6] * @@ -17163,7 +17163,7 @@ declare namespace Office { * * The ewsUrl value can be used by a remote service to make EWS calls to the user's mailbox. For example, you can create a remote service to {@link https://docs.microsoft.com/outlook/add-ins/get-attachments-of-an-outlook-item | get attachments from the selected item}. * - * Note: This member is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This member is not supported in Outlook for iOS or Outlook for Android. */ ewsUrl: string; /** @@ -17224,7 +17224,7 @@ declare namespace Office { * Item IDs retrieved via a REST API (such as the Outlook Mail API or the Microsoft Graph) use a different format than the format used by * Exchange Web Services (EWS). The convertToEwsId method converts a REST-formatted ID into the proper format for EWS. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.3] * @@ -17265,7 +17265,7 @@ declare namespace Office { /** * Converts an item ID formatted for EWS into REST format. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.3] * @@ -17316,7 +17316,7 @@ declare namespace Office { * If the specified item identifier does not identify an existing appointment, a blank pane opens on the client computer or device, and * no error message will be returned. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17342,7 +17342,7 @@ declare namespace Office { * Do not use the displayMessageForm with an itemId that represents an appointment. Use the displayAppointmentForm method to display * an existing appointment, and displayNewAppointmentForm to display a form to create a new appointment. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17371,7 +17371,7 @@ declare namespace Office { * * If any of the parameters exceed the specified size limits, or if an unknown parameter name is specified, an exception is thrown. * - * Note: This method is not supported in Outlook for iOS or Outlook for Android. + * **Note**: This method is not supported in Outlook for iOS or Outlook for Android. * * [Api set: Mailbox 1.0] * @@ -17453,7 +17453,7 @@ declare namespace Office { * * The add-in should use the ewsUrl property to determine the correct URL to use when making EWS calls. * - * Note: It is recommended that add-ins use the REST APIs instead of Exchange Web Services whenever possible. + * **Note**: It is recommended that add-ins use the REST APIs instead of Exchange Web Services whenever possible. * * [Api set: Mailbox 1.5] * @@ -17575,13 +17575,13 @@ declare namespace Office { * The XML result of the EWS call is provided as a string in the asyncResult.value property. * If the result exceeds 1 MB in size, an error message is returned instead. * - * Note: This method is not supported in the following scenarios: + * **Note**: This method is not supported in the following scenarios: * * - In Outlook for iOS or Outlook for Android. * * - When the add-in is loaded in a Gmail mailbox. * - * Note: The server administrator must set OAuthAuthentication to true on the Client Access Server EWS directory to enable the + * **Note**: The server administrator must set OAuthAuthentication to true on the Client Access Server EWS directory to enable the * makeEwsRequestAsync method to make EWS requests. * * *Version differences* @@ -18462,7 +18462,7 @@ declare namespace Office { /** * Sets the recurrence pattern of an appointment series. * - * Note: setAsync should only be available for series items and not instance items. + * **Note**: setAsync should only be available for series items and not instance items. * * [Api set: Mailbox 1.7] * @@ -18489,7 +18489,7 @@ declare namespace Office { /** * Sets the recurrence pattern of an appointment series. * - * Note: setAsync should only be available for series items and not instance items. + * **Note**: setAsync should only be available for series items and not instance items. * * [Api set: Mailbox 1.7] * @@ -18631,7 +18631,7 @@ declare namespace Office { * * The RoamingSettings object is accessible via the roamingSettings property in the Office.context namespace. * - * Important: The RoamingSettings object is initialized from the persisted storage only when the add-in is first loaded. + * **Important**: The RoamingSettings object is initialized from the persisted storage only when the add-in is first loaded. * For task panes, this means that it is only initialized when the task pane first opens. * If the task pane navigates to another page or reloads the current page, the in-memory object is reset to its initial values, even if * your add-in has persisted changes. The persisted changes will not be available until the task pane is closed and reopened. @@ -19271,7 +19271,7 @@ declare namespace Office { /** * Gets the account type of the user associated with the mailbox. * - * Note: This member is currently only supported in Outlook 2016 for Mac, build 16.9.1212 and greater. + * **Note**: This member is currently only supported in Outlook 2016 for Mac, build 16.9.1212 and greater. * * [Api set: Mailbox 1.6] * From c38b87afe6ff4cc7616c9a5253458e4d191c8774 Mon Sep 17 00:00:00 2001 From: Ethan Setnik <esetnik@gmail.com> Date: Thu, 7 Feb 2019 14:03:43 -0500 Subject: [PATCH 144/197] add tests --- types/redux-form/index.d.ts | 1 + types/redux-form/redux-form-tests.tsx | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/types/redux-form/index.d.ts b/types/redux-form/index.d.ts index 6915032138..28047e8007 100644 --- a/types/redux-form/index.d.ts +++ b/types/redux-form/index.d.ts @@ -12,6 +12,7 @@ // Maddi Joyce <https://github.com/maddijoyce> // Kamil Wojcik <https://github.com/smifun> // Mohamed Shaaban <https://github.com/mshaaban088> +// Ethan Setnik <https://github.com/esetnik> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 3.0 import { diff --git a/types/redux-form/redux-form-tests.tsx b/types/redux-form/redux-form-tests.tsx index 25f395884c..56d782eda7 100644 --- a/types/redux-form/redux-form-tests.tsx +++ b/types/redux-form/redux-form-tests.tsx @@ -26,9 +26,12 @@ import { SubmissionError, FieldArrayFieldsProps } from "redux-form"; + import { Field as ImmutableField, - reduxForm as immutableReduxForm + reduxForm as immutableReduxForm, + startSubmit as immutableStartSubmit, + stopSubmit as immutableStopSubmit } from "redux-form/immutable"; import LibField, { From 9784cd1cb4a12d96c40b3d529b72a34512d83f74 Mon Sep 17 00:00:00 2001 From: Ethan Setnik <esetnik@gmail.com> Date: Thu, 7 Feb 2019 14:06:16 -0500 Subject: [PATCH 145/197] increase version number --- types/redux-form/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/redux-form/index.d.ts b/types/redux-form/index.d.ts index 28047e8007..2a3281e62b 100644 --- a/types/redux-form/index.d.ts +++ b/types/redux-form/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for redux-form 7.4 +// Type definitions for redux-form 8.1.0 // Project: https://github.com/erikras/redux-form // Definitions by: Carson Full <https://github.com/carsonf> // Daniel Lytkin <https://github.com/aikoven> From ac1bb23ddc777b893867db10cf8049de08d8040c Mon Sep 17 00:00:00 2001 From: Elizabeth Samuel <elizs@microsoft.com> Date: Thu, 7 Feb 2019 11:12:18 -0800 Subject: [PATCH 146/197] Update based on feedback --- types/office-js-preview/index.d.ts | 4 ++-- types/office-js/index.d.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index bbed11cdea..be6822cf36 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -10541,7 +10541,7 @@ declare namespace Office { /** * Represents an attachment on an item from the server. Read mode only. * - * An array of `AttachmentDetails` objects is returned as the attachments property of an appointment or message item. + * An array of **AttachmentDetails** objects is returned as the attachments property of an appointment or message item. * * [Api set: Mailbox 1.0] * @@ -13702,7 +13702,7 @@ declare namespace Office { addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: Office.AsyncResult<void>) => void): void; /** - * Gets an attachment from a message or appointment and returns it as an `AttachmentContent` object. + * Gets an attachment from a message or appointment and returns it as an **AttachmentContent** object. * * The `getAttachmentContentAsync` method gets the attachment with the specified identifier from the item. As a best practice, you should use * the identifier to retrieve an attachment in the same session that the attachmentIds were retrieved with the `getAttachmentsAsync` or diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 027a90d0c2..caafa47822 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -10541,7 +10541,7 @@ declare namespace Office { /** * Represents an attachment on an item from the server. Read mode only. * - * An array of `AttachmentDetails` objects is returned as the attachments property of an appointment or message item. + * An array of **AttachmentDetails** objects is returned as the attachments property of an appointment or message item. * * [Api set: Mailbox 1.0] * @@ -13702,7 +13702,7 @@ declare namespace Office { addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: Office.AsyncResult<void>) => void): void; /** - * Gets an attachment from a message or appointment and returns it as an `AttachmentContent` object. + * Gets an attachment from a message or appointment and returns it as an **AttachmentContent** object. * * The `getAttachmentContentAsync` method gets the attachment with the specified identifier from the item. As a best practice, you should use * the identifier to retrieve an attachment in the same session that the attachmentIds were retrieved with the `getAttachmentsAsync` or From 633d80268241b453e17f6c704708b491895a9edd Mon Sep 17 00:00:00 2001 From: Ethan Setnik <esetnik@gmail.com> Date: Thu, 7 Feb 2019 14:25:13 -0500 Subject: [PATCH 147/197] fix header version --- types/redux-form/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/redux-form/index.d.ts b/types/redux-form/index.d.ts index 2a3281e62b..8997d682a8 100644 --- a/types/redux-form/index.d.ts +++ b/types/redux-form/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for redux-form 8.1.0 +// Type definitions for redux-form 7.5 // Project: https://github.com/erikras/redux-form // Definitions by: Carson Full <https://github.com/carsonf> // Daniel Lytkin <https://github.com/aikoven> From 924fed466198bc97a2d9a0eb2846dbe9d40a7ff8 Mon Sep 17 00:00:00 2001 From: Derek Finlinson <derek.finlinson@journeyteam.com> Date: Thu, 7 Feb 2019 15:59:25 -0700 Subject: [PATCH 148/197] Make imageOptions optional --- types/xrm/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/xrm/index.d.ts b/types/xrm/index.d.ts index 361e33bf92..61362fa208 100644 --- a/types/xrm/index.d.ts +++ b/types/xrm/index.d.ts @@ -4633,7 +4633,7 @@ declare namespace Xrm { * Invokes the device camera to capture an image. * @returns On success, returns Base64 encoded file */ - captureImage(imageOptions: Device.CaptureImageOptions): Async.PromiseLike<Device.CaptureFileResponse>; + captureImage(imageOptions?: Device.CaptureImageOptions): Async.PromiseLike<Device.CaptureFileResponse>; /** * Invokes the device camera to capture video. From 7a2e93fd89f9f179c9ba061fd1bd3d2ee4902ff6 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Thu, 7 Feb 2019 16:10:52 -0800 Subject: [PATCH 149/197] Revert "Merge pull request #32709 from MrBullfinsh/cordova-plugin-background-download-types" This reverts commit 401af3267f6c283b7ee95d89aad7ad99a2261d41, reversing changes made to 1d78804c81accd2557b287c4e451933d2190d4f4. --- ...ordova-plugin-background-download-tests.ts | 24 ------ .../index.d.ts | 86 ------------------- .../tsconfig.json | 24 ------ .../tslint.json | 3 - 4 files changed, 137 deletions(-) delete mode 100644 types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts delete mode 100644 types/cordova-plugin-background-download/index.d.ts delete mode 100644 types/cordova-plugin-background-download/tsconfig.json delete mode 100644 types/cordova-plugin-background-download/tslint.json diff --git a/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts b/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts deleted file mode 100644 index e56d14ce04..0000000000 --- a/types/cordova-plugin-background-download/cordova-plugin-background-download-tests.ts +++ /dev/null @@ -1,24 +0,0 @@ - let fileName = "PointerEventsCordovaPlugin.wmv"; - let uriString = "http://media.ch9.ms/ch9/8c03/f4fe2512-59e5-4a07-bded-124b06ac8c03/PointerEventsCordovaPlugin.wmv"; - - // open target file for download - (window as any).requestFileSystem(1, 0, (fileSystem: any) => { - fileSystem.root.getFile(fileName, { create: true }, (targetFile: File) => { - // plugin callbacks to track operation execution status and progress - const onSuccess = () => { - console.log('Done'); - }; - const onError = (err: any) => { - console.log(err); - }; - const onProgress = (progress: BackgroundTransfer.Progress) => { - console.log((100 * progress.bytesReceived / progress.totalBytesToReceive) + '%'); - }; - - const downloader = new BackgroundTransfer.BackgroundDownloader(); - // Create a new download operation. - const download = downloader.createDownload(uriString, targetFile); - // Start the download and persist the promise to be able to cancel the download. - const downloadPromise = download.startAsync().then(onSuccess, onError, onProgress); - }); - }); diff --git a/types/cordova-plugin-background-download/index.d.ts b/types/cordova-plugin-background-download/index.d.ts deleted file mode 100644 index 815d20bf66..0000000000 --- a/types/cordova-plugin-background-download/index.d.ts +++ /dev/null @@ -1,86 +0,0 @@ -// Type definitions for cordova-plugin-background-download 0.5 -// Project: https://github.com/sgrebnov/cordova-plugin-background-download -// Definitions by: Tobias Gimpel <https://github.com/mrbullfinsh> -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.2 - -/** - * Provides an advanced file transfer functionality that persists beyond app termination and - * runs in the background. Background transfer doesn't support concurrent downloads of the same uri. - */ -declare namespace BackgroundTransfer { - class BackgroundDownloader { - /** - * Initializes a new instance of BackgroundDownloader object. - * Used to configure downloads prior to the actual creation of the download operation using CreateDownload. - * - * @param uriMatcher The regexp to compare location of the resources with already downloading ones. - */ - constructor(uriMatcher?: RegExp); - /** - * Initializes a DownloadOperation object that contains the specified Uri and the file that the response is written to. - * - * @param uri The location of the resource. - * @param resultFile The file that the response will be written to. - * @param notificationTitle The title for downloading in notification. - */ - createDownload(uri: string, resultFile: File, notificationTitle?: string): DownloadOperation; - } - - interface Progress { - bytesReceived: number; - totalBytesToReceive: number; - } - - /** - * Provides a mechanism for managing interactions with asynchronous APIs based on Promises. - * See 'Asynchronous programming in JavaScript' for more details - * http://msdn.microsoft.com/en-us/library/windows/apps/hh700330.aspx - * http://msdn.microsoft.com/en-us/library/windows/apps/br211867.aspx - * Note. Functionality is limited, support of .then and .cancel methods only, other methods are in progress. - */ - interface Promise { - _completeCallbacks: Array<() => void>; - _errorCallbacks: Array<(error: any) => void>; - _progressCallbacks: Array<(progress: Progress) => void>; - _chainedDefer: Deferral; - _state: 'pending' | 'resolved' | 'rejected' | 'cancelled'; - result: any; - then(onComplete?: () => void, onError?: (error: any) => void, onProgress?: (progress: Progress) => void): Promise; - /** - * Attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and - * cancellation is supported, the promise enters the error state with a value of Error("Canceled"). - * http://msdn.microsoft.com/en-us/library/windows/apps/br211667.aspx - * @param flag - */ - cancel(flag?: boolean): void; - executeCallback(callback: (() => void) | ((error: any) => void) | ((progress: Progress) => void), args: any): void; - } - - interface Deferral { - resolve(data: any): void; - reject(error: any): void; - notify(value: any): void; - bind(promise: Promise): void; - } -} - -declare class DownloadOperation { - /** - * Performs an asynchronous download operation in the background. - * - * @param uri The location of the resource. - * @param resultFile The file that the response will be written to. - * @param uriMatcher The regexp to compare location of the resources with already downloading ones. - * @param notificationTitle The title for downloading in notification. - */ - constructor(uri: string, resultFile: File, uriMatcher?: RegExp, notificationTitle?: string); - /** - * Starts an asynchronous download operation. - */ - startAsync(): BackgroundTransfer.Promise; - /** - * Stops a download operation. - */ - stop(): void; -} diff --git a/types/cordova-plugin-background-download/tsconfig.json b/types/cordova-plugin-background-download/tsconfig.json deleted file mode 100644 index 830f1483ca..0000000000 --- a/types/cordova-plugin-background-download/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "cordova-plugin-background-download-tests.ts" - ] -} \ No newline at end of file diff --git a/types/cordova-plugin-background-download/tslint.json b/types/cordova-plugin-background-download/tslint.json deleted file mode 100644 index e60c15844f..0000000000 --- a/types/cordova-plugin-background-download/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "dtslint/dt.json" -} \ No newline at end of file From b737dc1ea56951ca7d06907c6a2433f0bebe6f36 Mon Sep 17 00:00:00 2001 From: Julian Gonggrijp <dev@juliangonggrijp.com> Date: Fri, 8 Feb 2019 01:16:51 +0100 Subject: [PATCH 150/197] Update backbone-relational to version 0.10.0 --- .../backbone-relational-tests.ts | 14 ++-- types/backbone-relational/index.d.ts | 71 ++++++++++--------- 2 files changed, 43 insertions(+), 42 deletions(-) diff --git a/types/backbone-relational/backbone-relational-tests.ts b/types/backbone-relational/backbone-relational-tests.ts index 6e0135fcd9..c8b94c4029 100644 --- a/types/backbone-relational/backbone-relational-tests.ts +++ b/types/backbone-relational/backbone-relational-tests.ts @@ -1,13 +1,13 @@ -import * as Backbone from 'backbone'; +import * as BackboneRel from 'backbone-relational'; -class House extends Backbone.RelationalModel { +class House extends BackboneRel.Model { // The 'relations' property, on the House's prototype. Initialized separately for each // instance of House. Each relation must define (as a minimum) the 'type', 'key' and // 'relatedModel'. Options include 'includeInJSON', 'createModels' and 'reverseRelation'. relations = [ { - type: Backbone.HasMany, // Use the type, or the string 'HasOne' or 'HasMany'. + type: BackboneRel.HasMany, // Use the type, or the string 'HasOne' or 'HasMany'. key: 'occupants', relatedModel: 'Person', includeInJSON: true, @@ -20,14 +20,14 @@ class House extends Backbone.RelationalModel { } -class Person extends Backbone.RelationalModel { +class Person extends BackboneRel.Model { relations = [ { // Create a (recursive) one-to-one relationship - type: Backbone.HasOne, + type: BackboneRel.HasOne, key: 'user', relatedModel: 'User', reverseRelation: { - type: Backbone.HasOne, + type: BackboneRel.HasOne, key: 'person' } } @@ -39,7 +39,7 @@ class Person extends Backbone.RelationalModel { } } -class User extends Backbone.RelationalModel { +class User extends BackboneRel.Model { } diff --git a/types/backbone-relational/index.d.ts b/types/backbone-relational/index.d.ts index 84406fb60a..f19cfa8daa 100644 --- a/types/backbone-relational/index.d.ts +++ b/types/backbone-relational/index.d.ts @@ -1,15 +1,16 @@ -// Type definitions for Backbone-relational 0.8.5 +// Type definitions for Backbone-relational 0.10.0 // Project: http://backbonerelational.org/ // Definitions by: Eirik Hoem <https://github.com/eirikhm> +// Julian Gonggrijp <https://github.com/jgonggrijp> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// <reference types="jquery" /> -import * as Backbone from 'backbone'; +import { Events, EventsHash, Model as BModel, Collection } from 'backbone'; -declare module 'backbone' { - class RelationalModel extends Model { +declare module 'backbone-relational' { + class Model extends BModel { /** * Do not use, prefer TypeScript's extend functionality. **/ @@ -47,7 +48,7 @@ declare module 'backbone' { static findOrCreate(attributes:any, options?:any); } - export class Relation extends Model { + export class Relation extends BModel { options:any; instance:any; @@ -60,11 +61,11 @@ declare module 'backbone' { checkPreconditions():boolean; - setRelated(related:Model):void; + setRelated(related:BModel):void; - setRelated(related:Collection<Model>):void; + setRelated(related:Collection<BModel>):void; - getReverseRelations(model:RelationalModel):Relation; + getReverseRelations(model:Model):Relation; destroy():void; } @@ -72,7 +73,7 @@ declare module 'backbone' { export class HasOne extends Relation { collectionType:any; - findRelated(options:any):Model; + findRelated(options:any):BModel; setKeyContents(keyContents:string):void; @@ -82,21 +83,21 @@ declare module 'backbone' { setKeyContents(keyContents:number[]):void; - setKeyContents(keyContents:Collection<Model>):void; + setKeyContents(keyContents:Collection<BModel>):void; - onChange(model:Model, attr:any, options:any):void; + onChange(model:BModel, attr:any, options:any):void; - handleAddition(model:Model, coll:Collection<Model>, options:any):void; + handleAddition(model:BModel, coll:Collection<BModel>, options:any):void; - handleRemoval(model:Model, coll:Collection<Model>, options:any):void; + handleRemoval(model:BModel, coll:Collection<BModel>, options:any):void; - handleReset(coll:Collection<Model>, options:any):void; + handleReset(coll:Collection<BModel>, options:any):void; - tryAddRelated(model:Model, coll:any, options:any):void; + tryAddRelated(model:BModel, coll:any, options:any):void; - addRelated(model:Model, options:any):void; + addRelated(model:BModel, options:any):void; - removeRelated(model:Model, coll:any, options:any):void; + removeRelated(model:BModel, coll:any, options:any):void; } @@ -104,21 +105,21 @@ declare module 'backbone' { export class HasMany extends Relation { collectionType:any; - findRelated(options:any):Model; + findRelated(options:any):BModel; setKeyContents(keyContents:string):void; setKeyContents(keyContents:number):void; - setKeyContents(keyContents:Model):void; + setKeyContents(keyContents:BModel):void; - onChange(model:Model, attr:any, options:any):void; + onChange(model:BModel, attr:any, options:any):void; - tryAddRelated(model:Model, coll:any, options:any):void; + tryAddRelated(model:BModel, coll:any, options:any):void; - addRelated(model:Model, options:any):void; + addRelated(model:BModel, options:any):void; - removeRelated(model:Model, coll:any, options:any):void; + removeRelated(model:BModel, coll:any, options:any):void; } @@ -141,9 +142,9 @@ declare module 'backbone' { removeModelScope(scope):void; - addSubModels(subModelTypes:RelationalModel, superModelType:RelationalModel):void; + addSubModels(subModelTypes:Model, superModelType:Model):void; - setupSuperModel(modelType:RelationalModel):void; + setupSuperModel(modelType:Model):void; addReverseRelation(relation:any):void; @@ -151,30 +152,30 @@ declare module 'backbone' { processOrphanRelations():void; - retroFitRelation(relation:RelationalModel, create:boolean):Collection<Model>; + retroFitRelation(relation:Model, create:boolean):Collection<BModel>; - getCollection(type:RelationalModel, create:boolean):Collection<Model>; + getCollection(type:Model, create:boolean):Collection<BModel>; getObjectByName(name:string):any; resolveIdForItem(type:any, item:any):any; - static find(type:any, item:string):RelationalModel; + static find(type:any, item:string):Model; - static find(type:any, item:number):RelationalModel; + static find(type:any, item:number):Model; - static find(type:any, item:RelationalModel):RelationalModel; + static find(type:any, item:Model):Model; - static find(type:any, item:any):RelationalModel; + static find(type:any, item:any):Model; - register(model:RelationalModel):void; + register(model:Model):void; - checkId(model:RelationalModel, id:any):void; + checkId(model:Model, id:any):void; - update(model:RelationalModel):void; + update(model:Model):void; - unregister(model:RelationalModel, collection:Collection<Model>, options:any):void; + unregister(model:Model, collection:Collection<BModel>, options:any):void; reset():void; From d4fe8750cc435a269e19e245480d2163751d189e Mon Sep 17 00:00:00 2001 From: antoinebrault <antoinebrault@gmail.com> Date: Thu, 7 Feb 2019 21:16:58 -0500 Subject: [PATCH 151/197] [jest] limit type inference for spyOn getter/setter to non fonction properties & spyOn method to function properties --- types/jest/index.d.ts | 9 ++++++--- types/jest/jest-tests.ts | 19 +++++++++++++++---- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index cfc9be2070..d5061a78d5 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -37,6 +37,9 @@ declare var xtest: jest.It; declare const expect: jest.Expect; type ArgsType<T> = T extends (...args: infer A) => any ? A : never; +// see https://github.com/Microsoft/TypeScript/issues/25215 +type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends (...args: any[]) => any ? never : K }[keyof T] & string; +type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never }[keyof T] & string; interface NodeRequire { /** @@ -215,9 +218,9 @@ declare namespace jest { * spy.mockRestore(); * }); */ - function spyOn<T extends {}, M extends keyof T>(object: T, method: M, accessType: 'get'): SpyInstance<T[M], []>; - function spyOn<T extends {}, M extends keyof T>(object: T, method: M, accessType: 'set'): SpyInstance<void, [T[M]]>; - function spyOn<T extends {}, M extends keyof T>(object: T, method: M): T[M] extends (...args: any[]) => any ? SpyInstance<ReturnType<T[M]>, ArgsType<T[M]>> : never; + function spyOn<T extends {}, M extends NonFunctionPropertyNames<T>>(object: T, method: M, accessType: 'get'): SpyInstance<T[M], []>; + function spyOn<T extends {}, M extends NonFunctionPropertyNames<T>>(object: T, method: M, accessType: 'set'): SpyInstance<void, [T[M]]>; + function spyOn<T extends {}, M extends FunctionPropertyNames<T>>(object: T, method: M): T[M] extends (...args: any[]) => any ? SpyInstance<ReturnType<T[M]>, ArgsType<T[M]>> : never; /** * Indicates that the module system should never return a mocked version of * the specified module from require() (e.g. that it should always return the real module). diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index c2e930c26f..eee5d73922 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -360,24 +360,35 @@ const spiedTarget = { class SpiedTargetClass { private _value = 3; + private _value2 = ''; get value() { return this._value; } set value(value) { this._value = value; } + get value2() { + return this._value2; + } + set value2(value2) { + this._value2 = value2; + } } const spiedTarget2 = new SpiedTargetClass(); +// $ExpectError +jest.spyOn(spiedTarget, "setValue", "get"); +// $ExpectError +jest.spyOn(spiedTarget2, "value"); + const spy1 = jest.spyOn(spiedTarget, "returnsVoid"); -const spy2 = jest.spyOn(spiedTarget, "returnsVoid", "get"); const spy3 = jest.spyOn(spiedTarget, "returnsString"); const spy1Name: string = spy1.getMockName(); -const spy2Calls: any[][] = spy2.mock.calls; +const spy1Calls: Array<[]> = spy1.mock.calls; -spy2.mockClear(); -spy2.mockReset(); +spy1.mockClear(); +spy1.mockReset(); const spy3Mock = spy3 .mockImplementation(() => "") From 96347030c1873408d32adf9a8c80cfb53681a026 Mon Sep 17 00:00:00 2001 From: David Edmondson <threehams@gmail.com> Date: Thu, 7 Feb 2019 21:34:26 -0800 Subject: [PATCH 152/197] Add missing justifyItems definition. --- types/styled-system/index.d.ts | 4 +++- types/styled-system/styled-system-tests.tsx | 10 +++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index 19b9afcd5f..028ced7314 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for styled-system 3.2 +// Type definitions for styled-system 3.2.1 // Project: https://github.com/jxnblk/styled-system#readme // Definitions by: Marshall Bowers <https://github.com/maxdeviant> // Ben McCormick <https://github.com/phobon> @@ -421,6 +421,8 @@ export interface JustifyItemsProps { justifyItems?: ResponsiveValue<CSS.JustifyItemsProperty>; } +export function justifyItems(...args: any[]): any; + export interface JustifyContentProps { /** * The CSS justify-content property defines how the browser distributes space between and around content items diff --git a/types/styled-system/styled-system-tests.tsx b/types/styled-system/styled-system-tests.tsx index 397e1b0402..bfedc38182 100644 --- a/types/styled-system/styled-system-tests.tsx +++ b/types/styled-system/styled-system-tests.tsx @@ -43,6 +43,8 @@ import { alignContent, justifyContent, JustifyContentProps, + justifyItems, + JustifyItemsProps, FlexWrapProps, flexWrap, flexBasis, @@ -273,7 +275,8 @@ interface GridComponentProps GridAutoColumnsProps, GridAutoRowsProps, GridTemplatesRowsProps, - GridTemplatesColumnsProps {} + GridTemplatesColumnsProps, + JustifyItemsProps {} const Grid: React.ComponentType<GridComponentProps> = styled` ${gridGap}; ${gridRowGap}; @@ -285,6 +288,7 @@ const Grid: React.ComponentType<GridComponentProps> = styled` ${gridAutoColumns}; ${gridTemplateRows}; ${gridTemplateColumns}; + ${justifyItems}; `; interface ButtonProps @@ -467,6 +471,10 @@ const test = () => ( <Grid gridTemplateColumns="auto" /> <Grid gridTemplateColumns={["auto", "1fr"]} /> <Grid gridTemplateColumns={{ sm: "auto", md: "1fr" }} /> + // justifyItems + <Grid justifyItems="baseline" /> + <Grid justifyItems={["baseline", "center"]} /> + <Grid justifyItems={{ sm: "baseline", md: "center" }} /> // flex (responsive) <Box flex="1 1 auto" /> <Box flex={["1 1 auto"]} /> From 247a03b2198d698e7283095f951aebf549705668 Mon Sep 17 00:00:00 2001 From: David Edmondson <threehams@gmail.com> Date: Thu, 7 Feb 2019 22:32:38 -0800 Subject: [PATCH 153/197] Remove patch version --- types/styled-system/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index 028ced7314..788e8c305f 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for styled-system 3.2.1 +// Type definitions for styled-system 3.2 // Project: https://github.com/jxnblk/styled-system#readme // Definitions by: Marshall Bowers <https://github.com/maxdeviant> // Ben McCormick <https://github.com/phobon> From f6036e83cf9b93ae5e7c890440a2021b1f80ffe9 Mon Sep 17 00:00:00 2001 From: David Edmondson <threehams@gmail.com> Date: Thu, 7 Feb 2019 23:10:35 -0800 Subject: [PATCH 154/197] Organize justifyItems with Flex --- types/styled-system/styled-system-tests.tsx | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/types/styled-system/styled-system-tests.tsx b/types/styled-system/styled-system-tests.tsx index bfedc38182..ce7b8d24ff 100644 --- a/types/styled-system/styled-system-tests.tsx +++ b/types/styled-system/styled-system-tests.tsx @@ -255,7 +255,8 @@ interface FlexComponentProps JustifyContentProps, FlexWrapProps, FlexBasisProps, - FlexDirectionProps {} + FlexDirectionProps, + JustifyItemsProps {} const Flex: React.ComponentType<FlexComponentProps> = styled` ${alignItems}; ${alignContent}; @@ -263,6 +264,7 @@ const Flex: React.ComponentType<FlexComponentProps> = styled` ${flexWrap}; ${flexBasis}; ${flexDirection}; + ${justifyItems}; `; interface GridComponentProps @@ -275,8 +277,7 @@ interface GridComponentProps GridAutoColumnsProps, GridAutoRowsProps, GridTemplatesRowsProps, - GridTemplatesColumnsProps, - JustifyItemsProps {} + GridTemplatesColumnsProps{} const Grid: React.ComponentType<GridComponentProps> = styled` ${gridGap}; ${gridRowGap}; @@ -288,7 +289,6 @@ const Grid: React.ComponentType<GridComponentProps> = styled` ${gridAutoColumns}; ${gridTemplateRows}; ${gridTemplateColumns}; - ${justifyItems}; `; interface ButtonProps @@ -431,6 +431,10 @@ const test = () => ( <Flex flexDirection="column" /> <Flex flexDirection={["column"]} /> <Flex flexDirection={{ sm: "column" }} /> + // justifyItems + <Flex justifyItems="baseline" /> + <Flex justifyItems={["baseline", "center"]} /> + <Flex justifyItems={{ sm: "baseline", md: "center" }} /> // gridGap <Grid gridGap="1px" /> <Grid gridGap={["1", "2"]} /> @@ -471,10 +475,6 @@ const test = () => ( <Grid gridTemplateColumns="auto" /> <Grid gridTemplateColumns={["auto", "1fr"]} /> <Grid gridTemplateColumns={{ sm: "auto", md: "1fr" }} /> - // justifyItems - <Grid justifyItems="baseline" /> - <Grid justifyItems={["baseline", "center"]} /> - <Grid justifyItems={{ sm: "baseline", md: "center" }} /> // flex (responsive) <Box flex="1 1 auto" /> <Box flex={["1 1 auto"]} /> From 7293f118b733961c970b251ac1cdd193364d1fa6 Mon Sep 17 00:00:00 2001 From: Takuma Suzuki <pferd262@gmail.com> Date: Fri, 8 Feb 2019 17:08:34 +0900 Subject: [PATCH 155/197] Fix args type for Interval.toDuration() --- types/luxon/index.d.ts | 4 ++-- types/luxon/luxon-tests.ts | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index b5f1134fb5..95a06b1d6a 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for luxon 1.10 +// Type definitions for luxon 1.11.1 // Project: https://github.com/moment/luxon#readme // Definitions by: Colby DeHart <https://github.com/colbydehart> // Hyeonseok Yang <https://github.com/FourwingsY> @@ -436,7 +436,7 @@ export class Interval { splitAt(...dateTimes: DateTime[]): Interval[]; splitBy(duration: Duration | DurationObject | number): Interval[]; toDuration( - unit: DurationUnit | DurationUnit[], + unit?: DurationUnit | DurationUnit[], options?: DiffOptions ): Duration; toFormat( diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index df5481094b..59566c35c3 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -144,6 +144,7 @@ i.mapEndpoints((d) => d); // $ExpectType Interval i.toISO(); // $ExpectType string i.toString(); // $ExpectType string i.toDuration('months'); // $ExpectType Duration +i.toDuration(); // $ExpectType Duration if (Interval.isInterval(anything)) { anything; // $ExpectType Interval From 3d34d9651e1771050f2fec7ef44230286f8787e3 Mon Sep 17 00:00:00 2001 From: Jannik Keye <jannik.keye@gmail.com> Date: Fri, 8 Feb 2019 09:28:03 +0100 Subject: [PATCH 156/197] fix: set fastify-cors typings not needed --- notNeededPackages.json | 6 ++ types/fastify-cors/fastify-cors-tests.ts | 89 ------------------------ types/fastify-cors/index.d.ts | 68 ------------------ types/fastify-cors/tsconfig.json | 23 ------ types/fastify-cors/tslint.json | 1 - 5 files changed, 6 insertions(+), 181 deletions(-) delete mode 100644 types/fastify-cors/fastify-cors-tests.ts delete mode 100644 types/fastify-cors/index.d.ts delete mode 100644 types/fastify-cors/tsconfig.json delete mode 100644 types/fastify-cors/tslint.json diff --git a/notNeededPackages.json b/notNeededPackages.json index db3d6b10d2..e3483b3c4b 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -564,6 +564,12 @@ "sourceRepoURL": "https://www.npmjs.com/package/fast-simplex-noise", "asOfVersion": "3.0.0" }, + { + "libraryName": "fastify-cors", + "typingsPackageName": "fastify-cors", + "sourceRepoURL": "https://github.com/fastify/fastify-cors", + "asOfVersion": "2.1.0" + }, { "libraryName": "Fastify-JWT", "typingsPackageName": "fastify-jwt", diff --git a/types/fastify-cors/fastify-cors-tests.ts b/types/fastify-cors/fastify-cors-tests.ts deleted file mode 100644 index 5fcd7e20d4..0000000000 --- a/types/fastify-cors/fastify-cors-tests.ts +++ /dev/null @@ -1,89 +0,0 @@ -import fastifyCors = require("fastify-cors"); - -fastifyCors(); - -const fastifyCorsOptions: fastifyCors.FastifyCorsOptions = { - origin: true, - allowedHeaders: "authorization,content-type", - methods: "GET,POST,PUT,PATCH,DELETE,OPTIONS", - credentials: true, - exposedHeaders: "authorization", - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const fastifyCorsOptionsArray: fastifyCors.FastifyCorsOptions = { - origin: true, - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const originString: fastifyCors.FastifyCorsOptions = { - origin: "*", - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const originRegexp: fastifyCors.FastifyCorsOptions = { - origin: /\*/, - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const originStringArray: fastifyCors.FastifyCorsOptions = { - origin: ["*", "something"], - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const originRegexpArray: fastifyCors.FastifyCorsOptions = { - origin: [/\*/, /something/], - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; - -const originCallback: fastifyCors.FastifyCorsOptions = { - origin: (err: Error, allow: boolean) => { - throw err; - }, - allowedHeaders: ["authorization", "content-type"], - methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], - credentials: true, - exposedHeaders: ["authorization"], - maxAge: 13000, - preflightContinue: false, - optionsSuccessStatus: 200, - preflight: false, -}; diff --git a/types/fastify-cors/index.d.ts b/types/fastify-cors/index.d.ts deleted file mode 100644 index 907689a72c..0000000000 --- a/types/fastify-cors/index.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -// Type definitions for fastify-cors 0.1 -// Project: https://github.com/fastify/fastify-cors#readme -// Definitions by: Jannik Keye <https://github.com/jannikkeye> -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -type originCallback = (err: Error, allow: boolean) => void; - -/** - * fastify-cors enables the use of CORS in a Fastify application. - */ -declare function fastifyCors(): void; - -declare namespace fastifyCors { - /** - * Options for configuring the fastify-cors plugin. - */ - interface FastifyCorsOptions { - /** - * Configures the Access-Control-Allow-Origin CORS header. - */ - origin?: string | boolean | RegExp | string[] | RegExp[] | originCallback; - /** - * Configures the Access-Control-Allow-Credentials CORS header. - * Set to true to pass the header, otherwise it is omitted. - */ - credentials?: boolean; - /** - * Configures the Access-Control-Expose-Headers CORS header. - * Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') - * or an array (ex: ['Content-Range', 'X-Content-Range']). - * If not specified, no custom headers are exposed. - */ - exposedHeaders?: string | string[]; - /** - * Configures the Access-Control-Allow-Headers CORS header. - * Expects a comma-delimited string (ex: 'Content-Type,Authorization') - * or an array (ex: ['Content-Type', 'Authorization']). If not - * specified, defaults to reflecting the headers specified in the - * request's Access-Control-Request-Headers header. - */ - allowedHeaders?: string | string[]; - /** - * Configures the Access-Control-Allow-Methods CORS header. - * Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: ['GET', 'PUT', 'POST']). - */ - methods?: string | string[]; - /** - * Configures the Access-Control-Max-Age CORS header. - * Set to an integer to pass the header, otherwise it is omitted. - */ - maxAge?: number; - /** - * Pass the CORS preflight response to the route handler (default: false). - */ - preflightContinue?: boolean; - /** - * Provides a status code to use for successful OPTIONS requests, - * since some legacy browsers (IE11, various SmartTVs) choke on 204. - */ - optionsSuccessStatus?: number; - /** - * Pass the CORS preflight response to the route handler (default: false). - */ - preflight?: boolean; - } -} - -export = fastifyCors; diff --git a/types/fastify-cors/tsconfig.json b/types/fastify-cors/tsconfig.json deleted file mode 100644 index 9e696b42e2..0000000000 --- a/types/fastify-cors/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "fastify-cors-tests.ts" - ] -} diff --git a/types/fastify-cors/tslint.json b/types/fastify-cors/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/fastify-cors/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } From 3caae783fe15d11a4ac24faba39d1ede9e4a7e92 Mon Sep 17 00:00:00 2001 From: Takuma Suzuki <pferd262@gmail.com> Date: Fri, 8 Feb 2019 18:35:16 +0900 Subject: [PATCH 157/197] fixup! Fix args type for Interval.toDuration() --- types/luxon/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index 95a06b1d6a..eebf89497d 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for luxon 1.11.1 +// Type definitions for luxon 1.11 // Project: https://github.com/moment/luxon#readme // Definitions by: Colby DeHart <https://github.com/colbydehart> // Hyeonseok Yang <https://github.com/FourwingsY> From 963e5d627569ae521f808f6670fbafa2e0169cd4 Mon Sep 17 00:00:00 2001 From: Gerardo Pacheco <gerardo@lingokids.com> Date: Fri, 8 Feb 2019 10:46:37 +0100 Subject: [PATCH 158/197] react-native-tab-view added prop --- types/react-native-tab-view/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/react-native-tab-view/index.d.ts b/types/react-native-tab-view/index.d.ts index 078247e97d..8118239f8a 100644 --- a/types/react-native-tab-view/index.d.ts +++ b/types/react-native-tab-view/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Kalle Ott <https://github.com/kaoDev> // Kyle Roach <https://github.com/iRoachie> // Tim Wang <https://github.com/timwangdev> +// Gerardo Pacheco <https://github.com/geriux> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { PureComponent, ReactNode, ComponentType } from 'react' @@ -214,6 +215,7 @@ export type TabBarProps<T extends RouteBase = RouteBase> = SceneRendererProps< indicatorStyle?: StyleProp<ViewStyle> labelStyle?: StyleProp<ViewStyle> style?: StyleProp<ViewStyle> + useNativeDriver?: boolean; } export class TabBar<T extends Route = Route> extends PureComponent<TabBarProps<T>> {} From 099ad3f2cb00505ae4c2556e80b8a08ca3aec343 Mon Sep 17 00:00:00 2001 From: Malthe Borch <mborch@gmail.com> Date: Fri, 8 Feb 2019 11:45:36 +0100 Subject: [PATCH 159/197] Add missing flag 'testOnReturn' --- types/generic-pool/generic-pool-tests.ts | 1 + types/generic-pool/index.d.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/types/generic-pool/generic-pool-tests.ts b/types/generic-pool/generic-pool-tests.ts index 4b8a69aa93..3ddc8477a6 100644 --- a/types/generic-pool/generic-pool-tests.ts +++ b/types/generic-pool/generic-pool-tests.ts @@ -29,6 +29,7 @@ const opts = { min: 2, maxWaitingClients: 2, testOnBorrow: true, + testOnReturn: true, acquireTimeoutMillis: 100, fifo: true, priorityRange: 5, diff --git a/types/generic-pool/index.d.ts b/types/generic-pool/index.d.ts index 0fd1f58b4b..0bb0bffe2d 100644 --- a/types/generic-pool/index.d.ts +++ b/types/generic-pool/index.d.ts @@ -38,6 +38,7 @@ export interface Options { min?: number; maxWaitingClients?: number; testOnBorrow?: boolean; + testOnReturn?: boolean; acquireTimeoutMillis?: number; fifo?: boolean; priorityRange?: number; From 7b7942707a5eb75f30e85d628b2cca0184de2d15 Mon Sep 17 00:00:00 2001 From: Dominique Rau <domi.github@gmail.com> Date: Fri, 8 Feb 2019 12:44:19 +0100 Subject: [PATCH 160/197] feat(react-native-document-picker): add more utils types --- types/react-native-document-picker/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/react-native-document-picker/index.d.ts b/types/react-native-document-picker/index.d.ts index 986da6e611..77b91e81bc 100644 --- a/types/react-native-document-picker/index.d.ts +++ b/types/react-native-document-picker/index.d.ts @@ -12,6 +12,8 @@ export const DocumentPickerUtil: { pdf(): string; audio(): string; plainText(): string; + video(): string; + images(): string; }; export interface Options { From 8a6fa48e294ebae36cfd3273c69047f21907bb63 Mon Sep 17 00:00:00 2001 From: Alan Ray <rayalan@users.noreply.github.com> Date: Thu, 31 Jan 2019 19:21:12 -0500 Subject: [PATCH 161/197] stripe: Update cancel subscription options as of 2018-11-08 --- types/stripe/index.d.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index 068755e157..366d2407b2 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -4870,6 +4870,18 @@ declare namespace Stripe { interface ISubscriptionCancellationOptions extends IDataOptions { /** + * Will generate a final invoice that invoices for any un-invoiced metered usage and new/pending proration invoice items. + */ + invoice_now?: boolean; + + /** + * Will generate a proration invoice item that credits remaining unused time until the subscription period end. + */ + prorate?: boolean; + + /** + * @deprecated Use subscription update with cancel_at_period_end option as of 2018-08-23. + * * A flag that if set to true will delay the cancellation of the subscription until the end of the current period. */ at_period_end?: boolean; From ef54ca7995197aac67c5c2b2709d2a4decdb96ef Mon Sep 17 00:00:00 2001 From: bLue <tbdblue@gmail.com> Date: Fri, 8 Feb 2019 21:29:05 +0800 Subject: [PATCH 162/197] [katex] Add contrib/auto-render --- types/katex/contrib/auto-render.d.ts | 64 ++++++++++++++++++++++++++++ types/katex/contrib/index.d.ts | 1 + types/katex/index.d.ts | 39 +++++++++-------- types/katex/katex-tests.ts | 41 ++++++++++++------ 4 files changed, 115 insertions(+), 30 deletions(-) create mode 100644 types/katex/contrib/auto-render.d.ts create mode 100644 types/katex/contrib/index.d.ts diff --git a/types/katex/contrib/auto-render.d.ts b/types/katex/contrib/auto-render.d.ts new file mode 100644 index 0000000000..efef3ffb7d --- /dev/null +++ b/types/katex/contrib/auto-render.d.ts @@ -0,0 +1,64 @@ +declare module 'katex/dist/contrib/auto-render' { + import { KatexOptions } from 'katex'; + + export interface RenderMathInElementSpecificOptionsDelimiters { + /** + * A string which starts the math expression (i.e. the left delimiter) + */ + left: string; + /** + * A string which ends the math expression (i.e. the right delimiter) + */ + right: string; + /** + * A boolean of whether the math in the expression should be rendered in display mode or not + */ + display: boolean + } + + export interface RenderMathInElementSpecificOptions { + /** + * A list of delimiters to look for math + * + * @default [ + * {left: "$$", right: "$$", display: true}, + * {left: "\\(", right: "\\)", display: false}, + * {left: "\\[", right: "\\]", display: true} + * ] + */ + delimiters?: ReadonlyArray<RenderMathInElementSpecificOptionsDelimiters>; + /** + * A list of DOM node types to ignore when recursing through + * + * @default ["script", "noscript", "style", "textarea", "pre", "code"] + */ + ignoredTags?: ReadonlyArray<keyof HTMLElementTagNameMap>; + /** + * A list of DOM node class names to ignore when recursing through + * + * @default [] + */ + ignoredClasses?: string[]; + /** + * A callback method returning a message and an error stack in case of an critical error during rendering + * @param msg Message generated by KaTeX + * @param err Caught error + * + * @default console.error + */ + errorCallback?(msg: string, err: Error): void; + } + + /** + * renderMathInElement options contain KaTeX render options and renderMathInElement specific options + */ + export type RenderMathInElementOptions = KatexOptions & RenderMathInElementSpecificOptions; + + /** + * Auto-render TeX expressions in HTML element + * @param elem HTML element to auto-render + * @param options Render options + */ + function renderMathInElement(elem: HTMLElement, options?: RenderMathInElementOptions): void; + export default renderMathInElement; +} diff --git a/types/katex/contrib/index.d.ts b/types/katex/contrib/index.d.ts new file mode 100644 index 0000000000..a365569333 --- /dev/null +++ b/types/katex/contrib/index.d.ts @@ -0,0 +1 @@ +/// <reference path="auto-render.d.ts" /> diff --git a/types/katex/index.d.ts b/types/katex/index.d.ts index ae126b3444..75633ad7f4 100644 --- a/types/katex/index.d.ts +++ b/types/katex/index.d.ts @@ -2,24 +2,27 @@ // Project: http://khan.github.io/KaTeX/ // Definitions by: Michael Randolph <https://github.com/mrand01> // Kevin Nguyen <https://github.com/knguyen0125> +// bLue <https://github.com/dreamerblue> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// <reference path="contrib/index.d.ts" /> + export as namespace katex; /** Documentation: https://katex.org/docs/options.html */ export interface KatexOptions { /** - * If `true`, math will be rendered in display mode + * If `true`, math will be rendered in display mode * (math in display style and center math on page) - * + * * If `false`, math will be rendered in inline mode * @default false */ displayMode?: boolean; /** - * If `true`, KaTeX will throw a `ParseError` when + * If `true`, KaTeX will throw a `ParseError` when * it encounters an unsupported command or invalid LaTex - * + * * If `false`, KaTeX will render unsupported commands as * text, and render invalid LaTeX as its source code with * hover text giving the error, in color given by errorColor @@ -32,56 +35,56 @@ export interface KatexOptions { errorColor?: string; /** * A collection of custom macros. - * + * * See `src/macros.js` for its usage */ macros?: any; /** * If `true`, `\color` will work like LaTeX's `\textcolor` * and takes 2 arguments - * + * * If `false`, `\color` will work like LaTeX's `\color` * and takes 1 argument - * + * * In both cases, `\textcolor` works as in LaTeX - * + * * @default false */ colorIsTextColor?: boolean; /** * All user-specified sizes will be caped to `maxSize` ems - * + * * If set to Infinity, users can make elements and space * arbitrarily large - * + * * @default Infinity */ maxSize?: number; /** * Limit the number of macro expansions to specified number - * + * * If set to `Infinity`, marco expander will try to fully expand * as in LaTex - * + * * @default 1000 */ maxExpand?: number; /** * Allowed protocols in `\href` - * + * * Use `_relative` to allow relative urls - * + * * Use `*` to allow all protocols */ - allowedProtocols?: string[] + allowedProtocols?: string[]; /** * If `false` or `"ignore"`, allow features that make * writing in LaTex convenient but not supported by LaTex - * + * * If `true` or `"error"`, throw an error for such transgressions - * + * * If `"warn"`, warn about behavior via `console.warn` - * + * * @default "warn" */ strict?: boolean | string | Function; diff --git a/types/katex/katex-tests.ts b/types/katex/katex-tests.ts index 6fd614c82c..6b3e223927 100644 --- a/types/katex/katex-tests.ts +++ b/types/katex/katex-tests.ts @@ -1,16 +1,33 @@ import katexLib = require('katex'); +import renderMathInElement, { RenderMathInElementOptions } from 'katex/dist/contrib/auto-render'; class KatexTest { - constructor() { - katexLib.render('My Latex String', document.createElement('div')); + constructor() { + katexLib.render('My Latex String', document.createElement('div')); - try { - let options: katexLib.KatexOptions = { throwOnError: true }; - let value: string = katexLib.renderToString('My Latex String', options); - } catch (error) { - if (error instanceof katexLib.ParseError) { - //do something with this error - } - } - } -} \ No newline at end of file + try { + let options: katexLib.KatexOptions = { throwOnError: true }; + let value: string = katexLib.renderToString('My Latex String', options); + } catch (error) { + if (error instanceof katexLib.ParseError) { + //do something with this error + } + } + + const renderMathInElementOptions: RenderMathInElementOptions = { + delimiters: [ + { left: "$$", right: "$$", display: true }, + { left: "\\[", right: "\\]", display: true }, + { left: "$", right: "$", display: false }, + { left: "\\(", right: "\\)", display: false }, + ], + errorCallback(msg: string, err: Error): void { + console.error(msg, err); + //do something with this error + } + }; + const container = document.createElement('div'); + container.innerText = 'LaTeX string $c = \\pm\\sqrt{a^2 + b^2}$'; + renderMathInElement(container, renderMathInElementOptions); + } +} From 80c0b6ff7be168578e7a068e7db59c50c45e578d Mon Sep 17 00:00:00 2001 From: bLue <tbdblue@gmail.com> Date: Fri, 8 Feb 2019 21:40:31 +0800 Subject: [PATCH 163/197] [katex] Add typescript version comment --- types/katex/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/katex/index.d.ts b/types/katex/index.d.ts index 75633ad7f4..9d89c7c329 100644 --- a/types/katex/index.d.ts +++ b/types/katex/index.d.ts @@ -4,6 +4,7 @@ // Kevin Nguyen <https://github.com/knguyen0125> // bLue <https://github.com/dreamerblue> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// <reference path="contrib/index.d.ts" /> From 276c76e22e721514cce2e7136f42fd19b1fd33c3 Mon Sep 17 00:00:00 2001 From: Nico Jansen <nico.jansen@infosupport.com> Date: Fri, 8 Feb 2019 10:24:17 +0100 Subject: [PATCH 164/197] Prettier: Add parser babel and babel-flow --- types/prettier/index.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/prettier/index.d.ts b/types/prettier/index.d.ts index 6cef2ef27a..22f82096a8 100644 --- a/types/prettier/index.d.ts +++ b/types/prettier/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for prettier 1.15 +// Type definitions for prettier 1.16 // Project: https://github.com/prettier/prettier // Definitions by: Ika <https://github.com/ikatyang> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -21,7 +21,9 @@ export interface FastPath<T = any> { export type BuiltInParser = (text: string, options?: any) => AST; export type BuiltInParserName = - | 'babylon' + | 'babylon' // deprecated + | 'babel' + | 'babel-flow' | 'flow' | 'typescript' | 'postcss' // deprecated From 34b8119dd7b0c967e3140988e41a41f9d55877c6 Mon Sep 17 00:00:00 2001 From: Patrick Chatain <patrick.chatain@fullsix.com> Date: Fri, 8 Feb 2019 16:34:23 +0100 Subject: [PATCH 165/197] change failedReason type to any --- types/bull/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index 36f05a7058..aab2385ea4 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -241,7 +241,7 @@ declare namespace Bull { delay: number, timestamp: number, attemptsMade: number, - failedReason: string, + failedReason: any, stacktrace: string[] | null, returnvalue: any, finishedOn: number | null, From cd27a249062075086a95d2d14fcaf9eaa5cf3377 Mon Sep 17 00:00:00 2001 From: Rusty Scrivens <34690530+rscrivens@users.noreply.github.com> Date: Fri, 8 Feb 2019 10:01:26 -0800 Subject: [PATCH 166/197] Update to latest sarif version 2.0.0-csd.2.beta-2019-01-09 --- types/sarif/index.d.ts | 308 ++++++++++++++++++++++++++++++----------- 1 file changed, 229 insertions(+), 79 deletions(-) diff --git a/types/sarif/index.d.ts b/types/sarif/index.d.ts index 4bece2d3f8..2a4e57fe25 100644 --- a/types/sarif/index.d.ts +++ b/types/sarif/index.d.ts @@ -5,8 +5,8 @@ // TypeScript Version: 2.4 /** - * Static Analysis Results Format (SARIF) Version 2.0.0-csd.2.beta-2018-10-10 JSON Schema: - * a standard format for the output of static analysis tools. + * Static Analysis Results Format (SARIF) Version 2.0.0-csd.2.beta-2019-01-09 JSON Schema: a standard format for the + * output of static analysis tools. */ export interface Log { /** @@ -23,11 +23,16 @@ export interface Log { * The set of runs contained in this log file. */ runs: Run[]; + + /** + * Key/value pairs that provide additional information about the log file. + */ + properties?: PropertyBag; } export namespace Log { type version = - "2.0.0-csd.2.beta.2018-10-10"; + "2.0.0-csd.2.beta.2019-01-09"; } /** @@ -53,6 +58,11 @@ export interface Attachment { * An array of regions of interest within the attachment. */ regions?: Region[]; + + /** + * Key/value pairs that provide additional information about the attachment. + */ + properties?: PropertyBag; } /** @@ -188,57 +198,81 @@ export interface Exception { stack?: Stack; /** - * Key/value pairs that provide additional information about the exception + * Key/value pairs that provide additional information about the exception. */ properties?: PropertyBag; } /** - * References to external files that should be inlined with the content of a root log file. + * TBD */ -export interface ExternalFiles { +export interface ExternalPropertyFile { /** - * The location of a file containing a run.conversion object to be merged with the root log file. + * The location of the external property file. */ - conversion?: FileLocation; + fileLocation?: FileLocation; /** - * The location of a file containing a run.files object to be merged with the root log file. + * A stable, unique identifer for the external property file in the form of a GUID. */ - files?: FileLocation; + instanceGuid?: string; /** - * The location of a file containing a run.graphs object to be merged with the root log file. + * A non-negative integer specifying the number of items contained in the external property file. */ - graphs?: FileLocation; + itemCount?: number; /** - * An array of locations of files containing arrays of run.invocation objects to be merged with the root log - * file. - */ - invocations?: FileLocation[]; - - /** - * The location of a file containing a run.logicalLocations object to be merged with the root log file. - */ - logicalLocations?: FileLocation; - - /** - * The location of a file containing a run.resources object to be merged with the root log file. - */ - resources?: FileLocation; - - /** - * An array of locations of files containins arrays of run.result objects to be merged with the root log file. - */ - results?: FileLocation[]; - - /** - * Key/value pairs that provide additional information about the external files + * Key/value pairs that provide additional information about the external property file. */ properties?: PropertyBag; } +/** + * References to external property files that should be inlined with the content of a root log file. + */ +export interface ExternalPropertyFiles { + /** + * An external property file containing a run.conversion object to be merged with the root log file. + */ + conversion?: ExternalPropertyFile; + + /** + * An array of external property files containing run.files arrays to be merged with the root log file. + */ + files?: ExternalPropertyFile[]; + + /** + * An external property file containing a run.graphs object to be merged with the root log file. + */ + graphs?: ExternalPropertyFile; + + /** + * An array of external property files containing run.invocations arrays to be merged with the root log file. + */ + invocations?: ExternalPropertyFile[]; + + /** + * An array of external property files containing run.logicalLocations arrays to be merged with the root log file. + */ + logicalLocations?: ExternalPropertyFile[]; + + /** + * An external property file containing a run.resources object to be merged with the root log file. + */ + resources?: ExternalPropertyFile; + + /** + * An array of external property files containing run.results arrays to be merged with the root log file. + */ + results?: ExternalPropertyFile[]; + + /** + * An external property file containing a run.properties object to be merged with the root log file. + */ + properties?: ExternalPropertyFile; +} + /** * A single file. In some cases, this file might be nested within another file. */ @@ -286,15 +320,20 @@ export interface File { offset?: number; /** - * Identifies the key of the immediate parent of the file, if this file is nested. + * Identifies the index of the immediate parent of the file, if this file is nested. */ - parentKey?: string; + parentIndex?: number; /** * The role or roles played by the file in the analysis. */ roles?: File.roles[]; + /** + * Specifies the source language for any file object that refers to a text file that contains source code. + */ + sourceLanguage?: string; + /** * Key/value pairs that provide additional information about the file. */ @@ -362,6 +401,11 @@ export interface FileContent { * Specifies the location of a file. */ export interface FileLocation { + /** + * The index within the run files array of the file object associated with the file location. + */ + fileIndex?: number; + /** * A string containing a valid relative or absolute URI. */ @@ -413,7 +457,7 @@ export interface Graph { /** * An array of edge objects representing the edges of the graph. */ - edges: Edge[]; + edges?: Edge[]; /** * A string that uniquely identifies the graph within a run.graphs or result.graphs array. @@ -423,7 +467,7 @@ export interface Graph { /** * An array of node objects representing the nodes of the graph. */ - nodes: Node[]; + nodes?: Node[]; /** * Key/value pairs that provide additional information about the graph. @@ -443,7 +487,7 @@ export interface GraphTraversal { /** * The sequences of edges traversed by this graph traversal. */ - edgeTraversals: EdgeTraversal[]; + edgeTraversals?: EdgeTraversal[]; /** * A string that uniquely identifies that graph being traversed. @@ -611,6 +655,11 @@ export interface Location { */ fullyQualifiedLogicalName?: string; + /** + * The index within the logical locations array of the logical location associated with the result. + */ + logicalLocationIndex?: number; + /** * A message relevant to the location. */ @@ -643,9 +692,9 @@ export interface LogicalLocation { fullyQualifiedName?: string; /** - * The type of construct this logicalLocationComponent refers to. Should be one of 'function', 'member', - * 'module', 'namespace', 'package', 'parameter', 'resource', 'returnType', 'type', or 'variable', if any of - * those accurately describe the construct. + * The type of construct this logical location component refers to. Should be one of 'function', 'member', + * 'module', 'namespace', 'parameter', 'resource', 'returnType', 'type', or 'variable', if any of those + * accurately describe the construct. */ kind?: string; @@ -656,10 +705,10 @@ export interface LogicalLocation { name?: string; /** - * Identifies the key of the immediate parent of the construct in which the result was detected. For example, + * Identifies the index of the immediate parent of the construct in which the result was detected. For example, * this property might point to a logical location that represents the namespace that holds a type. */ - parentKey?: string; + parentIndex?: number; /** * Key/value pairs that provide additional information about the logical location. @@ -763,11 +812,15 @@ export interface Notification { physicalLocation?: PhysicalLocation; /** - * The stable, unique identifier of the rule (if any) to which this notification is relevant. This member can be - * used to retrieve rule metadata from the rules dictionary, if it exists. + * The stable, unique identifier of the rule, if any, to which this notification is relevant. */ ruleId?: string; + /** + * The index within the run resources array of the rule object, if any, associated with this notification. + */ + ruleIndex?: number; + /** * The thread identifier of the code that generated the notification. */ @@ -917,6 +970,11 @@ export interface Region { */ snippet?: FileContent; + /** + * Specifies the source language, if any, of the portion of the file specified by the region object. + */ + sourceLanguage?: string; + /** * The column number of the first character in the region. */ @@ -963,10 +1021,14 @@ export interface Resources { messageStrings?: { [key: string]: string }; /** - * A dictionary, each of whose keys is a string and each of whose values is a 'rule' object, that describe all - * rules associated with an analysis tool or a specific run of an analysis tool. + * An array of rule objects relevant to the run. */ - rules?: { [key: string]: Rule }; + rules?: Rule[]; + + /** + * Key/value pairs that provide additional information about the resources. + */ + properties?: PropertyBag; } /** @@ -994,12 +1056,6 @@ export interface Result { */ codeFlows?: CodeFlow[]; - /** - * An array of physicalLocation objects which specify the portions of an analysis tool's output that a converter - * transformed into the result object. - */ - conversionProvenance?: PhysicalLocation[]; - /** * A stable, unique identifier for the equivalence class of logically identical results to which this result * belongs, in the form of a GUID. @@ -1027,6 +1083,11 @@ export interface Result { */ graphTraversals?: GraphTraversal[]; + /** + * An absolute URI at which the result can be viewed. + */ + hostedViewerUri?: string; + /** * A stable, unique identifer for the result in the form of a GUID. */ @@ -1038,7 +1099,7 @@ export interface Result { level?: Result.level; /** - * One or more locations where the result occurred. Specify only one location unless the problem indicated by + * The set of locations where the result was detected. Specify only one location unless the problem indicated by * the result can only be corrected by making a change at every specified location. */ locations?: Location[]; @@ -1047,7 +1108,7 @@ export interface Result { * A message that describes the result. The first sentence of the message only will be displayed when visible * space is limited. */ - message?: Message; + message: Message; /** * A positive integer specifying the number of times this logically unique result was observed in this run. @@ -1059,17 +1120,32 @@ export interface Result { */ partialFingerprints?: { [key: string]: string }; + /** + * Information about how and when the result was detected. + */ + provenance?: ResultProvenance; + + /** + * A number representing the priority or importance of the result. + */ + rank?: number; + /** * A set of locations relevant to this result. */ relatedLocations?: Location[]; /** - * The stable, unique identifier of the rule (if any) to which this notification is relevant. This member can be + * The stable, unique identifier of the rule, if any, to which this notification is relevant. This member can be * used to retrieve rule metadata from the rules dictionary, if it exists. */ ruleId?: string; + /** + * The index within the run resources array of the rule object associated with this result. + */ + ruleIndex?: number; + /** * An array of 'stack' objects relevant to the result. */ @@ -1081,7 +1157,7 @@ export interface Result { suppressionStates?: Result.suppressionStates[]; /** - * The URIs of the work items associated with this result + * The URIs of the work items associated with this result. */ workItemUris?: string[]; @@ -1110,6 +1186,52 @@ export namespace Result { "absent"; } +/** + * Contains information about how and when a result was detected. + */ +export interface ResultProvenance { + /** + * An array of physicalLocation objects which specify the portions of an analysis tool's output that a + * converter transformed into the result. + */ + conversionSources?: PhysicalLocation[]; + + /** + * A GUID-valued string equal to the id.instanceGuid property of the run in which the result was first + * detected. + */ + firstDetectionRunInstanceGuid?: string; + + /** + * The Coordinated Universal Time (UTC) date and time at which the result was first detected. See "Date/time + * properties" in the SARIF spec for the required format. + */ + firstDetectionTimeUtc?: string; + + /** + * The index within the run.invocations array of the invocation object which describes the tool invocation that + * detected the result. + */ + invocationIndex?: number; + + /** + * A GUID-valued string equal to the id.instanceGuid property of the run in which the result was most recently + * detected. + */ + lastDetectionRunInstanceGuid?: string; + + /** + * The Coordinated Universal Time (UTC) date and time at which the result was most recently detected. See + * "Date/time properties" in the SARIF spec for the required format. + */ + lastDetectionTimeUtc?: string; + + /** + * Key/value pairs that provide additional information about the result. + */ + properties?: PropertyBag; +} + /** * Describes an analysis rule. */ @@ -1119,6 +1241,12 @@ export interface Rule { */ configuration?: RuleConfiguration; + /** + * An array of stable, opaque identifiers by which this rule was known in some previous version of the analysis + * tool. + */ + deprecatedIds?: string[]; + /** * A description of the rule. Should, as far as possible, provide details sufficient to enable resolution of any * problem indicated by the result. @@ -1176,10 +1304,15 @@ export interface Rule { */ export interface RuleConfiguration { /** - * Specifies the default severity level of the result. + * Specifies the default severity level for results generated by this rule. */ defaultLevel?: RuleConfiguration.defaultLevel; + /** + * Specifies the default priority or importance for results generated by this rule. + */ + defaultRank?: number; + /** * Specifies whether the rule will be evaluated during the scan. */ @@ -1200,8 +1333,7 @@ export namespace RuleConfiguration { type defaultLevel = "note" | "warning" | - "error" | - "open"; + "error"; } /** @@ -1213,11 +1345,6 @@ export interface Run { */ aggregateIds?: RunAutomationDetails[]; - /** - * The hardware architecture for which the run was targeted. - */ - architecture?: string; - /** * The 'instanceGuid' property of a previous SARIF 'run' that comprises the baseline that was used to compute * result 'baselineState' properties for the run. @@ -1241,9 +1368,20 @@ export interface Run { defaultFileEncoding?: string; /** - * A dictionary, each of whose keys is a URI and each of whose values is a file object. + * Specifies the default source language for any file object that refers to a text file that contains source + * code. */ - files?: { [key: string]: File }; + defaultSourceLanguage?: string; + + /** + * References to external property files that should be inlined with the content of a root log file. + */ + externalPropertyFiles?: ExternalPropertyFiles; + + /** + * An array of file objects relevant to the run. + */ + files?: File[]; /** * A dictionary, each of whose keys is the id of a graph and each of whose values is a 'graph' object with that @@ -1262,9 +1400,15 @@ export interface Run { invocations?: Invocation[]; /** - * A dictionary, each of whose keys specifies a logical location such as a namespace, type or function. + * An array of logical locations such as namespaces, types or functions. */ - logicalLocations?: { [key: string]: LogicalLocation }; + logicalLocations?: LogicalLocation[]; + + /** + * An ordered list of character sequences that were treated as line breaks when computing region information + * for the run. + */ + newlineSequences?: string[]; /** * The file location specified by each uriBaseId symbol on the machine where the tool originally ran. @@ -1472,7 +1616,7 @@ export interface ThreadFlowLocation { module?: string; /** - * An integer representing a containment hierarchy within the thread flow + * An integer representing a containment hierarchy within the thread flow. */ nestingLevel?: number; @@ -1505,17 +1649,17 @@ export namespace ThreadFlowLocation { * The analysis tool that was run. */ export interface Tool { + /** + * The binary version of the tool's primary executable file expressed as four non-negative integers separated + * by a period (for operating systems that express file versions in this way). + */ + dottedQuadFileVersion?: string; + /** * The absolute URI from which the tool can be downloaded. */ downloadUri?: string; - /** - * The binary version of the tool's primary executable file (for operating systems such as Windows that provide - * that information). - */ - fileVersion?: string; - /** * The name of the tool along with its version and any other useful identifying information, such as its locale. */ @@ -1555,7 +1699,7 @@ export interface Tool { } /** - * TBD + * Specifies the information necessary to retrieve a desired revision from a version control system. */ export interface VersionControlDetails { /** @@ -1569,6 +1713,12 @@ export interface VersionControlDetails { */ branch?: string; + /** + * The location in the local file system to which the root of the repository was mapped at the time of the + * analysis. + */ + mappedTo?: FileLocation; + /** * The absolute URI of the repository. */ From b65f9a5bfe1aa37d7366be3c71ebca087b6a6a8b Mon Sep 17 00:00:00 2001 From: Guketlev Dmitry <yavanosta@yandex.ru> Date: Fri, 8 Feb 2019 23:57:43 +0300 Subject: [PATCH 167/197] Add typings for color support --- types/color-support/color-support-tests.ts | 48 ++++++++++++++++++++++ types/color-support/index.d.ts | 34 +++++++++++++++ types/color-support/tsconfig.json | 23 +++++++++++ types/color-support/tslint.json | 1 + 4 files changed, 106 insertions(+) create mode 100644 types/color-support/color-support-tests.ts create mode 100644 types/color-support/index.d.ts create mode 100644 types/color-support/tsconfig.json create mode 100644 types/color-support/tslint.json diff --git a/types/color-support/color-support-tests.ts b/types/color-support/color-support-tests.ts new file mode 100644 index 0000000000..5c61067dcf --- /dev/null +++ b/types/color-support/color-support-tests.ts @@ -0,0 +1,48 @@ +import * as colorSupport from 'color-support'; + +(() => { + const result = colorSupport(); + if (!result) { + console.log('color is not supported'); + } else if (result.has16m) { + console.log('\x1b[38;2;102;194;255m16m colors\x1b[0m'); + } else if (result.has256) { + console.log('\x1b[38;5;119m256 colors\x1b[0m'); + } else if (result.hasBasic) { + console.log('\x1b[31mbasic colors\x1b[0m'); + } else { + console.log('Level: ', result.level); + console.log('this is impossible, but colors are not supported'); + } +})(); + +(() => { + const result = colorSupport({ + alwaysReturn: false, + env: process.env, + ignoreCI: true, + ignoreDumb: true, + ignoreTTY: true, + level: 2, + stream: process.stdout, + term: process.env.TERM, + }, { + has16m: false, + has256: false, + hasBasic: false, + level: 0, + }); + + if (!result) { + console.log('color is not supported'); + } else if (result.has16m) { + console.log('\x1b[38;2;102;194;255m16m colors\x1b[0m'); + } else if (result.has256) { + console.log('\x1b[38;5;119m256 colors\x1b[0m'); + } else if (result.hasBasic) { + console.log('\x1b[31mbasic colors\x1b[0m'); + } else { + console.log('Level: ', result.level); + console.log('this is impossible, but colors are not supported'); + } +})(); diff --git a/types/color-support/index.d.ts b/types/color-support/index.d.ts new file mode 100644 index 0000000000..290a6e29b0 --- /dev/null +++ b/types/color-support/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for color-support 1.1 +// Project: https://github.com/isaacs/color-support#readme +// Definitions by: Guketlev Dmitry <https://github.com/Yavanosta> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// <reference types="node" /> + +type ColorSupportLevel = 0 | 1 | 2 | 3; + +interface ColorSupportOptions { + alwaysReturn?: boolean; + env?: NodeJS.ProcessEnv; + ignoreCI?: boolean; + ignoreDumb?: boolean; + ignoreTTY?: boolean; + level?: ColorSupportLevel; + stream?: NodeJS.WriteStream; + term?: string; +} + +interface ColorSupportResult { + level: ColorSupportLevel; + hasBasic: boolean; + has256: boolean; + has16m: boolean; +} + +type ColorSupport = (options?: ColorSupportOptions, + obj?: ColorSupportResult) => false | ColorSupportResult; + +declare var colorSupport: ColorSupport; + +export = colorSupport; diff --git a/types/color-support/tsconfig.json b/types/color-support/tsconfig.json new file mode 100644 index 0000000000..f1e6de8e28 --- /dev/null +++ b/types/color-support/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "color-support-tests.ts" + ] +} diff --git a/types/color-support/tslint.json b/types/color-support/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color-support/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From e69abd8af13b4dd17259e72898b118102993915d Mon Sep 17 00:00:00 2001 From: Simon Schick <demwizzy@gmail.com> Date: Thu, 7 Feb 2019 13:00:05 -0800 Subject: [PATCH 168/197] feat(node): v11.6 --- types/node/child_process.d.ts | 45 +- types/node/cluster.d.ts | 1 - types/node/crypto.d.ts | 16 +- types/node/dgram.d.ts | 19 +- types/node/fs.d.ts | 4 +- types/node/globals.d.ts | 103 +- types/node/http.d.ts | 11 + types/node/index.d.ts | 2 +- types/node/net.d.ts | 6 +- types/node/node-tests.ts | 987 ------ types/node/readline.d.ts | 1 + types/node/test/dgram.ts | 108 + types/node/test/global.ts | 17 + types/node/test/http.ts | 175 + types/node/test/net.ts | 293 ++ types/node/test/readline.ts | 183 ++ types/node/test/util.ts | 169 + types/node/test/worker_threads.ts | 46 + types/node/tls.d.ts | 19 + types/node/ts3.1/tsconfig.json | 3 +- types/node/tsconfig.json | 12 +- types/node/tty.d.ts | 29 + types/node/util.d.ts | 1 - types/node/v10/assert.d.ts | 52 + types/node/v10/async_hooks.d.ts | 144 + types/node/v10/base.d.ts | 41 + types/node/v10/buffer.d.ts | 6 + types/node/v10/child_process.d.ts | 358 ++ types/node/v10/cluster.d.ts | 261 ++ types/node/v10/console.d.ts | 3 + types/node/v10/constants.d.ts | 279 ++ types/node/v10/crypto.d.ts | 369 +++ types/node/v10/dgram.d.ts | 97 + types/node/v10/dns.d.ts | 292 ++ types/node/v10/domain.d.ts | 16 + types/node/v10/events.d.ts | 29 + types/node/v10/fs.d.ts | 2272 +++++++++++++ types/node/v10/globals.d.ts | 1005 ++++++ types/node/v10/http.d.ts | 247 ++ types/node/v10/http2.d.ts | 861 +++++ types/node/v10/https.d.ts | 37 + types/node/v10/index.d.ts | 85 + types/node/v10/inspector.d.ts | 3162 ++++++++++++++++++ types/node/v10/module.d.ts | 3 + types/node/v10/net.d.ts | 251 ++ types/node/v10/node-tests.ts | 4837 ++++++++++++++++++++++++++++ types/node/v10/os.d.ts | 192 ++ types/node/v10/package.json | 11 + types/node/v10/path.d.ts | 159 + types/node/v10/perf_hooks.d.ts | 241 ++ types/node/v10/process.d.ts | 3 + types/node/v10/punycode.d.ts | 12 + types/node/v10/querystring.d.ts | 17 + types/node/v10/readline.d.ts | 135 + types/node/v10/repl.d.ts | 372 +++ types/node/v10/stream.d.ts | 294 ++ types/node/v10/string_decoder.d.ts | 9 + types/node/v10/timers.d.ts | 16 + types/node/v10/tls.d.ts | 371 +++ types/node/v10/trace_events.d.ts | 61 + types/node/v10/ts3.1/index.d.ts | 18 + types/node/v10/ts3.1/node-tests.ts | 2 + types/node/v10/ts3.1/tsconfig.json | 30 + types/node/v10/ts3.1/tslint.json | 10 + types/node/v10/ts3.1/util.d.ts | 10 + types/node/v10/tsconfig.json | 71 + types/node/v10/tslint.json | 10 + types/node/v10/tty.d.ts | 15 + types/node/v10/url.d.ts | 104 + types/node/v10/util.d.ts | 169 + types/node/v10/v8.d.ts | 28 + types/node/v10/vm.d.ts | 64 + types/node/v10/worker_threads.d.ts | 124 + types/node/v10/zlib.d.ts | 141 + types/node/worker_threads.d.ts | 1 + types/ssh2/ssh2-tests.ts | 6 +- 76 files changed, 18570 insertions(+), 1083 deletions(-) create mode 100644 types/node/test/dgram.ts create mode 100644 types/node/test/global.ts create mode 100644 types/node/test/http.ts create mode 100644 types/node/test/net.ts create mode 100644 types/node/test/readline.ts create mode 100644 types/node/test/util.ts create mode 100644 types/node/test/worker_threads.ts create mode 100644 types/node/v10/assert.d.ts create mode 100644 types/node/v10/async_hooks.d.ts create mode 100644 types/node/v10/base.d.ts create mode 100644 types/node/v10/buffer.d.ts create mode 100644 types/node/v10/child_process.d.ts create mode 100644 types/node/v10/cluster.d.ts create mode 100644 types/node/v10/console.d.ts create mode 100644 types/node/v10/constants.d.ts create mode 100644 types/node/v10/crypto.d.ts create mode 100644 types/node/v10/dgram.d.ts create mode 100644 types/node/v10/dns.d.ts create mode 100644 types/node/v10/domain.d.ts create mode 100644 types/node/v10/events.d.ts create mode 100644 types/node/v10/fs.d.ts create mode 100644 types/node/v10/globals.d.ts create mode 100644 types/node/v10/http.d.ts create mode 100644 types/node/v10/http2.d.ts create mode 100644 types/node/v10/https.d.ts create mode 100644 types/node/v10/index.d.ts create mode 100644 types/node/v10/inspector.d.ts create mode 100644 types/node/v10/module.d.ts create mode 100644 types/node/v10/net.d.ts create mode 100644 types/node/v10/node-tests.ts create mode 100644 types/node/v10/os.d.ts create mode 100644 types/node/v10/package.json create mode 100644 types/node/v10/path.d.ts create mode 100644 types/node/v10/perf_hooks.d.ts create mode 100644 types/node/v10/process.d.ts create mode 100644 types/node/v10/punycode.d.ts create mode 100644 types/node/v10/querystring.d.ts create mode 100644 types/node/v10/readline.d.ts create mode 100644 types/node/v10/repl.d.ts create mode 100644 types/node/v10/stream.d.ts create mode 100644 types/node/v10/string_decoder.d.ts create mode 100644 types/node/v10/timers.d.ts create mode 100644 types/node/v10/tls.d.ts create mode 100644 types/node/v10/trace_events.d.ts create mode 100644 types/node/v10/ts3.1/index.d.ts create mode 100644 types/node/v10/ts3.1/node-tests.ts create mode 100644 types/node/v10/ts3.1/tsconfig.json create mode 100644 types/node/v10/ts3.1/tslint.json create mode 100644 types/node/v10/ts3.1/util.d.ts create mode 100644 types/node/v10/tsconfig.json create mode 100644 types/node/v10/tslint.json create mode 100644 types/node/v10/tty.d.ts create mode 100644 types/node/v10/url.d.ts create mode 100644 types/node/v10/util.d.ts create mode 100644 types/node/v10/v8.d.ts create mode 100644 types/node/v10/vm.d.ts create mode 100644 types/node/v10/worker_threads.d.ts create mode 100644 types/node/v10/zlib.d.ts diff --git a/types/node/child_process.d.ts b/types/node/child_process.d.ts index c8d20b8249..58a10d6916 100644 --- a/types/node/child_process.d.ts +++ b/types/node/child_process.d.ts @@ -77,32 +77,34 @@ declare module "child_process" { type StdioOptions = "pipe" | "ignore" | "inherit" | Array<("pipe" | "ipc" | "ignore" | "inherit" | stream.Stream | number | null | undefined)>; - interface SpawnOptions { + interface CommonOptions { + /** + * @default true + */ + windowsHide?: boolean; + uid?: number; + gid?: number; cwd?: string; env?: NodeJS.ProcessEnv; + } + + interface SpawnOptions extends CommonOptions { argv0?: string; stdio?: StdioOptions; detached?: boolean; - uid?: number; - gid?: number; shell?: boolean | string; windowsVerbatimArguments?: boolean; - windowsHide?: boolean; } function spawn(command: string, options?: SpawnOptions): ChildProcess; function spawn(command: string, args?: ReadonlyArray<string>, options?: SpawnOptions): ChildProcess; - interface ExecOptions { - cwd?: string; + interface ExecOptions extends CommonOptions { env?: NodeJS.ProcessEnv; shell?: string; timeout?: number; maxBuffer?: number; killSignal?: string; - uid?: number; - gid?: number; - windowsHide?: boolean; } interface ExecOptionsWithStringEncoding extends ExecOptions { @@ -152,15 +154,10 @@ declare module "child_process" { function __promisify__(command: string, options?: ({ encoding?: string | null } & ExecOptions) | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; } - interface ExecFileOptions { - cwd?: string; - env?: NodeJS.ProcessEnv; + interface ExecFileOptions extends CommonOptions { timeout?: number; maxBuffer?: number; killSignal?: string; - uid?: number; - gid?: number; - windowsHide?: boolean; windowsVerbatimArguments?: boolean; } interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { @@ -264,21 +261,16 @@ declare module "child_process" { } function fork(modulePath: string, args?: ReadonlyArray<string>, options?: ForkOptions): ChildProcess; - interface SpawnSyncOptions { + interface SpawnSyncOptions extends CommonOptions { argv0?: string; // Not specified in the docs - cwd?: string; input?: string | Buffer | NodeJS.TypedArray | DataView; stdio?: StdioOptions; - env?: NodeJS.ProcessEnv; - uid?: number; - gid?: number; timeout?: number; killSignal?: string | number; maxBuffer?: number; encoding?: string; shell?: boolean | string; windowsVerbatimArguments?: boolean; - windowsHide?: boolean; } interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { encoding: BufferEncoding; @@ -303,19 +295,14 @@ declare module "child_process" { function spawnSync(command: string, args?: ReadonlyArray<string>, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>; function spawnSync(command: string, args?: ReadonlyArray<string>, options?: SpawnSyncOptions): SpawnSyncReturns<Buffer>; - interface ExecSyncOptions { - cwd?: string; + interface ExecSyncOptions extends CommonOptions { input?: string | Buffer | Uint8Array; stdio?: StdioOptions; - env?: NodeJS.ProcessEnv; shell?: string; - uid?: number; - gid?: number; timeout?: number; killSignal?: string | number; maxBuffer?: number; encoding?: string; - windowsHide?: boolean; } interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { encoding: BufferEncoding; @@ -333,13 +320,11 @@ declare module "child_process" { input?: string | Buffer | NodeJS.TypedArray | DataView; stdio?: StdioOptions; env?: NodeJS.ProcessEnv; - uid?: number; - gid?: number; timeout?: number; killSignal?: string | number; maxBuffer?: number; encoding?: string; - windowsHide?: boolean; + shell?: boolean | string; } interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { diff --git a/types/node/cluster.d.ts b/types/node/cluster.d.ts index 2bfe353140..f089a41ebb 100644 --- a/types/node/cluster.d.ts +++ b/types/node/cluster.d.ts @@ -24,7 +24,6 @@ declare module "cluster" { class Worker extends events.EventEmitter { id: number; process: child.ChildProcess; - suicide: boolean; send(message: any, sendHandle?: any, callback?: (error: Error) => void): boolean; kill(signal?: string): void; destroy(signal?: string): void; diff --git a/types/node/crypto.d.ts b/types/node/crypto.d.ts index 0d37716a7e..e482f2014b 100644 --- a/types/node/crypto.d.ts +++ b/types/node/crypto.d.ts @@ -14,17 +14,7 @@ declare module "crypto" { /** @deprecated since v10.0.0 */ const fips: boolean; - interface CredentialDetails { - pfx: string; - key: string; - passphrase: string; - cert: string; - ca: string | string[]; - crl: string | string[]; - ciphers: string; - } interface Credentials { context?: any; } - function createCredentials(details: CredentialDetails): Credentials; function createHash(algorithm: string, options?: stream.TransformOptions): Hash; function createHmac(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Hmac; @@ -164,7 +154,13 @@ declare module "crypto" { getPublicKey(encoding: HexBase64Latin1Encoding): string; getPrivateKey(): Buffer; getPrivateKey(encoding: HexBase64Latin1Encoding): string; + /** + * @deprecated + */ setPublicKey(public_key: Buffer | NodeJS.TypedArray | DataView): void; + /** + * @deprecated + */ setPublicKey(public_key: string, encoding: string): void; setPrivateKey(private_key: Buffer | NodeJS.TypedArray | DataView): void; setPrivateKey(private_key: string, encoding: string): void; diff --git a/types/node/dgram.d.ts b/types/node/dgram.d.ts index 48049b47b8..93759406c7 100644 --- a/types/node/dgram.d.ts +++ b/types/node/dgram.d.ts @@ -5,8 +5,9 @@ declare module "dgram" { interface RemoteInfo { address: string; - family: string; + family: 'IPv4' | 'IPv6'; port: number; + size: number; } interface BindOptions { @@ -20,6 +21,10 @@ declare module "dgram" { interface SocketOptions { type: SocketType; reuseAddr?: boolean; + /** + * @default false + */ + ipv6Only?: boolean; recvBufferSize?: number; sendBufferSize?: number; lookup?: (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void) => void; @@ -62,36 +67,36 @@ declare module "dgram" { addListener(event: "close", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "listening", listener: () => void): this; - addListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "close"): boolean; emit(event: "error", err: Error): boolean; emit(event: "listening"): boolean; - emit(event: "message", msg: Buffer, rinfo: AddressInfo): boolean; + emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "listening", listener: () => void): this; - on(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; once(event: "listening", listener: () => void): this; - once(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "listening", listener: () => void): this; - prependListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: "listening", listener: () => void): this; - prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; } } diff --git a/types/node/fs.d.ts b/types/node/fs.d.ts index e3718475e5..a807c55617 100644 --- a/types/node/fs.d.ts +++ b/types/node/fs.d.ts @@ -275,6 +275,7 @@ declare module "fs" { /** * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @deprecated */ function lchown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; @@ -290,6 +291,7 @@ declare module "fs" { /** * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @deprecated */ function lchownSync(path: PathLike, uid: number, gid: number): void; @@ -1165,7 +1167,7 @@ declare module "fs" { offset: number, length: number, position: number | null, - callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void, + callback: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void, ): void; // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. diff --git a/types/node/globals.d.ts b/types/node/globals.d.ts index 0c4215fe7b..0ddc200312 100644 --- a/types/node/globals.d.ts +++ b/types/node/globals.d.ts @@ -181,6 +181,11 @@ declare namespace setImmediate { } declare function clearImmediate(immediateId: NodeJS.Immediate): void; +/** + * @experimental + */ +declare function queueMicrotask(callback: () => void): void; + // TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. interface NodeRequireFunction { /* tslint:disable-next-line:callable-types */ @@ -190,6 +195,9 @@ interface NodeRequireFunction { interface NodeRequire extends NodeRequireFunction { resolve: RequireResolve; cache: any; + /** + * @deprecated + */ extensions: NodeExtensions; main: NodeModule | undefined; } @@ -245,45 +253,45 @@ interface Buffer extends Uint8Array { compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; slice(start?: number, end?: number): Buffer; - writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; - readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; - readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; - readUInt8(offset: number, noAssert?: boolean): number; - readUInt16LE(offset: number, noAssert?: boolean): number; - readUInt16BE(offset: number, noAssert?: boolean): number; - readUInt32LE(offset: number, noAssert?: boolean): number; - readUInt32BE(offset: number, noAssert?: boolean): number; - readInt8(offset: number, noAssert?: boolean): number; - readInt16LE(offset: number, noAssert?: boolean): number; - readInt16BE(offset: number, noAssert?: boolean): number; - readInt32LE(offset: number, noAssert?: boolean): number; - readInt32BE(offset: number, noAssert?: boolean): number; - readFloatLE(offset: number, noAssert?: boolean): number; - readFloatBE(offset: number, noAssert?: boolean): number; - readDoubleLE(offset: number, noAssert?: boolean): number; - readDoubleBE(offset: number, noAssert?: boolean): number; + writeUIntLE(value: number, offset: number, byteLength: number): number; + writeUIntBE(value: number, offset: number, byteLength: number): number; + writeIntLE(value: number, offset: number, byteLength: number): number; + writeIntBE(value: number, offset: number, byteLength: number): number; + readUIntLE(offset: number, byteLength: number): number; + readUIntBE(offset: number, byteLength: number): number; + readIntLE(offset: number, byteLength: number): number; + readIntBE(offset: number, byteLength: number): number; + readUInt8(offset: number): number; + readUInt16LE(offset: number): number; + readUInt16BE(offset: number): number; + readUInt32LE(offset: number): number; + readUInt32BE(offset: number): number; + readInt8(offset: number): number; + readInt16LE(offset: number): number; + readInt16BE(offset: number): number; + readInt32LE(offset: number): number; + readInt32BE(offset: number): number; + readFloatLE(offset: number): number; + readFloatBE(offset: number): number; + readDoubleLE(offset: number): number; + readDoubleBE(offset: number): number; swap16(): Buffer; swap32(): Buffer; swap64(): Buffer; - writeUInt8(value: number, offset: number, noAssert?: boolean): number; - writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeInt8(value: number, offset: number, noAssert?: boolean): number; - writeInt16LE(value: number, offset: number, noAssert?: boolean): number; - writeInt16BE(value: number, offset: number, noAssert?: boolean): number; - writeInt32LE(value: number, offset: number, noAssert?: boolean): number; - writeInt32BE(value: number, offset: number, noAssert?: boolean): number; - writeFloatLE(value: number, offset: number, noAssert?: boolean): number; - writeFloatBE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; - writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + writeUInt8(value: number, offset: number): number; + writeUInt16LE(value: number, offset: number): number; + writeUInt16BE(value: number, offset: number): number; + writeUInt32LE(value: number, offset: number): number; + writeUInt32BE(value: number, offset: number): number; + writeInt8(value: number, offset: number): number; + writeInt16LE(value: number, offset: number): number; + writeInt16BE(value: number, offset: number): number; + writeInt32LE(value: number, offset: number): number; + writeInt32BE(value: number, offset: number): number; + writeFloatLE(value: number, offset: number): number; + writeFloatBE(value: number, offset: number): number; + writeDoubleLE(value: number, offset: number): number; + writeDoubleBE(value: number, offset: number): number; fill(value: any, offset?: number, end?: number): this; indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; @@ -444,7 +452,19 @@ declare const Buffer: { *-----------------------------------------------*/ declare namespace NodeJS { interface InspectOptions { + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default `false` + */ + getters?: 'get' | 'set' | boolean; showHidden?: boolean; + /** + * @default 2 + */ depth?: number | null; colors?: boolean; customInspect?: boolean; @@ -460,6 +480,7 @@ declare namespace NodeJS { stderr?: WritableStream; ignoreErrors?: boolean; colorMode?: boolean | 'auto'; + inspectOptions?: InspectOptions; } interface ConsoleConstructor { @@ -707,7 +728,13 @@ declare namespace NodeJS { } interface Process extends EventEmitter { + /** + * Can also be a tty.WriteStream, not typed due to limitation.s + */ stdout: WriteStream; + /** + * Can also be a tty.WriteStream, not typed due to limitation.s + */ stderr: WriteStream; stdin: ReadStream; openStdin(): Socket; @@ -774,6 +801,9 @@ declare namespace NodeJS { cpuUsage(previousValue?: CpuUsage): CpuUsage; nextTick(callback: Function, ...args: any[]): void; release: ProcessRelease; + /** + * Can only be set if not in worker thread. + */ umask(mask?: number): number; uptime(): number; hrtime(time?: [number, number]): [number, number]; @@ -957,6 +987,7 @@ declare namespace NodeJS { setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => Immediate; setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + queueMicrotask: typeof queueMicrotask; undefined: typeof undefined; unescape: (str: string) => string; gc: () => void; diff --git a/types/node/http.d.ts b/types/node/http.d.ts index e5f3741003..d5a3943d6a 100644 --- a/types/node/http.d.ts +++ b/types/node/http.d.ts @@ -95,6 +95,11 @@ declare module "http" { setTimeout(callback: () => void): this; maxHeadersCount: number; timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP headers. + * @default 40000 + */ + headersTimeout: number; keepAliveTimeout: number; } @@ -244,4 +249,10 @@ declare module "http" { function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; let globalAgent: Agent; + + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 8KB. Configurable using the [`--max-http-header-size`][] CLI option. + */ + const maxHeaderSize: number; } diff --git a/types/node/index.d.ts b/types/node/index.d.ts index a237502039..d5372b4594 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Node.js 10.12 +// Type definitions for Node.js 11.6 // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript <https://github.com/Microsoft> // DefinitelyTyped <https://github.com/DefinitelyTyped> diff --git a/types/node/net.d.ts b/types/node/net.d.ts index 27804375aa..33858de8df 100644 --- a/types/node/net.d.ts +++ b/types/node/net.d.ts @@ -158,6 +158,10 @@ declare module "net" { exclusive?: boolean; readableAll?: boolean; writableAll?: boolean; + /** + * @default false + */ + ipv6Only?: boolean; } // https://github.com/nodejs/node/blob/master/lib/net.js @@ -175,7 +179,7 @@ declare module "net" { listen(handle: any, backlog?: number, listeningListener?: Function): this; listen(handle: any, listeningListener?: Function): this; close(callback?: Function): this; - address(): AddressInfo | string; + address(): AddressInfo | string | null; getConnections(cb: (error: Error | null, count: number) => void): void; ref(): this; unref(): this; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 220de8ca8a..f257f89879 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -11,13 +11,10 @@ import * as http from "http"; import * as https from "https"; import * as net from "net"; import * as tty from "tty"; -import * as dgram from "dgram"; import * as querystring from "querystring"; import * as path from "path"; -import * as readline from "readline"; import * as childProcess from "child_process"; import * as cluster from "cluster"; -import * as workerThreads from "worker_threads"; import * as os from "os"; import * as vm from "vm"; import * as console2 from "console"; @@ -37,19 +34,6 @@ import Module = require("module"); // Specifically test buffer module regression. import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buffer"; -////////////////////////////////////////////////////////// -/// Global Tests : https://nodejs.org/api/global.html /// -////////////////////////////////////////////////////////// -{ - { - const x: NodeModule = {} as any; - const y: NodeModule = {} as any; - x.children.push(y); - x.parent = require.main; - require.main = y; - } -} - ////////////////////////////////////////////////////////// /// Assert Tests : https://nodejs.org/api/assert.html /// ////////////////////////////////////////////////////////// @@ -785,176 +769,6 @@ function bufferTests() { } } -///////////////////////////////////////////////////// -/// util tests : https://nodejs.org/api/util.html /// -///////////////////////////////////////////////////// - -{ - { - // Old and new util.inspect APIs - util.inspect(["This is nice"], false, 5); - util.inspect(["This is nice"], false, null); - util.inspect(["This is nice"], { - colors: true, - depth: 5, - customInspect: false, - showProxy: true, - maxArrayLength: 10, - breakLength: 20, - compact: true, - sorted(a, b) { - return b.localeCompare(a); - }, - }); - util.inspect(["This is nice"], { - colors: true, - depth: null, - customInspect: false, - showProxy: true, - maxArrayLength: null, - breakLength: Infinity, - compact: false, - sorted: true, - }); - assert(typeof util.inspect.custom === 'symbol'); - - util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); - - // util.callbackify - // tslint:disable-next-line no-unnecessary-class - class callbackifyTest { - static fn(): Promise<void> { - assert(arguments.length === 0); - - return Promise.resolve(); - } - - static fnE(): Promise<void> { - assert(arguments.length === 0); - - return Promise.reject(new Error('fail')); - } - - static fnT1(arg1: string): Promise<void> { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.resolve(); - } - - static fnT1E(arg1: string): Promise<void> { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.reject(new Error('fail')); - } - - static fnTResult(): Promise<string> { - assert(arguments.length === 0); - - return Promise.resolve('result'); - } - - static fnTResultE(): Promise<string> { - assert(arguments.length === 0); - - return Promise.reject(new Error('fail')); - } - - static fnT1TResult(arg1: string): Promise<string> { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.resolve('result'); - } - - static fnT1TResultE(arg1: string): Promise<string> { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.reject(new Error('fail')); - } - - static test(): void { - const cfn = util.callbackify(this.fn); - const cfnE = util.callbackify(this.fnE); - const cfnT1 = util.callbackify(this.fnT1); - const cfnT1E = util.callbackify(this.fnT1E); - const cfnTResult = util.callbackify(this.fnTResult); - const cfnTResultE = util.callbackify(this.fnTResultE); - const cfnT1TResult = util.callbackify(this.fnT1TResult); - const cfnT1TResultE = util.callbackify(this.fnT1TResultE); - - cfn((err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); - cfnE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - cfnT1('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); - cfnT1E('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - cfnTResult((err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === 'result')); - cfnTResultE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - cfnT1TResult('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === 'result')); - cfnT1TResultE('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); - } - } - callbackifyTest.test(); - - // util.promisify - const readPromised = util.promisify(fs.readFile); - const sampleRead: Promise<any> = readPromised(__filename).then((data: Buffer): void => { }).catch((error: Error): void => { }); - const arg0: () => Promise<number> = util.promisify((cb: (err: Error, result: number) => void): void => { }); - const arg0NoResult: () => Promise<any> = util.promisify((cb: (err: Error) => void): void => { }); - const arg1: (arg: string) => Promise<number> = util.promisify((arg: string, cb: (err: Error, result: number) => void): void => { }); - const arg1NoResult: (arg: string) => Promise<any> = util.promisify((arg: string, cb: (err: Error) => void): void => { }); - const cbOptionalError: () => Promise<void | {}> = util.promisify((cb: (err?: Error | null) => void): void => { cb(); }); // tslint:disable-line void-return - assert(typeof util.promisify.custom === 'symbol'); - // util.deprecate - const foo = () => {}; - // $ExpectType () => void - util.deprecate(foo, 'foo() is deprecated, use bar() instead'); - // $ExpectType <T extends Function>(fn: T, message: string) => T - util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead'); - - // util.isDeepStrictEqual - util.isDeepStrictEqual({foo: 'bar'}, {foo: 'bar'}); - - // util.TextDecoder() - const td = new util.TextDecoder(); - new util.TextDecoder("utf-8"); - new util.TextDecoder("utf-8", { fatal: true }); - new util.TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); - const ignoreBom: boolean = td.ignoreBOM; - const fatal: boolean = td.fatal; - const encoding: string = td.encoding; - td.decode(new Int8Array(1)); - td.decode(new Int16Array(1)); - td.decode(new Int32Array(1)); - td.decode(new Uint8Array(1)); - td.decode(new Uint16Array(1)); - td.decode(new Uint32Array(1)); - td.decode(new Uint8ClampedArray(1)); - td.decode(new Float32Array(1)); - td.decode(new Float64Array(1)); - td.decode(new DataView(new Int8Array(1).buffer)); - td.decode(new ArrayBuffer(1)); - td.decode(null); - td.decode(null, { stream: true }); - td.decode(new Int8Array(1), { stream: true }); - const decode: string = td.decode(new Int8Array(1)); - - // util.TextEncoder() - const te = new util.TextEncoder(); - const teEncoding: string = te.encoding; - const teEncodeRes: Uint8Array = te.encode("TextEncoder"); - - // util.types - - // tslint:disable-next-line:no-construct ban-types - const maybeBoxed: number | Number = new Number(1); - if (util.types.isBoxedPrimitive(maybeBoxed)) { - const boxed: Number = maybeBoxed; - } - const maybeBoxed2: number | Number = 1; - if (!util.types.isBoxedPrimitive(maybeBoxed2)) { - const boxed: number = maybeBoxed2; - } - } -} - //////////////////////////////////////////////////// /// Stream tests : http://nodejs.org/api/stream.html //////////////////////////////////////////////////// @@ -1864,179 +1678,6 @@ async function asyncStreamPipelineFinished() { } } -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html /// -//////////////////////////////////////////////////// - -{ - // http Server - { - const server: http.Server = new http.Server(); - - // test public props - const maxHeadersCount: number = server.maxHeadersCount; - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } - - // http IncomingMessage - // http ServerResponse - { - // incoming - const incoming: http.IncomingMessage = new http.IncomingMessage(new net.Socket()); - - incoming.setEncoding('utf8'); - - // stream - incoming.pause(); - incoming.resume(); - - // response - const res: http.ServerResponse = new http.ServerResponse(incoming); - - // test headers - res.setHeader('Content-Type', 'text/plain'); - const bool: boolean = res.hasHeader('Content-Type'); - const headers: string[] = res.getHeaderNames(); - - // trailers - res.addTrailers([ - ['x-fOo', 'xOxOxOx'], - ['x-foO', 'OxOxOxO'], - ['X-fOo', 'xOxOxOx'], - ['X-foO', 'OxOxOxO'] - ]); - res.addTrailers({ 'x-foo': 'bar' }); - - // writeHead - res.writeHead(200, 'OK\r\nContent-Type: text/html\r\n'); - res.writeHead(200, { 'Transfer-Encoding': 'chunked' }); - res.writeHead(200); - - // write string - res.write('Part of my res.'); - // write buffer - const chunk = Buffer.alloc(16390, 'Й'); - res.write(chunk); - res.write(chunk, 'hex'); - - // end - res.end("end msg"); - // without msg - res.end(); - - // flush - res.flushHeaders(); - } - - // http ClientRequest - { - let req: http.ClientRequest = new http.ClientRequest("https://www.google.com"); - req = new http.ClientRequest(new url.URL("https://www.google.com")); - req = new http.ClientRequest({ path: 'http://0.0.0.0' }); - req = new http.ClientRequest({ setHost: false }); - - // header - req.setHeader('Content-Type', 'text/plain'); - const bool: boolean = req.hasHeader('Content-Type'); - const headers: string[] = req.getHeaderNames(); - req.removeHeader('Date'); - - // write - const chunk = Buffer.alloc(16390, 'Й'); - req.write(chunk); - req.write('a'); - req.end(); - - // abort - req.abort(); - - // connection - req.connection.on('pause', () => { }); - - // event - req.on('data', () => { }); - } - - { - // Status codes - let codeMessage: string = http.STATUS_CODES['400']; - codeMessage = http.STATUS_CODES[400]; - } - - { - let agent: http.Agent = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256, - timeout: 15000 - }); - - agent = http.globalAgent; - - http.request({ agent: false }); - http.request({ agent }); - http.request({ agent: undefined }); - } - - { - http.get('http://www.example.com/xyz'); - http.request('http://www.example.com/xyz'); - - http.get('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); - http.request('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); - - http.get(new url.URL('http://www.example.com/xyz')); - http.request(new url.URL('http://www.example.com/xyz')); - - http.get(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); - http.request(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); - - const opts: http.RequestOptions = { - path: '"/some/path' - }; - http.get(new url.URL('http://www.example.com'), opts); - http.request(new url.URL('http://www.example.com'), opts); - http.get(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); - http.request(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); - } - - { - // Make sure .listen() and .close() return a Server instance - http.createServer().listen(0).close().address(); - net.createServer().listen(0).close().address(); - } - - { - const request = http.request({ path: 'http://0.0.0.0' }); - request.once('error', () => { }); - request.setNoDelay(true); - request.abort(); - } - - // http request options - { - const requestOpts: http.RequestOptions = { - timeout: 30000 - }; - - const clientArgs: http.ClientRequestArgs = { - timeout: 30000 - }; - } - - // http headers - { - const headers: http.IncomingHttpHeaders = { - 'content-type': 'application/json', - 'set-cookie': [ 'type=ninja', 'language=javascript' ] - }; - } -} - ////////////////////////////////////////////////////// /// Https tests : http://nodejs.org/api/https.html /// ////////////////////////////////////////////////////// @@ -2112,117 +1753,6 @@ async function asyncStreamPipelineFinished() { const isTTY: boolean = tty.isatty(1); } -//////////////////////////////////////////////////// -/// Dgram tests : http://nodejs.org/api/dgram.html -//////////////////////////////////////////////////// - -{ - { - let ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { - }); - ds.bind(); - ds.bind(41234); - ds.bind(4123, 'localhost'); - ds.bind(4123, 'localhost', () => { }); - ds.bind(4123, () => { }); - ds.bind(() => { }); - const addr: net.AddressInfo | string = ds.address(); - ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { - }); - ds.send(new Buffer("hello"), 5000, "127.0.0.1"); - ds.setMulticastInterface("127.0.0.1"); - ds = dgram.createSocket({ type: "udp4", reuseAddr: true, recvBufferSize: 1000, sendBufferSize: 1000, lookup: dns.lookup }); - } - - { - let _socket: dgram.Socket; - let _boolean: boolean; - const _err: Error = new Error(); - const _str = ''; - const _rinfo: net.AddressInfo = { - address: 'asd', - family: 'asd', - port: 1, - }; - /** - * events.EventEmitter - * 1. close - * 2. error - * 3. listening - * 4. message - */ - - _socket = _socket.addListener("close", () => { }); - _socket = _socket.addListener("error", (err) => { - const _err: Error = err; - }); - _socket = _socket.addListener("listening", () => { }); - _socket = _socket.addListener("message", (msg, rinfo) => { - const _msg: Buffer = msg; - const _rinfo: net.AddressInfo = rinfo; - }); - - _boolean = _socket.emit("close"); - _boolean = _socket.emit("error", _err); - _boolean = _socket.emit("listening"); - _boolean = _socket.emit("message", _str, _rinfo); - - _socket = _socket.on("close", () => { }); - _socket = _socket.on("error", (err) => { - const _err: Error = err; - }); - _socket = _socket.on("listening", () => { }); - _socket = _socket.on("message", (msg, rinfo) => { - const _msg: Buffer = msg; - const _rinfo: net.AddressInfo = rinfo; - }); - - _socket = _socket.once("close", () => { }); - _socket = _socket.once("error", (err) => { - const _err: Error = err; - }); - _socket = _socket.once("listening", () => { }); - _socket = _socket.once("message", (msg, rinfo) => { - const _msg: Buffer = msg; - const _rinfo: net.AddressInfo = rinfo; - }); - - _socket = _socket.prependListener("close", () => { }); - _socket = _socket.prependListener("error", (err) => { - const _err: Error = err; - }); - _socket = _socket.prependListener("listening", () => { }); - _socket = _socket.prependListener("message", (msg, rinfo) => { - const _msg: Buffer = msg; - const _rinfo: net.AddressInfo = rinfo; - }); - - _socket = _socket.prependOnceListener("close", () => { }); - _socket = _socket.prependOnceListener("error", (err) => { - const _err: Error = err; - }); - _socket = _socket.prependOnceListener("listening", () => { }); - _socket = _socket.prependOnceListener("message", (msg, rinfo) => { - const _msg: Buffer = msg; - const _rinfo: net.AddressInfo = rinfo; - }); - } - - { - const ds: dgram.Socket = dgram.createSocket({ - type: 'udp4', - recvBufferSize: 10000, - sendBufferSize: 15000 - }); - - let size: number; - size = ds.getRecvBufferSize(); - ds.setRecvBufferSize(size); - size = ds.getSendBufferSize(); - ds.setSendBufferSize(size); - } -} - //////////////////////////////////////////////////// /// Querystring tests : https://nodejs.org/api/querystring.html //////////////////////////////////////////////////// @@ -2438,180 +1968,6 @@ async function asyncStreamPipelineFinished() { // 'C:\home\user\dir\file.txt' } -//////////////////////////////////////////////////// -/// readline tests : https://nodejs.org/api/readline.html -//////////////////////////////////////////////////// - -{ - const rl: readline.ReadLine = readline.createInterface(new stream.Readable()); - - { - const options: readline.ReadLineOptions = { - input: new fs.ReadStream() - }; - const input: NodeJS.ReadableStream = new stream.Readable(); - const output: NodeJS.WritableStream = new stream.Writable(); - const completer: readline.Completer = str => [['asd'], 'asd']; - const terminal = false; - - let result: readline.ReadLine; - - result = readline.createInterface(options); - result = readline.createInterface(input); - result = readline.createInterface(input, output); - result = readline.createInterface(input, output, completer); - result = readline.createInterface(input, output, completer, terminal); - result = readline.createInterface({ - input, - completer(str: string): readline.CompleterResult { - return [['test'], 'test']; - } - }); - result = readline.createInterface({ - input, - completer(str: string, callback: (err: any, result: readline.CompleterResult) => void): any { - callback(null, [['test'], 'test']); - } - }); - } - - { - rl.setPrompt("prompt"); - } - - { - rl.prompt(); - rl.prompt(true); - } - - { - rl.question("query", (answer: string) => {}); - } - - { - let result: readline.ReadLine; - - result = rl.pause(); - } - - { - let result: readline.ReadLine; - - result = rl.resume(); - } - - { - rl.close(); - } - - { - const data: string | Buffer = "asd"; - const key: readline.Key = {}; - - rl.write(data); - rl.write(null, key); - } - - { - const strm: NodeJS.WritableStream = new stream.Writable(); - const x = 1; - const y = 1; - - readline.cursorTo(strm, x); - readline.cursorTo(strm, x, y); - } - - { - const strm: NodeJS.ReadableStream = new stream.Readable(); - const readLineInterface: readline.ReadLine = readline.createInterface(new stream.Readable()); - - readline.emitKeypressEvents(strm); - readline.emitKeypressEvents(strm, readLineInterface); - } - - { - const strm: NodeJS.WritableStream = new stream.Writable(); - const dx: number | string = 1; - const dy: number | string = 1; - - readline.moveCursor(strm, dx, dy); - } - - { - const strm: NodeJS.WritableStream = new stream.Writable(); - readline.clearLine(strm, 1); - } - - { - const strm: NodeJS.WritableStream = new stream.Writable(); - - readline.clearScreenDown(strm); - } - - { - let _rl: readline.ReadLine; - let _boolean: boolean; - - _rl = _rl.addListener("close", () => { }); - _rl = _rl.addListener("line", (input) => { - const _input: any = input; - }); - _rl = _rl.addListener("pause", () => { }); - _rl = _rl.addListener("resume", () => { }); - _rl = _rl.addListener("SIGCONT", () => { }); - _rl = _rl.addListener("SIGINT", () => { }); - _rl = _rl.addListener("SIGTSTP", () => { }); - - _boolean = _rl.emit("close", () => { }); - _boolean = _rl.emit("line", () => { }); - _boolean = _rl.emit("pause", () => { }); - _boolean = _rl.emit("resume", () => { }); - _boolean = _rl.emit("SIGCONT", () => { }); - _boolean = _rl.emit("SIGINT", () => { }); - _boolean = _rl.emit("SIGTSTP", () => { }); - - _rl = _rl.on("close", () => { }); - _rl = _rl.on("line", (input) => { - const _input: any = input; - }); - _rl = _rl.on("pause", () => { }); - _rl = _rl.on("resume", () => { }); - _rl = _rl.on("SIGCONT", () => { }); - _rl = _rl.on("SIGINT", () => { }); - _rl = _rl.on("SIGTSTP", () => { }); - - _rl = _rl.once("close", () => { }); - _rl = _rl.once("line", (input) => { - const _input: any = input; - }); - _rl = _rl.once("pause", () => { }); - _rl = _rl.once("resume", () => { }); - _rl = _rl.once("SIGCONT", () => { }); - _rl = _rl.once("SIGINT", () => { }); - _rl = _rl.once("SIGTSTP", () => { }); - - _rl = _rl.prependListener("close", () => { }); - _rl = _rl.prependListener("line", (input) => { - const _input: any = input; - }); - _rl = _rl.prependListener("pause", () => { }); - _rl = _rl.prependListener("resume", () => { }); - _rl = _rl.prependListener("SIGCONT", () => { }); - _rl = _rl.prependListener("SIGINT", () => { }); - _rl = _rl.prependListener("SIGTSTP", () => { }); - - _rl = _rl.prependOnceListener("close", () => { }); - _rl = _rl.prependOnceListener("line", (input) => { - const _input: any = input; - }); - _rl = _rl.prependOnceListener("pause", () => { }); - _rl = _rl.prependOnceListener("resume", () => { }); - _rl = _rl.prependOnceListener("SIGCONT", () => { }); - _rl = _rl.prependOnceListener("SIGINT", () => { }); - _rl = _rl.prependOnceListener("SIGTSTP", () => { }); - } -} - //////////////////////////////////////////////////// /// string_decoder tests : https://nodejs.org/api/string_decoder.html //////////////////////////////////////////////////// @@ -2931,56 +2287,6 @@ async function asyncStreamPipelineFinished() { } } -////////////////////////////////////////////////////////////////////// -/// worker_threads tests: https://nodejs.org/api/worker_threads.html /// -////////////////////////////////////////////////////////////////////// - -{ - { - if (workerThreads.isMainThread) { - module.exports = async function parseJSAsync(script: string) { - return new Promise((resolve, reject) => { - const worker = new workerThreads.Worker(__filename, { - workerData: script - }); - worker.on('message', resolve); - worker.on('error', reject); - worker.on('exit', (code) => { - if (code !== 0) - reject(new Error(`Worker stopped with exit code ${code}`)); - }); - }); - }; - } else { - const script = workerThreads.workerData; - workerThreads.parentPort.postMessage(script); - } - } - - { - const { port1, port2 } = new workerThreads.MessageChannel(); - port1.on('message', (message) => console.log('received', message)); - port2.postMessage({ foo: 'bar' }); - } - - { - if (workerThreads.isMainThread) { - const worker = new workerThreads.Worker(__filename); - const subChannel = new workerThreads.MessageChannel(); - worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]); - subChannel.port2.on('message', (value) => { - console.log('received:', value); - }); - } else { - workerThreads.parentPort.once('message', (value) => { - assert(value.hereIsYourPort instanceof MessagePort); - value.hereIsYourPort.postMessage('the worker is sending this'); - value.hereIsYourPort.close(); - }); - } - } -} - //////////////////////////////////////////////////// /// os tests : https://nodejs.org/api/os.html //////////////////////////////////////////////////// @@ -3427,299 +2733,6 @@ import * as p from "process"; } } -/////////////////////////////////////////////////// -/// Net Tests : https://nodejs.org/api/net.html /// -/////////////////////////////////////////////////// - -{ - { - const connectOpts: net.NetConnectOpts = { - allowHalfOpen: true, - family: 4, - host: "localhost", - port: 443, - timeout: 10E3 - }; - const socket: net.Socket = net.createConnection(connectOpts, (): void => { - // nothing - }); - } - - { - let server = net.createServer(); - // Check methods which return server instances by chaining calls - server = server.listen(0) - .close() - .ref() - .unref(); - - // close has an optional callback function. No callback parameters are - // specified, so any callback function is permissible. - server = server.close((...args: any[]) => { }); - - // test the types of the address object fields - const address: net.AddressInfo | string = server.address(); - } - - { - const constructorOpts: net.SocketConstructorOpts = { - fd: 1, - allowHalfOpen: false, - readable: false, - writable: false - }; - - /** - * net.Socket - events.EventEmitter - * 1. close - * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. timeout - */ - let _socket: net.Socket = new net.Socket(constructorOpts); - - let bool: boolean; - let buffer: Buffer; - let error: Error; - let str: string; - let num: number; - - const ipcConnectOpts: net.IpcSocketConnectOpts = { - path: "/" - }; - const tcpConnectOpts: net.TcpSocketConnectOpts = { - family: 4, - hints: 0, - host: "localhost", - localAddress: "10.0.0.1", - localPort: 1234, - lookup: (_hostname: string, _options: dns.LookupOneOptions, _callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void => { - // nothing - }, - port: 80 - }; - _socket = _socket.connect(ipcConnectOpts); - _socket = _socket.connect(ipcConnectOpts, (): void => {}); - _socket = _socket.connect(tcpConnectOpts); - _socket = _socket.connect(tcpConnectOpts, (): void => {}); - _socket = _socket.connect(80, "localhost"); - _socket = _socket.connect(80, "localhost", (): void => {}); - _socket = _socket.connect(80); - _socket = _socket.connect(80, (): void => {}); - - /// addListener - - _socket = _socket.addListener("close", had_error => { - bool = had_error; - }); - _socket = _socket.addListener("connect", () => { }); - _socket = _socket.addListener("data", data => { - buffer = data; - }); - _socket = _socket.addListener("drain", () => { }); - _socket = _socket.addListener("end", () => { }); - _socket = _socket.addListener("error", err => { - error = err; - }); - _socket = _socket.addListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.addListener("timeout", () => { }); - - /// emit - bool = _socket.emit("close", bool); - bool = _socket.emit("connect"); - bool = _socket.emit("data", buffer); - bool = _socket.emit("drain"); - bool = _socket.emit("end"); - bool = _socket.emit("error", error); - bool = _socket.emit("lookup", error, str, str, str); - bool = _socket.emit("lookup", error, str, num, str); - bool = _socket.emit("timeout"); - - /// on - _socket = _socket.on("close", had_error => { - bool = had_error; - }); - _socket = _socket.on("connect", () => { }); - _socket = _socket.on("data", data => { - buffer = data; - }); - _socket = _socket.on("drain", () => { }); - _socket = _socket.on("end", () => { }); - _socket = _socket.on("error", err => { - error = err; - }); - _socket = _socket.on("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.on("timeout", () => { }); - - /// once - _socket = _socket.once("close", had_error => { - bool = had_error; - }); - _socket = _socket.once("connect", () => { }); - _socket = _socket.once("data", data => { - buffer = data; - }); - _socket = _socket.once("drain", () => { }); - _socket = _socket.once("end", () => { }); - _socket = _socket.once("error", err => { - error = err; - }); - _socket = _socket.once("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.once("timeout", () => { }); - - /// prependListener - _socket = _socket.prependListener("close", had_error => { - bool = had_error; - }); - _socket = _socket.prependListener("connect", () => { }); - _socket = _socket.prependListener("data", data => { - buffer = data; - }); - _socket = _socket.prependListener("drain", () => { }); - _socket = _socket.prependListener("end", () => { }); - _socket = _socket.prependListener("error", err => { - error = err; - }); - _socket = _socket.prependListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.prependListener("timeout", () => { }); - - /// prependOnceListener - _socket = _socket.prependOnceListener("close", had_error => { - bool = had_error; - }); - _socket = _socket.prependOnceListener("connect", () => { }); - _socket = _socket.prependOnceListener("data", data => { - buffer = data; - }); - _socket = _socket.prependOnceListener("drain", () => { }); - _socket = _socket.prependOnceListener("end", () => { }); - _socket = _socket.prependOnceListener("error", err => { - error = err; - }); - _socket = _socket.prependOnceListener("lookup", (err, address, family, host) => { - error = err; - - if (typeof family === 'string') { - str = family; - } else if (typeof family === 'number') { - num = family; - } - - str = host; - }); - _socket = _socket.prependOnceListener("timeout", () => { }); - - bool = _socket.connecting; - bool = _socket.destroyed; - _socket.destroy(); - } - - { - /** - * net.Server - events.EventEmitter - * 1. close - * 2. connection - * 3. error - * 4. listening - */ - let _server: net.Server; - - let _socket: net.Socket; - let bool: boolean; - let error: Error; - - /// addListener - _server = _server.addListener("close", () => { }); - _server = _server.addListener("connection", socket => { - _socket = socket; - }); - _server = _server.addListener("error", err => { - error = err; - }); - _server = _server.addListener("listening", () => { }); - - /// emit - bool = _server.emit("close"); - bool = _server.emit("connection", _socket); - bool = _server.emit("error", error); - bool = _server.emit("listening"); - - /// once - _server = _server.once("close", () => { }); - _server = _server.once("connection", socket => { - _socket = socket; - }); - _server = _server.once("error", err => { - error = err; - }); - _server = _server.once("listening", () => { }); - - /// prependListener - _server = _server.prependListener("close", () => { }); - _server = _server.prependListener("connection", socket => { - _socket = socket; - }); - _server = _server.prependListener("error", err => { - error = err; - }); - _server = _server.prependListener("listening", () => { }); - - /// prependOnceListener - _server = _server.prependOnceListener("close", () => { }); - _server = _server.prependOnceListener("connection", socket => { - _socket = socket; - }); - _server = _server.prependOnceListener("error", err => { - error = err; - }); - _server = _server.prependOnceListener("listening", () => { }); - } -} - ///////////////////////////////////////////////////// /// repl Tests : https://nodejs.org/api/repl.html /// ///////////////////////////////////////////////////// diff --git a/types/node/readline.d.ts b/types/node/readline.d.ts index 9c25da4982..011cf7ad64 100644 --- a/types/node/readline.d.ts +++ b/types/node/readline.d.ts @@ -104,6 +104,7 @@ declare module "readline" { prependOnceListener(event: "SIGCONT", listener: () => void): this; prependOnceListener(event: "SIGINT", listener: () => void): this; prependOnceListener(event: "SIGTSTP", listener: () => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator<string>; } type ReadLine = Interface; // type forwarded for backwards compatiblity diff --git a/types/node/test/dgram.ts b/types/node/test/dgram.ts new file mode 100644 index 0000000000..5dfdae2b7b --- /dev/null +++ b/types/node/test/dgram.ts @@ -0,0 +1,108 @@ +import * as dgram from 'dgram'; +import * as net from 'net'; +import * as dns from 'dns'; + +{ + let ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { + }); + ds.bind(); + ds.bind(41234); + ds.bind(4123, 'localhost'); + ds.bind(4123, 'localhost', () => { }); + ds.bind(4123, () => { }); + ds.bind(() => { }); + const addr: net.AddressInfo | string = ds.address(); + ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { + }); + ds.send(new Buffer("hello"), 5000, "127.0.0.1"); + ds.setMulticastInterface("127.0.0.1"); + ds = dgram.createSocket({ type: "udp4", reuseAddr: true, recvBufferSize: 1000, sendBufferSize: 1000, lookup: dns.lookup }); +} + +{ + let _socket: dgram.Socket; + let _boolean: boolean; + const _err: Error = new Error(); + const _str = ''; + const _rinfo: net.AddressInfo = { + address: 'asd', + family: 'asd', + port: 1, + }; + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + */ + + _socket = _socket.addListener("close", () => { }); + _socket = _socket.addListener("error", (err) => { + const _err: Error = err; + }); + _socket = _socket.addListener("listening", () => { }); + _socket = _socket.addListener("message", (msg, rinfo) => { + const _msg: Buffer = msg; + const _rinfo: net.AddressInfo = rinfo; + }); + + _boolean = _socket.emit("close"); + _boolean = _socket.emit("error", _err); + _boolean = _socket.emit("listening"); + _boolean = _socket.emit("message", _str, _rinfo); + + _socket = _socket.on("close", () => { }); + _socket = _socket.on("error", (err) => { + const _err: Error = err; + }); + _socket = _socket.on("listening", () => { }); + _socket = _socket.on("message", (msg, rinfo) => { + const _msg: Buffer = msg; + const _rinfo: net.AddressInfo = rinfo; + }); + + _socket = _socket.once("close", () => { }); + _socket = _socket.once("error", (err) => { + const _err: Error = err; + }); + _socket = _socket.once("listening", () => { }); + _socket = _socket.once("message", (msg, rinfo) => { + const _msg: Buffer = msg; + const _rinfo: net.AddressInfo = rinfo; + }); + + _socket = _socket.prependListener("close", () => { }); + _socket = _socket.prependListener("error", (err) => { + const _err: Error = err; + }); + _socket = _socket.prependListener("listening", () => { }); + _socket = _socket.prependListener("message", (msg, rinfo) => { + const _msg: Buffer = msg; + const _rinfo: net.AddressInfo = rinfo; + }); + + _socket = _socket.prependOnceListener("close", () => { }); + _socket = _socket.prependOnceListener("error", (err) => { + const _err: Error = err; + }); + _socket = _socket.prependOnceListener("listening", () => { }); + _socket = _socket.prependOnceListener("message", (msg, rinfo) => { + const _msg: Buffer = msg; + const _rinfo: net.AddressInfo = rinfo; + }); +} + +{ + const ds: dgram.Socket = dgram.createSocket({ + type: 'udp4', + recvBufferSize: 10000, + sendBufferSize: 15000 + }); + + let size: number; + size = ds.getRecvBufferSize(); + ds.setRecvBufferSize(size); + size = ds.getSendBufferSize(); + ds.setSendBufferSize(size); +} diff --git a/types/node/test/global.ts b/types/node/test/global.ts new file mode 100644 index 0000000000..bc62d1dcb6 --- /dev/null +++ b/types/node/test/global.ts @@ -0,0 +1,17 @@ +{ + const x: NodeModule = {} as any; + const y: NodeModule = {} as any; + x.children.push(y); + x.parent = require.main; + require.main = y; +} + +{ + // const a = new TextEncoder(); +} + +{ + queueMicrotask(() => { + // cool + }); +} diff --git a/types/node/test/http.ts b/types/node/test/http.ts new file mode 100644 index 0000000000..199593b65b --- /dev/null +++ b/types/node/test/http.ts @@ -0,0 +1,175 @@ +import * as http from 'http'; +import * as url from 'url'; +import * as net from 'net'; + +// http Server +{ + const server: http.Server = new http.Server(); + + // test public props + const maxHeadersCount: number = server.maxHeadersCount; + const timeout: number = server.timeout; + const listening: boolean = server.listening; + const keepAliveTimeout: number = server.keepAliveTimeout; + server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); +} + +// http IncomingMessage +// http ServerResponse +{ + // incoming + const incoming: http.IncomingMessage = new http.IncomingMessage(new net.Socket()); + + incoming.setEncoding('utf8'); + + // stream + incoming.pause(); + incoming.resume(); + + // response + const res: http.ServerResponse = new http.ServerResponse(incoming); + + // test headers + res.setHeader('Content-Type', 'text/plain'); + const bool: boolean = res.hasHeader('Content-Type'); + const headers: string[] = res.getHeaderNames(); + + // trailers + res.addTrailers([ + ['x-fOo', 'xOxOxOx'], + ['x-foO', 'OxOxOxO'], + ['X-fOo', 'xOxOxOx'], + ['X-foO', 'OxOxOxO'] + ]); + res.addTrailers({ 'x-foo': 'bar' }); + + // writeHead + res.writeHead(200, 'OK\r\nContent-Type: text/html\r\n'); + res.writeHead(200, { 'Transfer-Encoding': 'chunked' }); + res.writeHead(200); + + // write string + res.write('Part of my res.'); + // write buffer + const chunk = Buffer.alloc(16390, 'Й'); + res.write(chunk); + res.write(chunk, 'hex'); + + // end + res.end("end msg"); + // without msg + res.end(); + + // flush + res.flushHeaders(); +} + +// http ClientRequest +{ + let req: http.ClientRequest = new http.ClientRequest("https://www.google.com"); + req = new http.ClientRequest(new url.URL("https://www.google.com")); + req = new http.ClientRequest({ path: 'http://0.0.0.0' }); + req = new http.ClientRequest({ setHost: false }); + + // header + req.setHeader('Content-Type', 'text/plain'); + const bool: boolean = req.hasHeader('Content-Type'); + const headers: string[] = req.getHeaderNames(); + req.removeHeader('Date'); + + // write + const chunk = Buffer.alloc(16390, 'Й'); + req.write(chunk); + req.write('a'); + req.end(); + + // abort + req.abort(); + + // connection + req.connection.on('pause', () => { }); + + // event + req.on('data', () => { }); +} + +{ + // Status codes + let codeMessage: string = http.STATUS_CODES['400']; + codeMessage = http.STATUS_CODES[400]; +} + +{ + let agent: http.Agent = new http.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256, + timeout: 15000 + }); + + agent = http.globalAgent; + + http.request({ agent: false }); + http.request({ agent }); + http.request({ agent: undefined }); +} + +{ + http.get('http://www.example.com/xyz'); + http.request('http://www.example.com/xyz'); + + http.get('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); + http.request('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); + + http.get(new url.URL('http://www.example.com/xyz')); + http.request(new url.URL('http://www.example.com/xyz')); + + http.get(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); + http.request(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); + + const opts: http.RequestOptions = { + path: '"/some/path' + }; + http.get(new url.URL('http://www.example.com'), opts); + http.request(new url.URL('http://www.example.com'), opts); + http.get(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); + http.request(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); +} + +{ + // Make sure .listen() and .close() return a Server instance + http.createServer().listen(0).close().address(); + net.createServer().listen(0).close().address(); +} + +{ + const request = http.request({ path: 'http://0.0.0.0' }); + request.once('error', () => { }); + request.setNoDelay(true); + request.abort(); +} + +// http request options +{ + const requestOpts: http.RequestOptions = { + timeout: 30000 + }; + + const clientArgs: http.ClientRequestArgs = { + timeout: 30000 + }; +} + +// http headers +{ + const headers: http.IncomingHttpHeaders = { + 'content-type': 'application/json', + 'set-cookie': [ 'type=ninja', 'language=javascript' ] + }; +} + +// statics +{ + const maxHeaderSize = http.maxHeaderSize; +} diff --git a/types/node/test/net.ts b/types/node/test/net.ts new file mode 100644 index 0000000000..709ad9b9c5 --- /dev/null +++ b/types/node/test/net.ts @@ -0,0 +1,293 @@ +import * as net from 'net'; +import { LookupOneOptions } from 'dns'; + +{ + const connectOpts: net.NetConnectOpts = { + allowHalfOpen: true, + family: 4, + host: "localhost", + port: 443, + timeout: 10E3 + }; + const socket: net.Socket = net.createConnection(connectOpts, (): void => { + // nothing + }); +} + +{ + let server = net.createServer(); + // Check methods which return server instances by chaining calls + server = server.listen(0) + .close() + .ref() + .unref(); + + server.listen({ + ipv6Only: true, + }); + + // close has an optional callback function. No callback parameters are + // specified, so any callback function is permissible. + server = server.close((...args: any[]) => { }); + + // test the types of the address object fields + const address: net.AddressInfo | string = server.address(); +} + +{ + const constructorOpts: net.SocketConstructorOpts = { + fd: 1, + allowHalfOpen: false, + readable: false, + writable: false, + }; + + /** + * net.Socket - events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + let _socket: net.Socket = new net.Socket(constructorOpts); + + let bool: boolean; + let buffer: Buffer; + let error: Error; + let str: string; + let num: number; + + const ipcConnectOpts: net.IpcSocketConnectOpts = { + path: "/" + }; + const tcpConnectOpts: net.TcpSocketConnectOpts = { + family: 4, + hints: 0, + host: "localhost", + localAddress: "10.0.0.1", + localPort: 1234, + lookup: (_hostname: string, _options: LookupOneOptions, _callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void => { + // nothing + }, + port: 80 + }; + _socket = _socket.connect(ipcConnectOpts); + _socket = _socket.connect(ipcConnectOpts, (): void => {}); + _socket = _socket.connect(tcpConnectOpts); + _socket = _socket.connect(tcpConnectOpts, (): void => {}); + _socket = _socket.connect(80, "localhost"); + _socket = _socket.connect(80, "localhost", (): void => {}); + _socket = _socket.connect(80); + _socket = _socket.connect(80, (): void => {}); + + /// addListener + + _socket = _socket.addListener("close", had_error => { + bool = had_error; + }); + _socket = _socket.addListener("connect", () => { }); + _socket = _socket.addListener("data", data => { + buffer = data; + }); + _socket = _socket.addListener("drain", () => { }); + _socket = _socket.addListener("end", () => { }); + _socket = _socket.addListener("error", err => { + error = err; + }); + _socket = _socket.addListener("lookup", (err, address, family, host) => { + error = err; + + if (typeof family === 'string') { + str = family; + } else if (typeof family === 'number') { + num = family; + } + + str = host; + }); + _socket = _socket.addListener("timeout", () => { }); + + /// emit + bool = _socket.emit("close", bool); + bool = _socket.emit("connect"); + bool = _socket.emit("data", buffer); + bool = _socket.emit("drain"); + bool = _socket.emit("end"); + bool = _socket.emit("error", error); + bool = _socket.emit("lookup", error, str, str, str); + bool = _socket.emit("lookup", error, str, num, str); + bool = _socket.emit("timeout"); + + /// on + _socket = _socket.on("close", had_error => { + bool = had_error; + }); + _socket = _socket.on("connect", () => { }); + _socket = _socket.on("data", data => { + buffer = data; + }); + _socket = _socket.on("drain", () => { }); + _socket = _socket.on("end", () => { }); + _socket = _socket.on("error", err => { + error = err; + }); + _socket = _socket.on("lookup", (err, address, family, host) => { + error = err; + + if (typeof family === 'string') { + str = family; + } else if (typeof family === 'number') { + num = family; + } + + str = host; + }); + _socket = _socket.on("timeout", () => { }); + + /// once + _socket = _socket.once("close", had_error => { + bool = had_error; + }); + _socket = _socket.once("connect", () => { }); + _socket = _socket.once("data", data => { + buffer = data; + }); + _socket = _socket.once("drain", () => { }); + _socket = _socket.once("end", () => { }); + _socket = _socket.once("error", err => { + error = err; + }); + _socket = _socket.once("lookup", (err, address, family, host) => { + error = err; + + if (typeof family === 'string') { + str = family; + } else if (typeof family === 'number') { + num = family; + } + + str = host; + }); + _socket = _socket.once("timeout", () => { }); + + /// prependListener + _socket = _socket.prependListener("close", had_error => { + bool = had_error; + }); + _socket = _socket.prependListener("connect", () => { }); + _socket = _socket.prependListener("data", data => { + buffer = data; + }); + _socket = _socket.prependListener("drain", () => { }); + _socket = _socket.prependListener("end", () => { }); + _socket = _socket.prependListener("error", err => { + error = err; + }); + _socket = _socket.prependListener("lookup", (err, address, family, host) => { + error = err; + + if (typeof family === 'string') { + str = family; + } else if (typeof family === 'number') { + num = family; + } + + str = host; + }); + _socket = _socket.prependListener("timeout", () => { }); + + /// prependOnceListener + _socket = _socket.prependOnceListener("close", had_error => { + bool = had_error; + }); + _socket = _socket.prependOnceListener("connect", () => { }); + _socket = _socket.prependOnceListener("data", data => { + buffer = data; + }); + _socket = _socket.prependOnceListener("drain", () => { }); + _socket = _socket.prependOnceListener("end", () => { }); + _socket = _socket.prependOnceListener("error", err => { + error = err; + }); + _socket = _socket.prependOnceListener("lookup", (err, address, family, host) => { + error = err; + + if (typeof family === 'string') { + str = family; + } else if (typeof family === 'number') { + num = family; + } + + str = host; + }); + _socket = _socket.prependOnceListener("timeout", () => { }); + + bool = _socket.connecting; + bool = _socket.destroyed; + _socket.destroy(); +} + +{ + /** + * net.Server - events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + let _server: net.Server; + + let _socket: net.Socket; + let bool: boolean; + let error: Error; + + /// addListener + _server = _server.addListener("close", () => { }); + _server = _server.addListener("connection", socket => { + _socket = socket; + }); + _server = _server.addListener("error", err => { + error = err; + }); + _server = _server.addListener("listening", () => { }); + + /// emit + bool = _server.emit("close"); + bool = _server.emit("connection", _socket); + bool = _server.emit("error", error); + bool = _server.emit("listening"); + + /// once + _server = _server.once("close", () => { }); + _server = _server.once("connection", socket => { + _socket = socket; + }); + _server = _server.once("error", err => { + error = err; + }); + _server = _server.once("listening", () => { }); + + /// prependListener + _server = _server.prependListener("close", () => { }); + _server = _server.prependListener("connection", socket => { + _socket = socket; + }); + _server = _server.prependListener("error", err => { + error = err; + }); + _server = _server.prependListener("listening", () => { }); + + /// prependOnceListener + _server = _server.prependOnceListener("close", () => { }); + _server = _server.prependOnceListener("connection", socket => { + _socket = socket; + }); + _server = _server.prependOnceListener("error", err => { + error = err; + }); + _server = _server.prependOnceListener("listening", () => { }); +} diff --git a/types/node/test/readline.ts b/types/node/test/readline.ts new file mode 100644 index 0000000000..5b92e170fe --- /dev/null +++ b/types/node/test/readline.ts @@ -0,0 +1,183 @@ +import * as readline from 'readline'; +import * as stream from 'stream'; +import * as fs from 'fs'; + +const rl: readline.ReadLine = readline.createInterface(new stream.Readable()); + +{ + const options: readline.ReadLineOptions = { + input: new fs.ReadStream() + }; + const input: NodeJS.ReadableStream = new stream.Readable(); + const output: NodeJS.WritableStream = new stream.Writable(); + const completer: readline.Completer = str => [['asd'], 'asd']; + const terminal = false; + + let result: readline.ReadLine; + + result = readline.createInterface(options); + result = readline.createInterface(input); + result = readline.createInterface(input, output); + result = readline.createInterface(input, output, completer); + result = readline.createInterface(input, output, completer, terminal); + result = readline.createInterface({ + input, + completer(str: string): readline.CompleterResult { + return [['test'], 'test']; + } + }); + result = readline.createInterface({ + input, + completer(str: string, callback: (err: any, result: readline.CompleterResult) => void): any { + callback(null, [['test'], 'test']); + } + }); +} + +{ + rl.setPrompt("prompt"); +} + +{ + rl.prompt(); + rl.prompt(true); +} + +{ + rl.question("query", (answer: string) => {}); +} + +{ + let result: readline.ReadLine; + + result = rl.pause(); +} + +{ + let result: readline.ReadLine; + + result = rl.resume(); +} + +{ + rl.close(); +} + +{ + const data: string | Buffer = "asd"; + const key: readline.Key = {}; + + rl.write(data); + rl.write(null, key); +} + +{ + const strm: NodeJS.WritableStream = new stream.Writable(); + const x = 1; + const y = 1; + + readline.cursorTo(strm, x); + readline.cursorTo(strm, x, y); +} + +{ + const strm: NodeJS.ReadableStream = new stream.Readable(); + const readLineInterface: readline.ReadLine = readline.createInterface(new stream.Readable()); + + readline.emitKeypressEvents(strm); + readline.emitKeypressEvents(strm, readLineInterface); +} + +{ + const strm: NodeJS.WritableStream = new stream.Writable(); + const dx: number | string = 1; + const dy: number | string = 1; + + readline.moveCursor(strm, dx, dy); +} + +{ + const strm: NodeJS.WritableStream = new stream.Writable(); + readline.clearLine(strm, 1); +} + +{ + const strm: NodeJS.WritableStream = new stream.Writable(); + + readline.clearScreenDown(strm); +} + +{ + let _rl: readline.ReadLine; + let _boolean: boolean; + + _rl = _rl.addListener("close", () => { }); + _rl = _rl.addListener("line", (input) => { + const _input: any = input; + }); + _rl = _rl.addListener("pause", () => { }); + _rl = _rl.addListener("resume", () => { }); + _rl = _rl.addListener("SIGCONT", () => { }); + _rl = _rl.addListener("SIGINT", () => { }); + _rl = _rl.addListener("SIGTSTP", () => { }); + + _boolean = _rl.emit("close", () => { }); + _boolean = _rl.emit("line", () => { }); + _boolean = _rl.emit("pause", () => { }); + _boolean = _rl.emit("resume", () => { }); + _boolean = _rl.emit("SIGCONT", () => { }); + _boolean = _rl.emit("SIGINT", () => { }); + _boolean = _rl.emit("SIGTSTP", () => { }); + + _rl = _rl.on("close", () => { }); + _rl = _rl.on("line", (input) => { + const _input: any = input; + }); + _rl = _rl.on("pause", () => { }); + _rl = _rl.on("resume", () => { }); + _rl = _rl.on("SIGCONT", () => { }); + _rl = _rl.on("SIGINT", () => { }); + _rl = _rl.on("SIGTSTP", () => { }); + + _rl = _rl.once("close", () => { }); + _rl = _rl.once("line", (input) => { + const _input: any = input; + }); + _rl = _rl.once("pause", () => { }); + _rl = _rl.once("resume", () => { }); + _rl = _rl.once("SIGCONT", () => { }); + _rl = _rl.once("SIGINT", () => { }); + _rl = _rl.once("SIGTSTP", () => { }); + + _rl = _rl.prependListener("close", () => { }); + _rl = _rl.prependListener("line", (input) => { + const _input: any = input; + }); + _rl = _rl.prependListener("pause", () => { }); + _rl = _rl.prependListener("resume", () => { }); + _rl = _rl.prependListener("SIGCONT", () => { }); + _rl = _rl.prependListener("SIGINT", () => { }); + _rl = _rl.prependListener("SIGTSTP", () => { }); + + _rl = _rl.prependOnceListener("close", () => { }); + _rl = _rl.prependOnceListener("line", (input) => { + const _input: any = input; + }); + _rl = _rl.prependOnceListener("pause", () => { }); + _rl = _rl.prependOnceListener("resume", () => { }); + _rl = _rl.prependOnceListener("SIGCONT", () => { }); + _rl = _rl.prependOnceListener("SIGINT", () => { }); + _rl = _rl.prependOnceListener("SIGTSTP", () => { }); +} + +{ + (async () => { + const result = readline.createInterface({ + input: process.stdin, + }); + // Pending lib upgrade + // for await (const line of result) { + // + // } + }); +} diff --git a/types/node/test/util.ts b/types/node/test/util.ts new file mode 100644 index 0000000000..252e8824ae --- /dev/null +++ b/types/node/test/util.ts @@ -0,0 +1,169 @@ +import * as util from 'util'; +import assert = require('assert'); +import { readFile } from 'fs'; + +{ + // Old and new util.inspect APIs + util.inspect(["This is nice"], false, 5); + util.inspect(["This is nice"], false, null); + util.inspect(["This is nice"], { + colors: true, + depth: 5, + customInspect: false, + showProxy: true, + maxArrayLength: 10, + breakLength: 20, + compact: true, + sorted(a, b) { + return b.localeCompare(a); + }, + getters: false, + }); + util.inspect(["This is nice"], { + colors: true, + depth: null, + customInspect: false, + showProxy: true, + maxArrayLength: null, + breakLength: Infinity, + compact: false, + sorted: true, + getters: 'set', + }); + assert(typeof util.inspect.custom === 'symbol'); + + util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + + // util.callbackify + // tslint:disable-next-line no-unnecessary-class + class callbackifyTest { + static fn(): Promise<void> { + assert(arguments.length === 0); + + return Promise.resolve(); + } + + static fnE(): Promise<void> { + assert(arguments.length === 0); + + return Promise.reject(new Error('fail')); + } + + static fnT1(arg1: string): Promise<void> { + assert(arguments.length === 1 && arg1 === 'parameter'); + + return Promise.resolve(); + } + + static fnT1E(arg1: string): Promise<void> { + assert(arguments.length === 1 && arg1 === 'parameter'); + + return Promise.reject(new Error('fail')); + } + + static fnTResult(): Promise<string> { + assert(arguments.length === 0); + + return Promise.resolve('result'); + } + + static fnTResultE(): Promise<string> { + assert(arguments.length === 0); + + return Promise.reject(new Error('fail')); + } + + static fnT1TResult(arg1: string): Promise<string> { + assert(arguments.length === 1 && arg1 === 'parameter'); + + return Promise.resolve('result'); + } + + static fnT1TResultE(arg1: string): Promise<string> { + assert(arguments.length === 1 && arg1 === 'parameter'); + + return Promise.reject(new Error('fail')); + } + + static test(): void { + const cfn = util.callbackify(this.fn); + const cfnE = util.callbackify(this.fnE); + const cfnT1 = util.callbackify(this.fnT1); + const cfnT1E = util.callbackify(this.fnT1E); + const cfnTResult = util.callbackify(this.fnTResult); + const cfnTResultE = util.callbackify(this.fnTResultE); + const cfnT1TResult = util.callbackify(this.fnT1TResult); + const cfnT1TResultE = util.callbackify(this.fnT1TResultE); + + cfn((err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); + cfnE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); + cfnT1('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); + cfnT1E('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); + cfnTResult((err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === 'result')); + cfnTResultE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); + cfnT1TResult('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === 'result')); + cfnT1TResultE('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); + } + } + callbackifyTest.test(); + + // util.promisify + const readPromised = util.promisify(readFile); + const sampleRead: Promise<any> = readPromised(__filename).then((data: Buffer): void => { }).catch((error: Error): void => { }); + const arg0: () => Promise<number> = util.promisify((cb: (err: Error, result: number) => void): void => { }); + const arg0NoResult: () => Promise<any> = util.promisify((cb: (err: Error) => void): void => { }); + const arg1: (arg: string) => Promise<number> = util.promisify((arg: string, cb: (err: Error, result: number) => void): void => { }); + const arg1NoResult: (arg: string) => Promise<any> = util.promisify((arg: string, cb: (err: Error) => void): void => { }); + const cbOptionalError: () => Promise<void | {}> = util.promisify((cb: (err?: Error | null) => void): void => { cb(); }); // tslint:disable-line void-return + assert(typeof util.promisify.custom === 'symbol'); + // util.deprecate + const foo = () => {}; + // $ExpectType () => void + util.deprecate(foo, 'foo() is deprecated, use bar() instead'); + // $ExpectType <T extends Function>(fn: T, message: string) => T + util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead'); + + // util.isDeepStrictEqual + util.isDeepStrictEqual({foo: 'bar'}, {foo: 'bar'}); + + // util.TextDecoder() + const td = new util.TextDecoder(); + new util.TextDecoder("utf-8"); + new util.TextDecoder("utf-8", { fatal: true }); + new util.TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + const ignoreBom: boolean = td.ignoreBOM; + const fatal: boolean = td.fatal; + const encoding: string = td.encoding; + td.decode(new Int8Array(1)); + td.decode(new Int16Array(1)); + td.decode(new Int32Array(1)); + td.decode(new Uint8Array(1)); + td.decode(new Uint16Array(1)); + td.decode(new Uint32Array(1)); + td.decode(new Uint8ClampedArray(1)); + td.decode(new Float32Array(1)); + td.decode(new Float64Array(1)); + td.decode(new DataView(new Int8Array(1).buffer)); + td.decode(new ArrayBuffer(1)); + td.decode(null); + td.decode(null, { stream: true }); + td.decode(new Int8Array(1), { stream: true }); + const decode: string = td.decode(new Int8Array(1)); + + // util.TextEncoder() + const te = new util.TextEncoder(); + const teEncoding: string = te.encoding; + const teEncodeRes: Uint8Array = te.encode("TextEncoder"); + + // util.types + + // tslint:disable-next-line:no-construct ban-types + const maybeBoxed: number | Number = new Number(1); + if (util.types.isBoxedPrimitive(maybeBoxed)) { + const boxed: Number = maybeBoxed; + } + const maybeBoxed2: number | Number = 1; + if (!util.types.isBoxedPrimitive(maybeBoxed2)) { + const boxed: number = maybeBoxed2; + } +} diff --git a/types/node/test/worker_threads.ts b/types/node/test/worker_threads.ts new file mode 100644 index 0000000000..1f0422554b --- /dev/null +++ b/types/node/test/worker_threads.ts @@ -0,0 +1,46 @@ +import * as workerThreads from "worker_threads"; +import assert = require("assert"); + +{ + if (workerThreads.isMainThread) { + module.exports = async function parseJSAsync(script: string) { + return new Promise((resolve, reject) => { + const worker = new workerThreads.Worker(__filename, { + workerData: script + }); + worker.on('message', resolve); + worker.on('error', reject); + worker.on('exit', (code) => { + if (code !== 0) + reject(new Error(`Worker stopped with exit code ${code}`)); + }); + }); + }; + } else { + const script = workerThreads.workerData; + workerThreads.parentPort.postMessage(script); + } +} + +{ + const { port1, port2 } = new workerThreads.MessageChannel(); + port1.on('message', (message) => console.log('received', message)); + port2.postMessage({ foo: 'bar' }); +} + +{ + if (workerThreads.isMainThread) { + const worker = new workerThreads.Worker(__filename); + const subChannel = new workerThreads.MessageChannel(); + worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]); + subChannel.port2.on('message', (value) => { + console.log('received:', value); + }); + } else { + workerThreads.parentPort.once('message', (value) => { + assert(value.hereIsYourPort instanceof workerThreads.MessagePort); + value.hereIsYourPort.postMessage('the worker is sending this'); + value.hereIsYourPort.close(); + }); + } +} diff --git a/types/node/tls.d.ts b/types/node/tls.d.ts index f59dcc7629..c65aef9f8b 100644 --- a/types/node/tls.d.ts +++ b/types/node/tls.d.ts @@ -265,6 +265,7 @@ declare module "tls" { minDHSize?: number; secureContext?: SecureContext; // If not provided, the entire ConnectionOptions object will be passed to tls.createSecureContext() lookup?: net.LookupFunction; + timeout?: number; } class Server extends net.Server { @@ -330,6 +331,8 @@ declare module "tls" { cleartext: any; } + type SecureVersion = 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; + interface SecureContextOptions { pfx?: string | Buffer | Array<string | Buffer | Object>; key?: string | Buffer | Array<Buffer | Object>; @@ -345,6 +348,22 @@ declare module "tls" { secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options secureProtocol?: string; // SSL Method, e.g. SSLv23_method sessionIdContext?: string; + /** + * Optionally set the maximum TLS version to allow. One + * of `TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. **Default:** `'TLSv1.2'`. + */ + maxVersion?: SecureVersion; + /** + * Optionally set the minimum TLS version to allow. One + * of `TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` changes the default to `'TLSv1'`. Using `--tls-v1.1` changes + * the default to `'TLSv1.1'`. + */ + minVersion?: SecureVersion; } interface SecureContext { diff --git a/types/node/ts3.1/tsconfig.json b/types/node/ts3.1/tsconfig.json index e1a9ddb149..3daf5b6f5d 100644 --- a/types/node/ts3.1/tsconfig.json +++ b/types/node/ts3.1/tsconfig.json @@ -7,8 +7,7 @@ "module": "commonjs", "target": "es6", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/node/tsconfig.json b/types/node/tsconfig.json index 37cfa4baed..d8f7829f72 100644 --- a/types/node/tsconfig.json +++ b/types/node/tsconfig.json @@ -42,14 +42,20 @@ "vm.d.ts", "worker_threads.d.ts", "zlib.d.ts", - "node-tests.ts" + "node-tests.ts", + "test/http.ts", + "test/readline.ts", + "test/global.ts", + "test/worker_threads.ts", + "test/util.ts", + "test/net.ts", + "test/dgram.ts" ], "compilerOptions": { "module": "commonjs", "target": "es6", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/node/tty.d.ts b/types/node/tty.d.ts index 7d75c89f58..d9b900e720 100644 --- a/types/node/tty.d.ts +++ b/types/node/tty.d.ts @@ -7,7 +7,36 @@ declare module "tty" { setRawMode(mode: boolean): void; isTTY: boolean; } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; class WriteStream extends net.Socket { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "resize", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "resize"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "resize", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "resize", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "resize", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "resize", listener: () => void): this; + + clearLine(dir: Direction): void; + clearScreenDown(): void; + cursorTo(x: number, y: number): void; + getColorDepth(env: {}): number; + getWindowSize(): [number, number]; columns: number; rows: number; isTTY: boolean; diff --git a/types/node/util.d.ts b/types/node/util.d.ts index 9da88fe9cb..1adf10059f 100644 --- a/types/node/util.d.ts +++ b/types/node/util.d.ts @@ -163,7 +163,6 @@ declare module "util" { class TextEncoder { readonly encoding: string; - constructor(); encode(input?: string): Uint8Array; } } diff --git a/types/node/v10/assert.d.ts b/types/node/v10/assert.d.ts new file mode 100644 index 0000000000..d73353c5d8 --- /dev/null +++ b/types/node/v10/assert.d.ts @@ -0,0 +1,52 @@ +declare module "assert" { + function internal(value: any, message?: string | Error): void; + namespace internal { + class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + code: 'ERR_ASSERTION'; + + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFn?: Function + }); + } + + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail(actual: any, expected: any, message?: string | Error, operator?: string, stackStartFn?: Function): never; + function ok(value: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use strictEqual() instead. */ + function equal(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notStrictEqual() instead. */ + function notEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use deepStrictEqual() instead. */ + function deepEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */ + function notDeepEqual(actual: any, expected: any, message?: string | Error): void; + function strictEqual(actual: any, expected: any, message?: string | Error): void; + function notStrictEqual(actual: any, expected: any, message?: string | Error): void; + function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; + function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; + + function throws(block: Function, message?: string | Error): void; + function throws(block: Function, error: RegExp | Function | Object | Error, message?: string | Error): void; + function doesNotThrow(block: Function, message?: string | Error): void; + function doesNotThrow(block: Function, error: RegExp | Function, message?: string | Error): void; + + function ifError(value: any): void; + + function rejects(block: Function | Promise<any>, message?: string | Error): Promise<void>; + function rejects(block: Function | Promise<any>, error: RegExp | Function | Object | Error, message?: string | Error): Promise<void>; + function doesNotReject(block: Function | Promise<any>, message?: string | Error): Promise<void>; + function doesNotReject(block: Function | Promise<any>, error: RegExp | Function, message?: string | Error): Promise<void>; + + const strict: typeof internal; + } + + export = internal; +} diff --git a/types/node/v10/async_hooks.d.ts b/types/node/v10/async_hooks.d.ts new file mode 100644 index 0000000000..2c77932ecd --- /dev/null +++ b/types/node/v10/async_hooks.d.ts @@ -0,0 +1,144 @@ +/** + * Async Hooks module: https://nodejs.org/api/async_hooks.html + */ +declare module "async_hooks" { + /** + * Returns the asyncId of the current execution context. + */ + function executionAsyncId(): number; + + /** + * Returns the ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: Object): void; + + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + + /** + * Registers functions to be called for different lifetime events of each async operation. + * @param options the callbacks to register + * @return an AsyncHooks instance used for disabling and enabling hooks + */ + function createHook(options: HookCallbacks): AsyncHook; + + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * Default: `executionAsyncId()` + */ + triggerAsyncId?: number; + + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * Default: `false` + */ + requireManualDestroy?: boolean; + } + + /** + * The class AsyncResource was designed to be extended by the embedder's async resources. + * Using this users can easily trigger the lifetime events of their own resources. + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since 9.3) + */ + constructor(type: string, triggerAsyncId?: number|AsyncResourceOptions); + + /** + * Call AsyncHooks before callbacks. + * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. + */ + emitBefore(): void; + + /** + * Call AsyncHooks after callbacks. + * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. + */ + emitAfter(): void; + + /** + * Call the provided function with the provided arguments in the + * execution context of the async resource. This will establish the + * context, trigger the AsyncHooks before callbacks, call the function, + * trigger the AsyncHooks after callbacks, and then restore the original + * execution context. + * @param fn The function to call in the execution context of this + * async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope<This, Result>(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; + + /** + * Call AsyncHooks destroy callbacks. + */ + emitDestroy(): void; + + /** + * @return the unique ID assigned to this AsyncResource instance. + */ + asyncId(): number; + + /** + * @return the trigger ID for this AsyncResource instance. + */ + triggerAsyncId(): number; + } +} diff --git a/types/node/v10/base.d.ts b/types/node/v10/base.d.ts new file mode 100644 index 0000000000..70983d9515 --- /dev/null +++ b/types/node/v10/base.d.ts @@ -0,0 +1,41 @@ +// base definnitions for all NodeJS modules that are not specific to any version of TypeScript +/// <reference path="globals.d.ts" /> +/// <reference path="assert.d.ts" /> +/// <reference path="async_hooks.d.ts" /> +/// <reference path="buffer.d.ts" /> +/// <reference path="child_process.d.ts" /> +/// <reference path="cluster.d.ts" /> +/// <reference path="console.d.ts" /> +/// <reference path="constants.d.ts" /> +/// <reference path="crypto.d.ts" /> +/// <reference path="dgram.d.ts" /> +/// <reference path="dns.d.ts" /> +/// <reference path="domain.d.ts" /> +/// <reference path="events.d.ts" /> +/// <reference path="fs.d.ts" /> +/// <reference path="http.d.ts" /> +/// <reference path="http2.d.ts" /> +/// <reference path="https.d.ts" /> +/// <reference path="inspector.d.ts" /> +/// <reference path="module.d.ts" /> +/// <reference path="net.d.ts" /> +/// <reference path="os.d.ts" /> +/// <reference path="path.d.ts" /> +/// <reference path="perf_hooks.d.ts" /> +/// <reference path="process.d.ts" /> +/// <reference path="punycode.d.ts" /> +/// <reference path="querystring.d.ts" /> +/// <reference path="readline.d.ts" /> +/// <reference path="repl.d.ts" /> +/// <reference path="stream.d.ts" /> +/// <reference path="string_decoder.d.ts" /> +/// <reference path="timers.d.ts" /> +/// <reference path="tls.d.ts" /> +/// <reference path="trace_events.d.ts" /> +/// <reference path="tty.d.ts" /> +/// <reference path="url.d.ts" /> +/// <reference path="util.d.ts" /> +/// <reference path="v8.d.ts" /> +/// <reference path="vm.d.ts" /> +/// <reference path="worker_threads.d.ts" /> +/// <reference path="zlib.d.ts" /> diff --git a/types/node/v10/buffer.d.ts b/types/node/v10/buffer.d.ts new file mode 100644 index 0000000000..86fdfdb36c --- /dev/null +++ b/types/node/v10/buffer.d.ts @@ -0,0 +1,6 @@ +declare module "buffer" { + export const INSPECT_MAX_BYTES: number; + const BuffType: typeof Buffer; + const SlowBuffType: typeof SlowBuffer; + export { BuffType as Buffer, SlowBuffType as SlowBuffer }; +} diff --git a/types/node/v10/child_process.d.ts b/types/node/v10/child_process.d.ts new file mode 100644 index 0000000000..c8d20b8249 --- /dev/null +++ b/types/node/v10/child_process.d.ts @@ -0,0 +1,358 @@ +declare module "child_process" { + import * as events from "events"; + import * as stream from "stream"; + import * as net from "net"; + + interface ChildProcess extends events.EventEmitter { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; + stdio: [stream.Writable, stream.Readable, stream.Readable]; + killed: boolean; + pid: number; + kill(signal?: string): void; + send(message: any, callback?: (error: Error) => void): boolean; + send(message: any, sendHandle?: net.Socket | net.Server, callback?: (error: Error) => void): boolean; + send(message: any, sendHandle?: net.Socket | net.Server, options?: MessageOptions, callback?: (error: Error) => void): boolean; + connected: boolean; + disconnect(): void; + unref(): void; + ref(): void; + + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number, signal: string) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number, signal: string): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: string | null): boolean; + emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number, signal: string) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number, signal: string) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number, signal: string) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + } + + interface MessageOptions { + keepOpen?: boolean; + } + + type StdioOptions = "pipe" | "ignore" | "inherit" | Array<("pipe" | "ipc" | "ignore" | "inherit" | stream.Stream | number | null | undefined)>; + + interface SpawnOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + argv0?: string; + stdio?: StdioOptions; + detached?: boolean; + uid?: number; + gid?: number; + shell?: boolean | string; + windowsVerbatimArguments?: boolean; + windowsHide?: boolean; + } + + function spawn(command: string, options?: SpawnOptions): ChildProcess; + function spawn(command: string, args?: ReadonlyArray<string>, options?: SpawnOptions): ChildProcess; + + interface ExecOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + shell?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + windowsHide?: boolean; + } + + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: string | null; // specify `null`. + } + + interface ExecException extends Error { + cmd?: string; + killed?: boolean; + code?: number; + signal?: string; + } + + // no `options` definitely means stdout/stderr are `string`. + function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: ({ encoding?: string | null } & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace exec { + function __promisify__(command: string): Promise<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options: { encoding: "buffer" | null } & ExecOptions): Promise<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(command: string, options: { encoding: BufferEncoding } & ExecOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options: ExecOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options?: ({ encoding?: string | null } & ExecOptions) | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + } + + interface ExecFileOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + windowsHide?: boolean; + windowsVerbatimArguments?: boolean; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: 'buffer' | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: string; + } + + function execFile(file: string): ChildProcess; + function execFile(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; + function execFile(file: string, args?: ReadonlyArray<string> | null): ChildProcess; + function execFile(file: string, args: ReadonlyArray<string> | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; + + // no `options` definitely means stdout/stderr are `string`. + function execFile(file: string, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray<string> | undefined | null, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray<string> | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray<string> | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback: (error: Error | null, stdout: string, stderr: string) => void, + ): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile( + file: string, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray<string> | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray<string> | undefined | null, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, + callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray<string> | undefined | null, + options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, + callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, + ): ChildProcess; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace execFile { + function __promisify__(file: string): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: string[] | undefined | null): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(file: string, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__(file: string, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__( + file: string, + args: string[] | undefined | null, + options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, + ): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + } + + interface ForkOptions { + cwd?: string; + env?: NodeJS.ProcessEnv; + execPath?: string; + execArgv?: string[]; + silent?: boolean; + stdio?: StdioOptions; + windowsVerbatimArguments?: boolean; + uid?: number; + gid?: number; + } + function fork(modulePath: string, args?: ReadonlyArray<string>, options?: ForkOptions): ChildProcess; + + interface SpawnSyncOptions { + argv0?: string; // Not specified in the docs + cwd?: string; + input?: string | Buffer | NodeJS.TypedArray | DataView; + stdio?: StdioOptions; + env?: NodeJS.ProcessEnv; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + shell?: boolean | string; + windowsVerbatimArguments?: boolean; + windowsHide?: boolean; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding: string; // specify `null`. + } + interface SpawnSyncReturns<T> { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number; + signal: string; + error: Error; + } + function spawnSync(command: string): SpawnSyncReturns<Buffer>; + function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>; + function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns<Buffer>; + function spawnSync(command: string, args?: ReadonlyArray<string>, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>; + function spawnSync(command: string, args?: ReadonlyArray<string>, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>; + function spawnSync(command: string, args?: ReadonlyArray<string>, options?: SpawnSyncOptions): SpawnSyncReturns<Buffer>; + + interface ExecSyncOptions { + cwd?: string; + input?: string | Buffer | Uint8Array; + stdio?: StdioOptions; + env?: NodeJS.ProcessEnv; + shell?: string; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + windowsHide?: boolean; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding: string; // specify `null`. + } + function execSync(command: string): Buffer; + function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): Buffer; + + interface ExecFileSyncOptions { + cwd?: string; + input?: string | Buffer | NodeJS.TypedArray | DataView; + stdio?: StdioOptions; + env?: NodeJS.ProcessEnv; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + windowsHide?: boolean; + shell?: boolean | string; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding: string; // specify `null`. + } + function execFileSync(command: string): Buffer; + function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; + function execFileSync(command: string, args?: ReadonlyArray<string>, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(command: string, args?: ReadonlyArray<string>, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(command: string, args?: ReadonlyArray<string>, options?: ExecFileSyncOptions): Buffer; +} diff --git a/types/node/v10/cluster.d.ts b/types/node/v10/cluster.d.ts new file mode 100644 index 0000000000..2bfe353140 --- /dev/null +++ b/types/node/v10/cluster.d.ts @@ -0,0 +1,261 @@ +declare module "cluster" { + import * as child from "child_process"; + import * as events from "events"; + import * as net from "net"; + + // interfaces + interface ClusterSettings { + execArgv?: string[]; // default: process.execArgv + exec?: string; + args?: string[]; + silent?: boolean; + stdio?: any[]; + uid?: number; + gid?: number; + inspectPort?: number | (() => number); + } + + interface Address { + address: string; + port: number; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" + } + + class Worker extends events.EventEmitter { + id: number; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any, callback?: (error: Error) => void): boolean; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + isConnected(): boolean; + isDead(): boolean; + exitedAfterDisconnect: boolean; + + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + + interface Cluster extends events.EventEmitter { + Worker: Worker; + disconnect(callback?: Function): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + // TODO: cluster.schedulingPolicy + settings: ClusterSettings; + setupMaster(settings?: ClusterSettings): void; + worker?: Worker; + workers?: { + [index: string]: Worker | undefined + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: any) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: any): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: any) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: any) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: any) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: any) => void): this; + } + + function disconnect(callback?: Function): void; + function fork(env?: any): Worker; + const isMaster: boolean; + const isWorker: boolean; + // TODO: cluster.schedulingPolicy + const settings: ClusterSettings; + function setupMaster(settings?: ClusterSettings): void; + const worker: Worker; + const workers: { + [index: string]: Worker | undefined + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + function addListener(event: string, listener: (...args: any[]) => void): Cluster; + function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + function addListener(event: "setup", listener: (settings: any) => void): Cluster; + + function emit(event: string | symbol, ...args: any[]): boolean; + function emit(event: "disconnect", worker: Worker): boolean; + function emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + function emit(event: "fork", worker: Worker): boolean; + function emit(event: "listening", worker: Worker, address: Address): boolean; + function emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + function emit(event: "online", worker: Worker): boolean; + function emit(event: "setup", settings: any): boolean; + + function on(event: string, listener: (...args: any[]) => void): Cluster; + function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function on(event: "fork", listener: (worker: Worker) => void): Cluster; + function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + function on(event: "online", listener: (worker: Worker) => void): Cluster; + function on(event: "setup", listener: (settings: any) => void): Cluster; + + function once(event: string, listener: (...args: any[]) => void): Cluster; + function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function once(event: "fork", listener: (worker: Worker) => void): Cluster; + function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + function once(event: "online", listener: (worker: Worker) => void): Cluster; + function once(event: "setup", listener: (settings: any) => void): Cluster; + + function removeListener(event: string, listener: (...args: any[]) => void): Cluster; + function removeAllListeners(event?: string): Cluster; + function setMaxListeners(n: number): Cluster; + function getMaxListeners(): number; + function listeners(event: string): Function[]; + function listenerCount(type: string): number; + + function prependListener(event: string, listener: (...args: any[]) => void): Cluster; + function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "setup", listener: (settings: any) => void): Cluster; + + function prependOnceListener(event: string, listener: (...args: any[]) => void): Cluster; + function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; + + function eventNames(): string[]; +} diff --git a/types/node/v10/console.d.ts b/types/node/v10/console.d.ts new file mode 100644 index 0000000000..d30d13f871 --- /dev/null +++ b/types/node/v10/console.d.ts @@ -0,0 +1,3 @@ +declare module "console" { + export = console; +} diff --git a/types/node/v10/constants.d.ts b/types/node/v10/constants.d.ts new file mode 100644 index 0000000000..6c39d64346 --- /dev/null +++ b/types/node/v10/constants.d.ts @@ -0,0 +1,279 @@ +declare module "constants" { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + const SIGHUP: number; + const SIGINT: number; + const SIGILL: number; + const SIGABRT: number; + const SIGFPE: number; + const SIGKILL: number; + const SIGSEGV: number; + const SIGTERM: number; + const SIGBREAK: number; + const SIGWINCH: number; + const SSL_OP_ALL: number; + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + const SSL_OP_CISCO_ANYCONNECT: number; + const SSL_OP_COOKIE_EXCHANGE: number; + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + const SSL_OP_EPHEMERAL_RSA: number; + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + const SSL_OP_SINGLE_DH_USE: number; + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: number; + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_ECDH: number; + const ENGINE_METHOD_ECDSA: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_STORE: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const NPN_ENABLED: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + const O_RDONLY: number; + const O_WRONLY: number; + const O_RDWR: number; + const S_IFMT: number; + const S_IFREG: number; + const S_IFDIR: number; + const S_IFCHR: number; + const S_IFBLK: number; + const S_IFIFO: number; + const S_IFSOCK: number; + const S_IRWXU: number; + const S_IRUSR: number; + const S_IWUSR: number; + const S_IXUSR: number; + const S_IRWXG: number; + const S_IRGRP: number; + const S_IWGRP: number; + const S_IXGRP: number; + const S_IRWXO: number; + const S_IROTH: number; + const S_IWOTH: number; + const S_IXOTH: number; + const S_IFLNK: number; + const O_CREAT: number; + const O_EXCL: number; + const O_NOCTTY: number; + const O_DIRECTORY: number; + const O_NOATIME: number; + const O_NOFOLLOW: number; + const O_SYNC: number; + const O_DSYNC: number; + const O_SYMLINK: number; + const O_DIRECT: number; + const O_NONBLOCK: number; + const O_TRUNC: number; + const O_APPEND: number; + const F_OK: number; + const R_OK: number; + const W_OK: number; + const X_OK: number; + const COPYFILE_EXCL: number; + const COPYFILE_FICLONE: number; + const COPYFILE_FICLONE_FORCE: number; + const UV_UDP_REUSEADDR: number; + const SIGQUIT: number; + const SIGTRAP: number; + const SIGIOT: number; + const SIGBUS: number; + const SIGUSR1: number; + const SIGUSR2: number; + const SIGPIPE: number; + const SIGALRM: number; + const SIGCHLD: number; + const SIGSTKFLT: number; + const SIGCONT: number; + const SIGSTOP: number; + const SIGTSTP: number; + const SIGTTIN: number; + const SIGTTOU: number; + const SIGURG: number; + const SIGXCPU: number; + const SIGXFSZ: number; + const SIGVTALRM: number; + const SIGPROF: number; + const SIGIO: number; + const SIGPOLL: number; + const SIGPWR: number; + const SIGSYS: number; + const SIGUNUSED: number; + const defaultCoreCipherList: string; + const defaultCipherList: string; + const ENGINE_METHOD_RSA: number; + const ALPN_ENABLED: number; +} diff --git a/types/node/v10/crypto.d.ts b/types/node/v10/crypto.d.ts new file mode 100644 index 0000000000..0d37716a7e --- /dev/null +++ b/types/node/v10/crypto.d.ts @@ -0,0 +1,369 @@ +declare module "crypto" { + import * as stream from "stream"; + + interface Certificate { + exportChallenge(spkac: string | Buffer | NodeJS.TypedArray | DataView): Buffer; + exportPublicKey(spkac: string | Buffer | NodeJS.TypedArray | DataView): Buffer; + verifySpkac(spkac: Buffer | NodeJS.TypedArray | DataView): boolean; + } + const Certificate: { + new(): Certificate; + (): Certificate; + }; + + /** @deprecated since v10.0.0 */ + const fips: boolean; + + interface CredentialDetails { + pfx: string; + key: string; + passphrase: string; + cert: string; + ca: string | string[]; + crl: string | string[]; + ciphers: string; + } + interface Credentials { context?: any; } + function createCredentials(details: CredentialDetails): Credentials; + function createHash(algorithm: string, options?: stream.TransformOptions): Hash; + function createHmac(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Hmac; + + type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; + type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; + type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; + type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + + interface Hash extends NodeJS.ReadWriteStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Hash; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hash; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + interface Hmac extends NodeJS.ReadWriteStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Hmac; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hmac; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm'; + type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number; + } + /** @deprecated since v10.0.0 use createCipheriv() */ + function createCipher(algorithm: CipherCCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createCipher(algorithm: CipherGCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createCipher(algorithm: string, password: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Cipher; + + function createCipheriv(algorithm: CipherCCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): CipherCCM; + function createCipheriv(algorithm: CipherGCMTypes, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): CipherGCM; + function createCipheriv(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Cipher; + + interface Cipher extends NodeJS.ReadWriteStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Buffer; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; + update(data: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64BinaryEncoding): string; + update(data: Buffer | NodeJS.TypedArray | DataView, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; + // second arg ignored + update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): this; + // getAuthTag(): Buffer; + // setAAD(buffer: Buffer): this; // docs only say buffer + } + interface CipherCCM extends Cipher { + setAAD(buffer: Buffer, options: { plaintextLength: number }): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD(buffer: Buffer, options?: { plaintextLength: number }): this; + getAuthTag(): Buffer; + } + /** @deprecated since v10.0.0 use createCipheriv() */ + function createDecipher(algorithm: CipherCCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createDecipher(algorithm: CipherGCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createDecipher(algorithm: string, password: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Decipher; + + function createDecipheriv( + algorithm: CipherCCMTypes, + key: string | Buffer | NodeJS.TypedArray | DataView, + iv: string | Buffer | NodeJS.TypedArray | DataView, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: string | Buffer | NodeJS.TypedArray | DataView, + iv: string | Buffer | NodeJS.TypedArray | DataView, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Decipher; + + interface Decipher extends NodeJS.ReadWriteStream { + update(data: Buffer | NodeJS.TypedArray | DataView): Buffer; + update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; + update(data: Buffer | NodeJS.TypedArray | DataView, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; + // second arg is ignored + update(data: string, input_encoding: HexBase64BinaryEncoding, output_encoding: Utf8AsciiBinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): this; + // setAuthTag(tag: Buffer | NodeJS.TypedArray | DataView): this; + // setAAD(buffer: Buffer | NodeJS.TypedArray | DataView): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: Buffer | NodeJS.TypedArray | DataView): this; + setAAD(buffer: Buffer | NodeJS.TypedArray | DataView, options: { plaintextLength: number }): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: Buffer | NodeJS.TypedArray | DataView): this; + setAAD(buffer: Buffer | NodeJS.TypedArray | DataView, options?: { plaintextLength: number }): this; + } + + function createSign(algorithm: string, options?: stream.WritableOptions): Signer; + interface Signer extends NodeJS.WritableStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Signer; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Signer; + sign(private_key: string | { key: string; passphrase?: string, padding?: number, saltLength?: number }): Buffer; + sign(private_key: string | { key: string; passphrase?: string, padding?: number, saltLength?: number }, output_format: HexBase64Latin1Encoding): string; + } + function createVerify(algorith: string, options?: stream.WritableOptions): Verify; + interface Verify extends NodeJS.WritableStream { + update(data: string | Buffer | NodeJS.TypedArray | DataView): Verify; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Verify; + verify(object: string | Object, signature: Buffer | NodeJS.TypedArray | DataView): boolean; + verify(object: string | Object, signature: string, signature_format: HexBase64Latin1Encoding): boolean; + // https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format + // The signature field accepts a TypedArray type, but it is only available starting ES2017 + } + function createDiffieHellman(prime_length: number, generator?: number | Buffer | NodeJS.TypedArray | DataView): DiffieHellman; + function createDiffieHellman(prime: Buffer | NodeJS.TypedArray | DataView): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Buffer | NodeJS.TypedArray | DataView): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; + interface DiffieHellman { + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrime(): Buffer; + getPrime(encoding: HexBase64Latin1Encoding): string; + getGenerator(): Buffer; + getGenerator(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + setPublicKey(public_key: Buffer | NodeJS.TypedArray | DataView): void; + setPublicKey(public_key: string, encoding: string): void; + setPrivateKey(private_key: Buffer | NodeJS.TypedArray | DataView): void; + setPrivateKey(private_key: string, encoding: string): void; + verifyError: number; + } + function getDiffieHellman(group_name: string): DiffieHellman; + function pbkdf2( + password: string | Buffer | NodeJS.TypedArray | DataView, + salt: string | Buffer | NodeJS.TypedArray | DataView, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: Buffer) => any, + ): void; + function pbkdf2Sync(password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, iterations: number, keylen: number, digest: string): Buffer; + + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + + function randomFillSync<T extends Buffer | NodeJS.TypedArray | DataView>(buffer: T, offset?: number, size?: number): T; + function randomFill<T extends Buffer | NodeJS.TypedArray | DataView>(buffer: T, callback: (err: Error | null, buf: T) => void): void; + function randomFill<T extends Buffer | NodeJS.TypedArray | DataView>(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; + function randomFill<T extends Buffer | NodeJS.TypedArray | DataView>(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; + + interface ScryptOptions { + N?: number; + r?: number; + p?: number; + maxmem?: number; + } + function scrypt( + password: string | Buffer | NodeJS.TypedArray | DataView, + salt: string | Buffer | NodeJS.TypedArray | DataView, + keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scrypt( + password: string | Buffer | NodeJS.TypedArray | DataView, + salt: string | Buffer | NodeJS.TypedArray | DataView, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scryptSync(password: string | Buffer | NodeJS.TypedArray | DataView, salt: string | Buffer | NodeJS.TypedArray | DataView, keylen: number, options?: ScryptOptions): Buffer; + + interface RsaPublicKey { + key: string; + padding?: number; + } + interface RsaPrivateKey { + key: string; + passphrase?: string; + padding?: number; + } + function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + function privateEncrypt(private_key: string | RsaPrivateKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + function publicDecrypt(public_key: string | RsaPublicKey, buffer: Buffer | NodeJS.TypedArray | DataView): Buffer; + function getCiphers(): string[]; + function getCurves(): string[]; + function getHashes(): string[]; + class ECDH { + static convertKey( + key: string | Buffer | NodeJS.TypedArray | DataView, + curve: string, + inputEncoding?: HexBase64Latin1Encoding, + outputEncoding?: "latin1" | "hex" | "base64", + format?: "uncompressed" | "compressed" | "hybrid", + ): Buffer | string; + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView, output_encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; + setPrivateKey(private_key: Buffer | NodeJS.TypedArray | DataView): void; + setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; + } + function createECDH(curve_name: string): ECDH; + function timingSafeEqual(a: Buffer | NodeJS.TypedArray | DataView, b: Buffer | NodeJS.TypedArray | DataView): boolean; + /** @deprecated since v10.0.0 */ + const DEFAULT_ENCODING: string; + + export type KeyType = 'rsa' | 'dsa' | 'ec'; + export type KeyFormat = 'pem' | 'der'; + + interface BasePrivateKeyEncodingOptions<T extends KeyFormat> { + format: T; + cipher: string; + passphrase: string; + } + + interface RSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> { + /** + * Key size in bits + */ + modulusLength: number; + /** + * @default 0x10001 + */ + publicExponent?: number; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { + type: 'pkcs1' | 'pkcs8'; + }; + } + + interface DSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { + type: 'pkcs8'; + }; + } + + interface ECKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> { + /** + * Name of the curve to use. + */ + namedCurve: string; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & { + type: 'sec1' | 'pkcs8'; + }; + } + + interface KeyPairSyncResult<T1 extends string | Buffer, T2 extends string | Buffer> { + publicKey: T1; + privateKey: T2; + } + + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>; + + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>; + + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>; + + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + + namespace generateKeyPair { + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + + function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + } +} diff --git a/types/node/v10/dgram.d.ts b/types/node/v10/dgram.d.ts new file mode 100644 index 0000000000..48049b47b8 --- /dev/null +++ b/types/node/v10/dgram.d.ts @@ -0,0 +1,97 @@ +declare module "dgram" { + import { AddressInfo } from "net"; + import * as dns from "dns"; + import * as events from "events"; + + interface RemoteInfo { + address: string; + family: string; + port: number; + } + + interface BindOptions { + port: number; + address?: string; + exclusive?: boolean; + } + + type SocketType = "udp4" | "udp6"; + + interface SocketOptions { + type: SocketType; + reuseAddr?: boolean; + recvBufferSize?: number; + sendBufferSize?: number; + lookup?: (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void) => void; + } + + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + class Socket extends events.EventEmitter { + send(msg: Buffer | string | Uint8Array | any[], port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + bind(port?: number, address?: string, callback?: () => void): void; + bind(port?: number, callback?: () => void): void; + bind(callback?: () => void): void; + bind(options: BindOptions, callback?: Function): void; + close(callback?: () => void): void; + address(): AddressInfo | string; + setBroadcast(flag: boolean): void; + setTTL(ttl: number): void; + setMulticastTTL(ttl: number): void; + setMulticastInterface(multicastInterface: string): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + ref(): this; + unref(): this; + setRecvBufferSize(size: number): void; + setSendBufferSize(size: number): void; + getRecvBufferSize(): number; + getSendBufferSize(): number; + + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: AddressInfo): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: AddressInfo) => void): this; + } +} diff --git a/types/node/v10/dns.d.ts b/types/node/v10/dns.d.ts new file mode 100644 index 0000000000..a77216f797 --- /dev/null +++ b/types/node/v10/dns.d.ts @@ -0,0 +1,292 @@ +declare module "dns" { + // Supported getaddrinfo flags. + const ADDRCONFIG: number; + const V4MAPPED: number; + + interface LookupOptions { + family?: number; + hints?: number; + all?: boolean; + verbatim?: boolean; + } + + interface LookupOneOptions extends LookupOptions { + all?: false; + } + + interface LookupAllOptions extends LookupOptions { + all: true; + } + + interface LookupAddress { + address: string; + family: number; + } + + function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException, addresses: LookupAddress[]) => void): void; + function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException, address: string | LookupAddress[], family: number) => void): void; + function lookup(hostname: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise<{ address: LookupAddress[] }>; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<{ address: string, family: number }>; + function __promisify__(hostname: string, options?: LookupOptions | number): Promise<{ address: string | LookupAddress[], family?: number }>; + } + + function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException, hostname: string, service: string) => void): void; + + namespace lookupService { + function __promisify__(address: string, port: number): Promise<{ hostname: string, service: string }>; + } + + interface ResolveOptions { + ttl: boolean; + } + + interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + + interface RecordWithTtl { + address: string; + ttl: number; + } + + /** @deprecated Use AnyARecord or AnyAaaaRecord instead. */ + type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + + interface AnyARecord extends RecordWithTtl { + type: "A"; + } + + interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + + interface MxRecord { + priority: number; + exchange: string; + } + + interface AnyMxRecord extends MxRecord { + type: "MX"; + } + + interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + + interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + + interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + + interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + + interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + + interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + + interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + + interface AnyNsRecord { + type: "NS"; + value: string; + } + + interface AnyPtrRecord { + type: "PTR"; + value: string; + } + + interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + + type AnyRecord = AnyARecord | + AnyAaaaRecord | + AnyCnameRecord | + AnyMxRecord | + AnyNaptrRecord | + AnyNsRecord | + AnyPtrRecord | + AnySoaRecord | + AnySrvRecord | + AnyTxtRecord; + + function resolve(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "ANY", callback: (err: NodeJS.ErrnoException, addresses: AnyRecord[]) => void): void; + function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException, addresses: SoaRecord) => void): void; + function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + function resolve( + hostname: string, + rrtype: string, + callback: (err: NodeJS.ErrnoException, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void, + ): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>; + function __promisify__(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>; + function __promisify__(hostname: string, rrtype: "MX"): Promise<MxRecord[]>; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>; + function __promisify__(hostname: string, rrtype: "SOA"): Promise<SoaRecord>; + function __promisify__(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>; + function __promisify__(hostname: string, rrtype: "TXT"): Promise<string[][]>; + function __promisify__(hostname: string, rrtype: string): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>; + } + + function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; + function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace resolve4 { + function __promisify__(hostname: string): Promise<string[]>; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>; + function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>; + } + + function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; + function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace resolve6 { + function __promisify__(hostname: string): Promise<string[]>; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>; + function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>; + } + + function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + namespace resolveCname { + function __promisify__(hostname: string): Promise<string[]>; + } + + function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + namespace resolveMx { + function __promisify__(hostname: string): Promise<MxRecord[]>; + } + + function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + namespace resolveNaptr { + function __promisify__(hostname: string): Promise<NaptrRecord[]>; + } + + function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + namespace resolveNs { + function __promisify__(hostname: string): Promise<string[]>; + } + + function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + namespace resolvePtr { + function __promisify__(hostname: string): Promise<string[]>; + } + + function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException, address: SoaRecord) => void): void; + namespace resolveSoa { + function __promisify__(hostname: string): Promise<SoaRecord>; + } + + function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + namespace resolveSrv { + function __promisify__(hostname: string): Promise<SrvRecord[]>; + } + + function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + namespace resolveTxt { + function __promisify__(hostname: string): Promise<string[][]>; + } + + function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: AnyRecord[]) => void): void; + namespace resolveAny { + function __promisify__(hostname: string): Promise<AnyRecord[]>; + } + + function reverse(ip: string, callback: (err: NodeJS.ErrnoException, hostnames: string[]) => void): void; + function setServers(servers: string[]): void; + function getServers(): string[]; + + // Error codes + const NODATA: string; + const FORMERR: string; + const SERVFAIL: string; + const NOTFOUND: string; + const NOTIMP: string; + const REFUSED: string; + const BADQUERY: string; + const BADNAME: string; + const BADFAMILY: string; + const BADRESP: string; + const CONNREFUSED: string; + const TIMEOUT: string; + const EOF: string; + const FILE: string; + const NOMEM: string; + const DESTRUCTION: string; + const BADSTR: string; + const BADFLAGS: string; + const NONAME: string; + const BADHINTS: string; + const NOTINITIALIZED: string; + const LOADIPHLPAPI: string; + const ADDRGETNETWORKPARAMS: string; + const CANCELLED: string; + + class Resolver { + getServers: typeof getServers; + setServers: typeof setServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + cancel(): void; + } +} diff --git a/types/node/v10/domain.d.ts b/types/node/v10/domain.d.ts new file mode 100644 index 0000000000..6a30decfa5 --- /dev/null +++ b/types/node/v10/domain.d.ts @@ -0,0 +1,16 @@ +declare module "domain" { + import * as events from "events"; + + class Domain extends events.EventEmitter implements NodeJS.Domain { + run(fn: Function): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + members: any[]; + enter(): void; + exit(): void; + } + + function create(): Domain; +} diff --git a/types/node/v10/events.d.ts b/types/node/v10/events.d.ts new file mode 100644 index 0000000000..dd0d8d191b --- /dev/null +++ b/types/node/v10/events.d.ts @@ -0,0 +1,29 @@ +declare module "events" { + class internal extends NodeJS.EventEmitter { } + + namespace internal { + class EventEmitter extends internal { + /** @deprecated since v4.0.0 */ + 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; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + eventNames(): Array<string | symbol>; + listenerCount(type: string | symbol): number; + } + } + + export = internal; +} diff --git a/types/node/v10/fs.d.ts b/types/node/v10/fs.d.ts new file mode 100644 index 0000000000..e3718475e5 --- /dev/null +++ b/types/node/v10/fs.d.ts @@ -0,0 +1,2272 @@ +declare module "fs" { + import * as stream from "stream"; + import * as events from "events"; + import { URL } from "url"; + + /** + * Valid types for path values in "fs". + */ + type PathLike = string | Buffer | URL; + + type BinaryData = Buffer | DataView | NodeJS.TypedArray; + class Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atimeMs: number; + mtimeMs: number; + ctimeMs: number; + birthtimeMs: number; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + class Dirent { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + name: string; + } + + interface FSWatcher extends events.EventEmitter { + close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (error: Error) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (error: Error) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + } + + class ReadStream extends stream.Readable { + close(): void; + bytesRead: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + class WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise<void>; + } + + /** + * Synchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function renameSync(oldPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function truncate(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise<void>; + } + + /** + * Synchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncateSync(path: PathLike, len?: number | null): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(fd: number, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + function ftruncate(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise<void>; + } + + /** + * Synchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function ftruncateSync(fd: number, len?: number | null): void; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise<void>; + } + + /** + * Synchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise<void>; + } + + /** + * Synchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function fchownSync(fd: number, uid: number, gid: number): void; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise<void>; + } + + /** + * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: string | number): Promise<void>; + } + + /** + * Synchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(fd: number, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: string | number): Promise<void>; + } + + /** + * Synchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmodSync(fd: number, mode: string | number): void; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: string | number): Promise<void>; + } + + /** + * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise<Stats>; + } + + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function statSync(path: PathLike): Stats; + + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise<Stats>; + } + + /** + * Synchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function fstatSync(fd: number): Stats; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise<Stats>; + } + + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstatSync(path: PathLike): Stats; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise<void>; + } + + /** + * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function linkSync(existingPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + function symlink(target: PathLike, path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise<void>; + + type Type = "dir" | "file" | "junction"; + } + + /** + * Synchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, linkString: Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string | Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise<string>; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise<Buffer>; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise<string | Buffer>; + } + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, resolvedPath: Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string | Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise<string>; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise<Buffer>; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise<string | Buffer>; + + function native(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + function native(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, resolvedPath: Buffer) => void): void; + function native(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string | Buffer) => void): void; + function native(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + } + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + namespace realpathSync { + function native(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + function native(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + function native(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + } + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise<void>; + } + + /** + * Synchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlinkSync(path: PathLike): void; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise<void>; + } + + /** + * Synchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdirSync(path: PathLike): void; + + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * @default false + */ + recursive?: boolean; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777. + */ + mode?: number; + } + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options: number | string | MakeDirectoryOptions | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function mkdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise<void>; + } + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdirSync(path: PathLike, options?: number | string | MakeDirectoryOptions | null): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException, folder: Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string | Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise<string>; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise<Buffer>; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: { encoding?: string | null } | string | null): Promise<string | Buffer>; + } + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException, files: string[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException, files: Buffer[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: { encoding?: string | null; withFileTypes?: false } | string | undefined | null, + callback: (err: NodeJS.ErrnoException, files: string[] | Buffer[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir(path: PathLike, options: { withFileTypes: true }, callback: (err: NodeJS.ErrnoException, files: Dirent[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise<string[]>; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise<Buffer[]>; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise<string[] | Buffer[]>; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__(path: PathLike, options: { withFileTypes: true }): Promise<Dirent[]>; + } + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): string[] | Buffer[]; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdirSync(path: PathLike, options: { withFileTypes: true }): Dirent[]; + + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function close(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise<void>; + } + + /** + * Synchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function closeSync(fd: number): void; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode: string | number | undefined | null, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function open(path: PathLike, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: string | number, mode?: string | number | null): Promise<number>; + } + + /** + * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function openSync(path: PathLike, flags: string | number, mode?: string | number | null): number; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise<void>; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise<void>; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function fsync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise<void>; + } + + /** + * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function fsyncSync(fd: number): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write<TBuffer extends BinaryData>( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + function write<TBuffer extends BinaryData>( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + function write<TBuffer extends BinaryData>(fd: number, buffer: TBuffer, offset: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + function write<TBuffer extends BinaryData>(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write( + fd: number, + string: any, + position: number | undefined | null, + encoding: string | undefined | null, + callback: (err: NodeJS.ErrnoException, written: number, str: string) => void, + ): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write(fd: number, string: any, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + */ + function write(fd: number, string: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__<TBuffer extends BinaryData>( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__(fd: number, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + } + + /** + * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function writeSync(fd: number, buffer: BinaryData, offset?: number | null, length?: number | null, position?: number | null): number; + + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function writeSync(fd: number, string: any, position?: number | null, encoding?: string | null): number; + + /** + * Asynchronously reads data from the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function read<TBuffer extends BinaryData>( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null, + callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void, + ): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__<TBuffer extends BinaryData>(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + } + + /** + * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function readSync(fd: number, buffer: BinaryData, offset: number, length: number, position: number | null): number; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | number, + options: { encoding?: string | null; flag?: string; } | string | undefined | null, + callback: (err: NodeJS.ErrnoException, data: string | Buffer) => void, + ): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise<Buffer>; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options: { encoding: string; flag?: string; } | string): Promise<string>; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): Promise<string | Buffer>; + } + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options: { encoding: string; flag?: string; } | string): string; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer; + + type WriteFileOptions = { encoding?: string | null; mode?: number | string; flag?: string; } | string | null; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function writeFile(path: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__(path: PathLike | number, data: any, options?: WriteFileOptions): Promise<void>; + } + + /** + * Synchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFileSync(path: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(file: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function appendFile(file: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__(file: PathLike | number, data: any, options?: WriteFileOptions): Promise<void>; + } + + /** + * Synchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFileSync(file: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + */ + function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Stop watching for changes on `filename`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, + listener?: (event: string, filename: string) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: { encoding?: string | null, persistent?: boolean, recursive?: boolean } | string | null, + listener?: (event: string, filename: string | Buffer) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; + + /** + * Asynchronously tests whether or not the given path exists by checking with the file system. + * @deprecated + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function exists(path: PathLike, callback: (exists: boolean) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise<boolean>; + } + + /** + * Synchronously tests whether or not the given path exists by checking with the file system. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function existsSync(path: PathLike): boolean; + + namespace constants { + // File Access Constants + + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + + // File Copy Constants + + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + + // File Open Constants + + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + + // File Type Constants + + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + + // File Mode Constants + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode: number | undefined, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise<void>; + } + + /** + * Synchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function accessSync(path: PathLike, mode?: number): void; + + /** + * Returns a new `ReadStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function createReadStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + end?: number; + highWaterMark?: number; + }): ReadStream; + + /** + * Returns a new `WriteStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function createWriteStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + }): WriteStream; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function fdatasync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise<void>; + } + + /** + * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function fdatasyncSync(fd: number): void; + + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + */ + function copyFile(src: PathLike, dest: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace copyFile { + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, + * which causes the copy operation to fail if dest already exists. + */ + function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise<void>; + } + + /** + * Synchronously copies src to dest. By default, dest is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; + + namespace promises { + interface FileHandle { + /** + * Gets the file descriptor for this file handle. + */ + readonly fd: number; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for appending. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + appendFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise<void>; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + */ + chown(uid: number, gid: number): Promise<void>; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + chmod(mode: string | number): Promise<void>; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + */ + datasync(): Promise<void>; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + */ + sync(): Promise<void>; + + /** + * Asynchronously reads data from the file. + * The `FileHandle` must have been opened for reading. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + read<TBuffer extends Buffer | Uint8Array>(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: null, flag?: string | number } | null): Promise<Buffer>; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise<string>; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: string | null, flag?: string | number } | string | null): Promise<string | Buffer>; + + /** + * Asynchronous fstat(2) - Get file status. + */ + stat(): Promise<Stats>; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param len If not specified, defaults to `0`. + */ + truncate(len?: number): Promise<void>; + + /** + * Asynchronously change file timestamps of the file. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + utimes(atime: string | number | Date, mtime: string | number | Date): Promise<void>; + + /** + * Asynchronously writes `buffer` to the file. + * The `FileHandle` must have been opened for writing. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + write<TBuffer extends Buffer | Uint8Array>(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + write(data: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + writeFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise<void>; + + /** + * Asynchronous close(2) - close a `FileHandle`. + */ + close(): Promise<void>; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode?: number): Promise<void>; + + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. The only + * supported flag is `fs.constants.COPYFILE_EXCL`, which causes the copy operation to fail if + * `dest` already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags?: number): Promise<void>; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not + * supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode?: string | number): Promise<FileHandle>; + + /** + * Asynchronously reads data from the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If + * `null`, data will be read from the current position. + */ + function read<TBuffer extends Buffer | Uint8Array>( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write<TBuffer extends Buffer | Uint8Array>( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write(handle: FileHandle, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise<void>; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len?: number): Promise<void>; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param handle A `FileHandle`. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(handle: FileHandle, len?: number): Promise<void>; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike): Promise<void>; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param handle A `FileHandle`. + */ + function fdatasync(handle: FileHandle): Promise<void>; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param handle A `FileHandle`. + */ + function fsync(handle: FileHandle): Promise<void>; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise<void>; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise<string[]>; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise<Buffer[]>; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: string | null } | string | null): Promise<string[] | Buffer[]>; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise<string>; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise<Buffer>; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: string | null } | string | null): Promise<string | Buffer>; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise<void>; + + /** + * Asynchronous fstat(2) - Get file status. + * @param handle A `FileHandle`. + */ + function fstat(handle: FileHandle): Promise<Stats>; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike): Promise<Stats>; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike): Promise<Stats>; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise<void>; + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike): Promise<void>; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param handle A `FileHandle`. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(handle: FileHandle, mode: string | number): Promise<void>; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: string | number): Promise<void>; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: string | number): Promise<void>; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise<void>; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param handle A `FileHandle`. + */ + function fchown(handle: FileHandle, uid: number, gid: number): Promise<void>; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number): Promise<void>; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise<void>; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise<void>; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise<string>; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise<Buffer>; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: string | null } | string | null): Promise<string | Buffer>; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise<string>; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise<Buffer>; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: string | null } | string | null): Promise<string | Buffer>; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * It is unsafe to call `fsPromises.writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise<void>; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise<void>; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: null, flag?: string | number } | null): Promise<Buffer>; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise<string>; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: string | null, flag?: string | number } | string | null): Promise<string | Buffer>; + } +} diff --git a/types/node/v10/globals.d.ts b/types/node/v10/globals.d.ts new file mode 100644 index 0000000000..0c4215fe7b --- /dev/null +++ b/types/node/v10/globals.d.ts @@ -0,0 +1,1005 @@ +// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build +interface Console { + Console: NodeJS.ConsoleConstructor; + /** + * A simple assertion test that verifies whether `value` is truthy. + * If it is not, an `AssertionError` is thrown. + * If provided, the error `message` is formatted using `util.format()` and used as the error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. + * When `stdout` is not a TTY, this method does nothing. + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link console.log()}. + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + */ + dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by two spaces. + * If one or more `label`s are provided, those are printed first without the additional indentation. + */ + group(...label: any[]): void; + /** + * The `console.groupCollapsed()` function is an alias for {@link console.group()}. + */ + groupCollapsed(): void; + /** + * Decreases indentation of subsequent lines by two spaces. + */ + groupEnd(): void; + /** + * The {@link console.info()} function is an alias for {@link console.log()}. + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * This method does not display anything unless used in the inspector. + * Prints to `stdout` the array `array` formatted as a table. + */ + table(tabularData: any, properties?: string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The {@link console.warn()} function is an alias for {@link console.error()}. + */ + warn(message?: any, ...optionalParams: any[]): void; + + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * The console.markTimeline() method is the deprecated form of console.timeStamp(). + * + * @deprecated Use console.timeStamp() instead. + */ + markTimeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timeline() method is the deprecated form of console.time(). + * + * @deprecated Use console.time() instead. + */ + timeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timelineEnd() method is the deprecated form of console.timeEnd(). + * + * @deprecated Use console.timeEnd() instead. + */ + timelineEnd(label?: string): void; +} + +interface Error { + stack?: string; +} + +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + + stackTraceLimit: number; +} + +interface SymbolConstructor { + readonly observable: symbol; +} + +// Node.js ESNEXT support +interface String { + /** Removes whitespace from the left end of a string. */ + trimLeft(): string; + /** Removes whitespace from the right end of a string. */ + trimRight(): string; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ +declare var process: NodeJS.Process; +declare var global: NodeJS.Global; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare namespace setTimeout { + function __promisify__(ms: number): Promise<void>; + function __promisify__<T>(ms: number, value: T): Promise<T>; +} +declare function clearTimeout(timeoutId: NodeJS.Timeout): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare function clearInterval(intervalId: NodeJS.Timeout): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; +declare namespace setImmediate { + function __promisify__(): Promise<void>; + function __promisify__<T>(value: T): Promise<T>; +} +declare function clearImmediate(immediateId: NodeJS.Immediate): void; + +// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. +interface NodeRequireFunction { + /* tslint:disable-next-line:callable-types */ + (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { + resolve: RequireResolve; + cache: any; + extensions: NodeExtensions; + main: NodeModule | undefined; +} + +interface RequireResolve { + (id: string, options?: { paths?: string[]; }): string; + paths(request: string): string[] | null; +} + +interface NodeExtensions { + '.js': (m: NodeModule, filename: string) => any; + '.json': (m: NodeModule, filename: string) => any; + '.node': (m: NodeModule, filename: string) => any; + [ext: string]: (m: NodeModule, filename: string) => any; +} + +declare var require: NodeRequire; + +interface NodeModule { + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: NodeModule | null; + children: NodeModule[]; + paths: string[]; +} + +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; +declare const SlowBuffer: { + new(str: string, encoding?: string): Buffer; + new(size: number): Buffer; + new(size: Uint8Array): Buffer; + new(array: any[]): Buffer; + prototype: Buffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: Buffer[], totalLength?: number): Buffer; +}; + +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "base64" | "latin1" | "binary" | "hex"; +interface Buffer extends Uint8Array { + constructor: typeof Buffer; + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Uint8Array): boolean; + compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: string): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + keys(): IterableIterator<number>; + values(): IterableIterator<number>; +} + +/** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ +declare const Buffer: { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new(buffer: Buffer): Buffer; + prototype: Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of any TypedArray or a new ArrayBuffer() + */ + from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: any[]): Buffer; + from(data: Uint8Array): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from(str: string, encoding?: string): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + isEncoding(encoding: string): boolean | undefined; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + byteLength(string: string | NodeJS.TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + concat(list: Uint8Array[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Uint8Array, buf2: Uint8Array): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. + */ + poolSize: number; +}; + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare namespace NodeJS { + interface InspectOptions { + showHidden?: boolean; + depth?: number | null; + colors?: boolean; + customInspect?: boolean; + showProxy?: boolean; + maxArrayLength?: number | null; + breakLength?: number; + compact?: boolean; + sorted?: boolean | ((a: string, b: string) => number); + } + + interface ConsoleConstructorOptions { + stdout: WritableStream; + stderr?: WritableStream; + ignoreErrors?: boolean; + colorMode?: boolean | 'auto'; + } + + interface ConsoleConstructor { + prototype: Console; + new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + + interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + class EventEmitter { + 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; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + listenerCount(type: string | symbol): number; + // Added in Node 6... + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + eventNames(): Array<string | symbol>; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe<T extends WritableStream>(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator<string | Buffer>; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Buffer | string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(cb?: Function): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + interface Events extends EventEmitter { } + + interface Domain extends Events { + run(fn: Function): void; + add(emitter: Events): void; + remove(emitter: Events): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string): this; + } + + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + } + + interface CpuUsage { + user: number; + system: number; + } + + interface ProcessRelease { + name: string; + sourceUrl?: string; + headersUrl?: string; + libUrl?: string; + lts?: string; + } + + interface ProcessVersions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + + type Platform = 'aix' + | 'android' + | 'darwin' + | 'freebsd' + | 'linux' + | 'openbsd' + | 'sunos' + | 'win32' + | 'cygwin'; + + type Signals = + "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | + "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | + "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | + "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; + + type MultipleResolveType = 'resolve' | 'reject'; + + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise<any>) => void; + type UncaughtExceptionListener = (error: Error) => void; + type UnhandledRejectionListener = (reason: any, promise: Promise<any>) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: any, sendHandle: any) => void; + type SignalsListener = (signal: Signals) => void; + type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise<any>, value: any) => void; + + interface Socket extends ReadWriteStream { + isTTY?: true; + } + + interface ProcessEnv { + [key: string]: string | undefined; + } + + interface WriteStream extends Socket { + readonly writableHighWaterMark: number; + readonly writableLength: number; + columns?: number; + rows?: number; + _write(chunk: any, encoding: string, callback: Function): void; + _destroy(err: Error | null, callback: Function): void; + _final(callback: Function): void; + setDefaultEncoding(encoding: string): this; + cork(): void; + uncork(): void; + destroy(error?: Error): void; + } + interface ReadStream extends Socket { + readonly readableHighWaterMark: number; + readonly readableLength: number; + isRaw?: boolean; + setRawMode?(mode: boolean): void; + _read(size: number): void; + _destroy(err: Error | null, callback: Function): void; + push(chunk: any, encoding?: string): boolean; + destroy(error?: Error): void; + } + + interface Process extends EventEmitter { + stdout: WriteStream; + stderr: WriteStream; + stdin: ReadStream; + openStdin(): Socket; + argv: string[]; + argv0: string; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + debugPort: number; + emitWarning(warning: string | Error, name?: string, ctor?: Function): void; + env: ProcessEnv; + exit(code?: number): never; + exitCode: number; + getgid(): number; + setgid(id: number | string): void; + getuid(): number; + setuid(id: number | string): void; + geteuid(): number; + seteuid(id: number | string): void; + getegid(): number; + setegid(id: number | string): void; + getgroups(): number[]; + setgroups(groups: Array<string | number>): void; + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + hasUncaughtExceptionCaptureCallback(): boolean; + version: string; + versions: ProcessVersions; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string | number): void; + pid: number; + ppid: number; + title: string; + arch: string; + platform: Platform; + mainModule?: NodeModule; + memoryUsage(): MemoryUsage; + cpuUsage(previousValue?: CpuUsage): CpuUsage; + nextTick(callback: Function, ...args: any[]): void; + release: ProcessRelease; + umask(mask?: number): number; + uptime(): number; + hrtime(time?: [number, number]): [number, number]; + domain: Domain; + + // Worker + send?(message: any, sendHandle?: any): void; + disconnect(): void; + connected: boolean; + + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] + * environment variable. + */ + allowedNodeEnvironmentFlags: ReadonlySet<string>; + + /** + * EventEmitter + * 1. beforeExit + * 2. disconnect + * 3. exit + * 4. message + * 5. rejectionHandled + * 6. uncaughtException + * 7. unhandledRejection + * 8. warning + * 9. message + * 10. <All OS Signals> + * 11. newListener/removeListener inherited from EventEmitter + */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "newListener", listener: NewListenerListener): this; + addListener(event: "removeListener", listener: RemoveListenerListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise<any>): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "unhandledRejection", reason: any, promise: Promise<any>): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: any, sendHandle: any): this; + emit(event: Signals, signal: Signals): boolean; + emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; + emit(event: "multipleResolves", listener: MultipleResolveListener): this; + + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "newListener", listener: NewListenerListener): this; + on(event: "removeListener", listener: RemoveListenerListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "newListener", listener: NewListenerListener): this; + once(event: "removeListener", listener: RemoveListenerListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "newListener", listener: NewListenerListener): this; + prependListener(event: "removeListener", listener: RemoveListenerListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "newListener", listener: NewListenerListener): this; + prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "newListener"): NewListenerListener[]; + listeners(event: "removeListener"): RemoveListenerListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + } + + interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: Immediate) => void; + clearInterval: (intervalId: Timeout) => void; + clearTimeout: (timeoutId: Timeout) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => Immediate; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + interface Timer { + ref(): void; + refresh(): void; + unref(): void; + } + + class Immediate { + ref(): void; + unref(): void; + _onImmediate: Function; // to distinguish it from the Timeout class + } + + class Timeout implements Timer { + ref(): void; + refresh(): void; + unref(): void; + } + + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequireFromPath(path: string): (path: string) => any; + static builtinModules: string[]; + + static Module: typeof Module; + + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: Module | null; + children: Module[]; + paths: string[]; + + constructor(id: string, parent?: Module); + } + + type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; +} diff --git a/types/node/v10/http.d.ts b/types/node/v10/http.d.ts new file mode 100644 index 0000000000..e5f3741003 --- /dev/null +++ b/types/node/v10/http.d.ts @@ -0,0 +1,247 @@ +declare module "http" { + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; + import { URL } from "url"; + + // incoming headers will never contain number + interface IncomingHttpHeaders { + 'accept'?: string; + 'access-control-allow-origin'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-headers'?: string; + 'accept-patch'?: string; + 'accept-ranges'?: string; + 'age'?: string; + 'allow'?: string; + 'alt-svc'?: string; + 'authorization'?: string; + 'cache-control'?: string; + 'connection'?: string; + 'content-disposition'?: string; + 'content-encoding'?: string; + 'content-language'?: string; + 'content-length'?: string; + 'content-location'?: string; + 'content-range'?: string; + 'content-type'?: string; + 'cookie'?: string; + 'date'?: string; + 'expect'?: string; + 'expires'?: string; + 'forwarded'?: string; + 'from'?: string; + 'host'?: string; + 'if-match'?: string; + 'if-modified-since'?: string; + 'if-none-match'?: string; + 'if-unmodified-since'?: string; + 'last-modified'?: string; + 'location'?: string; + 'pragma'?: string; + 'proxy-authenticate'?: string; + 'proxy-authorization'?: string; + 'public-key-pins'?: string; + 'range'?: string; + 'referer'?: string; + 'retry-after'?: string; + 'set-cookie'?: string[]; + 'strict-transport-security'?: string; + 'trailer'?: string; + 'transfer-encoding'?: string; + 'tk'?: string; + 'upgrade'?: string; + 'user-agent'?: string; + 'vary'?: string; + 'via'?: string; + 'warning'?: string; + 'www-authenticate'?: string; + [header: string]: string | string[] | undefined; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + interface OutgoingHttpHeaders { + [header: string]: number | string | string[] | undefined; + } + + interface ClientRequestArgs { + protocol?: string; + host?: string; + hostname?: string; + family?: number; + port?: number | string; + defaultPort?: number | string; + localAddress?: string; + socketPath?: string; + method?: string; + path?: string; + headers?: OutgoingHttpHeaders; + auth?: string; + agent?: Agent | boolean; + _defaultAgent?: Agent; + timeout?: number; + setHost?: boolean; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: (options: ClientRequestArgs, oncreate: (err: Error, socket: net.Socket) => void) => net.Socket; + } + + class Server extends net.Server { + constructor(requestListener?: (req: IncomingMessage, res: ServerResponse) => void); + + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + maxHeadersCount: number; + timeout: number; + keepAliveTimeout: number; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js + class OutgoingMessage extends stream.Writable { + upgrading: boolean; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + finished: boolean; + headersSent: boolean; + connection: net.Socket; + + constructor(); + + setTimeout(msecs: number, callback?: () => void): this; + setHeader(name: string, value: number | string | string[]): void; + getHeader(name: string): number | string | string[] | undefined; + getHeaders(): OutgoingHttpHeaders; + getHeaderNames(): string[]; + hasHeader(name: string): boolean; + removeHeader(name: string): void; + addTrailers(headers: OutgoingHttpHeaders | Array<[string, string]>): void; + flushHeaders(): void; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_server.js#L108-L256 + class ServerResponse extends OutgoingMessage { + statusCode: number; + statusMessage: string; + + constructor(req: IncomingMessage); + + assignSocket(socket: net.Socket): void; + detachSocket(socket: net.Socket): void; + // https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53 + // no args in writeContinue callback + writeContinue(callback?: () => void): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L77 + class ClientRequest extends OutgoingMessage { + connection: net.Socket; + socket: net.Socket; + aborted: number; + + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + + abort(): void; + onSocket(socket: net.Socket): void; + setTimeout(timeout: number, callback?: () => void): this; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + } + + class IncomingMessage extends stream.Readable { + constructor(socket: net.Socket); + + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + connection: net.Socket; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + trailers: { [key: string]: string | undefined }; + rawTrailers: string[]; + setTimeout(msecs: number, callback: () => void): this; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; + destroy(error?: Error): void; + } + + interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number; + } + + class Agent { + maxFreeSockets: number; + maxSockets: number; + sockets: any; + requests: any; + + constructor(opts?: AgentOptions); + + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } + + const METHODS: string[]; + + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + + function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; + function createClient(port?: number, host?: string): any; + + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs { } + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + let globalAgent: Agent; +} diff --git a/types/node/v10/http2.d.ts b/types/node/v10/http2.d.ts new file mode 100644 index 0000000000..aecbca783f --- /dev/null +++ b/types/node/v10/http2.d.ts @@ -0,0 +1,861 @@ +declare module "http2" { + import * as events from "events"; + import * as fs from "fs"; + import * as net from "net"; + import * as stream from "stream"; + import * as tls from "tls"; + import * as url from "url"; + + import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders } from "http"; + export { OutgoingHttpHeaders } from "http"; + + export interface IncomingHttpStatusHeader { + ":status"?: number; + } + + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string; + ":method"?: string; + ":authority"?: string; + ":scheme"?: string; + } + + // Http2Stream + + export interface StreamPriorityOptions { + exclusive?: boolean; + parent?: number; + weight?: number; + silent?: boolean; + } + + export interface StreamState { + localWindowSize?: number; + state?: number; + streamLocalClose?: number; + streamRemoteClose?: number; + sumDependencyWeight?: number; + weight?: number; + } + + export interface ServerStreamResponseOptions { + endStream?: boolean; + waitForTrailers?: boolean; + } + + export interface StatOptions { + offset: number; + length: number; + } + + export interface ServerStreamFileResponseOptions { + statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void | boolean; + getTrailers?: (trailers: OutgoingHttpHeaders) => void; + offset?: number; + length?: number; + } + + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?: (err: NodeJS.ErrnoException) => void; + } + + export interface Http2Stream extends stream.Duplex { + readonly aborted: boolean; + readonly closed: boolean; + readonly destroyed: boolean; + readonly pending: boolean; + readonly rstCode: number; + readonly sentHeaders: OutgoingHttpHeaders; + readonly sentInfoHeaders?: OutgoingHttpHeaders[]; + readonly sentTrailers?: OutgoingHttpHeaders; + readonly session: Http2Session; + readonly state: StreamState; + /** + * Set the true if the END_STREAM flag was set in the request or response HEADERS frame received, + * indicating that no additional data should be received and the readable side of the Http2Stream will be closed. + */ + readonly endAfterHeaders: boolean; + close(code?: number, callback?: () => void): void; + priority(options: StreamPriorityOptions): void; + setTimeout(msecs: number, callback?: () => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + + sendTrailers(headers: OutgoingHttpHeaders): this; + } + + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + } + + export interface ServerHttp2Stream extends Http2Stream { + additionalHeaders(headers: OutgoingHttpHeaders): void; + readonly headersSent: boolean; + readonly pushAllowed: boolean; + pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + respondWithFD(fd: number, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; + respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; + } + + // Http2Session + + export interface Settings { + headerTableSize?: number; + enablePush?: boolean; + initialWindowSize?: number; + maxFrameSize?: number; + maxConcurrentStreams?: number; + maxHeaderListSize?: number; + } + + export interface ClientSessionRequestOptions { + endStream?: boolean; + exclusive?: boolean; + parent?: number; + weight?: number; + getTrailers?: (trailers: OutgoingHttpHeaders, flags: number) => void; + } + + export interface SessionState { + effectiveLocalWindowSize?: number; + effectiveRecvDataLength?: number; + nextStreamID?: number; + localWindowSize?: number; + lastProcStreamID?: number; + remoteWindowSize?: number; + outboundQueueSize?: number; + deflateDynamicTableSize?: number; + inflateDynamicTableSize?: number; + } + + export interface Http2Session extends events.EventEmitter { + readonly alpnProtocol?: string; + close(callback?: () => void): void; + readonly closed: boolean; + readonly connecting: boolean; + destroy(error?: Error, code?: number): void; + readonly destroyed: boolean; + readonly encrypted?: boolean; + goaway(code?: number, lastStreamID?: number, opaqueData?: Buffer | DataView | NodeJS.TypedArray): void; + readonly localSettings: Settings; + readonly originSet?: string[]; + readonly pendingSettingsAck: boolean; + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping(payload: Buffer | DataView | NodeJS.TypedArray , callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ref(): void; + readonly remoteSettings: Settings; + rstStream(stream: Http2Stream, code?: number): void; + setTimeout(msecs: number, callback?: () => void): void; + readonly socket: net.Socket | tls.TLSSocket; + readonly state: SessionState; + priority(stream: Http2Stream, options: StreamPriorityOptions): void; + settings(settings: Settings): void; + readonly type: number; + unref(): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + addListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "ping", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: "ping"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "ping", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "ping", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "ping", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependOnceListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + } + + export interface ClientHttp2Session extends Http2Session { + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + } + + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + + export interface ServerHttp2Session extends Http2Session { + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + readonly server: Http2Server | Http2SecureServer; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + } + + // Http2Server + + export interface SessionOptions { + maxDeflateDynamicTableSize?: number; + maxReservedRemoteStreams?: number; + maxSendHeaderBlockLength?: number; + paddingStrategy?: number; + peerMaxConcurrentStreams?: number; + selectPadding?: (frameLen: number, maxFrameLen: number) => number; + settings?: Settings; + createConnection?: (option: SessionOptions) => stream.Duplex; + } + + export type ClientSessionOptions = SessionOptions; + export type ServerSessionOptions = SessionOptions; + + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions { } + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions { } + + export interface ServerOptions extends ServerSessionOptions { + allowHTTP1?: boolean; + } + + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean; + } + + export interface Http2Server extends net.Server { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "timeout", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + export interface Http2SecureServer extends tls.Server { + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + } + + export class Http2ServerRequest extends stream.Readable { + private constructor(); + headers: IncomingHttpHeaders; + httpVersion: string; + method: string; + rawHeaders: string[]; + rawTrailers: string[]; + setTimeout(msecs: number, callback?: () => void): void; + socket: net.Socket | tls.TLSSocket; + stream: ServerHttp2Stream; + trailers: IncomingHttpHeaders; + url: string; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "aborted", hadError: boolean, code: number): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + } + + export class Http2ServerResponse extends events.EventEmitter { + private constructor(); + addTrailers(trailers: OutgoingHttpHeaders): void; + connection: net.Socket | tls.TLSSocket; + end(callback?: () => void): void; + end(data?: string | Buffer, callback?: () => void): void; + end(data?: string | Buffer, encoding?: string, callback?: () => void): void; + readonly finished: boolean; + getHeader(name: string): string; + getHeaderNames(): string[]; + getHeaders(): OutgoingHttpHeaders; + hasHeader(name: string): boolean; + readonly headersSent: boolean; + removeHeader(name: string): void; + sendDate: boolean; + setHeader(name: string, value: number | string | string[]): void; + setTimeout(msecs: number, callback?: () => void): void; + socket: net.Socket | tls.TLSSocket; + statusCode: number; + statusMessage: ''; + stream: ServerHttp2Stream; + write(chunk: string | Buffer, callback?: (err: Error) => void): boolean; + write(chunk: string | Buffer, encoding?: string, callback?: (err: Error) => void): boolean; + writeContinue(): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, statusMessage?: string, headers?: OutgoingHttpHeaders): void; + createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + } + + // Public API + + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + + export function getDefaultSettings(): Settings; + export function getPackedSettings(settings: Settings): Settings; + export function getUnpackedSettings(buf: Buffer | Uint8Array): Settings; + + export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + + export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + + export function connect(authority: string | url.URL, listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; +} diff --git a/types/node/v10/https.d.ts b/types/node/v10/https.d.ts new file mode 100644 index 0000000000..c9bc7c5f63 --- /dev/null +++ b/types/node/v10/https.d.ts @@ -0,0 +1,37 @@ +declare module "https" { + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; + import { URL } from "url"; + + type ServerOptions = tls.SecureContextOptions & tls.TlsOptions; + + type RequestOptions = http.RequestOptions & tls.SecureContextOptions & { + rejectUnauthorized?: boolean; // Defaults to true + servername?: string; // SNI TLS Extension + }; + + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean; + maxCachedSessions?: number; + } + + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + + class Server extends tls.Server { + setTimeout(callback: () => void): this; + setTimeout(msecs?: number, callback?: () => void): this; + timeout: number; + keepAliveTimeout: number; + } + + function createServer(options: ServerOptions, requestListener?: (req: http.IncomingMessage, res: http.ServerResponse) => void): Server; + function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + let globalAgent: Agent; +} diff --git a/types/node/v10/index.d.ts b/types/node/v10/index.d.ts new file mode 100644 index 0000000000..a237502039 --- /dev/null +++ b/types/node/v10/index.d.ts @@ -0,0 +1,85 @@ +// Type definitions for Node.js 10.12 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript <https://github.com/Microsoft> +// DefinitelyTyped <https://github.com/DefinitelyTyped> +// Alberto Schiabel <https://github.com/jkomyno> +// Alexander T. <https://github.com/a-tarasyuk> +// Alvis HT Tang <https://github.com/alvis> +// Andrew Makarov <https://github.com/r3nya> +// Bruno Scheufler <https://github.com/brunoscheufler> +// Chigozirim C. <https://github.com/smac89> +// Christian Vaagland Tellnes <https://github.com/tellnes> +// Deividas Bakanas <https://github.com/DeividasBakanas> +// Eugene Y. Q. Shen <https://github.com/eyqs> +// Flarna <https://github.com/Flarna> +// Hannes Magnusson <https://github.com/Hannes-Magnusson-CK> +// Hoàng Văn Khải <https://github.com/KSXGitHub> +// Huw <https://github.com/hoo29> +// Kelvin Jin <https://github.com/kjin> +// Klaus Meinhardt <https://github.com/ajafff> +// Lishude <https://github.com/islishude> +// Mariusz Wiktorczyk <https://github.com/mwiktorczyk> +// Matthieu Sieben <https://github.com/matthieusieben> +// Mohsen Azimi <https://github.com/mohsen1> +// Nicolas Even <https://github.com/n-e> +// Nicolas Voigt <https://github.com/octo-sniffle> +// Parambir Singh <https://github.com/parambirs> +// Sebastian Silbermann <https://github.com/eps1lon> +// Simon Schick <https://github.com/SimonSchick> +// Thomas den Hollander <https://github.com/ThomasdenH> +// Wilco Bakker <https://github.com/WilcoBakker> +// wwwy3y3 <https://github.com/wwwy3y3> +// Zane Hannan AU <https://github.com/ZaneHannanAU> +// Jeremie Rodriguez <https://github.com/jeremiergz> +// Samuel Ainsworth <https://github.com/samuela> +// Kyle Uehlein <https://github.com/kuehlein> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// NOTE: These definitions support NodeJS and TypeScript 3.1. + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 2.1 +// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 + +// NOTE: Augmentations for TypeScript 3.1 and later should use individual files for overrides +// within the respective ~/ts3.1 (or later) folder. However, this is disallowed for versions +// prior to TypeScript 3.1, so the older definitions will be found here. + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// <reference path="base.d.ts" /> + +// TypeScript 2.1-specific augmentations: + +// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } +interface Set<T> {} +interface ReadonlySet<T> {} +interface IteratorResult<T> { } +interface Iterable<T> { } +interface Iterator<T> { + next(value?: any): IteratorResult<T>; +} +interface IterableIterator<T> { } +interface AsyncIterableIterator<T> {} +interface SymbolConstructor { + readonly iterator: symbol; + readonly asyncIterator: symbol; +} +declare var Symbol: SymbolConstructor; +interface SharedArrayBuffer { + readonly byteLength: number; + slice(begin?: number, end?: number): SharedArrayBuffer; +} + +declare module "util" { + namespace inspect { + const custom: symbol; + } + namespace promisify { + const custom: symbol; + } +} diff --git a/types/node/v10/inspector.d.ts b/types/node/v10/inspector.d.ts new file mode 100644 index 0000000000..2dcd2760ad --- /dev/null +++ b/types/node/v10/inspector.d.ts @@ -0,0 +1,3162 @@ +// tslint:disable-next-line:dt-header +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module "inspector" { + import { EventEmitter } from 'events'; + + interface InspectorNotification<T> { + method: string; + params: T; + } + + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number; + } + + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + + /** + * Call frame identifier. + */ + type CallFrameId = string; + + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the `Debugger.scriptParsed`. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number; + } + + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * `this` object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject; + } + + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For `global` and `with` scopes it represents the actual + * object; for the rest of the scopes, it is artificial transient object enumerating scope + * variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string; + /** + * Location in the source code where scope starts + */ + startLocation?: Location; + /** + * Location in the source code where scope ends + */ + endLocation?: Location; + } + + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + + interface BreakLocation { + /** + * Script identifier as reported in the `Debugger.scriptParsed`. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number; + type?: string; + } + + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string; + } + + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles + * using `releaseObjectGroup`). + */ + objectGroup?: string; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults + * to false. + */ + includeCommandLineAPI?: boolean; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean; + /** + * Terminate execution after timing out (number of milliseconds). + * @experimental + */ + timeout?: Runtime.TimeDelta; + } + + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end + * of scripts is used as end of range. + */ + end?: Location; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean; + } + + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean; + } + + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async + * call stacks (default). + */ + maxDepth: number; + } + + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the + * breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either `url` or + * `urlRegex` must be specified. + */ + urlRegex?: string; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the + * breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + interface SetBreakpointOnFunctionCallParameterType { + /** + * Function object id. + */ + objectId: Runtime.RemoteObjectId; + /** + * Expression to use as a breakpoint condition. When specified, debugger will + * stop on the breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result + * description without actually modifying the code. + */ + dryRun?: boolean; + } + + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' + * scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled + * before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean; + } + + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + } + + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + + interface SetBreakpointOnFunctionCallReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + } + + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[]; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {}; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. + * This field is available only after `Debugger.stepInto` call with `breakOnAsynCall` flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId; + } + + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {}; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean; + /** + * This script length. + */ + length?: number; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace; + } + + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {}; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean; + /** + * This script length. + */ + length?: number; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace; + } + } + + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + } + + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The + * default value is 32768 bytes. + */ + samplingInterval?: number; + } + + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean; + } + + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken + * when the tracking is stopped. + */ + reportProgress?: boolean; + } + + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean; + } + + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment + * index, the second integer is a total count of objects for the fragment, the third integer is + * a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean; + } + } + + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number; + /** + * Child node ids. + */ + children?: number[]; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't + * optimize. + */ + deoptReason?: string; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[]; + } + + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[]; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the + * profile startTime. + */ + timeDeltas?: number[]; + } + + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean; + /** + * Collect block-based coverage. + */ + detailed?: boolean; + } + + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + + interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string; + } + + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string; + } + } + + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + + /** + * Primitive value which cannot be JSON-stringified. Includes values `-0`, `NaN`, `Infinity`, + * `-Infinity`, and bigint literals. + */ + type UnserializableValue = string; + + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for `object` type values only. + */ + subtype?: string; + /** + * Object class (constructor) name. Specified for `object` type values only. + */ + className?: string; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have `value`, but gets this + * property. + */ + unserializableValue?: UnserializableValue; + /** + * String representation of the object. + */ + description?: string; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId; + /** + * Preview containing abbreviated property values. Specified for `object` type values only. + * @experimental + */ + preview?: ObjectPreview; + /** + * @experimental + */ + customPreview?: CustomPreview; + } + + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId; + } + + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for `object` type values only. + */ + subtype?: string; + /** + * String representation of the object. + */ + description?: string; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for `map` and `set` subtype values only. + */ + entries?: EntryPreview[]; + } + + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview; + /** + * Object subtype hint. Specified for `object` type values only. + */ + subtype?: string; + } + + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean; + /** + * A function which serves as a getter for the property, or `undefined` if there is no getter + * (accessor descriptors only). + */ + get?: RemoteObject; + /** + * A function which serves as a setter for the property, or `undefined` if there is no setter + * (accessor descriptors only). + */ + set?: RemoteObject; + /** + * True if the type of this property descriptor may be changed and if the property may be + * deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding + * object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean; + /** + * Property symbol object, if the property is of the `symbol` type. + */ + symbol?: RemoteObject; + } + + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject; + } + + /** + * Represents function call argument. Either remote object id `objectId`, primitive `value`, + * unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId; + } + + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context + * script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {}; + } + + /** + * Detailed information about exception (or error) that was thrown during script compilation or + * execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace; + /** + * Exception object if available. + */ + exception?: RemoteObject; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId; + } + + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + + /** + * Number of milliseconds. + */ + type TimeDelta = number; + + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that + * initiated the async call. + */ + description?: string; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId; + } + + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + + /** + * If `debuggerId` is set stack trace comes from another debugger and can be resolved there. This + * allows to track cross-debugger calls. See `Runtime.StackTrace` and `Debugger.paused` for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId; + } + + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean; + } + + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should + * be specified. + */ + objectId?: RemoteObjectId; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target + * object. + */ + arguments?: CallArgument[]; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean; + /** + * Whether execution should `await` for resulting value and return once awaited promise is + * resolved. + */ + awaitPromise?: boolean; + /** + * Specifies execution context which global object will be used to call function on. Either + * executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not + * specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string; + } + + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the + * evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId; + } + + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the + * evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean; + /** + * Whether execution should `await` for resulting value and return once awaited promise is + * resolved. + */ + awaitPromise?: boolean; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + * @experimental + */ + throwOnSideEffect?: boolean; + /** + * Terminate execution after timing out (number of milliseconds). + * @experimental + */ + timeout?: TimeDelta; + } + + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype + * chain. + */ + ownProperties?: boolean; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not + * returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean; + } + + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId; + } + + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + /** + * Symbolic group name that can be used to release the results. + */ + objectGroup?: string; + } + + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the + * evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean; + /** + * Whether execution should `await` for resulting value and return once awaited promise is + * resolved. + */ + awaitPromise?: boolean; + } + + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails; + } + + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface GetIsolateIdReturnType { + /** + * The isolate id. + */ + id: string; + } + + interface GetHeapUsageReturnType { + /** + * Used heap size in bytes. + */ + usedSize: number; + /** + * Allocated heap size in bytes. + */ + totalSize: number; + } + + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[]; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace; + /** + * Console context descriptor for calls on non-default console context (not console.*): + * 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call + * on named context. + * @experimental + */ + context?: string; + } + + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in `exceptionThrown`. + */ + exceptionId: number; + } + + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string; + /** + * Included category filters. + */ + includedCategories: string[]; + } + + interface StartParameterType { + traceConfig: TraceConfig; + } + + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + + namespace NodeWorker { + type WorkerID = string; + + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + + /** + * The inspector.Session is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if there is already a connected session established either + * through the API or by a front-end connected to the Inspector WebSocket port. + */ + connect(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * session.connect() will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. callback will be notified when a response is received. + * callback is a function that accepts two optional arguments - error and message-specific result. + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + + /** + * Does nothing. + */ + post(method: "Console.clearMessages", callback?: (err: Error | null) => void): void; + + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable", callback?: (err: Error | null) => void): void; + + /** + * Enables console domain, sends the messages collected so far to the client by means of the + * `messageAdded` notification. + */ + post(method: "Console.enable", callback?: (err: Error | null) => void): void; + + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.continueToLocation", callback?: (err: Error | null) => void): void; + + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable", callback?: (err: Error | null) => void): void; + + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been + * enabled until the result for this command is received. + */ + post(method: "Debugger.enable", callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: "Debugger.evaluateOnCallFrame", callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be + * the same. + */ + post( + method: "Debugger.getPossibleBreakpoints", + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: "Debugger.getPossibleBreakpoints", callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: "Debugger.getScriptSource", callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + + /** + * Returns stack trace with given `stackTraceId`. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: "Debugger.getStackTrace", callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause", callback?: (err: Error | null) => void): void; + + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.pauseOnAsyncCall", callback?: (err: Error | null) => void): void; + + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.removeBreakpoint", callback?: (err: Error | null) => void): void; + + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: "Debugger.restartFrame", callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume", callback?: (err: Error | null) => void): void; + + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and + * Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled + * before next pause. Returns success when async task is actually scheduled, returns error if no + * task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync", callback?: (err: Error | null) => void): void; + + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: "Debugger.searchInContent", callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setAsyncCallStackDepth", callback?: (err: Error | null) => void): void; + + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in + * scripts with url matching one of the patterns. VM will try to leave blackboxed script by + * performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxPatterns", callback?: (err: Error | null) => void): void; + + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted + * scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * Positions array contains positions where blackbox state is changed. First interval isn't + * blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxedRanges", callback?: (err: Error | null) => void): void; + + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: "Debugger.setBreakpoint", callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this + * command is issued, all existing parsed scripts will have breakpoints resolved and returned in + * `locations` property. Further matching script parsing will result in subsequent + * `breakpointResolved` events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: "Debugger.setBreakpointByUrl", callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + + /** + * Sets JavaScript breakpoint before each call to the given function. + * If another function was created from the same source as a given one, + * calling it will also trigger the breakpoint. + * @experimental + */ + post( + method: "Debugger.setBreakpointOnFunctionCall", + params?: Debugger.SetBreakpointOnFunctionCallParameterType, + callback?: (err: Error | null, params: Debugger.SetBreakpointOnFunctionCallReturnType) => void + ): void; + post(method: "Debugger.setBreakpointOnFunctionCall", callback?: (err: Error | null, params: Debugger.SetBreakpointOnFunctionCallReturnType) => void): void; + + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBreakpointsActive", callback?: (err: Error | null) => void): void; + + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or + * no exceptions. Initial pause on exceptions state is `none`. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setPauseOnExceptions", callback?: (err: Error | null) => void): void; + + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setReturnValue", callback?: (err: Error | null) => void): void; + + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: "Debugger.setScriptSource", callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setSkipAllPauses", callback?: (err: Error | null) => void): void; + + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be + * mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setVariableValue", callback?: (err: Error | null) => void): void; + + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.stepInto", callback?: (err: Error | null) => void): void; + + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut", callback?: (err: Error | null) => void): void; + + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; + + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details + * $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.addInspectedHeapObject", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.collectGarbage", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.disable", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.enable", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.getHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + + post( + method: "HeapProfiler.getObjectByHeapObjectId", + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: "HeapProfiler.getObjectByHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + + post(method: "HeapProfiler.getSamplingProfile", callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startSampling", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.stopSampling", callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; + + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to + * garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage", callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.setSamplingInterval", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.start", callback?: (err: Error | null) => void): void; + + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code + * coverage may be incomplete. Enabling prevents running optimized code and resets execution + * counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.startPreciseCoverage", callback?: (err: Error | null) => void): void; + + /** + * Enable type profile. + * @experimental + */ + post(method: "Profiler.startTypeProfile", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.stop", callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows + * executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage", callback?: (err: Error | null) => void): void; + + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: "Profiler.stopTypeProfile", callback?: (err: Error | null) => void): void; + + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code + * coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage", callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + + /** + * Collect type profile. + * @experimental + */ + post(method: "Profiler.takeTypeProfile", callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: "Runtime.awaitPromise", callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + + /** + * Calls function with given declaration on the given object. Object group of the result is + * inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: "Runtime.callFunctionOn", callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: "Runtime.compileScript", callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable", callback?: (err: Error | null) => void): void; + + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries", callback?: (err: Error | null) => void): void; + + /** + * Enables reporting of execution contexts creation by means of `executionContextCreated` event. + * When the reporting gets enabled the event will be sent immediately for each existing execution + * context. + */ + post(method: "Runtime.enable", callback?: (err: Error | null) => void): void; + + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: "Runtime.evaluate", callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + + /** + * Returns the isolate id. + * @experimental + */ + post(method: "Runtime.getIsolateId", callback?: (err: Error | null, params: Runtime.GetIsolateIdReturnType) => void): void; + + /** + * Returns the JavaScript heap usage. + * It is the total usage of the corresponding isolate not scoped to a particular Runtime. + * @experimental + */ + post(method: "Runtime.getHeapUsage", callback?: (err: Error | null, params: Runtime.GetHeapUsageReturnType) => void): void; + + /** + * Returns properties of a given object. Object group of the result is inherited from the target + * object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: "Runtime.getProperties", callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: "Runtime.globalLexicalScopeNames", + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: "Runtime.globalLexicalScopeNames", callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: "Runtime.queryObjects", callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObject", callback?: (err: Error | null) => void): void; + + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObjectGroup", callback?: (err: Error | null) => void): void; + + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger", callback?: (err: Error | null) => void): void; + + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.runScript", callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.setCustomObjectFormatterEnabled", callback?: (err: Error | null) => void): void; + + /** + * Terminate current or next JavaScript execution. + * Will cancel the termination when the outer-most script execution ends. + * @experimental + */ + post(method: "Runtime.terminateExecution", callback?: (err: Error | null) => void): void; + + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories", callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeTracing.start", callback?: (err: Error | null) => void): void; + + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop", callback?: (err: Error | null) => void): void; + + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.sendMessageToWorker", callback?: (err: Error | null) => void): void; + + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.enable", callback?: (err: Error | null) => void): void; + + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable", callback?: (err: Error | null) => void): void; + + // Events + + addListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification<Console.MessageAddedEventDataType>) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification<Debugger.PausedEventDataType>) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification<Debugger.ScriptParsedEventDataType>) => void): this; + + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>) => void): this; + + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>) => void): this; + + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification<Runtime.ExceptionThrownEventDataType>) => void): this; + + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>) => void): this; + + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification<Runtime.InspectRequestedEventDataType>) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification<NodeTracing.DataCollectedEventDataType>) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>) => void): this; + + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification<{}>): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification<Console.MessageAddedEventDataType>): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>): boolean; + emit(event: "Debugger.paused", message: InspectorNotification<Debugger.PausedEventDataType>): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification<Debugger.ScriptParsedEventDataType>): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification<Runtime.ExceptionThrownEventDataType>): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification<Runtime.InspectRequestedEventDataType>): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification<NodeTracing.DataCollectedEventDataType>): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification<Console.MessageAddedEventDataType>) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification<Debugger.PausedEventDataType>) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification<Debugger.ScriptParsedEventDataType>) => void): this; + + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>) => void): this; + + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>) => void): this; + + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification<Runtime.ExceptionThrownEventDataType>) => void): this; + + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>) => void): this; + + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification<Runtime.InspectRequestedEventDataType>) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification<NodeTracing.DataCollectedEventDataType>) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>) => void): this; + + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification<Console.MessageAddedEventDataType>) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification<Debugger.PausedEventDataType>) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification<Debugger.ScriptParsedEventDataType>) => void): this; + + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>) => void): this; + + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>) => void): this; + + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification<Runtime.ExceptionThrownEventDataType>) => void): this; + + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>) => void): this; + + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification<Runtime.InspectRequestedEventDataType>) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification<NodeTracing.DataCollectedEventDataType>) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>) => void): this; + + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification<Console.MessageAddedEventDataType>) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification<Debugger.PausedEventDataType>) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification<Debugger.ScriptParsedEventDataType>) => void): this; + + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>) => void): this; + + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>) => void): this; + + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification<Runtime.ExceptionThrownEventDataType>) => void): this; + + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification<Runtime.InspectRequestedEventDataType>) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification<NodeTracing.DataCollectedEventDataType>) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>) => void): this; + + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification<Console.MessageAddedEventDataType>) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification<Debugger.BreakpointResolvedEventDataType>) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification<Debugger.PausedEventDataType>) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification<Debugger.ScriptFailedToParseEventDataType>) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification<Debugger.ScriptParsedEventDataType>) => void): this; + + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification<HeapProfiler.AddHeapSnapshotChunkEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification<HeapProfiler.HeapStatsUpdateEventDataType>) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification<HeapProfiler.LastSeenObjectIdEventDataType>) => void): this; + + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification<HeapProfiler.ReportHeapSnapshotProgressEventDataType>) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification<Profiler.ConsoleProfileFinishedEventDataType>) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification<Profiler.ConsoleProfileStartedEventDataType>) => void): this; + + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification<Runtime.ConsoleAPICalledEventDataType>) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification<Runtime.ExceptionRevokedEventDataType>) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification<Runtime.ExceptionThrownEventDataType>) => void): this; + + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification<Runtime.ExecutionContextCreatedEventDataType>) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification<Runtime.ExecutionContextDestroyedEventDataType>) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification<Runtime.InspectRequestedEventDataType>) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification<NodeTracing.DataCollectedEventDataType>) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification<NodeWorker.AttachedToWorkerEventDataType>) => void): this; + + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification<NodeWorker.DetachedFromWorkerEventDataType>) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification<NodeWorker.ReceivedMessageFromWorkerEventDataType>) => void): this; + } + + // Top Level API + + /** + * Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programatically after node has started. + * If wait is true, will block until a client has connected to the inspect port and flow control has been passed to the debugger client. + * @param port Port to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Optional, defaults to false. + */ + function open(port?: number, host?: string, wait?: boolean): void; + + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + + /** + * Return the URL of the active inspector, or undefined if there is none. + */ + function url(): string; +} diff --git a/types/node/v10/module.d.ts b/types/node/v10/module.d.ts new file mode 100644 index 0000000000..f512be7e5e --- /dev/null +++ b/types/node/v10/module.d.ts @@ -0,0 +1,3 @@ +declare module "module" { + export = NodeJS.Module; +} diff --git a/types/node/v10/net.d.ts b/types/node/v10/net.d.ts new file mode 100644 index 0000000000..27804375aa --- /dev/null +++ b/types/node/v10/net.d.ts @@ -0,0 +1,251 @@ +declare module "net" { + import * as stream from "stream"; + import * as events from "events"; + import * as dns from "dns"; + + type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + interface SocketConstructorOpts { + fd?: number; + allowHalfOpen?: boolean; + readable?: boolean; + writable?: boolean; + } + + interface TcpSocketConnectOpts { + port: number; + host?: string; + localAddress?: string; + localPort?: number; + hints?: number; + family?: number; + lookup?: LookupFunction; + } + + interface IpcSocketConnectOpts { + path: string; + } + + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + write(data: any, encoding?: string, callback?: Function): void; + + connect(options: SocketConnectOpts, connectionListener?: Function): this; + connect(port: number, host: string, connectionListener?: Function): this; + connect(port: number, connectionListener?: Function): this; + connect(path: string, connectionListener?: Function): this; + + setEncoding(encoding?: string): this; + pause(): this; + resume(): this; + setTimeout(timeout: number, callback?: Function): this; + setNoDelay(noDelay?: boolean): this; + setKeepAlive(enable?: boolean, initialDelay?: number): this; + address(): AddressInfo | string; + unref(): void; + ref(): void; + + readonly bufferSize: number; + readonly bytesRead: number; + readonly bytesWritten: number; + readonly connecting: boolean; + readonly destroyed: boolean; + readonly localAddress: string; + readonly localPort: number; + readonly remoteAddress?: string; + readonly remoteFamily?: string; + readonly remotePort?: number; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (had_error: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: "timeout", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", had_error: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "timeout"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (had_error: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: "timeout", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (had_error: boolean) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (had_error: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + interface ListenOptions { + port?: number; + host?: string; + backlog?: number; + path?: string; + exclusive?: boolean; + readableAll?: boolean; + writableAll?: boolean; + } + + // https://github.com/nodejs/node/blob/master/lib/net.js + class Server extends events.EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void); + + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: Function): this; + listen(port?: number, hostname?: string, listeningListener?: Function): this; + listen(port?: number, backlog?: number, listeningListener?: Function): this; + listen(port?: number, listeningListener?: Function): this; + listen(path: string, backlog?: number, listeningListener?: Function): this; + listen(path: string, listeningListener?: Function): this; + listen(options: ListenOptions, listeningListener?: Function): this; + listen(handle: any, backlog?: number, listeningListener?: Function): this; + listen(handle: any, listeningListener?: Function): this; + close(callback?: Function): this; + address(): AddressInfo | string; + getConnections(cb: (error: Error | null, count: number) => void): void; + ref(): this; + unref(): this; + maxConnections: number; + connections: number; + listening: boolean; + + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + } + + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number; + } + + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number; + } + + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void): Server; + function connect(options: NetConnectOpts, connectionListener?: Function): Socket; + function connect(port: number, host?: string, connectionListener?: Function): Socket; + function connect(path: string, connectionListener?: Function): Socket; + function createConnection(options: NetConnectOpts, connectionListener?: Function): Socket; + function createConnection(port: number, host?: string, connectionListener?: Function): Socket; + function createConnection(path: string, connectionListener?: Function): Socket; + function isIP(input: string): number; + function isIPv4(input: string): boolean; + function isIPv6(input: string): boolean; +} diff --git a/types/node/v10/node-tests.ts b/types/node/v10/node-tests.ts new file mode 100644 index 0000000000..220de8ca8a --- /dev/null +++ b/types/node/v10/node-tests.ts @@ -0,0 +1,4837 @@ +import assert = require("assert"); +import * as fs from "fs"; +import * as events from "events"; +import events2 = require("events"); +import * as zlib from "zlib"; +import * as url from "url"; +import * as util from "util"; +import * as crypto from "crypto"; +import * as tls from "tls"; +import * as http from "http"; +import * as https from "https"; +import * as net from "net"; +import * as tty from "tty"; +import * as dgram from "dgram"; +import * as querystring from "querystring"; +import * as path from "path"; +import * as readline from "readline"; +import * as childProcess from "child_process"; +import * as cluster from "cluster"; +import * as workerThreads from "worker_threads"; +import * as os from "os"; +import * as vm from "vm"; +import * as console2 from "console"; +import * as string_decoder from "string_decoder"; +import * as stream from "stream"; +import * as timers from "timers"; +import * as repl from "repl"; +import * as v8 from "v8"; +import * as dns from "dns"; +import * as async_hooks from "async_hooks"; +import * as http2 from "http2"; +import * as inspector from "inspector"; +import * as perf_hooks from "perf_hooks"; +import * as trace_events from "trace_events"; +import Module = require("module"); + +// Specifically test buffer module regression. +import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buffer"; + +////////////////////////////////////////////////////////// +/// Global Tests : https://nodejs.org/api/global.html /// +////////////////////////////////////////////////////////// +{ + { + const x: NodeModule = {} as any; + const y: NodeModule = {} as any; + x.children.push(y); + x.parent = require.main; + require.main = y; + } +} + +////////////////////////////////////////////////////////// +/// Assert Tests : https://nodejs.org/api/assert.html /// +////////////////////////////////////////////////////////// + +{ + { + assert(1 + 1 - 2 === 0, "The universe isn't how it should."); + + assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); + + assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); + + assert.doesNotThrow(() => { + const b = false; + if (b) { throw new Error("a hammer at your face"); } + }, undefined, "What the...*crunch*"); + + assert.equal(3, "3", "uses == comparator"); + + assert.fail('stuff broke'); + + assert.fail('actual', 'expected', 'message'); + + assert.fail(1, 2, undefined, '>'); + + assert.ifError(0); + + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); + + assert.notEqual(1, 2, "uses != comparator"); + + assert.notStrictEqual(2, "2", "uses === comparator"); + + assert.ok(true); + assert.ok(1); + + assert.strictEqual(1, 1, "uses === comparator"); + + assert.throws(() => { throw new Error("a hammer at your face"); }, undefined, "DODGED IT"); + + assert.strict.strict.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); + } +} + +//////////////////////////////////////////////////// +/// Events tests : http://nodejs.org/api/events.html +//////////////////////////////////////////////////// + +{ + const emitter: events.EventEmitter = new events.EventEmitter(); + const event: string | symbol = ''; + const listener: (...args: any[]) => void = () => {}; + const any: any = 1; + + { + let result: events.EventEmitter; + + result = emitter.addListener(event, listener); + result = emitter.on(event, listener); + result = emitter.once(event, listener); + result = emitter.prependListener(event, listener); + result = emitter.prependOnceListener(event, listener); + result = emitter.removeListener(event, listener); + result = emitter.off(event, listener); + result = emitter.removeAllListeners(); + result = emitter.removeAllListeners(event); + result = emitter.setMaxListeners(42); + } + + { + let result: number; + + result = events.EventEmitter.defaultMaxListeners; + result = events.EventEmitter.listenerCount(emitter, event); // deprecated + + result = emitter.getMaxListeners(); + result = emitter.listenerCount(event); + } + + { + let result: Function[]; + + result = emitter.listeners(event); + } + + { + let result: boolean; + + result = emitter.emit(event); + result = emitter.emit(event, any); + result = emitter.emit(event, any, any); + result = emitter.emit(event, any, any, any); + } + + { + let result: Array<string | symbol>; + + result = emitter.eventNames(); + } + + { + class Networker extends events.EventEmitter { + constructor() { + super(); + + this.emit("mingling"); + } + } + } + + { + new events2(); + } +} + +//////////////////////////////////////////////////// +/// File system tests : http://nodejs.org/api/fs.html +//////////////////////////////////////////////////// + +{ + { + fs.writeFile("thebible.txt", + "Do unto others as you would have them do unto you.", + assert.ifError); + + fs.write(1234, "test", () => { }); + + fs.writeFile("Harry Potter", + "\"You be wizzing, Harry,\" jived Dumbledore.", + { + encoding: "ascii" + }, + assert.ifError); + + fs.writeFile("testfile", "content", "utf8", assert.ifError); + + fs.writeFileSync("testfile", "content", "utf8"); + fs.writeFileSync("testfile", "content", { encoding: "utf8" }); + fs.writeFileSync("testfile", new DataView(new ArrayBuffer(1)), { encoding: "utf8" }); + } + + { + fs.appendFile("testfile", "foobar", "utf8", assert.ifError); + fs.appendFile("testfile", "foobar", { encoding: "utf8" }, assert.ifError); + fs.appendFileSync("testfile", "foobar", "utf8"); + fs.appendFileSync("testfile", "foobar", { encoding: "utf8" }); + } + + { + let content: string; + let buffer: Buffer; + let stringOrBuffer: string | Buffer; + const nullEncoding: string | null = null; + const stringEncoding: string | null = 'utf8'; + + content = fs.readFileSync('testfile', 'utf8'); + content = fs.readFileSync('testfile', { encoding: 'utf8' }); + stringOrBuffer = fs.readFileSync('testfile', stringEncoding); + stringOrBuffer = fs.readFileSync('testfile', { encoding: stringEncoding }); + + buffer = fs.readFileSync('testfile'); + buffer = fs.readFileSync('testfile', null); + buffer = fs.readFileSync('testfile', { encoding: null }); + stringOrBuffer = fs.readFileSync('testfile', nullEncoding); + stringOrBuffer = fs.readFileSync('testfile', { encoding: nullEncoding }); + + buffer = fs.readFileSync('testfile', { flag: 'r' }); + + fs.readFile('testfile', 'utf8', (err, data) => content = data); + fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data); + fs.readFile('testfile', stringEncoding, (err, data) => stringOrBuffer = data); + fs.readFile('testfile', { encoding: stringEncoding }, (err, data) => stringOrBuffer = data); + + fs.readFile('testfile', (err, data) => buffer = data); + fs.readFile('testfile', null, (err, data) => buffer = data); + fs.readFile('testfile', { encoding: null }, (err, data) => buffer = data); + fs.readFile('testfile', nullEncoding, (err, data) => stringOrBuffer = data); + fs.readFile('testfile', { encoding: nullEncoding }, (err, data) => stringOrBuffer = data); + + fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); + } + + { + fs.read(1, new DataView(new ArrayBuffer(1)), 0, 1, 0, (err: NodeJS.ErrnoException, bytesRead: number, buffer: DataView) => {}); + } + + { + fs.readSync(1, new DataView(new ArrayBuffer(1)), 0, 1, 0); + } + + { + let errno: number; + fs.readFile('testfile', (err, data) => { + if (err && err.errno) { + errno = err.errno; + } + }); + } + + { + let listS: string[]; + listS = fs.readdirSync('path'); + listS = fs.readdirSync('path', { encoding: 'utf8' }); + listS = fs.readdirSync('path', { encoding: null }); + listS = fs.readdirSync('path', { encoding: undefined }); + listS = fs.readdirSync('path', 'utf8'); + listS = fs.readdirSync('path', null); + listS = fs.readdirSync('path', undefined); + const listDir: fs.Dirent[] = fs.readdirSync('path', { withFileTypes: true }); + const listDir2: Buffer[] = fs.readdirSync('path', { withFileTypes: false, encoding: 'buffer' }); + + let listB: Buffer[]; + listB = fs.readdirSync('path', { encoding: 'buffer' }); + listB = fs.readdirSync("path", 'buffer'); + + const enc = 'buffer'; + fs.readdirSync('path', { encoding: enc }); + fs.readdirSync('path', { }); + + fs.readdir('path', { withFileTypes: true }, (err: NodeJS.ErrnoException, files: fs.Dirent[]) => {}); + } + { + fs.mkdtemp('/tmp/foo-', (err, folder) => { + console.log(folder); + // Prints: /tmp/foo-itXde2 + }); + } + + { + let tempDir: string; + tempDir = fs.mkdtempSync('/tmp/foo-'); + } + + { + fs.watch('/tmp/foo-', (event, filename) => { + console.log(event, filename); + }); + + fs.watch('/tmp/foo-', 'utf8', (event, filename) => { + console.log(event, filename); + }); + + fs.watch('/tmp/foo-', { + recursive: true, + persistent: true, + encoding: 'utf8' + }, (event, filename) => { + console.log(event, filename); + }); + } + + { + fs.access('/path/to/folder', (err) => { }); + + fs.access(Buffer.from(''), (err) => { }); + + fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => { }); + + fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => { }); + + fs.accessSync('/path/to/folder'); + + fs.accessSync(Buffer.from('')); + + fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK); + + fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK); + } + + { + let s: string; + let b: Buffer; + fs.readlink('/path/to/folder', (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', undefined, (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', 'utf8', (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', 'buffer', (err, linkString) => b = linkString); + fs.readlink('/path/to/folder', s, (err, linkString) => typeof linkString === 'string' ? s = linkString : b = linkString); + fs.readlink('/path/to/folder', {}, (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', { encoding: undefined }, (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', { encoding: 'utf8' }, (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', { encoding: 'buffer' }, (err, linkString) => b = linkString); + fs.readlink('/path/to/folder', { encoding: s }, (err, linkString) => typeof linkString === "string" ? s = linkString : b = linkString); + + s = fs.readlinkSync('/path/to/folder'); + s = fs.readlinkSync('/path/to/folder', undefined); + s = fs.readlinkSync('/path/to/folder', 'utf8'); + b = fs.readlinkSync('/path/to/folder', 'buffer'); + const v1 = fs.readlinkSync('/path/to/folder', s); + typeof v1 === "string" ? s = v1 : b = v1; + + s = fs.readlinkSync('/path/to/folder', {}); + s = fs.readlinkSync('/path/to/folder', { encoding: undefined }); + s = fs.readlinkSync('/path/to/folder', { encoding: 'utf8' }); + b = fs.readlinkSync('/path/to/folder', { encoding: 'buffer' }); + const v2 = fs.readlinkSync('/path/to/folder', { encoding: s }); + typeof v2 === "string" ? s = v2 : b = v2; + } + + { + let s: string; + let b: Buffer; + fs.realpath('/path/to/folder', (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', undefined, (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', 'utf8', (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', 'buffer', (err, resolvedPath) => b = resolvedPath); + fs.realpath('/path/to/folder', s, (err, resolvedPath) => typeof resolvedPath === 'string' ? s = resolvedPath : b = resolvedPath); + fs.realpath('/path/to/folder', {}, (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', { encoding: undefined }, (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', { encoding: 'utf8' }, (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', { encoding: 'buffer' }, (err, resolvedPath) => b = resolvedPath); + fs.realpath('/path/to/folder', { encoding: s }, (err, resolvedPath) => typeof resolvedPath === "string" ? s = resolvedPath : b = resolvedPath); + + s = fs.realpathSync('/path/to/folder'); + s = fs.realpathSync('/path/to/folder', undefined); + s = fs.realpathSync('/path/to/folder', 'utf8'); + b = fs.realpathSync('/path/to/folder', 'buffer'); + const v1 = fs.realpathSync('/path/to/folder', s); + typeof v1 === "string" ? s = v1 : b = v1; + + s = fs.realpathSync('/path/to/folder', {}); + s = fs.realpathSync('/path/to/folder', { encoding: undefined }); + s = fs.realpathSync('/path/to/folder', { encoding: 'utf8' }); + b = fs.realpathSync('/path/to/folder', { encoding: 'buffer' }); + const v2 = fs.realpathSync('/path/to/folder', { encoding: s }); + typeof v2 === "string" ? s = v2 : b = v2; + + // native + fs.realpath.native('/path/to/folder', (err, resolvedPath) => s = resolvedPath); + fs.realpath.native('/path/to/folder', undefined, (err, resolvedPath) => s = resolvedPath); + fs.realpath.native('/path/to/folder', 'utf8', (err, resolvedPath) => s = resolvedPath); + fs.realpath.native('/path/to/folder', 'buffer', (err, resolvedPath) => b = resolvedPath); + fs.realpath.native('/path/to/folder', s, (err, resolvedPath) => typeof resolvedPath === 'string' ? s = resolvedPath : b = resolvedPath); + fs.realpath.native('/path/to/folder', {}, (err, resolvedPath) => s = resolvedPath); + fs.realpath.native('/path/to/folder', { encoding: undefined }, (err, resolvedPath) => s = resolvedPath); + fs.realpath.native('/path/to/folder', { encoding: 'utf8' }, (err, resolvedPath) => s = resolvedPath); + fs.realpath.native('/path/to/folder', { encoding: 'buffer' }, (err, resolvedPath) => b = resolvedPath); + fs.realpath.native('/path/to/folder', { encoding: s }, (err, resolvedPath) => typeof resolvedPath === "string" ? s = resolvedPath : b = resolvedPath); + + s = fs.realpathSync.native('/path/to/folder'); + s = fs.realpathSync.native('/path/to/folder', undefined); + s = fs.realpathSync.native('/path/to/folder', 'utf8'); + b = fs.realpathSync.native('/path/to/folder', 'buffer'); + const v3 = fs.realpathSync.native('/path/to/folder', s); + typeof v3 === "string" ? s = v3 : b = v3; + + s = fs.realpathSync.native('/path/to/folder', {}); + s = fs.realpathSync.native('/path/to/folder', { encoding: undefined }); + s = fs.realpathSync.native('/path/to/folder', { encoding: 'utf8' }); + b = fs.realpathSync.native('/path/to/folder', { encoding: 'buffer' }); + const v4 = fs.realpathSync.native('/path/to/folder', { encoding: s }); + typeof v4 === "string" ? s = v4 : b = v4; + } + + { + fs.copyFile('/path/to/src', '/path/to/dest', (err) => console.error(err)); + fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL, (err) => console.error(err)); + fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE, (err) => console.error(err)); + fs.copyFile('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE_FORCE, (err) => console.error(err)); + + fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL); + fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE); + fs.copyFileSync('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_FICLONE_FORCE); + + const cf = util.promisify(fs.copyFile); + cf('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL).then(console.log); + } + + { + fs.mkdir('some/test/path', { + recursive: true, + mode: 0o777, + }, () => { + }); + + fs.mkdirSync('some/test/path', { + recursive: true, + mode: 0o777, + }); + } +} + +/////////////////////////////////////////////////////// +/// Buffer tests : https://nodejs.org/api/buffer.html +/////////////////////////////////////////////////////// + +function bufferTests() { + const utf8Buffer = new Buffer('test'); + const base64Buffer = new Buffer('', 'base64'); + const octets: Uint8Array = null; + const octetBuffer = new Buffer(octets); + const sharedBuffer = new Buffer(octets.buffer); + const copiedBuffer = new Buffer(utf8Buffer); + console.log(Buffer.isBuffer(octetBuffer)); + console.log(Buffer.isEncoding('utf8')); + console.log(Buffer.byteLength('xyz123')); + console.log(Buffer.byteLength('xyz123', 'ascii')); + const result1 = Buffer.concat([utf8Buffer, base64Buffer]); + const result2 = Buffer.concat([utf8Buffer, base64Buffer], 9999999); + + // Class Methods: Buffer.swap16(), Buffer.swa32(), Buffer.swap64() + { + const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + buf.swap16(); + buf.swap32(); + buf.swap64(); + } + + // Class Method: Buffer.from(data) + { + // Array + const buf1: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + // Buffer + const buf2: Buffer = Buffer.from(buf1); + // String + const buf3: Buffer = Buffer.from('this is a tést'); + // ArrayBuffer + const arrUint16: Uint16Array = new Uint16Array(2); + arrUint16[0] = 5000; + arrUint16[1] = 4000; + const buf4: Buffer = Buffer.from(arrUint16.buffer); + const arrUint8: Uint8Array = new Uint8Array(2); + const buf5: Buffer = Buffer.from(arrUint8); + const buf6: Buffer = Buffer.from(buf1); + const buf7: Buffer = Buffer.from(undefined as SharedArrayBuffer); + } + + // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + { + const arr: Uint16Array = new Uint16Array(2); + arr[0] = 5000; + arr[1] = 4000; + + let buf: Buffer; + buf = Buffer.from(arr.buffer, 1); + buf = Buffer.from(arr.buffer, 0, 1); + } + + // Class Method: Buffer.from(str[, encoding]) + { + const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); + } + + // Class Method: Buffer.alloc(size[, fill[, encoding]]) + { + const buf1: Buffer = Buffer.alloc(5); + const buf2: Buffer = Buffer.alloc(5, 'a'); + const buf3: Buffer = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + } + // Class Method: Buffer.allocUnsafe(size) + { + const buf: Buffer = Buffer.allocUnsafe(5); + } + // Class Method: Buffer.allocUnsafeSlow(size) + { + const buf: Buffer = Buffer.allocUnsafeSlow(10); + } + + // Class Method byteLenght + { + let len: number; + len = Buffer.byteLength("foo"); + len = Buffer.byteLength("foo", "utf8"); + + const b = Buffer.from("bar"); + len = Buffer.byteLength(b); + len = Buffer.byteLength(b, "utf16le"); + + const ab = new ArrayBuffer(15); + len = Buffer.byteLength(ab); + len = Buffer.byteLength(ab, "ascii"); + + const dv = new DataView(ab); + len = Buffer.byteLength(dv); + len = Buffer.byteLength(dv, "utf16le"); + } + + // Class Method poolSize + { + let s: number; + s = Buffer.poolSize; + Buffer.poolSize = 4096; + } + + // Test that TS 1.6 works with the 'as Buffer' annotation + // on isBuffer. + let a: Buffer | number; + a = new Buffer(10); + if (Buffer.isBuffer(a)) { + a.writeUInt8(3, 4); + } + + // write* methods return offsets. + const b = new Buffer(16); + let result: number = b.writeUInt32LE(0, 0); + result = b.writeUInt16LE(0, 4); + result = b.writeUInt8(0, 6); + result = b.writeInt8(0, 7); + result = b.writeDoubleLE(0, 8); + + // fill returns the input buffer. + b.fill('a').fill('b'); + + { + const buffer = new Buffer('123'); + let index: number; + index = buffer.indexOf("23"); + index = buffer.indexOf("23", 1); + index = buffer.indexOf("23", 1, "utf8"); + index = buffer.indexOf(23); + index = buffer.indexOf(buffer); + } + + { + const buffer = new Buffer('123'); + let index: number; + index = buffer.lastIndexOf("23"); + index = buffer.lastIndexOf("23", 1); + index = buffer.lastIndexOf("23", 1, "utf8"); + index = buffer.lastIndexOf(23); + index = buffer.lastIndexOf(buffer); + } + + { + const buffer = new Buffer('123'); + const val: [number, number] = [1, 1]; + + /* comment out for --target es5 + for (let entry of buffer.entries()) { + val = entry; + } + */ + } + + { + const buffer = new Buffer('123'); + let includes: boolean; + includes = buffer.includes("23"); + includes = buffer.includes("23", 1); + includes = buffer.includes("23", 1, "utf8"); + includes = buffer.includes(23); + includes = buffer.includes(23, 1); + includes = buffer.includes(23, 1, "utf8"); + includes = buffer.includes(buffer); + includes = buffer.includes(buffer, 1); + includes = buffer.includes(buffer, 1, "utf8"); + } + + { + const buffer = new Buffer('123'); + const val = 1; + + /* comment out for --target es5 + for (let key of buffer.keys()) { + val = key; + } + */ + } + + { + const buffer = new Buffer('123'); + const val = 1; + + /* comment out for --target es5 + for (let value of buffer.values()) { + val = value; + } + */ + } + + // Imported Buffer from buffer module works properly + { + const b = new ImportedBuffer('123'); + b.writeUInt8(0, 6); + const sb = new ImportedSlowBuffer(43); + b.writeUInt8(0, 6); + } + + // Buffer has Uint8Array's buffer field (an ArrayBuffer). + { + const buffer = new Buffer('123'); + const octets = new Uint8Array(buffer.buffer); + } +} + +//////////////////////////////////////////////////// +/// Url tests : http://nodejs.org/api/url.html +//////////////////////////////////////////////////// + +{ + { + url.format(url.parse('http://www.example.com/xyz')); + + url.format('http://www.example.com/xyz'); + + // https://google.com/search?q=you're%20a%20lizard%2C%20gary + url.format({ + protocol: 'https', + host: "google.com", + pathname: 'search', + query: { q: "you're a lizard, gary" } + }); + + const myURL = new url.URL('https://a:b@你好你好?abc#foo'); + url.format(myURL, { fragment: false, unicode: true, auth: false }); + } + + { + const helloUrl = url.parse('http://example.com/?hello=world', true); + let helloQuery = helloUrl.query['hello']; + assert.equal(helloUrl.query['hello'], 'world'); + + let strUrl = url.parse('http://example.com/?hello=world'); + let queryStr: string = strUrl.query; + + strUrl = url.parse('http://example.com/?hello=world', false); + queryStr = strUrl.query; + + function getBoolean(): boolean { return false; } + const urlUrl = url.parse('http://example.com/?hello=world', getBoolean()); + if (typeof(urlUrl.query) === 'string') { + queryStr = urlUrl.query; + } else if (urlUrl.query) { + helloQuery = urlUrl.query['hello']; + } + } + + { + const ascii: string = url.domainToASCII('español.com'); + const unicode: string = url.domainToUnicode('xn--espaol-zwa.com'); + } + + { + let myURL = new url.URL('https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); + assert.equal(myURL.hash, '#bar'); + assert.equal(myURL.host, 'example.org:81'); + assert.equal(myURL.hostname, 'example.org'); + assert.equal(myURL.href, 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); + assert.equal(myURL.origin, 'https://example.org:81'); + assert.equal(myURL.password, 'thepwd'); + assert.equal(myURL.username, 'theuser'); + assert.equal(myURL.pathname, '/foo/path'); + assert.equal(myURL.port, "81"); + assert.equal(myURL.protocol, "https:"); + assert.equal(myURL.search, "?query=string"); + assert.equal(myURL.toString(), 'https://theuser:thepwd@example.org:81/foo/path?query=string#bar'); + assert(myURL.searchParams instanceof url.URLSearchParams); + + myURL.host = 'example.org:82'; + myURL.hostname = 'example.com'; + myURL.href = 'http://other.com'; + myURL.hash = 'baz'; + myURL.password = "otherpwd"; + myURL.username = "otheruser"; + myURL.pathname = "/otherPath"; + myURL.port = "82"; + myURL.protocol = "http"; + myURL.search = "a=b"; + assert.equal(myURL.href, 'http://otheruser:otherpwd@other.com:82/otherPath?a=b#baz'); + + myURL = new url.URL('/foo', 'https://example.org/'); + assert.equal(myURL.href, 'https://example.org/foo'); + assert.equal(myURL.toJSON(), myURL.href); + } + + { + const searchParams = new url.URLSearchParams('abc=123'); + + assert.equal(searchParams.toString(), 'abc=123'); + searchParams.forEach((value: string, name: string, me: url.URLSearchParams): void => { + assert.equal(name, 'abc'); + assert.equal(value, '123'); + assert.equal(me, searchParams); + }); + + assert.equal(searchParams.get('abc'), '123'); + + searchParams.append('abc', 'xyz'); + + assert.deepEqual(searchParams.getAll('abc'), ['123', 'xyz']); + + const entries = searchParams.entries(); + assert.deepEqual(entries.next(), { value: ["abc", "123"], done: false }); + assert.deepEqual(entries.next(), { value: ["abc", "xyz"], done: false }); + assert.deepEqual(entries.next(), { value: undefined, done: true }); + + const keys = searchParams.keys(); + assert.deepEqual(keys.next(), { value: "abc", done: false }); + assert.deepEqual(keys.next(), { value: "abc", done: false }); + assert.deepEqual(keys.next(), { value: undefined, done: true }); + + const values = searchParams.values(); + assert.deepEqual(values.next(), { value: "123", done: false }); + assert.deepEqual(values.next(), { value: "xyz", done: false }); + assert.deepEqual(values.next(), { value: undefined, done: true }); + + searchParams.set('abc', 'b'); + assert.deepEqual(searchParams.getAll('abc'), ['b']); + + searchParams.delete('a'); + assert(!searchParams.has('a')); + assert.equal(searchParams.get('a'), null); + + searchParams.sort(); + } + + { + const searchParams = new url.URLSearchParams({ + user: 'abc', + query: ['first', 'second'] + }); + + assert.equal(searchParams.toString(), 'user=abc&query=first%2Csecond'); + assert.deepEqual(searchParams.getAll('query'), ['first,second']); + } + + { + // Using an array + const params = new url.URLSearchParams([ + ['user', 'abc'], + ['query', 'first'], + ['query', 'second'] + ]); + assert.equal(params.toString(), 'user=abc&query=first&query=second'); + } + + { + let path: string = url.fileURLToPath('file://test'); + path = url.fileURLToPath(new url.URL('file://test')); + } + + { + const path: url.URL = url.pathToFileURL('file://test'); + } +} + +///////////////////////////////////////////////////// +/// util tests : https://nodejs.org/api/util.html /// +///////////////////////////////////////////////////// + +{ + { + // Old and new util.inspect APIs + util.inspect(["This is nice"], false, 5); + util.inspect(["This is nice"], false, null); + util.inspect(["This is nice"], { + colors: true, + depth: 5, + customInspect: false, + showProxy: true, + maxArrayLength: 10, + breakLength: 20, + compact: true, + sorted(a, b) { + return b.localeCompare(a); + }, + }); + util.inspect(["This is nice"], { + colors: true, + depth: null, + customInspect: false, + showProxy: true, + maxArrayLength: null, + breakLength: Infinity, + compact: false, + sorted: true, + }); + assert(typeof util.inspect.custom === 'symbol'); + + util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + + // util.callbackify + // tslint:disable-next-line no-unnecessary-class + class callbackifyTest { + static fn(): Promise<void> { + assert(arguments.length === 0); + + return Promise.resolve(); + } + + static fnE(): Promise<void> { + assert(arguments.length === 0); + + return Promise.reject(new Error('fail')); + } + + static fnT1(arg1: string): Promise<void> { + assert(arguments.length === 1 && arg1 === 'parameter'); + + return Promise.resolve(); + } + + static fnT1E(arg1: string): Promise<void> { + assert(arguments.length === 1 && arg1 === 'parameter'); + + return Promise.reject(new Error('fail')); + } + + static fnTResult(): Promise<string> { + assert(arguments.length === 0); + + return Promise.resolve('result'); + } + + static fnTResultE(): Promise<string> { + assert(arguments.length === 0); + + return Promise.reject(new Error('fail')); + } + + static fnT1TResult(arg1: string): Promise<string> { + assert(arguments.length === 1 && arg1 === 'parameter'); + + return Promise.resolve('result'); + } + + static fnT1TResultE(arg1: string): Promise<string> { + assert(arguments.length === 1 && arg1 === 'parameter'); + + return Promise.reject(new Error('fail')); + } + + static test(): void { + const cfn = util.callbackify(this.fn); + const cfnE = util.callbackify(this.fnE); + const cfnT1 = util.callbackify(this.fnT1); + const cfnT1E = util.callbackify(this.fnT1E); + const cfnTResult = util.callbackify(this.fnTResult); + const cfnTResultE = util.callbackify(this.fnTResultE); + const cfnT1TResult = util.callbackify(this.fnT1TResult); + const cfnT1TResultE = util.callbackify(this.fnT1TResultE); + + cfn((err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); + cfnE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); + cfnT1('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); + cfnT1E('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); + cfnTResult((err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === 'result')); + cfnTResultE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); + cfnT1TResult('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === 'result')); + cfnT1TResultE('parameter', (err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); + } + } + callbackifyTest.test(); + + // util.promisify + const readPromised = util.promisify(fs.readFile); + const sampleRead: Promise<any> = readPromised(__filename).then((data: Buffer): void => { }).catch((error: Error): void => { }); + const arg0: () => Promise<number> = util.promisify((cb: (err: Error, result: number) => void): void => { }); + const arg0NoResult: () => Promise<any> = util.promisify((cb: (err: Error) => void): void => { }); + const arg1: (arg: string) => Promise<number> = util.promisify((arg: string, cb: (err: Error, result: number) => void): void => { }); + const arg1NoResult: (arg: string) => Promise<any> = util.promisify((arg: string, cb: (err: Error) => void): void => { }); + const cbOptionalError: () => Promise<void | {}> = util.promisify((cb: (err?: Error | null) => void): void => { cb(); }); // tslint:disable-line void-return + assert(typeof util.promisify.custom === 'symbol'); + // util.deprecate + const foo = () => {}; + // $ExpectType () => void + util.deprecate(foo, 'foo() is deprecated, use bar() instead'); + // $ExpectType <T extends Function>(fn: T, message: string) => T + util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead'); + + // util.isDeepStrictEqual + util.isDeepStrictEqual({foo: 'bar'}, {foo: 'bar'}); + + // util.TextDecoder() + const td = new util.TextDecoder(); + new util.TextDecoder("utf-8"); + new util.TextDecoder("utf-8", { fatal: true }); + new util.TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); + const ignoreBom: boolean = td.ignoreBOM; + const fatal: boolean = td.fatal; + const encoding: string = td.encoding; + td.decode(new Int8Array(1)); + td.decode(new Int16Array(1)); + td.decode(new Int32Array(1)); + td.decode(new Uint8Array(1)); + td.decode(new Uint16Array(1)); + td.decode(new Uint32Array(1)); + td.decode(new Uint8ClampedArray(1)); + td.decode(new Float32Array(1)); + td.decode(new Float64Array(1)); + td.decode(new DataView(new Int8Array(1).buffer)); + td.decode(new ArrayBuffer(1)); + td.decode(null); + td.decode(null, { stream: true }); + td.decode(new Int8Array(1), { stream: true }); + const decode: string = td.decode(new Int8Array(1)); + + // util.TextEncoder() + const te = new util.TextEncoder(); + const teEncoding: string = te.encoding; + const teEncodeRes: Uint8Array = te.encode("TextEncoder"); + + // util.types + + // tslint:disable-next-line:no-construct ban-types + const maybeBoxed: number | Number = new Number(1); + if (util.types.isBoxedPrimitive(maybeBoxed)) { + const boxed: Number = maybeBoxed; + } + const maybeBoxed2: number | Number = 1; + if (!util.types.isBoxedPrimitive(maybeBoxed2)) { + const boxed: number = maybeBoxed2; + } + } +} + +//////////////////////////////////////////////////// +/// Stream tests : http://nodejs.org/api/stream.html +//////////////////////////////////////////////////// + +// http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options +function stream_readable_pipe_test() { + const rs = fs.createReadStream(Buffer.from('file.txt')); + const r = fs.createReadStream('file.txt'); + const z = zlib.createGzip({ finishFlush: zlib.constants.Z_FINISH }); + const w = fs.createWriteStream('file.txt.gz'); + + assert(typeof z.bytesRead === 'number'); + assert(typeof r.bytesRead === 'number'); + assert(typeof r.path === 'string'); + assert(rs.path instanceof Buffer); + + r.pipe(z).pipe(w); + + z.flush(); + r.close(); + z.close(); + rs.close(); +} + +// helpers +const compressMe = new Buffer("some data"); +const compressMeString = "compress me!"; + +zlib.deflate(compressMe, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); +zlib.deflate(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflate(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); +zlib.deflate(compressMeString, (err: Error, result: Buffer) => zlib.inflate(result, (err: Error, result: Buffer) => result)); +zlib.deflate(compressMeString, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflate(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); +const inflated = zlib.inflateSync(zlib.deflateSync(compressMe)); +const inflatedString = zlib.inflateSync(zlib.deflateSync(compressMeString)); + +zlib.deflateRaw(compressMe, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); +zlib.deflateRaw(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.inflateRaw(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); +zlib.deflateRaw(compressMeString, (err: Error, result: Buffer) => zlib.inflateRaw(result, (err: Error, result: Buffer) => result)); +zlib.deflateRaw( + compressMeString, + { finishFlush: zlib.Z_SYNC_FLUSH }, + (err: Error, result: Buffer) => zlib.inflateRaw(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result), +); +const inflatedRaw: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMe)); +const inflatedRawString: Buffer = zlib.inflateRawSync(zlib.deflateRawSync(compressMeString)); + +zlib.gzip(compressMe, (err: Error, result: Buffer) => zlib.gunzip(result, (err: Error, result: Buffer) => result)); +zlib.gzip(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => zlib.gunzip(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result)); +const gunzipped: Buffer = zlib.gunzipSync(zlib.gzipSync(compressMe)); + +zlib.unzip(compressMe, (err: Error, result: Buffer) => result); +zlib.unzip(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error, result: Buffer) => result); +const unzipped: Buffer = zlib.unzipSync(compressMe); + +// Simplified constructors +function simplified_stream_ctor_test() { + new stream.Readable({ + read(size) { + // $ExpectType Readable + this; + // $ExpectType number + size; + }, + destroy(error, cb) { + // $ExpectType Error + error; + // $ExpectType (error: Error) => void + cb; + } + }); + + new stream.Writable({ + write(chunk, enc, cb) { + // $ExpectType Writable + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType (error?: Error) => void + cb; + }, + writev(chunks, cb) { + // $ExpectType Writable + this; + // $ExpectType { chunk: any; encoding: string; }[] + chunks; + // $ExpectType (error?: Error) => void + cb; + }, + destroy(error, cb) { + // $ExpectType Writable + this; + // $ExpectType Error + error; + // $ExpectType (error: Error) => void + cb; + }, + final(cb) { + // $ExpectType Writable + this; + // $ExpectType (error?: Error) => void + cb; + } + }); + + new stream.Duplex({ + read(size) { + // $ExpectType Duplex + this; + // $ExpectType number + size; + }, + write(chunk, enc, cb) { + // $ExpectType Duplex + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType (error?: Error) => void + cb; + }, + writev(chunks, cb) { + // $ExpectType Duplex + this; + // $ExpectType { chunk: any; encoding: string; }[] + chunks; + // $ExpectType (error?: Error) => void + cb; + }, + destroy(error, cb) { + // $ExpectType Duplex + this; + // $ExpectType Error + error; + // $ExpectType (error: Error) => void + cb; + }, + final(cb) { + // $ExpectType Duplex + this; + // $ExpectType (error?: Error) => void + cb; + }, + readableObjectMode: true, + writableObjectMode: true + }); + + new stream.Transform({ + read(size) { + // $ExpectType Transform + this; + // $ExpectType number + size; + }, + write(chunk, enc, cb) { + // $ExpectType Transform + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType (error?: Error) => void + cb; + }, + writev(chunks, cb) { + // $ExpectType Transform + this; + // $ExpectType { chunk: any; encoding: string; }[] + chunks; + // $ExpectType (error?: Error) => void + cb; + }, + destroy(error, cb) { + // $ExpectType Transform + this; + // $ExpectType Error + error; + // $ExpectType (error: Error) => void + cb; + }, + final(cb) { + // $ExpectType Transform + this; + // $ExpectType (error?: Error) => void + cb; + }, + transform(chunk, enc, cb) { + // $ExpectType Transform + this; + // $ExpectType any + chunk; + // $ExpectType string + enc; + // $ExpectType TransformCallback + cb; + }, + flush(cb) { + // $ExpectType TransformCallback + cb; + }, + allowHalfOpen: true, + readableObjectMode: true, + writableObjectMode: true + }); +} + +function streamPipelineFinished() { + const cancel = stream.finished(process.stdin, (err?: Error) => {}); + cancel(); + + stream.pipeline(process.stdin, process.stdout, (err?: Error) => {}); +} + +async function asyncStreamPipelineFinished() { + const finished = util.promisify(stream.finished); + await finished(process.stdin); + + const pipeline = util.promisify(stream.pipeline); + await pipeline(process.stdin, process.stdout); +} + +//////////////////////////////////////////////////////// +/// Crypto tests : http://nodejs.org/api/crypto.html /// +//////////////////////////////////////////////////////// + +{ + { + // crypto_hash_string_test + const hashResult: string = crypto.createHash('md5').update('world').digest('hex'); + } + + { + // crypto_hash_buffer_test + const hashResult: string = crypto.createHash('md5') + .update(new Buffer('world')).digest('hex'); + } + + { + // crypto_hash_dataview_test + const hashResult: string = crypto.createHash('md5') + .update(new DataView(new Buffer('world').buffer)).digest('hex'); + } + + { + // crypto_hash_int8array_test + const hashResult: string = crypto.createHash('md5') + .update(new Int8Array(new Buffer('world').buffer)).digest('hex'); + } + + { + // crypto_hmac_string_test + const hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); + } + + { + // crypto_hmac_buffer_test + const hmacResult: string = crypto.createHmac('md5', 'hello') + .update(new Buffer('world')).digest('hex'); + } + + { + // crypto_hmac_dataview_test + const hmacResult: string = crypto.createHmac('md5', 'hello') + .update(new DataView(new Buffer('world').buffer)).digest('hex'); + } + + { + // crypto_hmac_int8array_test + const hmacResult: string = crypto.createHmac('md5', 'hello') + .update(new Int8Array(new Buffer('world').buffer)).digest('hex'); + } + + { + let hmac: crypto.Hmac; + (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { + const hash: Buffer | string = hmac.read(); + }); + } + + { + // crypto_cipher_decipher_string_test + const key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + const clearText = "This is the clear text."; + const cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherText: string = cipher.update(clearText, "utf8", "hex"); + cipherText += cipher.final("hex"); + + const decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let clearText2: string = decipher.update(cipherText, "hex", "utf8"); + clearText2 += decipher.final("utf8"); + + assert.equal(clearText2, clearText); + } + + { + // crypto_cipher_decipher_buffer_test + const key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + const clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); + const cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + const cipherBuffers: Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); + + const cipherText: Buffer = Buffer.concat(cipherBuffers); + + const decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + const decipherBuffers: Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); + + const clearText2: Buffer = Buffer.concat(decipherBuffers); + + assert.deepEqual(clearText2, clearText); + } + + { + // crypto_cipher_decipher_dataview_test + const key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + const clearText: DataView = new DataView(new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]).buffer); + const cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + const cipherBuffers: Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); + + const cipherText: DataView = new DataView(Buffer.concat(cipherBuffers).buffer); + + const decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + const decipherBuffers: Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); + + const clearText2: Buffer = Buffer.concat(decipherBuffers); + + assert.deepEqual(clearText2, clearText); + } + + { + const key = 'keykeykeykeykeykeykeykey'; + const nonce = crypto.randomBytes(12); + const aad = Buffer.from('0123456789', 'hex'); + + const cipher = crypto.createCipheriv('aes-192-ccm', key, nonce, { + authTagLength: 16 + }); + const plaintext = 'Hello world'; + cipher.setAAD(aad, { + plaintextLength: Buffer.byteLength(plaintext) + }); + const ciphertext = cipher.update(plaintext, 'utf8'); + cipher.final(); + const tag = cipher.getAuthTag(); + + const decipher = crypto.createDecipheriv('aes-192-ccm', key, nonce, { + authTagLength: 16 + }); + decipher.setAuthTag(tag); + decipher.setAAD(aad, { + plaintextLength: ciphertext.length + }); + const receivedPlaintext: string = decipher.update(ciphertext, null, 'utf8'); + decipher.final(); + } + + { + const key = 'keykeykeykeykeykeykeykey'; + const nonce = crypto.randomBytes(12); + const aad = Buffer.from('0123456789', 'hex'); + + const cipher = crypto.createCipheriv('aes-192-gcm', key, nonce); + const plaintext = 'Hello world'; + cipher.setAAD(aad, { + plaintextLength: Buffer.byteLength(plaintext) + }); + const ciphertext = cipher.update(plaintext, 'utf8'); + cipher.final(); + const tag = cipher.getAuthTag(); + + const decipher = crypto.createDecipheriv('aes-192-gcm', key, nonce); + decipher.setAuthTag(tag); + decipher.setAAD(aad, { + plaintextLength: ciphertext.length + }); + const receivedPlaintext: string = decipher.update(ciphertext, null, 'utf8'); + decipher.final(); + } + + { + // crypto_timingsafeequal_buffer_test + const buffer1: Buffer = new Buffer([1, 2, 3, 4, 5]); + const buffer2: Buffer = new Buffer([1, 2, 3, 4, 5]); + const buffer3: Buffer = new Buffer([5, 4, 3, 2, 1]); + + assert(crypto.timingSafeEqual(buffer1, buffer2)); + assert(!crypto.timingSafeEqual(buffer1, buffer3)); + } + + { + // crypto_timingsafeequal_uint32array_test + const arr1: Uint32Array = Uint32Array.of(1, 2, 3, 4, 5); + const arr2: Uint32Array = Uint32Array.of(1, 2, 3, 4, 5); + const arr3: Uint32Array = Uint32Array.of(5, 4, 3, 2, 1); + + assert(crypto.timingSafeEqual(arr1, arr2)); + assert(!crypto.timingSafeEqual(arr1, arr3)); + } + + { + // crypto_timingsafeequal_safe_typedarray_variant_test + const arr1: Uint32Array = Uint32Array.of(1, 2, 3, 4, 5); + const arr2: Int32Array = Int32Array.of(1, 2, 3, 4, 5); + const arr3: Uint32Array = Uint32Array.of(5, 4, 3, 2, 1); + + assert(crypto.timingSafeEqual(arr1, arr2)); + assert(!crypto.timingSafeEqual(arr1, arr3)); + } + + { + // crypto_timingsafeequal_safe_int8array_variant_test + const arr1: Int8Array = Int8Array.of(1, 2, 3, 4, 5, ~0, ~1, ~2, ~3, ~4); + const arr2: Uint8Array = Uint8Array.of(1, 2, 3, 4, 5, ~0, ~1, ~2, ~3, ~4); + const arr3: Uint8ClampedArray = Uint8ClampedArray.of(1, 2, 3, 4, 5, ~0, ~1, ~2, ~3, ~4); + + assert(crypto.timingSafeEqual(arr1, arr2)); // binary same + assert(!crypto.timingSafeEqual(arr1, arr3)); // binary differ + } + + { + // crypto_timingsafeequal_safe_arraybufferiew_variant_test + /* throws as of v10.4.1 */ + // let arr1: Uint8Array = Uint8Array.of(1, 0, 2, 0, 3, 0, 4, 0); + // let arr2: Uint16Array = Uint16Array.of(1, 2, 3, 4); + // let arr3: Uint32Array = Uint8ClampedArray.of(131073, 262147); + + // assert(crypto.timingSafeEqual(arr1, arr2)); // binary same + // assert(crypto.timingSafeEqual(arr1, arr3)); // binary same + } + + { + // crypto_timingsafeequal_unsafe_arraybufferiew_variant_test + /* dumps core as of v10.4.1 */ + // let arr1: Uint8Array = Uint8Array.of(1, 2, 3, 4); + // let arr2: Uint16Array = Uint16Array.of(1, 2, 3, 4); + // let arr3: Uint32Array = Uint8ClampedArray.of(1, 2, 3, 4); + + // assert(!crypto.timingSafeEqual(arr1, arr2)); // dumps core + // assert(!crypto.timingSafeEqual(arr1, arr3)); // dumps core + } + + { + // crypto_timingsafeequal_dataview_test + const dv1B: Uint8Array = Uint8Array.of(1, 2, 3, 4, 5); + const dv2B: Int8Array = Int8Array.of(1, 2, 3, 4, 5); + const dv3B: Buffer = Buffer.of(5, 4, 3, 2, 1); + const dv4B: Uint8ClampedArray = Uint8ClampedArray.of(5, 4, 3, 2, 1); + const dv1: DataView = new DataView(dv1B.buffer, dv1B.byteOffset, dv1B.byteLength); + const dv2: DataView = new DataView(dv2B.buffer, dv2B.byteOffset, dv2B.byteLength); + const dv3: DataView = new DataView(dv3B.buffer, dv3B.byteOffset, dv3B.byteLength); + const dv4: DataView = new DataView(dv4B.buffer, dv4B.byteOffset, dv4B.byteLength); + + assert(crypto.timingSafeEqual(dv1, dv2)); + assert(crypto.timingSafeEqual(dv1, dv1B)); + assert(crypto.timingSafeEqual(dv2, dv1B)); + assert(crypto.timingSafeEqual(dv3, dv4)); + + assert(!crypto.timingSafeEqual(dv1, dv3)); + assert(!crypto.timingSafeEqual(dv2, dv3)); + assert(!crypto.timingSafeEqual(dv1, dv4)); + // ... I'm not going to write all those tests. + } + + { + // crypto_timingsafeequal_uint32array_test + const ui32_1: Uint32Array = Uint32Array.of(1, 2, 3, 4, 5); + const ui32_2: Uint32Array = Uint32Array.of(1, 2, 3, 4, 5); + const ui32_3: Uint32Array = Uint32Array.of(5, 4, 3, 2, 1); + + assert(crypto.timingSafeEqual(ui32_1, ui32_2)); + assert(!crypto.timingSafeEqual(ui32_1, ui32_3)); + } + + { + // crypto_randomfill_buffer_test + const buffer: Buffer = new Buffer(10); + crypto.randomFillSync(buffer); + crypto.randomFillSync(buffer, 2); + crypto.randomFillSync(buffer, 2, 3); + + crypto.randomFill(buffer, (err: Error, buf: Buffer) => void {}); + crypto.randomFill(buffer, 2, (err: Error, buf: Buffer) => void {}); + crypto.randomFill(buffer, 2, 3, (err: Error, buf: Buffer) => void {}); + + // crypto_randomfill_uint8array_test + const ui8arr: Uint8Array = new Uint8Array(10); + crypto.randomFillSync(ui8arr); + crypto.randomFillSync(ui8arr, 2); + crypto.randomFillSync(ui8arr, 2, 3); + + crypto.randomFill(ui8arr, (err: Error, buf: Uint8Array) => void {}); + crypto.randomFill(ui8arr, 2, (err: Error, buf: Uint8Array) => void {}); + crypto.randomFill(ui8arr, 2, 3, (err: Error, buf: Uint8Array) => void {}); + + // crypto_randomfill_int32array_test + const i32arr: Int32Array = new Int32Array(10); + crypto.randomFillSync(i32arr); + crypto.randomFillSync(i32arr, 2); + crypto.randomFillSync(i32arr, 2, 3); + + crypto.randomFill(i32arr, (err: Error, buf: Int32Array) => void {}); + crypto.randomFill(i32arr, 2, (err: Error, buf: Int32Array) => void {}); + crypto.randomFill(i32arr, 2, 3, (err: Error, buf: Int32Array) => void {}); + } + + { + // scrypt + const pwd: string | Buffer | Int32Array | DataView = Buffer.alloc(16); + const salt: string | Buffer | Int32Array | DataView = Buffer.alloc(16); + crypto.scrypt(pwd, salt, 64, (err: Error | null, derivedKey: Buffer): void => {}); + const opts: crypto.ScryptOptions = { + N: 16384, + r: 8, + p: 1, + maxmem: 32 * 1024 * 1024 + }; + crypto.scrypt(pwd, salt, 64, opts, (err: Error | null, derivedKey: Buffer): void => {}); + crypto.scrypt(pwd, salt, 64, { maxmem: 16 * 1024 * 1024 }, (err: Error | null, derivedKey: Buffer): void => {}); + let buf: Buffer = crypto.scryptSync(pwd, salt, 64); + buf = crypto.scryptSync(pwd, salt, 64, opts); + buf = crypto.scryptSync(pwd, salt, 64, { N: 1024 }); + } + + { + let key: string | Buffer = Buffer.from("buf"); + const curve = "secp256k1"; + let ret: string | Buffer = crypto.ECDH.convertKey(key, curve); + key = "0xfff"; + ret = crypto.ECDH.convertKey(key, curve); + ret = crypto.ECDH.convertKey(key, curve, "hex"); + ret = crypto.ECDH.convertKey(key, curve, "hex", "hex"); + ret = crypto.ECDH.convertKey(key, curve, "hex", "hex", "uncompressed"); + ret = crypto.ECDH.convertKey(key, curve, "hex", "hex", "compressed"); + ret = crypto.ECDH.convertKey(key, curve, "hex", "hex", "hybrid"); + } + + { + const rsaRes: { + publicKey: Buffer; + privateKey: string; + } = crypto.generateKeyPairSync('rsa', { + modulusLength: 123, + publicKeyEncoding: { + format: 'der', + type: 'pkcs1', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'pem', + passphrase: 'secret', + type: 'pkcs8', + }, + }); + + const dsaRes: { + publicKey: string; + privateKey: Buffer; + } = crypto.generateKeyPairSync('dsa', { + modulusLength: 123, + divisorLength: 123, + publicKeyEncoding: { + format: 'pem', + type: 'spki', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'der', + passphrase: 'secret', + type: 'pkcs8', + }, + }); + + const ecRes: { + publicKey: string; + privateKey: string; + } = crypto.generateKeyPairSync('ec', { + namedCurve: 'curve', + publicKeyEncoding: { + format: 'pem', + type: 'pkcs1', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'pem', + passphrase: 'secret', + type: 'pkcs8', + }, + }); + } + + { + crypto.generateKeyPair('rsa', { + modulusLength: 123, + publicKeyEncoding: { + format: 'der', + type: 'pkcs1', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'pem', + passphrase: 'secret', + type: 'pkcs8', + }, + }, (err: NodeJS.ErrnoException | null, publicKey: Buffer, privateKey: string) => {}); + + crypto.generateKeyPair('dsa', { + modulusLength: 123, + divisorLength: 123, + publicKeyEncoding: { + format: 'pem', + type: 'spki', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'der', + passphrase: 'secret', + type: 'pkcs8', + }, + }, (err: NodeJS.ErrnoException | null, publicKey: string, privateKey: Buffer) => {}); + + crypto.generateKeyPair('ec', { + namedCurve: 'curve', + publicKeyEncoding: { + format: 'pem', + type: 'pkcs1', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'pem', + passphrase: 'secret', + type: 'pkcs8', + }, + }, (err: NodeJS.ErrnoException | null, publicKey: string, privateKey: string) => {}); + } + + { + const generateKeyPairPromisified = util.promisify(crypto.generateKeyPair); + + const rsaRes: Promise<{ + publicKey: Buffer; + privateKey: string; + }> = generateKeyPairPromisified('rsa', { + modulusLength: 123, + publicKeyEncoding: { + format: 'der', + type: 'pkcs1', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'pem', + passphrase: 'secret', + type: 'pkcs8', + }, + }); + + const dsaRes: Promise<{ + publicKey: string; + privateKey: Buffer; + }> = generateKeyPairPromisified('dsa', { + modulusLength: 123, + divisorLength: 123, + publicKeyEncoding: { + format: 'pem', + type: 'spki', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'der', + passphrase: 'secret', + type: 'pkcs8', + }, + }); + + const ecRes: Promise<{ + publicKey: string; + privateKey: string; + }> = generateKeyPairPromisified('ec', { + namedCurve: 'curve', + publicKeyEncoding: { + format: 'pem', + type: 'pkcs1', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'pem', + passphrase: 'secret', + type: 'pkcs8', + }, + }); + } +} + +////////////////////////////////////////////////// +/// TLS tests : http://nodejs.org/api/tls.html /// +////////////////////////////////////////////////// + +{ + { + const ctx: tls.SecureContext = tls.createSecureContext({ + key: "NOT REALLY A KEY", + cert: "SOME CERTIFICATE", + }); + const blah = ctx.context; + + const connOpts: tls.ConnectionOptions = { + host: "127.0.0.1", + port: 55 + }; + const tlsSocket = tls.connect(connOpts); + + const ciphers: string[] = tls.getCiphers(); + const curve: string = tls.DEFAULT_ECDH_CURVE; + } + + { + let _server: tls.Server; + let _boolean: boolean; + const _func1 = (err: Error, resp: Buffer) => { }; + const _func2 = (err: Error, sessionData: any) => { }; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + */ + + _server = _server.addListener("tlsClientError", (err, tlsSocket) => { + const _err: Error = err; + const _tlsSocket: tls.TLSSocket = tlsSocket; + }); + _server = _server.addListener("newSession", (sessionId, sessionData, callback) => { + const _sessionId: any = sessionId; + const _sessionData: any = sessionData; + const _func1 = callback; + }); + _server = _server.addListener("OCSPRequest", (certificate, issuer, callback) => { + const _certificate: Buffer = certificate; + const _issuer: Buffer = issuer; + const _callback: Function = callback; + }); + _server = _server.addListener("resumeSession", (sessionId, callback) => { + const _sessionId: any = sessionId; + const _func2 = callback; + }); + _server = _server.addListener("secureConnection", (tlsSocket) => { + const _tlsSocket: tls.TLSSocket = tlsSocket; + }); + + const _err: Error = new Error(); + const _tlsSocket: tls.TLSSocket = tls.connect(1); + const _any: any = 1; + const _func: Function = () => {}; + const _buffer: Buffer = Buffer.from('a'); + _boolean = _server.emit("tlsClientError", _err, _tlsSocket); + _boolean = _server.emit("newSession", _any, _any, _func1); + _boolean = _server.emit("OCSPRequest", _buffer, _buffer, _func); + _boolean = _server.emit("resumeSession", _any, _func2); + _boolean = _server.emit("secureConnection", _tlsSocket); + + _server = _server.on("tlsClientError", (err, tlsSocket) => { + const _err: Error = err; + const _tlsSocket: tls.TLSSocket = tlsSocket; + }); + _server = _server.on("newSession", (sessionId, sessionData, callback) => { + const _sessionId: any = sessionId; + const _sessionData: any = sessionData; + const _func1 = callback; + }); + _server = _server.on("OCSPRequest", (certificate, issuer, callback) => { + const _certificate: Buffer = certificate; + const _issuer: Buffer = issuer; + const _callback: Function = callback; + }); + _server = _server.on("resumeSession", (sessionId, callback) => { + const _sessionId: any = sessionId; + const _func2 = callback; + }); + _server = _server.on("secureConnection", (tlsSocket) => { + const _tlsSocket: tls.TLSSocket = tlsSocket; + }); + + _server = _server.once("tlsClientError", (err, tlsSocket) => { + const _err: Error = err; + const _tlsSocket: tls.TLSSocket = tlsSocket; + }); + _server = _server.once("newSession", (sessionId, sessionData, callback) => { + const _sessionId: any = sessionId; + const _sessionData: any = sessionData; + const _func1 = callback; + }); + _server = _server.once("OCSPRequest", (certificate, issuer, callback) => { + const _certificate: Buffer = certificate; + const _issuer: Buffer = issuer; + const _callback: Function = callback; + }); + _server = _server.once("resumeSession", (sessionId, callback) => { + const _sessionId: any = sessionId; + const _func2 = callback; + }); + _server = _server.once("secureConnection", (tlsSocket) => { + const _tlsSocket: tls.TLSSocket = tlsSocket; + }); + + _server = _server.prependListener("tlsClientError", (err, tlsSocket) => { + const _err: Error = err; + const _tlsSocket: tls.TLSSocket = tlsSocket; + }); + _server = _server.prependListener("newSession", (sessionId, sessionData, callback) => { + const _sessionId: any = sessionId; + const _sessionData: any = sessionData; + const _func1 = callback; + }); + _server = _server.prependListener("OCSPRequest", (certificate, issuer, callback) => { + const _certificate: Buffer = certificate; + const _issuer: Buffer = issuer; + const _callback: Function = callback; + }); + _server = _server.prependListener("resumeSession", (sessionId, callback) => { + const _sessionId: any = sessionId; + const _func2 = callback; + }); + _server = _server.prependListener("secureConnection", (tlsSocket) => { + const _tlsSocket: tls.TLSSocket = tlsSocket; + }); + + _server = _server.prependOnceListener("tlsClientError", (err, tlsSocket) => { + const _err: Error = err; + const _tlsSocket: tls.TLSSocket = tlsSocket; + }); + _server = _server.prependOnceListener("newSession", (sessionId, sessionData, callback) => { + const _sessionId: any = sessionId; + const _sessionData: any = sessionData; + const _func1 = callback; + }); + _server = _server.prependOnceListener("OCSPRequest", (certificate, issuer, callback) => { + const _certificate: Buffer = certificate; + const _issuer: Buffer = issuer; + const _callback: Function = callback; + }); + _server = _server.prependOnceListener("resumeSession", (sessionId, callback) => { + const _sessionId: any = sessionId; + const _func2 = callback; + }); + _server = _server.prependOnceListener("secureConnection", (tlsSocket) => { + const _tlsSocket: tls.TLSSocket = tlsSocket; + }); + + // close callback parameter is optional + _server = _server.close(); + + // close callback parameter doesn't specify any arguments, so any + // function is acceptable + _server = _server.close(() => { }); + _server = _server.close((...args: any[]) => { }); + } + + { + let _TLSSocket: tls.TLSSocket; + let _boolean: boolean; + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + */ + + _TLSSocket = _TLSSocket.addListener("OCSPResponse", (response) => { + const _response: Buffer = response; + }); + _TLSSocket = _TLSSocket.addListener("secureConnect", () => { }); + + const _buffer: Buffer = Buffer.from(""); + _boolean = _TLSSocket.emit("OCSPResponse", _buffer); + _boolean = _TLSSocket.emit("secureConnect"); + + _TLSSocket = _TLSSocket.on("OCSPResponse", (response) => { + const _response: Buffer = response; + }); + _TLSSocket = _TLSSocket.on("secureConnect", () => { }); + + _TLSSocket = _TLSSocket.once("OCSPResponse", (response) => { + const _response: Buffer = response; + }); + _TLSSocket = _TLSSocket.once("secureConnect", () => { }); + + _TLSSocket = _TLSSocket.prependListener("OCSPResponse", (response) => { + const _response: Buffer = response; + }); + _TLSSocket = _TLSSocket.prependListener("secureConnect", () => { }); + + _TLSSocket = _TLSSocket.prependOnceListener("OCSPResponse", (response) => { + const _response: Buffer = response; + }); + _TLSSocket = _TLSSocket.prependOnceListener("secureConnect", () => { }); + } +} + +//////////////////////////////////////////////////// +/// Http tests : http://nodejs.org/api/http.html /// +//////////////////////////////////////////////////// + +{ + // http Server + { + const server: http.Server = new http.Server(); + + // test public props + const maxHeadersCount: number = server.maxHeadersCount; + const timeout: number = server.timeout; + const listening: boolean = server.listening; + const keepAliveTimeout: number = server.keepAliveTimeout; + server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); + } + + // http IncomingMessage + // http ServerResponse + { + // incoming + const incoming: http.IncomingMessage = new http.IncomingMessage(new net.Socket()); + + incoming.setEncoding('utf8'); + + // stream + incoming.pause(); + incoming.resume(); + + // response + const res: http.ServerResponse = new http.ServerResponse(incoming); + + // test headers + res.setHeader('Content-Type', 'text/plain'); + const bool: boolean = res.hasHeader('Content-Type'); + const headers: string[] = res.getHeaderNames(); + + // trailers + res.addTrailers([ + ['x-fOo', 'xOxOxOx'], + ['x-foO', 'OxOxOxO'], + ['X-fOo', 'xOxOxOx'], + ['X-foO', 'OxOxOxO'] + ]); + res.addTrailers({ 'x-foo': 'bar' }); + + // writeHead + res.writeHead(200, 'OK\r\nContent-Type: text/html\r\n'); + res.writeHead(200, { 'Transfer-Encoding': 'chunked' }); + res.writeHead(200); + + // write string + res.write('Part of my res.'); + // write buffer + const chunk = Buffer.alloc(16390, 'Й'); + res.write(chunk); + res.write(chunk, 'hex'); + + // end + res.end("end msg"); + // without msg + res.end(); + + // flush + res.flushHeaders(); + } + + // http ClientRequest + { + let req: http.ClientRequest = new http.ClientRequest("https://www.google.com"); + req = new http.ClientRequest(new url.URL("https://www.google.com")); + req = new http.ClientRequest({ path: 'http://0.0.0.0' }); + req = new http.ClientRequest({ setHost: false }); + + // header + req.setHeader('Content-Type', 'text/plain'); + const bool: boolean = req.hasHeader('Content-Type'); + const headers: string[] = req.getHeaderNames(); + req.removeHeader('Date'); + + // write + const chunk = Buffer.alloc(16390, 'Й'); + req.write(chunk); + req.write('a'); + req.end(); + + // abort + req.abort(); + + // connection + req.connection.on('pause', () => { }); + + // event + req.on('data', () => { }); + } + + { + // Status codes + let codeMessage: string = http.STATUS_CODES['400']; + codeMessage = http.STATUS_CODES[400]; + } + + { + let agent: http.Agent = new http.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256, + timeout: 15000 + }); + + agent = http.globalAgent; + + http.request({ agent: false }); + http.request({ agent }); + http.request({ agent: undefined }); + } + + { + http.get('http://www.example.com/xyz'); + http.request('http://www.example.com/xyz'); + + http.get('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); + http.request('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); + + http.get(new url.URL('http://www.example.com/xyz')); + http.request(new url.URL('http://www.example.com/xyz')); + + http.get(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); + http.request(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); + + const opts: http.RequestOptions = { + path: '"/some/path' + }; + http.get(new url.URL('http://www.example.com'), opts); + http.request(new url.URL('http://www.example.com'), opts); + http.get(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); + http.request(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); + } + + { + // Make sure .listen() and .close() return a Server instance + http.createServer().listen(0).close().address(); + net.createServer().listen(0).close().address(); + } + + { + const request = http.request({ path: 'http://0.0.0.0' }); + request.once('error', () => { }); + request.setNoDelay(true); + request.abort(); + } + + // http request options + { + const requestOpts: http.RequestOptions = { + timeout: 30000 + }; + + const clientArgs: http.ClientRequestArgs = { + timeout: 30000 + }; + } + + // http headers + { + const headers: http.IncomingHttpHeaders = { + 'content-type': 'application/json', + 'set-cookie': [ 'type=ninja', 'language=javascript' ] + }; + } +} + +////////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html /// +////////////////////////////////////////////////////// + +{ + let agent: https.Agent = new https.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256, + maxCachedSessions: 100, + timeout: 15000 + }); + + agent = https.globalAgent; + + https.request({ + agent: false + }); + https.request({ + agent + }); + https.request({ + agent: undefined + }); + + https.get('http://www.example.com/xyz'); + https.request('http://www.example.com/xyz'); + + https.get('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); + https.request('http://www.example.com/xyz', (res: http.IncomingMessage): void => {}); + + https.get(new url.URL('http://www.example.com/xyz')); + https.request(new url.URL('http://www.example.com/xyz')); + + https.get(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); + https.request(new url.URL('http://www.example.com/xyz'), (res: http.IncomingMessage): void => {}); + + const opts: https.RequestOptions = { + path: '/some/path' + }; + https.get(new url.URL('http://www.example.com'), opts); + https.request(new url.URL('http://www.example.com'), opts); + https.get(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); + https.request(new url.URL('http://www.example.com/xyz'), opts, (res: http.IncomingMessage): void => {}); + + https.globalAgent.options.ca = []; + + { + const server = new https.Server(); + + const timeout: number = server.timeout; + const listening: boolean = server.listening; + const keepAliveTimeout: number = server.keepAliveTimeout; + server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); + } +} + +//////////////////////////////////////////////////// +/// TTY tests : http://nodejs.org/api/tty.html +//////////////////////////////////////////////////// + +{ + const rs: tty.ReadStream = new tty.ReadStream(); + const ws: tty.WriteStream = new tty.WriteStream(); + + const rsIsRaw: boolean = rs.isRaw; + rs.setRawMode(true); + + const wsColumns: number = ws.columns; + const wsRows: number = ws.rows; + + const isTTY: boolean = tty.isatty(1); +} + +//////////////////////////////////////////////////// +/// Dgram tests : http://nodejs.org/api/dgram.html +//////////////////////////////////////////////////// + +{ + { + let ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { + }); + ds.bind(); + ds.bind(41234); + ds.bind(4123, 'localhost'); + ds.bind(4123, 'localhost', () => { }); + ds.bind(4123, () => { }); + ds.bind(() => { }); + const addr: net.AddressInfo | string = ds.address(); + ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { + }); + ds.send(new Buffer("hello"), 5000, "127.0.0.1"); + ds.setMulticastInterface("127.0.0.1"); + ds = dgram.createSocket({ type: "udp4", reuseAddr: true, recvBufferSize: 1000, sendBufferSize: 1000, lookup: dns.lookup }); + } + + { + let _socket: dgram.Socket; + let _boolean: boolean; + const _err: Error = new Error(); + const _str = ''; + const _rinfo: net.AddressInfo = { + address: 'asd', + family: 'asd', + port: 1, + }; + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + */ + + _socket = _socket.addListener("close", () => { }); + _socket = _socket.addListener("error", (err) => { + const _err: Error = err; + }); + _socket = _socket.addListener("listening", () => { }); + _socket = _socket.addListener("message", (msg, rinfo) => { + const _msg: Buffer = msg; + const _rinfo: net.AddressInfo = rinfo; + }); + + _boolean = _socket.emit("close"); + _boolean = _socket.emit("error", _err); + _boolean = _socket.emit("listening"); + _boolean = _socket.emit("message", _str, _rinfo); + + _socket = _socket.on("close", () => { }); + _socket = _socket.on("error", (err) => { + const _err: Error = err; + }); + _socket = _socket.on("listening", () => { }); + _socket = _socket.on("message", (msg, rinfo) => { + const _msg: Buffer = msg; + const _rinfo: net.AddressInfo = rinfo; + }); + + _socket = _socket.once("close", () => { }); + _socket = _socket.once("error", (err) => { + const _err: Error = err; + }); + _socket = _socket.once("listening", () => { }); + _socket = _socket.once("message", (msg, rinfo) => { + const _msg: Buffer = msg; + const _rinfo: net.AddressInfo = rinfo; + }); + + _socket = _socket.prependListener("close", () => { }); + _socket = _socket.prependListener("error", (err) => { + const _err: Error = err; + }); + _socket = _socket.prependListener("listening", () => { }); + _socket = _socket.prependListener("message", (msg, rinfo) => { + const _msg: Buffer = msg; + const _rinfo: net.AddressInfo = rinfo; + }); + + _socket = _socket.prependOnceListener("close", () => { }); + _socket = _socket.prependOnceListener("error", (err) => { + const _err: Error = err; + }); + _socket = _socket.prependOnceListener("listening", () => { }); + _socket = _socket.prependOnceListener("message", (msg, rinfo) => { + const _msg: Buffer = msg; + const _rinfo: net.AddressInfo = rinfo; + }); + } + + { + const ds: dgram.Socket = dgram.createSocket({ + type: 'udp4', + recvBufferSize: 10000, + sendBufferSize: 15000 + }); + + let size: number; + size = ds.getRecvBufferSize(); + ds.setRecvBufferSize(size); + size = ds.getSendBufferSize(); + ds.setSendBufferSize(size); + } +} + +//////////////////////////////////////////////////// +/// Querystring tests : https://nodejs.org/api/querystring.html +//////////////////////////////////////////////////// + +{ + interface SampleObject { a: string; } + + { + const obj: SampleObject = { a: "" }; + const sep = ''; + const eq = ''; + const options: querystring.StringifyOptions = {}; + let result: string; + + result = querystring.stringify(obj); + result = querystring.stringify(obj, sep); + result = querystring.stringify(obj, sep, eq); + result = querystring.stringify(obj, sep, eq); + result = querystring.stringify(obj, sep, eq, options); + } + + { + const str = ''; + const sep = ''; + const eq = ''; + const options: querystring.ParseOptions = {}; + let result: querystring.ParsedUrlQuery; + + result = querystring.parse(str); + result = querystring.parse(str, sep); + result = querystring.parse(str, sep, eq); + result = querystring.parse(str, sep, eq, options); + } + + { + const str = ''; + let result: string; + + result = querystring.escape(str); + result = querystring.unescape(str); + } +} + +//////////////////////////////////////////////////// +/// path tests : http://nodejs.org/api/path.html +//////////////////////////////////////////////////// + +{ + path.normalize('/foo/bar//baz/asdf/quux/..'); + + path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); + // returns + // '/foo/bar/baz/asdf' + + try { + path.join('foo', 'bar'); + } catch (error) { } + + path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile'); + // Is similar to: + // + // cd foo/bar + // cd /tmp/file/ + // cd .. + // cd a/../subfile + // pwd + + path.resolve('/foo/bar', './baz'); + // returns + // '/foo/bar/baz' + + path.resolve('/foo/bar', '/tmp/file/'); + // returns + // '/tmp/file' + + path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif'); + // if currently in /home/myself/node, it returns + // '/home/myself/node/wwwroot/static_files/gif/image.gif' + + path.isAbsolute('/foo/bar'); // true + path.isAbsolute('/baz/..'); // true + path.isAbsolute('qux/'); // false + path.isAbsolute('.'); // false + + path.isAbsolute('//server'); // true + path.isAbsolute('C:/foo/..'); // true + path.isAbsolute('bar\\baz'); // false + path.isAbsolute('.'); // false + + path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb'); + // returns + // '..\\..\\impl\\bbb' + + path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb'); + // returns + // '../../impl/bbb' + + path.dirname('/foo/bar/baz/asdf/quux'); + // returns + // '/foo/bar/baz/asdf' + + path.basename('/foo/bar/baz/asdf/quux.html'); + // returns + // 'quux.html' + + path.basename('/foo/bar/baz/asdf/quux.html', '.html'); + // returns + // 'quux' + + path.extname('index.html'); + // returns + // '.html' + + path.extname('index.coffee.md'); + // returns + // '.md' + + path.extname('index.'); + // returns + // '.' + + path.extname('index'); + // returns + // '' + + 'foo/bar/baz'.split(path.sep); + // returns + // ['foo', 'bar', 'baz'] + + 'foo\\bar\\baz'.split(path.sep); + // returns + // ['foo', 'bar', 'baz'] + + process.env["PATH"]; // $ExpectType string + + path.parse('/home/user/dir/file.txt'); + // returns + // { + // root : "/", + // dir : "/home/user/dir", + // base : "file.txt", + // ext : ".txt", + // name : "file" + // } + + path.parse('C:\\path\\dir\\index.html'); + // returns + // { + // root : "C:\", + // dir : "C:\path\dir", + // base : "index.html", + // ext : ".html", + // name : "index" + // } + + path.format({ + root: "/", + dir: "/home/user/dir", + base: "file.txt", + ext: ".txt", + name: "file" + }); + // returns + // '/home/user/dir/file.txt' + + path.format({ + root: "/", + dir: "/home/user/dir", + ext: ".txt", + name: "file" + }); + // returns + // '/home/user/dir/file.txt' + + path.format({ + dir: "/home/user/dir", + base: "file.txt" + }); + // returns + // '/home/user/dir/file.txt' + + path.posix.format({ + root: "/", + dir: "/home/user/dir", + base: "file.txt", + ext: ".txt", + name: "file" + }); + // returns + // '/home/user/dir/file.txt' + + path.posix.format({ + dir: "/home/user/dir", + base: "file.txt" + }); + // returns + // '/home/user/dir/file.txt' + + path.win32.format({ + root: "C:\\", + dir: "C:\\home\\user\\dir", + ext: ".txt", + name: "file" + }); + // returns + // 'C:\home\user\dir\file.txt' + + path.win32.format({ + dir: "C:\\home\\user\\dir", + base: "file.txt" + }); + // returns + // 'C:\home\user\dir\file.txt' +} + +//////////////////////////////////////////////////// +/// readline tests : https://nodejs.org/api/readline.html +//////////////////////////////////////////////////// + +{ + const rl: readline.ReadLine = readline.createInterface(new stream.Readable()); + + { + const options: readline.ReadLineOptions = { + input: new fs.ReadStream() + }; + const input: NodeJS.ReadableStream = new stream.Readable(); + const output: NodeJS.WritableStream = new stream.Writable(); + const completer: readline.Completer = str => [['asd'], 'asd']; + const terminal = false; + + let result: readline.ReadLine; + + result = readline.createInterface(options); + result = readline.createInterface(input); + result = readline.createInterface(input, output); + result = readline.createInterface(input, output, completer); + result = readline.createInterface(input, output, completer, terminal); + result = readline.createInterface({ + input, + completer(str: string): readline.CompleterResult { + return [['test'], 'test']; + } + }); + result = readline.createInterface({ + input, + completer(str: string, callback: (err: any, result: readline.CompleterResult) => void): any { + callback(null, [['test'], 'test']); + } + }); + } + + { + rl.setPrompt("prompt"); + } + + { + rl.prompt(); + rl.prompt(true); + } + + { + rl.question("query", (answer: string) => {}); + } + + { + let result: readline.ReadLine; + + result = rl.pause(); + } + + { + let result: readline.ReadLine; + + result = rl.resume(); + } + + { + rl.close(); + } + + { + const data: string | Buffer = "asd"; + const key: readline.Key = {}; + + rl.write(data); + rl.write(null, key); + } + + { + const strm: NodeJS.WritableStream = new stream.Writable(); + const x = 1; + const y = 1; + + readline.cursorTo(strm, x); + readline.cursorTo(strm, x, y); + } + + { + const strm: NodeJS.ReadableStream = new stream.Readable(); + const readLineInterface: readline.ReadLine = readline.createInterface(new stream.Readable()); + + readline.emitKeypressEvents(strm); + readline.emitKeypressEvents(strm, readLineInterface); + } + + { + const strm: NodeJS.WritableStream = new stream.Writable(); + const dx: number | string = 1; + const dy: number | string = 1; + + readline.moveCursor(strm, dx, dy); + } + + { + const strm: NodeJS.WritableStream = new stream.Writable(); + readline.clearLine(strm, 1); + } + + { + const strm: NodeJS.WritableStream = new stream.Writable(); + + readline.clearScreenDown(strm); + } + + { + let _rl: readline.ReadLine; + let _boolean: boolean; + + _rl = _rl.addListener("close", () => { }); + _rl = _rl.addListener("line", (input) => { + const _input: any = input; + }); + _rl = _rl.addListener("pause", () => { }); + _rl = _rl.addListener("resume", () => { }); + _rl = _rl.addListener("SIGCONT", () => { }); + _rl = _rl.addListener("SIGINT", () => { }); + _rl = _rl.addListener("SIGTSTP", () => { }); + + _boolean = _rl.emit("close", () => { }); + _boolean = _rl.emit("line", () => { }); + _boolean = _rl.emit("pause", () => { }); + _boolean = _rl.emit("resume", () => { }); + _boolean = _rl.emit("SIGCONT", () => { }); + _boolean = _rl.emit("SIGINT", () => { }); + _boolean = _rl.emit("SIGTSTP", () => { }); + + _rl = _rl.on("close", () => { }); + _rl = _rl.on("line", (input) => { + const _input: any = input; + }); + _rl = _rl.on("pause", () => { }); + _rl = _rl.on("resume", () => { }); + _rl = _rl.on("SIGCONT", () => { }); + _rl = _rl.on("SIGINT", () => { }); + _rl = _rl.on("SIGTSTP", () => { }); + + _rl = _rl.once("close", () => { }); + _rl = _rl.once("line", (input) => { + const _input: any = input; + }); + _rl = _rl.once("pause", () => { }); + _rl = _rl.once("resume", () => { }); + _rl = _rl.once("SIGCONT", () => { }); + _rl = _rl.once("SIGINT", () => { }); + _rl = _rl.once("SIGTSTP", () => { }); + + _rl = _rl.prependListener("close", () => { }); + _rl = _rl.prependListener("line", (input) => { + const _input: any = input; + }); + _rl = _rl.prependListener("pause", () => { }); + _rl = _rl.prependListener("resume", () => { }); + _rl = _rl.prependListener("SIGCONT", () => { }); + _rl = _rl.prependListener("SIGINT", () => { }); + _rl = _rl.prependListener("SIGTSTP", () => { }); + + _rl = _rl.prependOnceListener("close", () => { }); + _rl = _rl.prependOnceListener("line", (input) => { + const _input: any = input; + }); + _rl = _rl.prependOnceListener("pause", () => { }); + _rl = _rl.prependOnceListener("resume", () => { }); + _rl = _rl.prependOnceListener("SIGCONT", () => { }); + _rl = _rl.prependOnceListener("SIGINT", () => { }); + _rl = _rl.prependOnceListener("SIGTSTP", () => { }); + } +} + +//////////////////////////////////////////////////// +/// string_decoder tests : https://nodejs.org/api/string_decoder.html +//////////////////////////////////////////////////// + +{ + const StringDecoder = string_decoder.StringDecoder; + const buffer = new Buffer('test'); + const decoder1 = new StringDecoder(); + const decoder2 = new StringDecoder('utf8'); + const part1: string = decoder1.write(new Buffer('test')); + const end1: string = decoder1.end(); + const part2: string = decoder2.write(new Buffer('test')); + const end2: string = decoder1.end(new Buffer('test')); +} + +////////////////////////////////////////////////////////////////////// +/// Child Process tests: https://nodejs.org/api/child_process.html /// +////////////////////////////////////////////////////////////////////// + +{ + { + childProcess.exec("echo test"); + childProcess.exec("echo test", { windowsHide: true }); + childProcess.spawn("echo"); + childProcess.spawn("echo", { windowsHide: true }); + childProcess.spawn("echo", ["test"], { windowsHide: true }); + childProcess.spawn("echo", ["test"], { windowsHide: true, argv0: "echo-test" }); + childProcess.spawn("echo", ["test"], { stdio: [0xdeadbeef, "inherit", undefined, "pipe"] }); + childProcess.spawnSync("echo test"); + childProcess.spawnSync("echo test", {windowsVerbatimArguments: false}); + childProcess.spawnSync("echo test", {windowsVerbatimArguments: false, argv0: "echo-test"}); + childProcess.spawnSync("echo test", {input: new Uint8Array([])}); + childProcess.spawnSync("echo test", {input: new DataView(new ArrayBuffer(1))}); + } + + { + childProcess.execFile("npm", () => {}); + childProcess.execFile("npm", { windowsHide: true }, () => {}); + childProcess.execFile("npm", ["-v"], () => {}); + childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); + childProcess.execFile("npm", ["-v"], { windowsHide: true, encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); + childProcess.execFile("npm", { encoding: 'utf-8' }, (stdout, stderr) => { assert(stdout instanceof String); }); + childProcess.execFile("npm", { encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); + } + + { + childProcess.execFileSync("echo test", {input: new Uint8Array([])}); + childProcess.execFileSync("echo test", {input: new DataView(new ArrayBuffer(1))}); + } + + async function testPromisify() { + const execFile = util.promisify(childProcess.execFile); + let r: { stdout: string | Buffer, stderr: string | Buffer } = await execFile("npm"); + r = await execFile("npm", ["-v"]); + r = await execFile("npm", ["-v"], { encoding: 'utf-8' }); + r = await execFile("npm", ["-v"], { encoding: 'buffer' }); + r = await execFile("npm", { encoding: 'utf-8' }); + r = await execFile("npm", { encoding: 'buffer' }); + } + + { + let _cp: childProcess.ChildProcess; + const _socket: net.Socket = net.createConnection(1); + const _server: net.Server = net.createServer(); + let _boolean: boolean; + + _boolean = _cp.send(1); + _boolean = _cp.send('one'); + _boolean = _cp.send({ + type: 'test' + }); + + _boolean = _cp.send(1, (error) => { + const _err: Error = error; + }); + _boolean = _cp.send('one', (error) => { + const _err: Error = error; + }); + _boolean = _cp.send({ + type: 'test' + }, (error) => { + const _err: Error = error; + }); + + _boolean = _cp.send(1, _socket); + _boolean = _cp.send('one', _socket); + _boolean = _cp.send({ + type: 'test' + }, _socket); + + _boolean = _cp.send(1, _socket, (error) => { + const _err: Error = error; + }); + _boolean = _cp.send('one', _socket, (error) => { + const _err: Error = error; + }); + _boolean = _cp.send({ + type: 'test' + }, _socket, (error) => { + const _err: Error = error; + }); + + _boolean = _cp.send(1, _socket, { + keepOpen: true + }); + _boolean = _cp.send('one', _socket, { + keepOpen: true + }); + _boolean = _cp.send({ + type: 'test' + }, _socket, { + keepOpen: true + }); + + _boolean = _cp.send(1, _socket, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + _boolean = _cp.send('one', _socket, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + _boolean = _cp.send({ + type: 'test' + }, _socket, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + + _boolean = _cp.send(1, _server); + _boolean = _cp.send('one', _server); + _boolean = _cp.send({ + type: 'test' + }, _server); + + _boolean = _cp.send(1, _server, (error) => { + const _err: Error = error; + }); + _boolean = _cp.send('one', _server, (error) => { + const _err: Error = error; + }); + _boolean = _cp.send({ + type: 'test' + }, _server, (error) => { + const _err: Error = error; + }); + + _boolean = _cp.send(1, _server, { + keepOpen: true + }); + _boolean = _cp.send('one', _server, { + keepOpen: true + }); + _boolean = _cp.send({ + type: 'test' + }, _server, { + keepOpen: true + }); + + _boolean = _cp.send(1, _server, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + _boolean = _cp.send('one', _server, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + _boolean = _cp.send({ + type: 'test' + }, _server, { + keepOpen: true + }, (error) => { + const _err: Error = error; + }); + + _cp = _cp.addListener("close", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + _cp = _cp.addListener("disconnect", () => { }); + _cp = _cp.addListener("error", (err) => { + const _err: Error = err; + }); + _cp = _cp.addListener("exit", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + _cp = _cp.addListener("message", (message, sendHandle) => { + const _message: any = message; + const _sendHandle: net.Socket | net.Server = sendHandle; + }); + + _boolean = _cp.emit("close", () => { }); + _boolean = _cp.emit("disconnect", () => { }); + _boolean = _cp.emit("error", () => { }); + _boolean = _cp.emit("exit", () => { }); + _boolean = _cp.emit("message", () => { }); + + _cp = _cp.on("close", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + _cp = _cp.on("disconnect", () => { }); + _cp = _cp.on("error", (err) => { + const _err: Error = err; + }); + _cp = _cp.on("exit", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + _cp = _cp.on("message", (message, sendHandle) => { + const _message: any = message; + const _sendHandle: net.Socket | net.Server = sendHandle; + }); + + _cp = _cp.once("close", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + _cp = _cp.once("disconnect", () => { }); + _cp = _cp.once("error", (err) => { + const _err: Error = err; + }); + _cp = _cp.once("exit", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + _cp = _cp.once("message", (message, sendHandle) => { + const _message: any = message; + const _sendHandle: net.Socket | net.Server = sendHandle; + }); + + _cp = _cp.prependListener("close", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + _cp = _cp.prependListener("disconnect", () => { }); + _cp = _cp.prependListener("error", (err) => { + const _err: Error = err; + }); + _cp = _cp.prependListener("exit", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + _cp = _cp.prependListener("message", (message, sendHandle) => { + const _message: any = message; + const _sendHandle: net.Socket | net.Server = sendHandle; + }); + + _cp = _cp.prependOnceListener("close", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + _cp = _cp.prependOnceListener("disconnect", () => { }); + _cp = _cp.prependOnceListener("error", (err) => { + const _err: Error = err; + }); + _cp = _cp.prependOnceListener("exit", (code, signal) => { + const _code: number = code; + const _signal: string = signal; + }); + _cp = _cp.prependOnceListener("message", (message, sendHandle) => { + const _message: any = message; + const _sendHandle: net.Socket | net.Server = sendHandle; + }); + } + { + process.stdin.setEncoding('utf8'); + + process.stdin.on('readable', () => { + const chunk = process.stdin.read(); + if (chunk !== null) { + process.stdout.write(`data: ${chunk}`); + } + }); + + process.stdin.on('end', () => { + process.stdout.write('end'); + }); + + process.stdin.pipe(process.stdout); + + console.log(process.stdin.isTTY); + console.log(process.stdout.isTTY); + + console.log(process.stdin instanceof net.Socket); + console.log(process.stdout instanceof fs.ReadStream); + + const stdin: stream.Readable = process.stdin; + console.log(stdin instanceof net.Socket); + console.log(stdin instanceof fs.ReadStream); + + const stdout: stream.Writable = process.stdout; + console.log(stdout instanceof net.Socket); + console.log(stdout instanceof fs.WriteStream); + } +} + +////////////////////////////////////////////////////////////////////// +/// cluster tests: https://nodejs.org/api/cluster.html /// +////////////////////////////////////////////////////////////////////// + +{ + { + cluster.fork(); + Object.keys(cluster.workers).forEach(key => { + const worker = cluster.workers[key]; + if (worker.isDead()) { + console.log('worker %d is dead', worker.process.pid); + } + }); + } +} + +////////////////////////////////////////////////////////////////////// +/// worker_threads tests: https://nodejs.org/api/worker_threads.html /// +////////////////////////////////////////////////////////////////////// + +{ + { + if (workerThreads.isMainThread) { + module.exports = async function parseJSAsync(script: string) { + return new Promise((resolve, reject) => { + const worker = new workerThreads.Worker(__filename, { + workerData: script + }); + worker.on('message', resolve); + worker.on('error', reject); + worker.on('exit', (code) => { + if (code !== 0) + reject(new Error(`Worker stopped with exit code ${code}`)); + }); + }); + }; + } else { + const script = workerThreads.workerData; + workerThreads.parentPort.postMessage(script); + } + } + + { + const { port1, port2 } = new workerThreads.MessageChannel(); + port1.on('message', (message) => console.log('received', message)); + port2.postMessage({ foo: 'bar' }); + } + + { + if (workerThreads.isMainThread) { + const worker = new workerThreads.Worker(__filename); + const subChannel = new workerThreads.MessageChannel(); + worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]); + subChannel.port2.on('message', (value) => { + console.log('received:', value); + }); + } else { + workerThreads.parentPort.once('message', (value) => { + assert(value.hereIsYourPort instanceof MessagePort); + value.hereIsYourPort.postMessage('the worker is sending this'); + value.hereIsYourPort.close(); + }); + } + } +} + +//////////////////////////////////////////////////// +/// os tests : https://nodejs.org/api/os.html +//////////////////////////////////////////////////// + +{ + { + let result: string; + + result = os.tmpdir(); + result = os.homedir(); + result = os.endianness(); + result = os.hostname(); + result = os.type(); + result = os.arch(); + result = os.release(); + result = os.EOL; + } + + { + let result: number; + + result = os.uptime(); + result = os.totalmem(); + result = os.freemem(); + } + + { + let result: number[]; + + result = os.loadavg(); + } + + { + let result: os.CpuInfo[]; + + result = os.cpus(); + } + + { + let result: { [index: string]: os.NetworkInterfaceInfo[] }; + + result = os.networkInterfaces(); + } + + { + let result: number; + + result = os.constants.signals.SIGHUP; + result = os.constants.signals.SIGINT; + result = os.constants.signals.SIGQUIT; + result = os.constants.signals.SIGILL; + result = os.constants.signals.SIGTRAP; + result = os.constants.signals.SIGABRT; + result = os.constants.signals.SIGIOT; + result = os.constants.signals.SIGBUS; + result = os.constants.signals.SIGFPE; + result = os.constants.signals.SIGKILL; + result = os.constants.signals.SIGUSR1; + result = os.constants.signals.SIGSEGV; + result = os.constants.signals.SIGUSR2; + result = os.constants.signals.SIGPIPE; + result = os.constants.signals.SIGALRM; + result = os.constants.signals.SIGTERM; + result = os.constants.signals.SIGCHLD; + result = os.constants.signals.SIGSTKFLT; + result = os.constants.signals.SIGCONT; + result = os.constants.signals.SIGSTOP; + result = os.constants.signals.SIGTSTP; + result = os.constants.signals.SIGTTIN; + result = os.constants.signals.SIGTTOU; + result = os.constants.signals.SIGURG; + result = os.constants.signals.SIGXCPU; + result = os.constants.signals.SIGXFSZ; + result = os.constants.signals.SIGVTALRM; + result = os.constants.signals.SIGPROF; + result = os.constants.signals.SIGWINCH; + result = os.constants.signals.SIGIO; + result = os.constants.signals.SIGPOLL; + result = os.constants.signals.SIGPWR; + result = os.constants.signals.SIGSYS; + result = os.constants.signals.SIGUNUSED; + } + + { + let result: number; + + result = os.constants.errno.E2BIG; + result = os.constants.errno.EACCES; + result = os.constants.errno.EADDRINUSE; + result = os.constants.errno.EADDRNOTAVAIL; + result = os.constants.errno.EAFNOSUPPORT; + result = os.constants.errno.EAGAIN; + result = os.constants.errno.EALREADY; + result = os.constants.errno.EBADF; + result = os.constants.errno.EBADMSG; + result = os.constants.errno.EBUSY; + result = os.constants.errno.ECANCELED; + result = os.constants.errno.ECHILD; + result = os.constants.errno.ECONNABORTED; + result = os.constants.errno.ECONNREFUSED; + result = os.constants.errno.ECONNRESET; + result = os.constants.errno.EDEADLK; + result = os.constants.errno.EDESTADDRREQ; + result = os.constants.errno.EDOM; + result = os.constants.errno.EDQUOT; + result = os.constants.errno.EEXIST; + result = os.constants.errno.EFAULT; + result = os.constants.errno.EFBIG; + result = os.constants.errno.EHOSTUNREACH; + result = os.constants.errno.EIDRM; + result = os.constants.errno.EILSEQ; + result = os.constants.errno.EINPROGRESS; + result = os.constants.errno.EINTR; + result = os.constants.errno.EINVAL; + result = os.constants.errno.EIO; + result = os.constants.errno.EISCONN; + result = os.constants.errno.EISDIR; + result = os.constants.errno.ELOOP; + result = os.constants.errno.EMFILE; + result = os.constants.errno.EMLINK; + result = os.constants.errno.EMSGSIZE; + result = os.constants.errno.EMULTIHOP; + result = os.constants.errno.ENAMETOOLONG; + result = os.constants.errno.ENETDOWN; + result = os.constants.errno.ENETRESET; + result = os.constants.errno.ENETUNREACH; + result = os.constants.errno.ENFILE; + result = os.constants.errno.ENOBUFS; + result = os.constants.errno.ENODATA; + result = os.constants.errno.ENODEV; + result = os.constants.errno.ENOENT; + result = os.constants.errno.ENOEXEC; + result = os.constants.errno.ENOLCK; + result = os.constants.errno.ENOLINK; + result = os.constants.errno.ENOMEM; + result = os.constants.errno.ENOMSG; + result = os.constants.errno.ENOPROTOOPT; + result = os.constants.errno.ENOSPC; + result = os.constants.errno.ENOSR; + result = os.constants.errno.ENOSTR; + result = os.constants.errno.ENOSYS; + result = os.constants.errno.ENOTCONN; + result = os.constants.errno.ENOTDIR; + result = os.constants.errno.ENOTEMPTY; + result = os.constants.errno.ENOTSOCK; + result = os.constants.errno.ENOTSUP; + result = os.constants.errno.ENOTTY; + result = os.constants.errno.ENXIO; + result = os.constants.errno.EOPNOTSUPP; + result = os.constants.errno.EOVERFLOW; + result = os.constants.errno.EPERM; + result = os.constants.errno.EPIPE; + result = os.constants.errno.EPROTO; + result = os.constants.errno.EPROTONOSUPPORT; + result = os.constants.errno.EPROTOTYPE; + result = os.constants.errno.ERANGE; + result = os.constants.errno.EROFS; + result = os.constants.errno.ESPIPE; + result = os.constants.errno.ESRCH; + result = os.constants.errno.ESTALE; + result = os.constants.errno.ETIME; + result = os.constants.errno.ETIMEDOUT; + result = os.constants.errno.ETXTBSY; + result = os.constants.errno.EWOULDBLOCK; + result = os.constants.errno.EXDEV; + } + + { + const prio = os.getPriority(); + os.setPriority(prio + 1); + + const prio2 = os.getPriority(1); + os.setPriority(2, prio + 1); + + os.setPriority(os.constants.priority.PRIORITY_LOW); + } +} + +//////////////////////////////////////////////////// +/// vm tests : https://nodejs.org/api/vm.html +//////////////////////////////////////////////////// + +{ + { + const sandbox = { + animal: 'cat', + count: 2 + }; + + const context = vm.createContext(sandbox); + console.log(vm.isContext(context)); + const script = new vm.Script('count += 1; name = "kitty"'); + + for (let i = 0; i < 10; ++i) { + script.runInContext(context); + } + + console.log(util.inspect(sandbox)); + + vm.runInNewContext('count += 1; name = "kitty"', sandbox); + console.log(util.inspect(sandbox)); + } + + { + const sandboxes = [{}, {}, {}]; + + const script = new vm.Script('globalVar = "set"'); + + sandboxes.forEach((sandbox) => { + script.runInNewContext(sandbox); + script.runInThisContext(); + }); + + console.log(util.inspect(sandboxes)); + + const localVar = 'initial value'; + vm.runInThisContext('localVar = "vm";'); + + console.log(localVar); + } + + { + vm.runInThisContext('console.log("hello world"', './my-file.js'); + } + + { + const fn: Function = vm.compileFunction('console.log("test")', [], { + parsingContext: vm.createContext(), + contextExtensions: [{ + a: 1, + }], + produceCachedData: false, + cachedData: Buffer.from('nope'), + }); + } +} + +///////////////////////////////////////////////////// +/// Timers tests : https://nodejs.org/api/timers.html +///////////////////////////////////////////////////// + +{ + { + const immediateId = timers.setImmediate(() => { console.log("immediate"); }); + timers.clearImmediate(immediateId); + } + { + const counter = 0; + const timeout = timers.setInterval(() => { console.log("interval"); }, 20); + timeout.unref(); + timeout.ref(); + timers.clearInterval(timeout); + } + { + const counter = 0; + const timeout = timers.setTimeout(() => { console.log("timeout"); }, 20); + timeout.unref(); + timeout.ref(); + timers.clearTimeout(timeout); + } + async function testPromisify() { + const setTimeout = util.promisify(timers.setTimeout); + let v: void = await setTimeout(100); // tslint:disable-line no-void-expression void-return + let s: string = await setTimeout(100, ""); + + const setImmediate = util.promisify(timers.setImmediate); + v = await setImmediate(); // tslint:disable-line no-void-expression + s = await setImmediate(""); + } +} + +///////////////////////////////////////////////////////// +/// Errors Tests : https://nodejs.org/api/errors.html /// +///////////////////////////////////////////////////////// + +{ + { + Error.stackTraceLimit = Infinity; + } + { + const myObject = {}; + Error.captureStackTrace(myObject); + } + { + const frames: NodeJS.CallSite[] = []; + Error.prepareStackTrace(new Error(), frames); + } + { + const frame: NodeJS.CallSite = null; + const frameThis: any = frame.getThis(); + const typeName: string = frame.getTypeName(); + const func: Function = frame.getFunction(); + const funcName: string = frame.getFunctionName(); + const meth: string = frame.getMethodName(); + const fname: string = frame.getFileName(); + const lineno: number = frame.getLineNumber(); + const colno: number = frame.getColumnNumber(); + const evalOrigin: string = frame.getEvalOrigin(); + const isTop: boolean = frame.isToplevel(); + const isEval: boolean = frame.isEval(); + const isNative: boolean = frame.isNative(); + const isConstr: boolean = frame.isConstructor(); + } +} + +/////////////////////////////////////////////////////////// +/// Process Tests : https://nodejs.org/api/process.html /// +/////////////////////////////////////////////////////////// + +import * as p from "process"; +{ + { + let eventEmitter: events.EventEmitter; + eventEmitter = process; // Test that process implements EventEmitter... + + let _p: NodeJS.Process = process; + _p = p; + } + { + assert(process.argv[0] === process.argv0); + } + { + let module: NodeModule | undefined; + module = process.mainModule; + } + { + process.on("message", (req: any) => { }); + process.addListener("beforeExit", (code: number) => { }); + process.once("disconnect", () => { }); + process.prependListener("exit", (code: number) => { }); + process.prependOnceListener("rejectionHandled", (promise: Promise<any>) => { }); + process.on("uncaughtException", (error: Error) => { }); + process.addListener("unhandledRejection", (reason: any, promise: Promise<any>) => { }); + process.once("warning", (warning: Error) => { }); + process.prependListener("message", (message: any, sendHandle: any) => { }); + process.prependOnceListener("SIGBREAK", () => { }); + process.on("newListener", (event: string | symbol, listener: Function) => { }); + process.once("removeListener", (event: string | symbol, listener: Function) => { }); + process.on("multipleResolves", (type: NodeJS.MultipleResolveType, prom: Promise<any>, value: any) => {}); + + const listeners = process.listeners('uncaughtException'); + const oldHandler = listeners[listeners.length - 1]; + process.addListener('uncaughtException', oldHandler); + } + { + function myCb(err: Error): void { + } + process.setUncaughtExceptionCaptureCallback(myCb); + process.setUncaughtExceptionCaptureCallback(null); + const b: boolean = process.hasUncaughtExceptionCaptureCallback(); + } + { + // process.allowedNodeEnvironmentFlags.has('asdf'); + } +} + +/////////////////////////////////////////////////////////// +/// Console Tests : https://nodejs.org/api/console.html /// +/////////////////////////////////////////////////////////// + +{ + { + let _c: Console = console; + _c = console2; + } + { + const writeStream = fs.createWriteStream('./index.d.ts'); + let consoleInstance: Console = new console.Console(writeStream); + + consoleInstance = new console.Console(writeStream, writeStream); + consoleInstance = new console.Console(writeStream, writeStream, true); + consoleInstance = new console.Console({ + stdout: writeStream, + stderr: writeStream, + colorMode: 'auto', + ignoreErrors: true + }); + consoleInstance = new console.Console({ + stdout: writeStream, + colorMode: false + }); + consoleInstance = new console.Console({ + stdout: writeStream + }); + } + { + console.assert('value'); + console.assert('value', 'message'); + console.assert('value', 'message', 'foo', 'bar'); + console.clear(); + console.count(); + console.count('label'); + console.countReset(); + console.countReset('label'); + console.debug(); + console.debug('message'); + console.debug('message', 'foo', 'bar'); + console.dir('obj'); + console.dir('obj', { depth: 1 }); + console.error(); + console.error('message'); + console.error('message', 'foo', 'bar'); + console.group(); + console.group('label'); + console.group('label1', 'label2'); + console.groupCollapsed(); + console.groupEnd(); + console.info(); + console.info('message'); + console.info('message', 'foo', 'bar'); + console.log(); + console.log('message'); + console.log('message', 'foo', 'bar'); + console.table({ foo: 'bar' }); + console.table([{ foo: 'bar' }]); + console.table([{ foo: 'bar' }], ['foo']); + console.time(); + console.time('label'); + console.timeEnd(); + console.timeEnd('label'); + console.timeLog(); + console.timeLog('label'); + console.timeLog('label', 'foo', 'bar'); + console.trace(); + console.trace('message'); + console.trace('message', 'foo', 'bar'); + console.warn(); + console.warn('message'); + console.warn('message', 'foo', 'bar'); + + // --- Inspector mode only --- + console.markTimeline(); + console.markTimeline('label'); + console.profile(); + console.profile('label'); + console.profileEnd(); + console.profileEnd('label'); + console.timeStamp(); + console.timeStamp('label'); + console.timeline(); + console.timeline('label'); + console.timelineEnd(); + console.timelineEnd('label'); + } +} + +/////////////////////////////////////////////////// +/// Net Tests : https://nodejs.org/api/net.html /// +/////////////////////////////////////////////////// + +{ + { + const connectOpts: net.NetConnectOpts = { + allowHalfOpen: true, + family: 4, + host: "localhost", + port: 443, + timeout: 10E3 + }; + const socket: net.Socket = net.createConnection(connectOpts, (): void => { + // nothing + }); + } + + { + let server = net.createServer(); + // Check methods which return server instances by chaining calls + server = server.listen(0) + .close() + .ref() + .unref(); + + // close has an optional callback function. No callback parameters are + // specified, so any callback function is permissible. + server = server.close((...args: any[]) => { }); + + // test the types of the address object fields + const address: net.AddressInfo | string = server.address(); + } + + { + const constructorOpts: net.SocketConstructorOpts = { + fd: 1, + allowHalfOpen: false, + readable: false, + writable: false + }; + + /** + * net.Socket - events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + let _socket: net.Socket = new net.Socket(constructorOpts); + + let bool: boolean; + let buffer: Buffer; + let error: Error; + let str: string; + let num: number; + + const ipcConnectOpts: net.IpcSocketConnectOpts = { + path: "/" + }; + const tcpConnectOpts: net.TcpSocketConnectOpts = { + family: 4, + hints: 0, + host: "localhost", + localAddress: "10.0.0.1", + localPort: 1234, + lookup: (_hostname: string, _options: dns.LookupOneOptions, _callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void => { + // nothing + }, + port: 80 + }; + _socket = _socket.connect(ipcConnectOpts); + _socket = _socket.connect(ipcConnectOpts, (): void => {}); + _socket = _socket.connect(tcpConnectOpts); + _socket = _socket.connect(tcpConnectOpts, (): void => {}); + _socket = _socket.connect(80, "localhost"); + _socket = _socket.connect(80, "localhost", (): void => {}); + _socket = _socket.connect(80); + _socket = _socket.connect(80, (): void => {}); + + /// addListener + + _socket = _socket.addListener("close", had_error => { + bool = had_error; + }); + _socket = _socket.addListener("connect", () => { }); + _socket = _socket.addListener("data", data => { + buffer = data; + }); + _socket = _socket.addListener("drain", () => { }); + _socket = _socket.addListener("end", () => { }); + _socket = _socket.addListener("error", err => { + error = err; + }); + _socket = _socket.addListener("lookup", (err, address, family, host) => { + error = err; + + if (typeof family === 'string') { + str = family; + } else if (typeof family === 'number') { + num = family; + } + + str = host; + }); + _socket = _socket.addListener("timeout", () => { }); + + /// emit + bool = _socket.emit("close", bool); + bool = _socket.emit("connect"); + bool = _socket.emit("data", buffer); + bool = _socket.emit("drain"); + bool = _socket.emit("end"); + bool = _socket.emit("error", error); + bool = _socket.emit("lookup", error, str, str, str); + bool = _socket.emit("lookup", error, str, num, str); + bool = _socket.emit("timeout"); + + /// on + _socket = _socket.on("close", had_error => { + bool = had_error; + }); + _socket = _socket.on("connect", () => { }); + _socket = _socket.on("data", data => { + buffer = data; + }); + _socket = _socket.on("drain", () => { }); + _socket = _socket.on("end", () => { }); + _socket = _socket.on("error", err => { + error = err; + }); + _socket = _socket.on("lookup", (err, address, family, host) => { + error = err; + + if (typeof family === 'string') { + str = family; + } else if (typeof family === 'number') { + num = family; + } + + str = host; + }); + _socket = _socket.on("timeout", () => { }); + + /// once + _socket = _socket.once("close", had_error => { + bool = had_error; + }); + _socket = _socket.once("connect", () => { }); + _socket = _socket.once("data", data => { + buffer = data; + }); + _socket = _socket.once("drain", () => { }); + _socket = _socket.once("end", () => { }); + _socket = _socket.once("error", err => { + error = err; + }); + _socket = _socket.once("lookup", (err, address, family, host) => { + error = err; + + if (typeof family === 'string') { + str = family; + } else if (typeof family === 'number') { + num = family; + } + + str = host; + }); + _socket = _socket.once("timeout", () => { }); + + /// prependListener + _socket = _socket.prependListener("close", had_error => { + bool = had_error; + }); + _socket = _socket.prependListener("connect", () => { }); + _socket = _socket.prependListener("data", data => { + buffer = data; + }); + _socket = _socket.prependListener("drain", () => { }); + _socket = _socket.prependListener("end", () => { }); + _socket = _socket.prependListener("error", err => { + error = err; + }); + _socket = _socket.prependListener("lookup", (err, address, family, host) => { + error = err; + + if (typeof family === 'string') { + str = family; + } else if (typeof family === 'number') { + num = family; + } + + str = host; + }); + _socket = _socket.prependListener("timeout", () => { }); + + /// prependOnceListener + _socket = _socket.prependOnceListener("close", had_error => { + bool = had_error; + }); + _socket = _socket.prependOnceListener("connect", () => { }); + _socket = _socket.prependOnceListener("data", data => { + buffer = data; + }); + _socket = _socket.prependOnceListener("drain", () => { }); + _socket = _socket.prependOnceListener("end", () => { }); + _socket = _socket.prependOnceListener("error", err => { + error = err; + }); + _socket = _socket.prependOnceListener("lookup", (err, address, family, host) => { + error = err; + + if (typeof family === 'string') { + str = family; + } else if (typeof family === 'number') { + num = family; + } + + str = host; + }); + _socket = _socket.prependOnceListener("timeout", () => { }); + + bool = _socket.connecting; + bool = _socket.destroyed; + _socket.destroy(); + } + + { + /** + * net.Server - events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + let _server: net.Server; + + let _socket: net.Socket; + let bool: boolean; + let error: Error; + + /// addListener + _server = _server.addListener("close", () => { }); + _server = _server.addListener("connection", socket => { + _socket = socket; + }); + _server = _server.addListener("error", err => { + error = err; + }); + _server = _server.addListener("listening", () => { }); + + /// emit + bool = _server.emit("close"); + bool = _server.emit("connection", _socket); + bool = _server.emit("error", error); + bool = _server.emit("listening"); + + /// once + _server = _server.once("close", () => { }); + _server = _server.once("connection", socket => { + _socket = socket; + }); + _server = _server.once("error", err => { + error = err; + }); + _server = _server.once("listening", () => { }); + + /// prependListener + _server = _server.prependListener("close", () => { }); + _server = _server.prependListener("connection", socket => { + _socket = socket; + }); + _server = _server.prependListener("error", err => { + error = err; + }); + _server = _server.prependListener("listening", () => { }); + + /// prependOnceListener + _server = _server.prependOnceListener("close", () => { }); + _server = _server.prependOnceListener("connection", socket => { + _socket = socket; + }); + _server = _server.prependOnceListener("error", err => { + error = err; + }); + _server = _server.prependOnceListener("listening", () => { }); + } +} + +///////////////////////////////////////////////////// +/// repl Tests : https://nodejs.org/api/repl.html /// +///////////////////////////////////////////////////// + +{ + { + let _server: repl.REPLServer; + let _boolean: boolean; + const _ctx: vm.Context = {}; + + _server = _server.addListener("exit", () => { }); + _server = _server.addListener("reset", () => { }); + + _boolean = _server.emit("exit", () => { }); + _boolean = _server.emit("reset", _ctx); + + _server = _server.on("exit", () => { }); + _server = _server.on("reset", () => { }); + + _server = _server.once("exit", () => { }); + _server = _server.once("reset", () => { }); + + _server = _server.prependListener("exit", () => { }); + _server = _server.prependListener("reset", () => { }); + + _server = _server.prependOnceListener("exit", () => { }); + _server = _server.prependOnceListener("reset", () => { }); + + _server.outputStream.write("test"); + const line = _server.inputStream.read(); + + _server.clearBufferedCommand(); + _server.displayPrompt(); + _server.displayPrompt(true); + _server.defineCommand("cmd", function(text) { + // $ExpectType string + text; + // $ExpectType REPLServer + this; + }); + _server.defineCommand("cmd", { + help: "", + action(text) { + // $ExpectType string + text; + // $ExpectType REPLServer + this; + } + }); + + repl.start({ + eval() { + // $ExpectType REPLServer + this; + }, + writer() { + // $ExpectType REPLServer + this; + return ""; + } + }); + + function test() { + throw new repl.Recoverable(new Error("test")); + } + + _server.context['key0'] = 1; + _server.context['key1'] = ""; + _server.context['key2'] = true; + _server.context['key3'] = []; + _server.context['key4'] = {}; + } +} + +/////////////////////////////////////////////////// +/// DNS Tests : https://nodejs.org/api/dns.html /// +/////////////////////////////////////////////////// + +{ + dns.lookup("nodejs.org", (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 4, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 6, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", {}, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup( + "nodejs.org", + { + family: 4, + hints: dns.ADDRCONFIG | dns.V4MAPPED, + all: false + }, + (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + } + ); + dns.lookup("nodejs.org", { all: true }, (err, addresses) => { + const _err: NodeJS.ErrnoException = err; + const _address: dns.LookupAddress[] = addresses; + }); + dns.lookup("nodejs.org", { all: true, verbatim: true }, (err, addresses) => { + const _err: NodeJS.ErrnoException = err; + const _address: dns.LookupAddress[] = addresses; + }); + + function trueOrFalse(): boolean { + return Math.random() > 0.5 ? true : false; + } + dns.lookup("nodejs.org", { all: trueOrFalse() }, (err, addresses, family) => { + const _err: NodeJS.ErrnoException = err; + const _addresses: string | dns.LookupAddress[] = addresses; + const _family: number | undefined = family; + }); + + dns.lookupService("127.0.0.1", 0, (err, hostname, service) => { + const _err: NodeJS.ErrnoException = err; + const _hostname: string = hostname; + const _service: string = service; + }); + + dns.resolve("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "A", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "AAAA", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve("nodejs.org", "ANY", (err, addresses) => { + const _addresses: dns.AnyRecord[] = addresses; + }); + dns.resolve("nodejs.org", "MX", (err, addresses) => { + const _addresses: dns.MxRecord[] = addresses; + }); + + dns.resolve4("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve4("nodejs.org", { ttl: true }, (err, addresses) => { + const _addresses: dns.RecordWithTtl[] = addresses; + }); + { + const ttl = false; + dns.resolve4("nodejs.org", { ttl }, (err, addresses) => { + const _addresses: string[] | dns.RecordWithTtl[] = addresses; + }); + } + + dns.resolve6("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + dns.resolve6("nodejs.org", { ttl: true }, (err, addresses) => { + const _addresses: dns.RecordWithTtl[] = addresses; + }); + { + const ttl = false; + dns.resolve6("nodejs.org", { ttl }, (err, addresses) => { + const _addresses: string[] | dns.RecordWithTtl[] = addresses; + }); + } + { + const resolver = new dns.Resolver(); + resolver.setServers(["4.4.4.4"]); + resolver.resolve("nodejs.org", (err, addresses) => { + const _addresses: string[] = addresses; + }); + resolver.cancel(); + } +} + +/***************************************************************************** + * * + * The following tests are the modules not mentioned in document but existed * + * * + *****************************************************************************/ + +/////////////////////////////////////////////////////////// +/// Constants Tests /// +/////////////////////////////////////////////////////////// + +import * as constants from 'constants'; +{ + let str: string; + let num: number; + num = constants.SIGHUP; + num = constants.SIGINT; + num = constants.SIGQUIT; + num = constants.SIGILL; + num = constants.SIGTRAP; + num = constants.SIGABRT; + num = constants.SIGIOT; + num = constants.SIGBUS; + num = constants.SIGFPE; + num = constants.SIGKILL; + num = constants.SIGUSR1; + num = constants.SIGSEGV; + num = constants.SIGUSR2; + num = constants.SIGPIPE; + num = constants.SIGALRM; + num = constants.SIGTERM; + num = constants.SIGCHLD; + num = constants.SIGSTKFLT; + num = constants.SIGCONT; + num = constants.SIGSTOP; + num = constants.SIGTSTP; + num = constants.SIGTTIN; + num = constants.SIGTTOU; + num = constants.SIGURG; + num = constants.SIGXCPU; + num = constants.SIGXFSZ; + num = constants.SIGVTALRM; + num = constants.SIGPROF; + num = constants.SIGWINCH; + num = constants.SIGIO; + num = constants.SIGPOLL; + num = constants.SIGPWR; + num = constants.SIGSYS; + num = constants.SIGUNUSED; + num = constants.O_RDONLY; + num = constants.O_WRONLY; + num = constants.O_RDWR; + num = constants.S_IFMT; + num = constants.S_IFREG; + num = constants.S_IFDIR; + num = constants.S_IFCHR; + num = constants.S_IFBLK; + num = constants.S_IFIFO; + num = constants.S_IFLNK; + num = constants.S_IFSOCK; + num = constants.O_CREAT; + num = constants.O_EXCL; + num = constants.O_NOCTTY; + num = constants.O_TRUNC; + num = constants.O_APPEND; + num = constants.O_DIRECTORY; + num = constants.O_NOATIME; + num = constants.O_NOFOLLOW; + num = constants.O_SYNC; + num = constants.O_DSYNC; + num = constants.O_DIRECT; + num = constants.O_NONBLOCK; + num = constants.S_IRWXU; + num = constants.S_IRUSR; + num = constants.S_IWUSR; + num = constants.S_IXUSR; + num = constants.S_IRWXG; + num = constants.S_IRGRP; + num = constants.S_IWGRP; + num = constants.S_IXGRP; + num = constants.S_IRWXO; + num = constants.S_IROTH; + num = constants.S_IWOTH; + num = constants.S_IXOTH; + num = constants.F_OK; + num = constants.R_OK; + num = constants.W_OK; + num = constants.X_OK; + num = constants.SSL_OP_ALL; + num = constants.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION; + num = constants.SSL_OP_CIPHER_SERVER_PREFERENCE; + num = constants.SSL_OP_CISCO_ANYCONNECT; + num = constants.SSL_OP_COOKIE_EXCHANGE; + num = constants.SSL_OP_CRYPTOPRO_TLSEXT_BUG; + num = constants.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; + num = constants.SSL_OP_EPHEMERAL_RSA; + num = constants.SSL_OP_LEGACY_SERVER_CONNECT; + num = constants.SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER; + num = constants.SSL_OP_MICROSOFT_SESS_ID_BUG; + num = constants.SSL_OP_MSIE_SSLV2_RSA_PADDING; + num = constants.SSL_OP_NETSCAPE_CA_DN_BUG; + num = constants.SSL_OP_NETSCAPE_CHALLENGE_BUG; + num = constants.SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG; + num = constants.SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG; + num = constants.SSL_OP_NO_COMPRESSION; + num = constants.SSL_OP_NO_QUERY_MTU; + num = constants.SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION; + num = constants.SSL_OP_NO_SSLv2; + num = constants.SSL_OP_NO_SSLv3; + num = constants.SSL_OP_NO_TICKET; + num = constants.SSL_OP_NO_TLSv1; + num = constants.SSL_OP_NO_TLSv1_1; + num = constants.SSL_OP_NO_TLSv1_2; + num = constants.SSL_OP_PKCS1_CHECK_1; + num = constants.SSL_OP_PKCS1_CHECK_2; + num = constants.SSL_OP_SINGLE_DH_USE; + num = constants.SSL_OP_SINGLE_ECDH_USE; + num = constants.SSL_OP_SSLEAY_080_CLIENT_DH_BUG; + num = constants.SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG; + num = constants.SSL_OP_TLS_BLOCK_PADDING_BUG; + num = constants.SSL_OP_TLS_D5_BUG; + num = constants.SSL_OP_TLS_ROLLBACK_BUG; + num = constants.ENGINE_METHOD_RSA; + num = constants.ENGINE_METHOD_DSA; + num = constants.ENGINE_METHOD_DH; + num = constants.ENGINE_METHOD_RAND; + num = constants.ENGINE_METHOD_ECDH; + num = constants.ENGINE_METHOD_ECDSA; + num = constants.ENGINE_METHOD_CIPHERS; + num = constants.ENGINE_METHOD_DIGESTS; + num = constants.ENGINE_METHOD_STORE; + num = constants.ENGINE_METHOD_PKEY_METHS; + num = constants.ENGINE_METHOD_PKEY_ASN1_METHS; + num = constants.ENGINE_METHOD_ALL; + num = constants.ENGINE_METHOD_NONE; + num = constants.DH_CHECK_P_NOT_SAFE_PRIME; + num = constants.DH_CHECK_P_NOT_PRIME; + num = constants.DH_UNABLE_TO_CHECK_GENERATOR; + num = constants.DH_NOT_SUITABLE_GENERATOR; + num = constants.NPN_ENABLED; + num = constants.ALPN_ENABLED; + num = constants.RSA_PKCS1_PADDING; + num = constants.RSA_SSLV23_PADDING; + num = constants.RSA_NO_PADDING; + num = constants.RSA_PKCS1_OAEP_PADDING; + num = constants.RSA_X931_PADDING; + num = constants.RSA_PKCS1_PSS_PADDING; + num = constants.POINT_CONVERSION_COMPRESSED; + num = constants.POINT_CONVERSION_UNCOMPRESSED; + num = constants.POINT_CONVERSION_HYBRID; + str = constants.defaultCoreCipherList; + str = constants.defaultCipherList; +} + +//////////////////////////////////////////////////// +/// v8 tests : https://nodejs.org/api/v8.html +//////////////////////////////////////////////////// + +{ + const heapStats = v8.getHeapStatistics(); + const heapSpaceStats = v8.getHeapSpaceStatistics(); + + const zapsGarbage: number = heapStats.does_zap_garbage; + + v8.setFlagsFromString('--collect_maps'); +} + +//////////////////////////////////////////////////// +/// PerfHooks tests : https://nodejs.org/api/perf_hooks.html +//////////////////////////////////////////////////// +{ + perf_hooks.performance.mark('start'); + ( + () => {} + )(); + perf_hooks.performance.mark('end'); + + const { duration } = perf_hooks.performance.getEntriesByName('discover')[0]; + const timeOrigin = perf_hooks.performance.timeOrigin; + + const performanceObserverCallback: perf_hooks.PerformanceObserverCallback = (list, obs) => { + const { + duration, + entryType, + name, + startTime, + } = list.getEntries()[0]; + obs.disconnect(); + perf_hooks.performance.clearFunctions(); + }; + const obs = new perf_hooks.PerformanceObserver(performanceObserverCallback); + obs.observe({ + entryTypes: ['function'], + buffered: true, + }); +} + +//////////////////////////////////////////////////// +/// AsyncHooks tests : https://nodejs.org/api/async_hooks.html +//////////////////////////////////////////////////// +{ + const hooks: async_hooks.HookCallbacks = { + init() {}, + before() {}, + after() {}, + destroy() {}, + promiseResolve() {}, + }; + + const asyncHook = async_hooks.createHook(hooks); + + asyncHook.enable().disable().enable(); + + const tId: number = async_hooks.triggerAsyncId(); + const eId: number = async_hooks.executionAsyncId(); + + class TestResource extends async_hooks.AsyncResource { + constructor() { + super('TEST_RESOURCE'); + } + } + + class AnotherTestResource extends async_hooks.AsyncResource { + constructor() { + super('TEST_RESOURCE', 42); + const aId: number = this.asyncId(); + const tId: number = this.triggerAsyncId(); + } + run() { + this.runInAsyncScope(() => {}); + this.runInAsyncScope(Array.prototype.find, [], () => true); + } + destroy() { + this.emitDestroy(); + } + } + + // check AsyncResource constructor options. + new async_hooks.AsyncResource(''); + new async_hooks.AsyncResource('', 0); + new async_hooks.AsyncResource('', {}); + new async_hooks.AsyncResource('', { triggerAsyncId: 0 }); + new async_hooks.AsyncResource('', { + triggerAsyncId: 0, + requireManualDestroy: true + }); +} + +//////////////////////////////////////////////////// +/// zlib tests : http://nodejs.org/api/zlib.html /// +//////////////////////////////////////////////////// + +{ + { + const gzipped = zlib.gzipSync('test'); + const unzipped = zlib.gunzipSync(gzipped.toString()); + } + + { + const deflate = zlib.deflateSync('test'); + const inflate = zlib.inflateSync(deflate.toString()); + } + + { + const gzip = zlib.createGzip(); + const written: number = gzip.bytesWritten; + } +} + +/////////////////////////////////////////////////////////// +/// HTTP/2 Tests /// +/////////////////////////////////////////////////////////// + +{ + // Headers & Settings + { + const headers: http2.OutgoingHttpHeaders = { + ':status': 200, + 'content-type': 'text-plain', + ABC: ['has', 'more', 'than', 'one', 'value'], + undef: undefined + }; + + const settings: http2.Settings = { + headerTableSize: 0, + enablePush: true, + initialWindowSize: 0, + maxFrameSize: 0, + maxConcurrentStreams: 0, + maxHeaderListSize: 0 + }; + } + + // Http2Session + { + const http2Session: http2.Http2Session = {} as any; + const ee: events.EventEmitter = http2Session; + + http2Session.on('close', () => {}); + http2Session.on('connect', (session: http2.Http2Session, socket: net.Socket) => {}); + http2Session.on('error', (err: Error) => {}); + http2Session.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); + http2Session.on('goaway', (errorCode: number, lastStreamID: number, opaqueData: Buffer) => {}); + http2Session.on('localSettings', (settings: http2.Settings) => {}); + http2Session.on('remoteSettings', (settings: http2.Settings) => {}); + http2Session.on('stream', (stream: http2.Http2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); + http2Session.on('timeout', () => {}); + http2Session.on('ping', () => {}); + + http2Session.destroy(); + + const alpnProtocol: string = http2Session.alpnProtocol; + const destroyed: boolean = http2Session.destroyed; + const encrypted: boolean = http2Session.encrypted; + const originSet: string[] = http2Session.originSet; + const pendingSettingsAck: boolean = http2Session.pendingSettingsAck; + let settings: http2.Settings = http2Session.localSettings; + const closed: boolean = http2Session.closed; + const connecting: boolean = http2Session.connecting; + settings = http2Session.remoteSettings; + + http2Session.ref(); + http2Session.unref(); + + const headers: http2.OutgoingHttpHeaders = {}; + const options: http2.ClientSessionRequestOptions = { + endStream: true, + exclusive: true, + parent: 0, + weight: 0, + getTrailers: (trailers: http2.OutgoingHttpHeaders) => {} + }; + (http2Session as http2.ClientHttp2Session).request(); + (http2Session as http2.ClientHttp2Session).request(headers); + (http2Session as http2.ClientHttp2Session).request(headers, options); + + const stream: http2.Http2Stream = {} as any; + http2Session.rstStream(stream); + http2Session.rstStream(stream, 0); + + http2Session.setTimeout(100, () => {}); + http2Session.close(() => {}); + + const socket: net.Socket | tls.TLSSocket = http2Session.socket; + let state: http2.SessionState = http2Session.state; + state = { + effectiveLocalWindowSize: 0, + effectiveRecvDataLength: 0, + nextStreamID: 0, + localWindowSize: 0, + lastProcStreamID: 0, + remoteWindowSize: 0, + outboundQueueSize: 0, + deflateDynamicTableSize: 0, + inflateDynamicTableSize: 0 + }; + + http2Session.priority(stream, { + exclusive: true, + parent: 0, + weight: 0, + silent: true + }); + + http2Session.settings(settings); + + http2Session.ping((err: Error | null, duration: number, payload: Buffer) => {}); + http2Session.ping(Buffer.from(''), (err: Error | null, duration: number, payload: Buffer) => {}); + http2Session.ping(new DataView(new Int8Array(1).buffer), (err: Error | null, duration: number, payload: Buffer) => {}); + } + + // Http2Stream + { + const http2Stream: http2.Http2Stream = {} as any; + const duplex: stream.Duplex = http2Stream; + + http2Stream.on('aborted', () => {}); + http2Stream.on('error', (err: Error) => {}); + http2Stream.on('frameError', (frameType: number, errorCode: number, streamID: number) => {}); + http2Stream.on('streamClosed', (code: number) => {}); + http2Stream.on('timeout', () => {}); + http2Stream.on('trailers', (trailers: http2.IncomingHttpHeaders, flags: number) => {}); + http2Stream.on('wantTrailers', () => {}); + + const aborted: boolean = http2Stream.aborted; + const closed: boolean = http2Stream.closed; + const destroyed: boolean = http2Stream.destroyed; + const pending: boolean = http2Stream.pending; + + http2Stream.priority({ + exclusive: true, + parent: 0, + weight: 0, + silent: true + }); + + const sesh: http2.Http2Session = http2Stream.session; + + http2Stream.setTimeout(100, () => {}); + + let state: http2.StreamState = http2Stream.state; + state = { + localWindowSize: 0, + state: 0, + streamLocalClose: 0, + streamRemoteClose: 0, + sumDependencyWeight: 0, + weight: 0 + }; + + http2Stream.close(); + http2Stream.close(0); + http2Stream.close(0, () => {}); + http2Stream.close(undefined, () => {}); + + // ClientHttp2Stream + const clientHttp2Stream: http2.ClientHttp2Stream = {} as any; + clientHttp2Stream.on('headers', (headers: http2.IncomingHttpHeaders, flags: number) => {}); + clientHttp2Stream.on('push', (headers: http2.IncomingHttpHeaders, flags: number) => {}); + clientHttp2Stream.on('response', (headers: http2.IncomingHttpHeaders & http2.IncomingHttpStatusHeader, flags: number) => { + const s: number = headers[':status']; + }); + + // ServerHttp2Stream + const serverHttp2Stream: http2.ServerHttp2Stream = {} as any; + const headers: http2.OutgoingHttpHeaders = {}; + + serverHttp2Stream.additionalHeaders(headers); + const headerSent: boolean = serverHttp2Stream.headersSent; + const pushAllowed: boolean = serverHttp2Stream.pushAllowed; + serverHttp2Stream.pushStream(headers, (err: Error | null, pushStream: http2.ServerHttp2Stream, headers: http2.OutgoingHttpHeaders) => {}); + + const options: http2.ServerStreamResponseOptions = { + endStream: true, + waitForTrailers: true, + }; + serverHttp2Stream.respond(); + serverHttp2Stream.respond(headers); + serverHttp2Stream.respond(headers, options); + + const options2: http2.ServerStreamFileResponseOptions = { + statCheck: (stats: fs.Stats, headers: http2.OutgoingHttpHeaders, statOptions: http2.StatOptions) => {}, + getTrailers: (trailers: http2.OutgoingHttpHeaders) => {}, + offset: 0, + length: 0 + }; + serverHttp2Stream.respondWithFD(0); + serverHttp2Stream.respondWithFD(0, headers); + serverHttp2Stream.respondWithFD(0, headers, options2); + serverHttp2Stream.respondWithFD(0, headers, {statCheck: () => false}); + const options3: http2.ServerStreamFileResponseOptionsWithError = { + onError: (err: NodeJS.ErrnoException) => {}, + statCheck: (stats: fs.Stats, headers: http2.OutgoingHttpHeaders, statOptions: http2.StatOptions) => {}, + getTrailers: (trailers: http2.OutgoingHttpHeaders) => {}, + offset: 0, + length: 0 + }; + serverHttp2Stream.respondWithFile(''); + serverHttp2Stream.respondWithFile('', headers); + serverHttp2Stream.respondWithFile('', headers, options3); + serverHttp2Stream.respondWithFile('', headers, {statCheck: () => false}); + } + + // Http2Server / Http2SecureServer + { + const http2Server: http2.Http2Server = http2.createServer(); + const http2SecureServer: http2.Http2SecureServer = http2.createSecureServer(); + const s1: net.Server = http2Server; + const s2: tls.Server = http2SecureServer; + [http2Server, http2SecureServer].forEach((server) => { + server.on('sessionError', (err: Error) => {}); + server.on('checkContinue', (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); + server.on('stream', (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); + server.on('request', (request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => {}); + server.on('timeout', () => {}); + }); + + http2SecureServer.on('unknownProtocol', (socket: tls.TLSSocket) => {}); + } + + // Public API (except constants) + { + let settings: http2.Settings; + const serverOptions: http2.ServerOptions = { + maxDeflateDynamicTableSize: 0, + maxReservedRemoteStreams: 0, + maxSendHeaderBlockLength: 0, + paddingStrategy: 0, + peerMaxConcurrentStreams: 0, + selectPadding: (frameLen: number, maxFrameLen: number) => 0, + settings, + allowHTTP1: true + }; + // tslint:disable-next-line prefer-object-spread (ts2.1 feature) + const secureServerOptions: http2.SecureServerOptions = Object.assign({}, serverOptions); + secureServerOptions.ca = ''; + const onRequestHandler = (request: http2.Http2ServerRequest, response: http2.Http2ServerResponse) => { + // Http2ServerRequest + + const readable: stream.Readable = request; + let incomingHeaders: http2.IncomingHttpHeaders = request.headers; + incomingHeaders = request.trailers; + const httpVersion: string = request.httpVersion; + let method: string = request.method; + let rawHeaders: string[] = request.rawHeaders; + rawHeaders = request.rawTrailers; + let socket: net.Socket | tls.TLSSocket = request.socket; + let stream: http2.ServerHttp2Stream = request.stream; + const url: string = request.url; + + request.setTimeout(0, () => {}); + request.on('aborted', (hadError: boolean, code: number) => {}); + + // Http2ServerResponse + + let outgoingHeaders: http2.OutgoingHttpHeaders; + response.addTrailers(outgoingHeaders); + socket = response.connection; + const finished: boolean = response.finished; + response.sendDate = true; + response.statusCode = 200; + response.statusMessage = ''; + socket = response.socket; + stream = response.stream; + + method = response.getHeader(':method'); + const headers: string[] = response.getHeaderNames(); + outgoingHeaders = response.getHeaders(); + const hasMethod = response.hasHeader(':method'); + response.removeHeader(':method'); + response.setHeader(':method', 'GET'); + response.setHeader(':status', 200); + response.setHeader('some-list', ['', '']); + const headersSent: boolean = response.headersSent; + + response.setTimeout(0, () => {}); + response.createPushResponse(outgoingHeaders, (err: Error | null, res: http2.Http2ServerResponse) => {}); + + response.writeContinue(); + response.writeHead(200); + response.writeHead(200, outgoingHeaders); + response.writeHead(200, 'OK', outgoingHeaders); + response.writeHead(200, 'OK'); + response.write(''); + response.write('', (err: Error) => {}); + response.write('', 'utf8'); + response.write('', 'utf8', (err: Error) => {}); + response.write(Buffer.from([])); + response.write(Buffer.from([]), (err: Error) => {}); + response.write(Buffer.from([]), 'utf8'); + response.write(Buffer.from([]), 'utf8', (err: Error) => {}); + response.end(); + response.end(() => {}); + response.end(''); + response.end('', () => {}); + response.end('', 'utf8'); + response.end('', 'utf8', () => {}); + response.end(Buffer.from([])); + response.end(Buffer.from([]), () => {}); + response.end(Buffer.from([]), 'utf8'); + response.end(Buffer.from([]), 'utf8', () => {}); + + request.on('aborted', (hadError: boolean, code: number) => {}); + request.on('close', () => {}); + request.on('drain', () => {}); + request.on('error', (error: Error) => {}); + request.on('finish', () => {}); + }; + + let http2Server: http2.Http2Server; + let http2SecureServer: http2.Http2SecureServer; + + http2Server = http2.createServer(); + http2Server = http2.createServer(serverOptions); + http2Server = http2.createServer(onRequestHandler); + http2Server = http2.createServer(serverOptions, onRequestHandler); + + http2SecureServer = http2.createSecureServer(); + http2SecureServer = http2.createSecureServer(secureServerOptions); + http2SecureServer = http2.createSecureServer(onRequestHandler); + http2SecureServer = http2.createSecureServer(secureServerOptions, onRequestHandler); + + const clientSessionOptions: http2.ClientSessionOptions = { + maxDeflateDynamicTableSize: 0, + maxReservedRemoteStreams: 0, + maxSendHeaderBlockLength: 0, + paddingStrategy: 0, + peerMaxConcurrentStreams: 0, + selectPadding: (frameLen: number, maxFrameLen: number) => 0, + settings + }; + // tslint:disable-next-line prefer-object-spread (ts2.1 feature) + const secureClientSessionOptions: http2.SecureClientSessionOptions = Object.assign({}, clientSessionOptions); + secureClientSessionOptions.ca = ''; + const onConnectHandler = (session: http2.Http2Session, socket: net.Socket) => {}; + + const serverHttp2Session: http2.ServerHttp2Session = {} as any; + + serverHttp2Session.altsvc('', ''); + serverHttp2Session.altsvc('', 0); + serverHttp2Session.altsvc('', new url.URL('')); + serverHttp2Session.altsvc('', { origin: '' }); + serverHttp2Session.altsvc('', { origin: 0 }); + serverHttp2Session.altsvc('', { origin: new url.URL('') }); + + let clientHttp2Session: http2.ClientHttp2Session; + + clientHttp2Session = http2.connect(''); + clientHttp2Session = http2.connect('', onConnectHandler); + clientHttp2Session = http2.connect('', clientSessionOptions); + clientHttp2Session = http2.connect('', clientSessionOptions, onConnectHandler); + clientHttp2Session = http2.connect('', secureClientSessionOptions); + clientHttp2Session = http2.connect('', secureClientSessionOptions, onConnectHandler); + clientHttp2Session.on('altsvc', (alt: string, origin: string, number: number) => {}); + + settings = http2.getDefaultSettings(); + settings = http2.getPackedSettings(settings); + settings = http2.getUnpackedSettings(Buffer.from([])); + settings = http2.getUnpackedSettings(Uint8Array.from([])); + } + + // constants + { + const constants = http2.constants; + let num: number; + let str: string; + num = constants.NGHTTP2_SESSION_SERVER; + num = constants.NGHTTP2_SESSION_CLIENT; + num = constants.NGHTTP2_STREAM_STATE_IDLE; + num = constants.NGHTTP2_STREAM_STATE_OPEN; + num = constants.NGHTTP2_STREAM_STATE_RESERVED_LOCAL; + num = constants.NGHTTP2_STREAM_STATE_RESERVED_REMOTE; + num = constants.NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL; + num = constants.NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE; + num = constants.NGHTTP2_STREAM_STATE_CLOSED; + num = constants.NGHTTP2_NO_ERROR; + num = constants.NGHTTP2_PROTOCOL_ERROR; + num = constants.NGHTTP2_INTERNAL_ERROR; + num = constants.NGHTTP2_FLOW_CONTROL_ERROR; + num = constants.NGHTTP2_SETTINGS_TIMEOUT; + num = constants.NGHTTP2_STREAM_CLOSED; + num = constants.NGHTTP2_FRAME_SIZE_ERROR; + num = constants.NGHTTP2_REFUSED_STREAM; + num = constants.NGHTTP2_CANCEL; + num = constants.NGHTTP2_COMPRESSION_ERROR; + num = constants.NGHTTP2_CONNECT_ERROR; + num = constants.NGHTTP2_ENHANCE_YOUR_CALM; + num = constants.NGHTTP2_INADEQUATE_SECURITY; + num = constants.NGHTTP2_HTTP_1_1_REQUIRED; + num = constants.NGHTTP2_ERR_FRAME_SIZE_ERROR; + num = constants.NGHTTP2_FLAG_NONE; + num = constants.NGHTTP2_FLAG_END_STREAM; + num = constants.NGHTTP2_FLAG_END_HEADERS; + num = constants.NGHTTP2_FLAG_ACK; + num = constants.NGHTTP2_FLAG_PADDED; + num = constants.NGHTTP2_FLAG_PRIORITY; + num = constants.DEFAULT_SETTINGS_HEADER_TABLE_SIZE; + num = constants.DEFAULT_SETTINGS_ENABLE_PUSH; + num = constants.DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE; + num = constants.DEFAULT_SETTINGS_MAX_FRAME_SIZE; + num = constants.MAX_MAX_FRAME_SIZE; + num = constants.MIN_MAX_FRAME_SIZE; + num = constants.MAX_INITIAL_WINDOW_SIZE; + num = constants.NGHTTP2_DEFAULT_WEIGHT; + num = constants.NGHTTP2_SETTINGS_HEADER_TABLE_SIZE; + num = constants.NGHTTP2_SETTINGS_ENABLE_PUSH; + num = constants.NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS; + num = constants.NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; + num = constants.NGHTTP2_SETTINGS_MAX_FRAME_SIZE; + num = constants.NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE; + num = constants.PADDING_STRATEGY_NONE; + num = constants.PADDING_STRATEGY_MAX; + num = constants.PADDING_STRATEGY_CALLBACK; + num = constants.HTTP_STATUS_CONTINUE; + num = constants.HTTP_STATUS_SWITCHING_PROTOCOLS; + num = constants.HTTP_STATUS_PROCESSING; + num = constants.HTTP_STATUS_OK; + num = constants.HTTP_STATUS_CREATED; + num = constants.HTTP_STATUS_ACCEPTED; + num = constants.HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION; + num = constants.HTTP_STATUS_NO_CONTENT; + num = constants.HTTP_STATUS_RESET_CONTENT; + num = constants.HTTP_STATUS_PARTIAL_CONTENT; + num = constants.HTTP_STATUS_MULTI_STATUS; + num = constants.HTTP_STATUS_ALREADY_REPORTED; + num = constants.HTTP_STATUS_IM_USED; + num = constants.HTTP_STATUS_MULTIPLE_CHOICES; + num = constants.HTTP_STATUS_MOVED_PERMANENTLY; + num = constants.HTTP_STATUS_FOUND; + num = constants.HTTP_STATUS_SEE_OTHER; + num = constants.HTTP_STATUS_NOT_MODIFIED; + num = constants.HTTP_STATUS_USE_PROXY; + num = constants.HTTP_STATUS_TEMPORARY_REDIRECT; + num = constants.HTTP_STATUS_PERMANENT_REDIRECT; + num = constants.HTTP_STATUS_BAD_REQUEST; + num = constants.HTTP_STATUS_UNAUTHORIZED; + num = constants.HTTP_STATUS_PAYMENT_REQUIRED; + num = constants.HTTP_STATUS_FORBIDDEN; + num = constants.HTTP_STATUS_NOT_FOUND; + num = constants.HTTP_STATUS_METHOD_NOT_ALLOWED; + num = constants.HTTP_STATUS_NOT_ACCEPTABLE; + num = constants.HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED; + num = constants.HTTP_STATUS_REQUEST_TIMEOUT; + num = constants.HTTP_STATUS_CONFLICT; + num = constants.HTTP_STATUS_GONE; + num = constants.HTTP_STATUS_LENGTH_REQUIRED; + num = constants.HTTP_STATUS_PRECONDITION_FAILED; + num = constants.HTTP_STATUS_PAYLOAD_TOO_LARGE; + num = constants.HTTP_STATUS_URI_TOO_LONG; + num = constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE; + num = constants.HTTP_STATUS_RANGE_NOT_SATISFIABLE; + num = constants.HTTP_STATUS_EXPECTATION_FAILED; + num = constants.HTTP_STATUS_TEAPOT; + num = constants.HTTP_STATUS_MISDIRECTED_REQUEST; + num = constants.HTTP_STATUS_UNPROCESSABLE_ENTITY; + num = constants.HTTP_STATUS_LOCKED; + num = constants.HTTP_STATUS_FAILED_DEPENDENCY; + num = constants.HTTP_STATUS_UNORDERED_COLLECTION; + num = constants.HTTP_STATUS_UPGRADE_REQUIRED; + num = constants.HTTP_STATUS_PRECONDITION_REQUIRED; + num = constants.HTTP_STATUS_TOO_MANY_REQUESTS; + num = constants.HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE; + num = constants.HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS; + num = constants.HTTP_STATUS_INTERNAL_SERVER_ERROR; + num = constants.HTTP_STATUS_NOT_IMPLEMENTED; + num = constants.HTTP_STATUS_BAD_GATEWAY; + num = constants.HTTP_STATUS_SERVICE_UNAVAILABLE; + num = constants.HTTP_STATUS_GATEWAY_TIMEOUT; + num = constants.HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED; + num = constants.HTTP_STATUS_VARIANT_ALSO_NEGOTIATES; + num = constants.HTTP_STATUS_INSUFFICIENT_STORAGE; + num = constants.HTTP_STATUS_LOOP_DETECTED; + num = constants.HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED; + num = constants.HTTP_STATUS_NOT_EXTENDED; + num = constants.HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED; + str = constants.HTTP2_HEADER_STATUS; + str = constants.HTTP2_HEADER_METHOD; + str = constants.HTTP2_HEADER_AUTHORITY; + str = constants.HTTP2_HEADER_SCHEME; + str = constants.HTTP2_HEADER_PATH; + str = constants.HTTP2_HEADER_ACCEPT_CHARSET; + str = constants.HTTP2_HEADER_ACCEPT_ENCODING; + str = constants.HTTP2_HEADER_ACCEPT_LANGUAGE; + str = constants.HTTP2_HEADER_ACCEPT_RANGES; + str = constants.HTTP2_HEADER_ACCEPT; + str = constants.HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN; + str = constants.HTTP2_HEADER_AGE; + str = constants.HTTP2_HEADER_ALLOW; + str = constants.HTTP2_HEADER_AUTHORIZATION; + str = constants.HTTP2_HEADER_CACHE_CONTROL; + str = constants.HTTP2_HEADER_CONNECTION; + str = constants.HTTP2_HEADER_CONTENT_DISPOSITION; + str = constants.HTTP2_HEADER_CONTENT_ENCODING; + str = constants.HTTP2_HEADER_CONTENT_LANGUAGE; + str = constants.HTTP2_HEADER_CONTENT_LENGTH; + str = constants.HTTP2_HEADER_CONTENT_LOCATION; + str = constants.HTTP2_HEADER_CONTENT_MD5; + str = constants.HTTP2_HEADER_CONTENT_RANGE; + str = constants.HTTP2_HEADER_CONTENT_TYPE; + str = constants.HTTP2_HEADER_COOKIE; + str = constants.HTTP2_HEADER_DATE; + str = constants.HTTP2_HEADER_ETAG; + str = constants.HTTP2_HEADER_EXPECT; + str = constants.HTTP2_HEADER_EXPIRES; + str = constants.HTTP2_HEADER_FROM; + str = constants.HTTP2_HEADER_HOST; + str = constants.HTTP2_HEADER_IF_MATCH; + str = constants.HTTP2_HEADER_IF_MODIFIED_SINCE; + str = constants.HTTP2_HEADER_IF_NONE_MATCH; + str = constants.HTTP2_HEADER_IF_RANGE; + str = constants.HTTP2_HEADER_IF_UNMODIFIED_SINCE; + str = constants.HTTP2_HEADER_LAST_MODIFIED; + str = constants.HTTP2_HEADER_LINK; + str = constants.HTTP2_HEADER_LOCATION; + str = constants.HTTP2_HEADER_MAX_FORWARDS; + str = constants.HTTP2_HEADER_PREFER; + str = constants.HTTP2_HEADER_PROXY_AUTHENTICATE; + str = constants.HTTP2_HEADER_PROXY_AUTHORIZATION; + str = constants.HTTP2_HEADER_RANGE; + str = constants.HTTP2_HEADER_REFERER; + str = constants.HTTP2_HEADER_REFRESH; + str = constants.HTTP2_HEADER_RETRY_AFTER; + str = constants.HTTP2_HEADER_SERVER; + str = constants.HTTP2_HEADER_SET_COOKIE; + str = constants.HTTP2_HEADER_STRICT_TRANSPORT_SECURITY; + str = constants.HTTP2_HEADER_TRANSFER_ENCODING; + str = constants.HTTP2_HEADER_TE; + str = constants.HTTP2_HEADER_UPGRADE; + str = constants.HTTP2_HEADER_USER_AGENT; + str = constants.HTTP2_HEADER_VARY; + str = constants.HTTP2_HEADER_VIA; + str = constants.HTTP2_HEADER_WWW_AUTHENTICATE; + str = constants.HTTP2_HEADER_HTTP2_SETTINGS; + str = constants.HTTP2_HEADER_KEEP_ALIVE; + str = constants.HTTP2_HEADER_PROXY_CONNECTION; + str = constants.HTTP2_METHOD_ACL; + str = constants.HTTP2_METHOD_BASELINE_CONTROL; + str = constants.HTTP2_METHOD_BIND; + str = constants.HTTP2_METHOD_CHECKIN; + str = constants.HTTP2_METHOD_CHECKOUT; + str = constants.HTTP2_METHOD_CONNECT; + str = constants.HTTP2_METHOD_COPY; + str = constants.HTTP2_METHOD_DELETE; + str = constants.HTTP2_METHOD_GET; + str = constants.HTTP2_METHOD_HEAD; + str = constants.HTTP2_METHOD_LABEL; + str = constants.HTTP2_METHOD_LINK; + str = constants.HTTP2_METHOD_LOCK; + str = constants.HTTP2_METHOD_MERGE; + str = constants.HTTP2_METHOD_MKACTIVITY; + str = constants.HTTP2_METHOD_MKCALENDAR; + str = constants.HTTP2_METHOD_MKCOL; + str = constants.HTTP2_METHOD_MKREDIRECTREF; + str = constants.HTTP2_METHOD_MKWORKSPACE; + str = constants.HTTP2_METHOD_MOVE; + str = constants.HTTP2_METHOD_OPTIONS; + str = constants.HTTP2_METHOD_ORDERPATCH; + str = constants.HTTP2_METHOD_PATCH; + str = constants.HTTP2_METHOD_POST; + str = constants.HTTP2_METHOD_PRI; + str = constants.HTTP2_METHOD_PROPFIND; + str = constants.HTTP2_METHOD_PROPPATCH; + str = constants.HTTP2_METHOD_PUT; + str = constants.HTTP2_METHOD_REBIND; + str = constants.HTTP2_METHOD_REPORT; + str = constants.HTTP2_METHOD_SEARCH; + str = constants.HTTP2_METHOD_TRACE; + str = constants.HTTP2_METHOD_UNBIND; + str = constants.HTTP2_METHOD_UNCHECKOUT; + str = constants.HTTP2_METHOD_UNLINK; + str = constants.HTTP2_METHOD_UNLOCK; + str = constants.HTTP2_METHOD_UPDATE; + str = constants.HTTP2_METHOD_UPDATEREDIRECTREF; + str = constants.HTTP2_METHOD_VERSION_CONTROL; + } +} + +/////////////////////////////////////////////////////////// +/// Inspector Tests /// +/////////////////////////////////////////////////////////// + +{ + { + const b: inspector.Console.ConsoleMessage = {source: 'test', text: 'test', level: 'error' }; + inspector.open(); + inspector.open(0); + inspector.open(0, 'localhost'); + inspector.open(0, 'localhost', true); + inspector.close(); + const inspectorUrl: string = inspector.url(); + + const session = new inspector.Session(); + session.connect(); + session.disconnect(); + + // Unknown post method + session.post('A.b', { key: 'value' }, (err, params) => {}); + // TODO: parameters are implicitly 'any' and need type annotation + session.post('A.b', (err: Error | null, params?: {}) => {}); + session.post('A.b'); + // Known post method + const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' }; + session.post('Runtime.evaluate', parameter, + (err: Error, params: inspector.Runtime.EvaluateReturnType) => {}); + session.post('Runtime.evaluate', (err: Error, params: inspector.Runtime.EvaluateReturnType) => { + const exceptionDetails: inspector.Runtime.ExceptionDetails = params.exceptionDetails; + const resultClassName: string = params.result.className; + }); + session.post('Runtime.evaluate'); + + // General event + session.on('inspectorNotification', message => { + message; // $ExpectType InspectorNotification<{}> + }); + // Known events + session.on('Debugger.paused', (message: inspector.InspectorNotification<inspector.Debugger.PausedEventDataType>) => { + const method: string = message.method; + const pauseReason: string = message.params.reason; + }); + session.on('Debugger.resumed', () => {}); + // Node Inspector events + session.on('NodeTracing.dataCollected', (message: inspector.InspectorNotification<inspector.NodeTracing.DataCollectedEventDataType>) => { + const value: Array<{}> = message.params.value; + }); + } +} + +/////////////////////////////////////////////////////////// +/// Trace Events Tests /// +/////////////////////////////////////////////////////////// + +{ + const enabledCategories: string = trace_events.getEnabledCategories(); + const tracing: trace_events.Tracing = trace_events.createTracing({ categories: ['node', 'v8'] }); + const categories: string = tracing.categories; + const enabled: boolean = tracing.enabled; + tracing.enable(); + tracing.disable(); +} + +//////////////////////////////////////////////////// +/// module tests : http://nodejs.org/api/modules.html +//////////////////////////////////////////////////// +import moduleModule = require('module'); + +{ + require.extensions[".ts"] = () => ""; + + Module.runMain(); + const s: string = Module.wrap("some code"); + + const m1: Module = new Module("moduleId"); + const m2: Module = new Module.Module("moduleId"); + const b: string[] = Module.builtinModules; + let paths: string[] = module.paths; + paths = m1.paths; + + moduleModule.createRequireFromPath('./test')('test'); +} + +//////////////////////////////////////////////////// +/// Node.js ESNEXT Support +//////////////////////////////////////////////////// + +{ + const s = 'foo'; + const s1: string = s.trimLeft(); + const s2: string = s.trimRight(); +} diff --git a/types/node/v10/os.d.ts b/types/node/v10/os.d.ts new file mode 100644 index 0000000000..c85d217f91 --- /dev/null +++ b/types/node/v10/os.d.ts @@ -0,0 +1,192 @@ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + } + + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + + function hostname(): string; + function loadavg(): number[]; + function uptime(): number; + function freemem(): number; + function totalmem(): number; + function cpus(): CpuInfo[]; + function type(): string; + function release(): string; + function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; + function homedir(): string; + function userInfo(options?: { encoding: string }): { username: string, uid: number, gid: number, shell: any, homedir: string }; + const constants: { + UV_UDP_REUSEADDR: number; + signals: { + SIGHUP: number; + SIGINT: number; + SIGQUIT: number; + SIGILL: number; + SIGTRAP: number; + SIGABRT: number; + SIGIOT: number; + SIGBUS: number; + SIGFPE: number; + SIGKILL: number; + SIGUSR1: number; + SIGSEGV: number; + SIGUSR2: number; + SIGPIPE: number; + SIGALRM: number; + SIGTERM: number; + SIGCHLD: number; + SIGSTKFLT: number; + SIGCONT: number; + SIGSTOP: number; + SIGTSTP: number; + SIGTTIN: number; + SIGTTOU: number; + SIGURG: number; + SIGXCPU: number; + SIGXFSZ: number; + SIGVTALRM: number; + SIGPROF: number; + SIGWINCH: number; + SIGIO: number; + SIGPOLL: number; + SIGPWR: number; + SIGSYS: number; + SIGUNUSED: number; + }; + errno: { + E2BIG: number; + EACCES: number; + EADDRINUSE: number; + EADDRNOTAVAIL: number; + EAFNOSUPPORT: number; + EAGAIN: number; + EALREADY: number; + EBADF: number; + EBADMSG: number; + EBUSY: number; + ECANCELED: number; + ECHILD: number; + ECONNABORTED: number; + ECONNREFUSED: number; + ECONNRESET: number; + EDEADLK: number; + EDESTADDRREQ: number; + EDOM: number; + EDQUOT: number; + EEXIST: number; + EFAULT: number; + EFBIG: number; + EHOSTUNREACH: number; + EIDRM: number; + EILSEQ: number; + EINPROGRESS: number; + EINTR: number; + EINVAL: number; + EIO: number; + EISCONN: number; + EISDIR: number; + ELOOP: number; + EMFILE: number; + EMLINK: number; + EMSGSIZE: number; + EMULTIHOP: number; + ENAMETOOLONG: number; + ENETDOWN: number; + ENETRESET: number; + ENETUNREACH: number; + ENFILE: number; + ENOBUFS: number; + ENODATA: number; + ENODEV: number; + ENOENT: number; + ENOEXEC: number; + ENOLCK: number; + ENOLINK: number; + ENOMEM: number; + ENOMSG: number; + ENOPROTOOPT: number; + ENOSPC: number; + ENOSR: number; + ENOSTR: number; + ENOSYS: number; + ENOTCONN: number; + ENOTDIR: number; + ENOTEMPTY: number; + ENOTSOCK: number; + ENOTSUP: number; + ENOTTY: number; + ENXIO: number; + EOPNOTSUPP: number; + EOVERFLOW: number; + EPERM: number; + EPIPE: number; + EPROTO: number; + EPROTONOSUPPORT: number; + EPROTOTYPE: number; + ERANGE: number; + EROFS: number; + ESPIPE: number; + ESRCH: number; + ESTALE: number; + ETIME: number; + ETIMEDOUT: number; + ETXTBSY: number; + EWOULDBLOCK: number; + EXDEV: number; + }; + priority: { + PRIORITY_LOW: number; + PRIORITY_BELOW_NORMAL: number; + PRIORITY_NORMAL: number; + PRIORITY_ABOVE_NORMAL: number; + PRIORITY_HIGH: number; + PRIORITY_HIGHEST: number; + } + }; + function arch(): string; + function platform(): NodeJS.Platform; + function tmpdir(): string; + const EOL: string; + function endianness(): "BE" | "LE"; + /** + * Gets the priority of a process. + * Defaults to current process. + */ + function getPriority(pid?: number): number; + /** + * Sets the priority of the current process. + * @param priority Must be in range of -20 to 19 + */ + function setPriority(priority: number): void; + /** + * Sets the priority of the process specified process. + * @param priority Must be in range of -20 to 19 + */ + function setPriority(pid: number, priority: number): void; +} diff --git a/types/node/v10/package.json b/types/node/v10/package.json new file mode 100644 index 0000000000..c1f0c68752 --- /dev/null +++ b/types/node/v10/package.json @@ -0,0 +1,11 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { + "*": [ + "ts3.1/*" + ] + } + } +} \ No newline at end of file diff --git a/types/node/v10/path.d.ts b/types/node/v10/path.d.ts new file mode 100644 index 0000000000..bbc17098f4 --- /dev/null +++ b/types/node/v10/path.d.ts @@ -0,0 +1,159 @@ +declare module "path" { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string; + /** + * The file extension (if any) such as '.html' + */ + ext?: string; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string; + } + + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + function normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths paths to join. + */ + function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + function resolve(...pathSegments: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + */ + function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + function dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + function basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + const sep: '\\' | '/'; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + const delimiter: ';' | ':'; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + function parse(pathString: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + function format(pathObject: FormatInputPathObject): string; + + namespace posix { + function normalize(p: string): string; + function join(...paths: any[]): string; + function resolve(...pathSegments: any[]): string; + function isAbsolute(p: string): boolean; + function relative(from: string, to: string): string; + function dirname(p: string): string; + function basename(p: string, ext?: string): string; + function extname(p: string): string; + const sep: string; + const delimiter: string; + function parse(p: string): ParsedPath; + function format(pP: FormatInputPathObject): string; + } + + namespace win32 { + function normalize(p: string): string; + function join(...paths: any[]): string; + function resolve(...pathSegments: any[]): string; + function isAbsolute(p: string): boolean; + function relative(from: string, to: string): string; + function dirname(p: string): string; + function basename(p: string, ext?: string): string; + function extname(p: string): string; + const sep: string; + const delimiter: string; + function parse(p: string): ParsedPath; + function format(pP: FormatInputPathObject): string; + } +} diff --git a/types/node/v10/perf_hooks.d.ts b/types/node/v10/perf_hooks.d.ts new file mode 100644 index 0000000000..4f68895ce6 --- /dev/null +++ b/types/node/v10/perf_hooks.d.ts @@ -0,0 +1,241 @@ +declare module "perf_hooks" { + import { AsyncResource } from "async_hooks"; + + interface PerformanceEntry { + /** + * The total number of milliseconds elapsed for this entry. + * This value will not be meaningful for all Performance Entry types. + */ + readonly duration: number; + + /** + * The name of the performance entry. + */ + readonly name: string; + + /** + * The high resolution millisecond timestamp marking the starting time of the Performance Entry. + */ + readonly startTime: number; + + /** + * The type of the performance entry. + * Currently it may be one of: 'node', 'mark', 'measure', 'gc', or 'function'. + */ + readonly entryType: string; + + /** + * When performanceEntry.entryType is equal to 'gc', the performance.kind property identifies + * the type of garbage collection operation that occurred. + * The value may be one of perf_hooks.constants. + */ + readonly kind?: number; + } + + interface PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process completed bootstrap. + */ + readonly bootstrapComplete: number; + + /** + * The high resolution millisecond timestamp at which cluster processing ended. + */ + readonly clusterSetupEnd: number; + + /** + * The high resolution millisecond timestamp at which cluster processing started. + */ + readonly clusterSetupStart: number; + + /** + * The high resolution millisecond timestamp at which the Node.js event loop exited. + */ + readonly loopExit: number; + + /** + * The high resolution millisecond timestamp at which the Node.js event loop started. + */ + readonly loopStart: number; + + /** + * The high resolution millisecond timestamp at which main module load ended. + */ + readonly moduleLoadEnd: number; + + /** + * The high resolution millisecond timestamp at which main module load started. + */ + readonly moduleLoadStart: number; + + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + */ + readonly nodeStart: number; + + /** + * The high resolution millisecond timestamp at which preload module load ended. + */ + readonly preloadModuleLoadEnd: number; + + /** + * The high resolution millisecond timestamp at which preload module load started. + */ + readonly preloadModuleLoadStart: number; + + /** + * The high resolution millisecond timestamp at which third_party_main processing ended. + */ + readonly thirdPartyMainEnd: number; + + /** + * The high resolution millisecond timestamp at which third_party_main processing started. + */ + readonly thirdPartyMainStart: number; + + /** + * The high resolution millisecond timestamp at which the V8 platform was initialized. + */ + readonly v8Start: number; + } + + interface Performance { + /** + * If name is not provided, removes all PerformanceFunction objects from the Performance Timeline. + * If name is provided, removes entries with name. + * @param name + */ + clearFunctions(name?: string): void; + + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + + /** + * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. + * If name is provided, removes only objects whose performanceEntry.name matches name. + */ + clearMeasures(name?: string): void; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. + * @return list of all PerformanceEntry objects + */ + getEntries(): PerformanceEntry[]; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. + * @param name + * @param type + * @return list of all PerformanceEntry objects + */ + getEntriesByName(name: string, type?: string): PerformanceEntry[]; + + /** + * Returns a list of all PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.entryType is equal to type. + * @param type + * @return list of all PerformanceEntry objects + */ + getEntriesByType(type: string): PerformanceEntry[]; + + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + */ + mark(name?: string): void; + + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + */ + measure(name: string, startMark: string, endMark: string): void; + + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify<T extends (...optionalParams: any[]) => any>(fn: T): T; + } + + interface PerformanceObserverEntryList { + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. + */ + getEntries(): PerformanceEntry[]; + + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. + */ + getEntriesByName(name: string, type?: string): PerformanceEntry[]; + + /** + * @return Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.entryType is equal to type. + */ + getEntriesByType(type: string): PerformanceEntry[]; + } + + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + + /** + * Disconnects the PerformanceObserver instance from all notifications. + */ + disconnect(): void; + + /** + * Subscribes the PerformanceObserver instance to notifications of new PerformanceEntry instances identified by options.entryTypes. + * When options.buffered is false, the callback will be invoked once for every PerformanceEntry instance. + * Property buffered defaults to false. + * @param options + */ + observe(options: { entryTypes: string[], buffered?: boolean }): void; + } + + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + } + + const performance: Performance; +} diff --git a/types/node/v10/process.d.ts b/types/node/v10/process.d.ts new file mode 100644 index 0000000000..ccd5c9c198 --- /dev/null +++ b/types/node/v10/process.d.ts @@ -0,0 +1,3 @@ +declare module "process" { + export = process; +} diff --git a/types/node/v10/punycode.d.ts b/types/node/v10/punycode.d.ts new file mode 100644 index 0000000000..efc55622f1 --- /dev/null +++ b/types/node/v10/punycode.d.ts @@ -0,0 +1,12 @@ +declare module "punycode" { + function decode(string: string): string; + function encode(string: string): string; + function toUnicode(domain: string): string; + function toASCII(domain: string): string; + const ucs2: ucs2; + interface ucs2 { + decode(string: string): number[]; + encode(codePoints: number[]): string; + } + const version: any; +} diff --git a/types/node/v10/querystring.d.ts b/types/node/v10/querystring.d.ts new file mode 100644 index 0000000000..f54d352c6c --- /dev/null +++ b/types/node/v10/querystring.d.ts @@ -0,0 +1,17 @@ +declare module "querystring" { + interface StringifyOptions { + encodeURIComponent?: Function; + } + + interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: Function; + } + + interface ParsedUrlQuery { [key: string]: string | string[]; } + + function stringify(obj?: {}, sep?: string, eq?: string, options?: StringifyOptions): string; + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + function escape(str: string): string; + function unescape(str: string): string; +} diff --git a/types/node/v10/readline.d.ts b/types/node/v10/readline.d.ts new file mode 100644 index 0000000000..9c25da4982 --- /dev/null +++ b/types/node/v10/readline.d.ts @@ -0,0 +1,135 @@ +declare module "readline" { + import * as events from "events"; + import * as stream from "stream"; + + interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } + + class Interface extends events.EventEmitter { + readonly terminal: boolean; + + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: (answer: string) => void): void; + pause(): this; + resume(): this; + close(): void; + write(data: string | Buffer, key?: Key): void; + + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + } + + type ReadLine = Interface; // type forwarded for backwards compatiblity + + type Completer = (line: string) => CompleterResult; + type AsyncCompleter = (line: string, callback: (err: any, result: CompleterResult) => void) => any; + + type CompleterResult = [string[], string]; + + interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + completer?: Completer | AsyncCompleter; + terminal?: boolean; + historySize?: number; + prompt?: string; + crlfDelay?: number; + removeHistoryDuplicates?: boolean; + } + + function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + function createInterface(options: ReadLineOptions): Interface; + + function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number): void; + function emitKeypressEvents(stream: NodeJS.ReadableStream, interface?: Interface): void; + function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; + function clearLine(stream: NodeJS.WritableStream, dir: number): void; + function clearScreenDown(stream: NodeJS.WritableStream): void; +} diff --git a/types/node/v10/repl.d.ts b/types/node/v10/repl.d.ts new file mode 100644 index 0000000000..cb5a3d037b --- /dev/null +++ b/types/node/v10/repl.d.ts @@ -0,0 +1,372 @@ +declare module "repl" { + import { Interface, Completer, AsyncCompleter } from "readline"; + import { Context } from "vm"; + import { InspectOptions } from "util"; + + interface ReplOptions { + /** + * The input prompt to display. + * Default: `"> "` + */ + prompt?: string; + /** + * The `Readable` stream from which REPL input will be read. + * Default: `process.stdin` + */ + input?: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + * Default: `process.stdout` + */ + output?: NodeJS.WritableStream; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ + useColors?: boolean; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ + useGlobal?: boolean; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ + ignoreUndefined?: boolean; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean; + } + + type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { options: InspectOptions }; + + type REPLCommandAction = (this: REPLServer, text: string) => void; + + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + + /** + * Provides a customizable Read-Eval-Print-Loop (REPL). + * + * Instances of `repl.REPLServer` will accept individual lines of user input, evaluate those + * according to a user-defined evaluation function, then output the result. Input and output + * may be from `stdin` and `stdout`, respectively, or may be connected to any Node.js `stream`. + * + * Instances of `repl.REPLServer` support automatic completion of inputs, simplistic Emacs-style + * line editing, multi-line inputs, ANSI-styled output, saving and restoring current REPL session + * state, error recovery, and customizable evaluation functions. + * + * Instances of `repl.REPLServer` are created using the `repl.start()` method and _should not_ + * be created directly using the JavaScript `new` keyword. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_repl + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: { readonly [name: string]: REPLCommand | undefined }; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + + /** + * Used to add new `.`-prefixed commands to the REPL instance. Such commands are invoked + * by typing a `.` followed by the `keyword`. + * + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_replserver_definecommand_keyword_cmd + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * Readies the REPL instance for input from the user, printing the configured `prompt` to a + * new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the 'prompt'. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @param preserveCursor When `true`, the cursor placement will not be reset to `0`. + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * Clears any command that has been buffered but not yet executed. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @since v9.0.0 + */ + clearBufferedCommand(): void; + + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + export const REPL_MODE_SLOPPY: symbol; // TODO: unique symbol + + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + export const REPL_MODE_STRICT: symbol; // TODO: unique symbol + + /** + * Creates and starts a `repl.REPLServer` instance. + * + * @param options The options for the `REPLServer`. If `options` is a string, then it specifies + * the input prompt. + */ + function start(options?: string | ReplOptions): REPLServer; + + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + + constructor(err: Error); + } +} diff --git a/types/node/v10/stream.d.ts b/types/node/v10/stream.d.ts new file mode 100644 index 0000000000..a4428728db --- /dev/null +++ b/types/node/v10/stream.d.ts @@ -0,0 +1,294 @@ +declare module "stream" { + import * as events from "events"; + + class internal extends events.EventEmitter { + pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T; + } + + namespace internal { + class Stream extends internal { } + + interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?(this: Readable, size: number): void; + destroy?(this: Readable, error: Error | null, callback: (error: Error | null) => void): void; + } + + class Readable extends Stream implements NodeJS.ReadableStream { + readable: boolean; + readonly readableHighWaterMark: number; + readonly readableLength: number; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + unpipe(destination?: NodeJS.WritableStream): this; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: string): boolean; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + destroy(error?: Error): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. readable + * 5. error + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + [Symbol.asyncIterator](): AsyncIterableIterator<any>; + } + + interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + write?(this: Writable, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Writable, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + destroy?(this: Writable, error: Error | null, callback: (error: Error | null) => void): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + + class Writable extends Stream implements NodeJS.WritableStream { + writable: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: string): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: string, cb?: () => void): void; + cork(): void; + uncork(): void; + destroy(error?: Error): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Duplex, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; + } + + // Note: Duplex extends both Readable and Writable. + class Duplex extends Readable implements Writable { + writable: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + constructor(opts?: DuplexOptions); + _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: string): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: string, cb?: () => void): void; + cork(): void; + uncork(): void; + } + + type TransformCallback = (error?: Error, data?: any) => void; + + interface TransformOptions extends DuplexOptions { + read?(this: Transform, size: number): void; + write?(this: Transform, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Transform, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: string, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: string, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + + class PassThrough extends Transform { } + + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException) => void): () => void; + namespace finished { + function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream): Promise<void>; + } + + function pipeline<T extends NodeJS.WritableStream>(stream1: NodeJS.ReadableStream, stream2: T, callback?: (err: NodeJS.ErrnoException) => void): T; + function pipeline<T extends NodeJS.WritableStream>(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: T, callback?: (err: NodeJS.ErrnoException) => void): T; + function pipeline<T extends NodeJS.WritableStream>( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: T, + callback?: (err: NodeJS.ErrnoException) => void, + ): T; + function pipeline<T extends NodeJS.WritableStream>( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: NodeJS.ReadWriteStream, + stream5: T, + callback?: (err: NodeJS.ErrnoException) => void, + ): T; + function pipeline(streams: Array<NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream>, callback?: (err: NodeJS.ErrnoException) => void): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array<NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException) => void)>, + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.WritableStream): Promise<void>; + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.WritableStream): Promise<void>; + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: NodeJS.WritableStream): Promise<void>; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: NodeJS.ReadWriteStream, + stream5: NodeJS.WritableStream, + ): Promise<void>; + function __promisify__(streams: Array<NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream>): Promise<void>; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array<NodeJS.ReadWriteStream | NodeJS.WritableStream>, + ): Promise<void>; + } + } + + export = internal; +} diff --git a/types/node/v10/string_decoder.d.ts b/types/node/v10/string_decoder.d.ts new file mode 100644 index 0000000000..762a4d8d50 --- /dev/null +++ b/types/node/v10/string_decoder.d.ts @@ -0,0 +1,9 @@ +declare module "string_decoder" { + interface NodeStringDecoder { + write(buffer: Buffer): string; + end(buffer?: Buffer): string; + } + const StringDecoder: { + new(encoding?: string): NodeStringDecoder; + }; +} diff --git a/types/node/v10/timers.d.ts b/types/node/v10/timers.d.ts new file mode 100644 index 0000000000..e64a6735c3 --- /dev/null +++ b/types/node/v10/timers.d.ts @@ -0,0 +1,16 @@ +declare module "timers" { + function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; + namespace setTimeout { + function __promisify__(ms: number): Promise<void>; + function __promisify__<T>(ms: number, value: T): Promise<T>; + } + function clearTimeout(timeoutId: NodeJS.Timeout): void; + function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; + function clearInterval(intervalId: NodeJS.Timeout): void; + function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; + namespace setImmediate { + function __promisify__(): Promise<void>; + function __promisify__<T>(value: T): Promise<T>; + } + function clearImmediate(immediateId: NodeJS.Immediate): void; +} diff --git a/types/node/v10/tls.d.ts b/types/node/v10/tls.d.ts new file mode 100644 index 0000000000..f59dcc7629 --- /dev/null +++ b/types/node/v10/tls.d.ts @@ -0,0 +1,371 @@ +declare module "tls" { + import * as crypto from "crypto"; + import * as dns from "dns"; + import * as net from "net"; + import * as stream from "stream"; + + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + + interface PeerCertificate { + subject: Certificate; + issuer: Certificate; + subjectaltname: string; + infoAccess: { [index: string]: string[] | undefined }; + modulus: string; + exponent: string; + valid_from: string; + valid_to: string; + fingerprint: string; + ext_key_usage: string[]; + serialNumber: string; + raw: Buffer; + } + + interface DetailedPeerCertificate extends PeerCertificate { + issuerCertificate: DetailedPeerCertificate; + } + + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + } + + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext, + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean, + /** + * An optional net.Server instance. + */ + server?: net.Server, + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean, + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. Defaults to false. + */ + rejectUnauthorized?: boolean, + /** + * An array of strings or a Buffer naming possible NPN protocols. + * (Protocols should be ordered by their priority.) + */ + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) When the server + * receives both NPN and ALPN extensions from the client, ALPN takes + * precedence over NPN and the server does not send an NPN extension + * to the client. + */ + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, + /** + * SNICallback(servername, cb) <Function> A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void, + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer, + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean + }); + + /** + * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. + */ + authorized: boolean; + /** + * The reason why the peer's certificate has not been verified. + * This property becomes available only when tlsSocket.authorized === false. + */ + authorizationError: Error; + /** + * Static boolean value, always true. + * May be used to distinguish TLS sockets from regular ones. + */ + encrypted: boolean; + + /** + * String containing the selected ALPN protocol. + * When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol?: string; + + /** + * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. + * @returns Returns an object representing the cipher name + * and the SSL/TLS protocol version of the current connection. + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the peer's certificate. + * The returned object has some properties corresponding to the field of the certificate. + * If detailed argument is true the full chain with issuer property will be returned, + * if false only the top certificate without issuer property. + * If the peer does not provide a certificate, it returns null or an empty object. + * @param detailed - If true; the full chain with issuer property will be returned. + * @returns An object representing the peer's certificate. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. + * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. + * The value `null` will be returned for server sockets or disconnected client sockets. + * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. + * @returns negotiated SSL/TLS protocol version of the current connection + */ + getProtocol(): string | null; + /** + * Could be used to speed up handshake establishment when reconnecting to the server. + * @returns ASN.1 encoded TLS session or undefined if none was negotiated. + */ + getSession(): any; + /** + * NOTE: Works only with client TLS sockets. + * Useful only for debugging, for session reuse provide session option to tls.connect(). + * @returns TLS session ticket or undefined if none was negotiated. + */ + getTLSTicket(): any; + /** + * Initiate TLS renegotiation process. + * + * NOTE: Can be used to request peer's certificate after the secure connection has been established. + * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. + * @param options - The options may contain the following fields: rejectUnauthorized, + * requestCert (See tls.createServer() for details). + * @param callback - callback(err) will be executed with null as err, once the renegotiation + * is successfully completed. + */ + renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): any; + /** + * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by + * the TLS layer until the entire fragment is received and its integrity is verified; + * large fragments can span multiple roundtrips, and their processing can be delayed due to packet + * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, + * which may decrease overall server throughput. + * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns Returns true on success, false otherwise. + */ + setMaxSendFragment(size: number): boolean; + + /** + * events.EventEmitter + * 1. OCSPResponse + * 2. secureConnect + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + } + + interface TlsOptions extends SecureContextOptions { + handshakeTimeout?: number; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; + sessionTimeout?: number; + ticketKeys?: Buffer; + } + + interface ConnectionOptions extends SecureContextOptions { + host?: string; + port?: number; + path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket + rejectUnauthorized?: boolean; // Defaults to true + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + checkServerIdentity?: typeof checkServerIdentity; + servername?: string; // SNI TLS Extension + session?: Buffer; + minDHSize?: number; + secureContext?: SecureContext; // If not provided, the entire ConnectionOptions object will be passed to tls.createSecureContext() + lookup?: net.LookupFunction; + } + + class Server extends net.Server { + addContext(hostName: string, credentials: { + key: string; + cert: string; + ca: string; + }): void; + + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; + emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + } + + interface SecurePair { + encrypted: any; + cleartext: any; + } + + interface SecureContextOptions { + pfx?: string | Buffer | Array<string | Buffer | Object>; + key?: string | Buffer | Array<Buffer | Object>; + passphrase?: string; + cert?: string | Buffer | Array<string | Buffer>; + ca?: string | Buffer | Array<string | Buffer>; + ciphers?: string; + honorCipherOrder?: boolean; + ecdhCurve?: string; + clientCertEngine?: string; + crl?: string | Buffer | Array<string | Buffer>; + dhparam?: string | Buffer; + secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options + secureProtocol?: string; // SSL Method, e.g. SSLv23_method + sessionIdContext?: string; + } + + interface SecureContext { + context: any; + } + + /* + * Verifies the certificate `cert` is issued to host `host`. + * @host The hostname to verify the certificate against + * @cert PeerCertificate representing the peer's certificate + * + * Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined. + */ + function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + function createSecureContext(details: SecureContextOptions): SecureContext; + function getCiphers(): string[]; + + const DEFAULT_ECDH_CURVE: string; +} diff --git a/types/node/v10/trace_events.d.ts b/types/node/v10/trace_events.d.ts new file mode 100644 index 0000000000..9d1a59bdd0 --- /dev/null +++ b/types/node/v10/trace_events.d.ts @@ -0,0 +1,61 @@ +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + export interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + + /** + * Creates and returns a Tracing object for the given set of categories. + */ + export function createTracing(options: CreateTracingOptions): Tracing; + + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is + * determined by the union of all currently-enabled `Tracing` objects and + * any categories enabled using the `--trace-event-categories` flag. + */ + export function getEnabledCategories(): string; +} diff --git a/types/node/v10/ts3.1/index.d.ts b/types/node/v10/ts3.1/index.d.ts new file mode 100644 index 0000000000..be36602300 --- /dev/null +++ b/types/node/v10/ts3.1/index.d.ts @@ -0,0 +1,18 @@ +// NOTE: These definitions support NodeJS and TypeScript 3.1. + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 2.1 +// - ~/ts3.1/index.d.ts - Definitions specific to TypeScript 3.1 + +// Reference required types from the default lib: +/// <reference lib="es2018" /> +/// <reference lib="esnext.asyncIterable" /> +/// <reference lib="esnext.intl" /> + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +// tslint:disable-next-line:no-bad-reference +/// <reference path="../base.d.ts" /> + +// TypeScript 3.1-specific augmentations: +/// <reference path="util.d.ts" /> diff --git a/types/node/v10/ts3.1/node-tests.ts b/types/node/v10/ts3.1/node-tests.ts new file mode 100644 index 0000000000..18db498871 --- /dev/null +++ b/types/node/v10/ts3.1/node-tests.ts @@ -0,0 +1,2 @@ +// tslint:disable-next-line:no-bad-reference +import "../node-tests"; diff --git a/types/node/v10/ts3.1/tsconfig.json b/types/node/v10/ts3.1/tsconfig.json new file mode 100644 index 0000000000..de75d02481 --- /dev/null +++ b/types/node/v10/ts3.1/tsconfig.json @@ -0,0 +1,30 @@ +{ + "files": [ + "index.d.ts", + "node-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../../", + "typeRoots": [ + "../../../" + ], + "paths": { + "node": [ + "node/v10" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/node/v10/ts3.1/tslint.json b/types/node/v10/ts3.1/tslint.json new file mode 100644 index 0000000000..1a8ddd9863 --- /dev/null +++ b/types/node/v10/ts3.1/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "unified-signatures": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "strict-export-declare-modifiers": false // http2 needs this + } +} diff --git a/types/node/v10/ts3.1/util.d.ts b/types/node/v10/ts3.1/util.d.ts new file mode 100644 index 0000000000..e35ef8d0f1 --- /dev/null +++ b/types/node/v10/ts3.1/util.d.ts @@ -0,0 +1,10 @@ +// tslint:disable-next-line:no-bad-reference +/// <reference path="../util.d.ts" /> +declare module "util" { + namespace inspect { + const custom: unique symbol; + } + namespace promisify { + const custom: unique symbol; + } +} diff --git a/types/node/v10/tsconfig.json b/types/node/v10/tsconfig.json new file mode 100644 index 0000000000..d6dea0e2b3 --- /dev/null +++ b/types/node/v10/tsconfig.json @@ -0,0 +1,71 @@ +{ + "files": [ + "index.d.ts", + "base.d.ts", + "globals.d.ts", + "assert.d.ts", + "async_hooks.d.ts", + "buffer.d.ts", + "child_process.d.ts", + "cluster.d.ts", + "console.d.ts", + "constants.d.ts", + "crypto.d.ts", + "dgram.d.ts", + "dns.d.ts", + "domain.d.ts", + "events.d.ts", + "fs.d.ts", + "http.d.ts", + "http2.d.ts", + "https.d.ts", + "inspector.d.ts", + "module.d.ts", + "net.d.ts", + "os.d.ts", + "path.d.ts", + "perf_hooks.d.ts", + "process.d.ts", + "punycode.d.ts", + "querystring.d.ts", + "readline.d.ts", + "repl.d.ts", + "stream.d.ts", + "string_decoder.d.ts", + "timers.d.ts", + "tls.d.ts", + "trace_events.d.ts", + "tty.d.ts", + "url.d.ts", + "util.d.ts", + "v8.d.ts", + "vm.d.ts", + "worker_threads.d.ts", + "zlib.d.ts", + "node-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "node": [ + "node/v10" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/types/node/v10/tslint.json b/types/node/v10/tslint.json new file mode 100644 index 0000000000..1a8ddd9863 --- /dev/null +++ b/types/node/v10/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "unified-signatures": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "strict-export-declare-modifiers": false // http2 needs this + } +} diff --git a/types/node/v10/tty.d.ts b/types/node/v10/tty.d.ts new file mode 100644 index 0000000000..7d75c89f58 --- /dev/null +++ b/types/node/v10/tty.d.ts @@ -0,0 +1,15 @@ +declare module "tty" { + import * as net from "net"; + + function isatty(fd: number): boolean; + class ReadStream extends net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + isTTY: boolean; + } + class WriteStream extends net.Socket { + columns: number; + rows: number; + isTTY: boolean; + } +} diff --git a/types/node/v10/url.d.ts b/types/node/v10/url.d.ts new file mode 100644 index 0000000000..1e1d154e8e --- /dev/null +++ b/types/node/v10/url.d.ts @@ -0,0 +1,104 @@ +declare module "url" { + import { ParsedUrlQuery } from 'querystring'; + + interface UrlObjectCommon { + auth?: string; + hash?: string; + host?: string; + hostname?: string; + href?: string; + path?: string; + pathname?: string; + protocol?: string; + search?: string; + slashes?: boolean; + } + + // Input to `url.format` + interface UrlObject extends UrlObjectCommon { + port?: string | number; + query?: string | null | { [key: string]: any }; + } + + // Output of `url.parse` + interface Url extends UrlObjectCommon { + port?: string; + query?: string | null | ParsedUrlQuery; + } + + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + + interface UrlWithStringQuery extends Url { + query: string | null; + } + + function parse(urlStr: string): UrlWithStringQuery; + function parse(urlStr: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; + function parse(urlStr: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlStr: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + + function format(URL: URL, options?: URLFormatOptions): string; + function format(urlObject: UrlObject | string): string; + function resolve(from: string, to: string): string; + + function domainToASCII(domain: string): string; + function domainToUnicode(domain: string): string; + + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * @param url The file URL string or URL object to convert to a path. + */ + function fileURLToPath(url: string | URL): string; + + /** + * This function ensures that path is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * @param url The path to convert to a File URL. + */ + function pathToFileURL(url: string): URL; + + interface URLFormatOptions { + auth?: boolean; + fragment?: boolean; + search?: boolean; + unicode?: boolean; + } + + class URL { + constructor(input: string, base?: string | URL); + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toString(): string; + toJSON(): string; + } + + class URLSearchParams implements Iterable<[string, string]> { + constructor(init?: URLSearchParams | string | { [key: string]: string | string[] | undefined } | Iterable<[string, string]> | Array<[string, string]>); + append(name: string, value: string): void; + delete(name: string): void; + entries(): IterableIterator<[string, string]>; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + keys(): IterableIterator<string>; + set(name: string, value: string): void; + sort(): void; + toString(): string; + values(): IterableIterator<string>; + [Symbol.iterator](): IterableIterator<[string, string]>; + } +} diff --git a/types/node/v10/util.d.ts b/types/node/v10/util.d.ts new file mode 100644 index 0000000000..9da88fe9cb --- /dev/null +++ b/types/node/v10/util.d.ts @@ -0,0 +1,169 @@ +declare module "util" { + interface InspectOptions extends NodeJS.InspectOptions { } + function format(format: any, ...param: any[]): string; + function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + function debug(string: string): void; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + function error(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + function puts(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + function print(...param: any[]): void; + /** @deprecated since v0.11.3 - use a third party module instead. */ + function log(string: string): void; + function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + function inspect(object: any, options: InspectOptions): string; + namespace inspect { + let colors: { + [color: string]: [number, number] | undefined + }; + let styles: { + [style: string]: string | undefined + }; + let defaultOptions: InspectOptions; + } + /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ + function isArray(object: any): object is any[]; + /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ + function isRegExp(object: any): object is RegExp; + /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ + function isDate(object: any): object is Date; + /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ + function isError(object: any): object is Error; + function inherits(constructor: any, superConstructor: any): void; + function debuglog(key: string): (msg: string, ...param: any[]) => void; + /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ + function isBoolean(object: any): object is boolean; + /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ + function isBuffer(object: any): object is Buffer; + /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ + function isFunction(object: any): boolean; + /** @deprecated since v4.0.0 - use `value === null` instead. */ + function isNull(object: any): object is null; + /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ + function isNullOrUndefined(object: any): object is null | undefined; + /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ + function isNumber(object: any): object is number; + /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ + function isObject(object: any): boolean; + /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ + function isPrimitive(object: any): boolean; + /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ + function isString(object: any): object is string; + /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ + function isSymbol(object: any): object is symbol; + /** @deprecated since v4.0.0 - use `value === undefined` instead. */ + function isUndefined(object: any): object is undefined; + function deprecate<T extends Function>(fn: T, message: string): T; + function isDeepStrictEqual(val1: any, val2: any): boolean; + + interface CustomPromisify<TCustom extends Function> extends Function { + __promisify__: TCustom; + } + + function callbackify(fn: () => Promise<void>): (callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify<TResult>(fn: () => Promise<TResult>): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify<T1>(fn: (arg1: T1) => Promise<void>): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify<T1, TResult>(fn: (arg1: T1) => Promise<TResult>): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify<T1, T2>(fn: (arg1: T1, arg2: T2) => Promise<void>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify<T1, T2, TResult>(fn: (arg1: T1, arg2: T2) => Promise<TResult>): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify<T1, T2, T3>(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify<T1, T2, T3, TResult>( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify<T1, T2, T3, T4>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify<T1, T2, T3, T4, TResult>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify<T1, T2, T3, T4, T5>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify<T1, T2, T3, T4, T5, TResult>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify<T1, T2, T3, T4, T5, T6>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<void>, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify<T1, T2, T3, T4, T5, T6, TResult>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise<TResult> + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + + function promisify<TCustom extends Function>(fn: CustomPromisify<TCustom>): TCustom; + function promisify<TResult>(fn: (callback: (err: Error | null, result: TResult) => void) => void): () => Promise<TResult>; + function promisify(fn: (callback: (err?: Error | null) => void) => void): () => Promise<void>; + function promisify<T1, TResult>(fn: (arg1: T1, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1) => Promise<TResult>; + function promisify<T1>(fn: (arg1: T1, callback: (err?: Error | null) => void) => void): (arg1: T1) => Promise<void>; + function promisify<T1, T2, TResult>(fn: (arg1: T1, arg2: T2, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise<TResult>; + function promisify<T1, T2>(fn: (arg1: T1, arg2: T2, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2) => Promise<void>; + function promisify<T1, T2, T3, TResult>(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise<TResult>; + function promisify<T1, T2, T3>(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise<void>; + function promisify<T1, T2, T3, T4, TResult>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: Error | null, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<TResult>; + function promisify<T1, T2, T3, T4>(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise<void>; + function promisify<T1, T2, T3, T4, T5, TResult>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: Error | null, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<TResult>; + function promisify<T1, T2, T3, T4, T5>( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: Error | null) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise<void>; + function promisify(fn: Function): Function; + + namespace types { + function isAnyArrayBuffer(object: any): boolean; + function isArgumentsObject(object: any): object is IArguments; + function isArrayBuffer(object: any): object is ArrayBuffer; + function isAsyncFunction(object: any): boolean; + function isBooleanObject(object: any): object is Boolean; + function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* BigInt */); + function isDataView(object: any): object is DataView; + function isDate(object: any): object is Date; + function isExternal(object: any): boolean; + function isFloat32Array(object: any): object is Float32Array; + function isFloat64Array(object: any): object is Float64Array; + function isGeneratorFunction(object: any): boolean; + function isGeneratorObject(object: any): boolean; + function isInt8Array(object: any): object is Int8Array; + function isInt16Array(object: any): object is Int16Array; + function isInt32Array(object: any): object is Int32Array; + function isMap(object: any): boolean; + function isMapIterator(object: any): boolean; + function isNativeError(object: any): object is Error; + function isNumberObject(object: any): object is Number; + function isPromise(object: any): boolean; + function isProxy(object: any): boolean; + function isRegExp(object: any): object is RegExp; + function isSet(object: any): boolean; + function isSetIterator(object: any): boolean; + function isSharedArrayBuffer(object: any): boolean; + function isStringObject(object: any): boolean; + function isSymbolObject(object: any): boolean; + function isTypedArray(object: any): object is NodeJS.TypedArray; + function isUint8Array(object: any): object is Uint8Array; + function isUint8ClampedArray(object: any): object is Uint8ClampedArray; + function isUint16Array(object: any): object is Uint16Array; + function isUint32Array(object: any): object is Uint32Array; + function isWeakMap(object: any): boolean; + function isWeakSet(object: any): boolean; + function isWebAssemblyCompiledModule(object: any): boolean; + } + + class TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { fatal?: boolean; ignoreBOM?: boolean } + ); + decode( + input?: NodeJS.TypedArray | DataView | ArrayBuffer | null, + options?: { stream?: boolean } + ): string; + } + + class TextEncoder { + readonly encoding: string; + constructor(); + encode(input?: string): Uint8Array; + } +} diff --git a/types/node/v10/v8.d.ts b/types/node/v10/v8.d.ts new file mode 100644 index 0000000000..ee5f707234 --- /dev/null +++ b/types/node/v10/v8.d.ts @@ -0,0 +1,28 @@ +declare module "v8" { + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + } + + function getHeapStatistics(): HeapInfo; + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + function setFlagsFromString(flags: string): void; +} diff --git a/types/node/v10/vm.d.ts b/types/node/v10/vm.d.ts new file mode 100644 index 0000000000..404fa9c820 --- /dev/null +++ b/types/node/v10/vm.d.ts @@ -0,0 +1,64 @@ +declare module "vm" { + interface Context { + [key: string]: any; + } + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * Default: `''`. + */ + filename?: string; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * Default: `0`. + */ + lineOffset?: number; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * Default: `0` + */ + columnOffset?: number; + } + interface ScriptOptions extends BaseOptions { + displayErrors?: boolean; + timeout?: number; + cachedData?: Buffer; + produceCachedData?: boolean; + } + interface RunningScriptOptions extends BaseOptions { + displayErrors?: boolean; + timeout?: number; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context; + + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[]; + } + class Script { + constructor(code: string, options?: ScriptOptions); + runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; + runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; + runInThisContext(options?: RunningScriptOptions): any; + } + function createContext(sandbox?: Context): Context; + function isContext(sandbox: Context): boolean; + function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions | string): any; + function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions | string): any; + function runInThisContext(code: string, options?: RunningScriptOptions | string): any; + function compileFunction(code: string, params: string[], options: CompileFunctionOptions): Function; +} diff --git a/types/node/v10/worker_threads.d.ts b/types/node/v10/worker_threads.d.ts new file mode 100644 index 0000000000..b20748a34f --- /dev/null +++ b/types/node/v10/worker_threads.d.ts @@ -0,0 +1,124 @@ +declare module "worker_threads" { + import { EventEmitter } from "events"; + import { Readable, Writable } from "stream"; + + const isMainThread: boolean; + const parentPort: null | MessagePort; + const threadId: number; + const workerData: any; + + class MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; + } + + class MessagePort extends EventEmitter { + close(): void; + postMessage(value: any, transferList?: Array<ArrayBuffer | MessagePort>): void; + ref(): void; + unref(): void; + start(): void; + + addListener(event: "close", listener: () => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "message", value: any): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "close", listener: () => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface WorkerOptions { + eval?: boolean; + workerData?: any; + stdin?: boolean; + stdout?: boolean; + stderr?: boolean; + } + + class Worker extends EventEmitter { + readonly stdin: Writable | null; + readonly stdout: Readable; + readonly stderr: Readable; + readonly threadId: number; + + constructor(filename: string, options?: WorkerOptions); + + postMessage(value: any, transferList?: Array<ArrayBuffer | MessagePort>): void; + ref(): void; + unref(): void; + terminate(callback?: (err: any, exitCode: number) => void): void; + + addListener(event: "error", listener: (err: any) => void): this; + addListener(event: "exit", listener: (exitCode: number) => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: "online", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "error", err: any): boolean; + emit(event: "exit", exitCode: number): boolean; + emit(event: "message", value: any): boolean; + emit(event: "online"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "error", listener: (err: any) => void): this; + on(event: "exit", listener: (exitCode: number) => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: "online", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "error", listener: (err: any) => void): this; + once(event: "exit", listener: (exitCode: number) => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: "online", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "error", listener: (err: any) => void): this; + prependListener(event: "exit", listener: (exitCode: number) => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: "online", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "error", listener: (err: any) => void): this; + prependOnceListener(event: "exit", listener: (exitCode: number) => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: "online", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "error", listener: (err: any) => void): this; + removeListener(event: "exit", listener: (exitCode: number) => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: "online", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "error", listener: (err: any) => void): this; + off(event: "exit", listener: (exitCode: number) => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: "online", listener: () => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } +} diff --git a/types/node/v10/zlib.d.ts b/types/node/v10/zlib.d.ts new file mode 100644 index 0000000000..dff374b8f5 --- /dev/null +++ b/types/node/v10/zlib.d.ts @@ -0,0 +1,141 @@ +declare module "zlib" { + import * as stream from "stream"; + + interface ZlibOptions { + flush?: number; // default: zlib.constants.Z_NO_FLUSH + finishFlush?: number; // default: zlib.constants.Z_FINISH + chunkSize?: number; // default: 16*1024 + windowBits?: number; + level?: number; // compression only + memLevel?: number; // compression only + strategy?: number; // compression only + dictionary?: Buffer | NodeJS.TypedArray | DataView | ArrayBuffer; // deflate/inflate only, empty dictionary by default + } + + interface Zlib { + /** @deprecated Use bytesWritten instead. */ + readonly bytesRead: number; + readonly bytesWritten: number; + shell?: boolean | string; + close(callback?: () => void): void; + flush(kind?: number | (() => void), callback?: () => void): void; + } + + interface ZlibParams { + params(level: number, strategy: number, callback: () => void): void; + } + + interface ZlibReset { + reset(): void; + } + + interface Gzip extends stream.Transform, Zlib { } + interface Gunzip extends stream.Transform, Zlib { } + interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + interface Inflate extends stream.Transform, Zlib, ZlibReset { } + interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + interface InflateRaw extends stream.Transform, Zlib, ZlibReset { } + interface Unzip extends stream.Transform, Zlib { } + + function createGzip(options?: ZlibOptions): Gzip; + function createGunzip(options?: ZlibOptions): Gunzip; + function createDeflate(options?: ZlibOptions): Deflate; + function createInflate(options?: ZlibOptions): Inflate; + function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + function createInflateRaw(options?: ZlibOptions): InflateRaw; + function createUnzip(options?: ZlibOptions): Unzip; + + type InputType = string | Buffer | DataView | ArrayBuffer | NodeJS.TypedArray; + function deflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function deflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; + function deflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function deflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + function gzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function gzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; + function gunzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function gunzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; + function inflate(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function inflate(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; + function inflateRaw(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function inflateRaw(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + function unzip(buf: InputType, callback: (error: Error | null, result: Buffer) => void): void; + function unzip(buf: InputType, options: ZlibOptions, callback: (error: Error | null, result: Buffer) => void): void; + function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; + + namespace constants { + // Allowed flush values. + + const Z_NO_FLUSH: number; + const Z_PARTIAL_FLUSH: number; + const Z_SYNC_FLUSH: number; + const Z_FULL_FLUSH: number; + const Z_FINISH: number; + const Z_BLOCK: number; + const Z_TREES: number; + + // Return codes for the compression/decompression functions. Negative values are errors, positive values are used for special but normal events. + + const Z_OK: number; + const Z_STREAM_END: number; + const Z_NEED_DICT: number; + const Z_ERRNO: number; + const Z_STREAM_ERROR: number; + const Z_DATA_ERROR: number; + const Z_MEM_ERROR: number; + const Z_BUF_ERROR: number; + const Z_VERSION_ERROR: number; + + // Compression levels. + + const Z_NO_COMPRESSION: number; + const Z_BEST_SPEED: number; + const Z_BEST_COMPRESSION: number; + const Z_DEFAULT_COMPRESSION: number; + + // Compression strategy. + + const Z_FILTERED: number; + const Z_HUFFMAN_ONLY: number; + const Z_RLE: number; + const Z_FIXED: number; + const Z_DEFAULT_STRATEGY: number; + } + + // Constants + const Z_NO_FLUSH: number; + const Z_PARTIAL_FLUSH: number; + const Z_SYNC_FLUSH: number; + const Z_FULL_FLUSH: number; + const Z_FINISH: number; + const Z_BLOCK: number; + const Z_TREES: number; + const Z_OK: number; + const Z_STREAM_END: number; + const Z_NEED_DICT: number; + const Z_ERRNO: number; + const Z_STREAM_ERROR: number; + const Z_DATA_ERROR: number; + const Z_MEM_ERROR: number; + const Z_BUF_ERROR: number; + const Z_VERSION_ERROR: number; + const Z_NO_COMPRESSION: number; + const Z_BEST_SPEED: number; + const Z_BEST_COMPRESSION: number; + const Z_DEFAULT_COMPRESSION: number; + const Z_FILTERED: number; + const Z_HUFFMAN_ONLY: number; + const Z_RLE: number; + const Z_FIXED: number; + const Z_DEFAULT_STRATEGY: number; + const Z_BINARY: number; + const Z_TEXT: number; + const Z_ASCII: number; + const Z_UNKNOWN: number; + const Z_DEFLATED: number; +} diff --git a/types/node/worker_threads.d.ts b/types/node/worker_threads.d.ts index b20748a34f..b011b8ff32 100644 --- a/types/node/worker_threads.d.ts +++ b/types/node/worker_threads.d.ts @@ -58,6 +58,7 @@ declare module "worker_threads" { stdin?: boolean; stdout?: boolean; stderr?: boolean; + execArgv?: string[]; } class Worker extends EventEmitter { diff --git a/types/ssh2/ssh2-tests.ts b/types/ssh2/ssh2-tests.ts index 432fad281d..b3364cd489 100644 --- a/types/ssh2/ssh2-tests.ts +++ b/types/ssh2/ssh2-tests.ts @@ -402,11 +402,11 @@ new ssh2.Server({ // the file on the disk var handle = new Buffer(4); openFiles.add(handleCount); - handle.writeUInt32BE(handleCount++, 0, true); + handle.writeUInt32BE(handleCount++, 0); sftpStream.handle(reqid, handle); console.log('Opening file for write') }).on('WRITE', (reqid: any, handle: any, offset: any, data: any) => { - if (handle.length !== 4 || !openFiles.has(handle.readUInt32BE(0, true))) + if (handle.length !== 4 || !openFiles.has(handle.readUInt32BE(0))) return sftpStream.status(reqid, STATUS_CODE.FAILURE); // fake the write sftpStream.status(reqid, STATUS_CODE.OK); @@ -414,7 +414,7 @@ new ssh2.Server({ console.log('Write to file at offset %d: %s', offset, inspected); }).on('CLOSE', (reqid: any, handle: any) => { var fnum: any; - if (handle.length !== 4 || !openFiles.has((fnum = handle.readUInt32BE(0, true)))) + if (handle.length !== 4 || !openFiles.has((fnum = handle.readUInt32BE(0)))) return sftpStream.status(reqid, STATUS_CODE.FAILURE); openFiles.delete(fnum); sftpStream.status(reqid, STATUS_CODE.OK); From 721a40407c920b55a3a9981262423dd383b13dbd Mon Sep 17 00:00:00 2001 From: Guketlev Dmitry <yavanosta@yandex.ru> Date: Sat, 9 Feb 2019 01:35:05 +0300 Subject: [PATCH 169/197] Review fixes --- types/color-support/color-support-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/color-support/color-support-tests.ts b/types/color-support/color-support-tests.ts index 5c61067dcf..45bb6317cf 100644 --- a/types/color-support/color-support-tests.ts +++ b/types/color-support/color-support-tests.ts @@ -1,4 +1,4 @@ -import * as colorSupport from 'color-support'; +import colorSupport = require('color-support'); (() => { const result = colorSupport(); From 30b1546c31f938b90aebbbec86a6aedd5b69b256 Mon Sep 17 00:00:00 2001 From: Janne Ramstedt <janne.ramstedt@aniway.fi> Date: Sat, 9 Feb 2019 03:45:21 +0200 Subject: [PATCH 170/197] Switch to latest version from Clark Stevenson --- types/p2/index.d.ts | 889 +++++++++++++++++++++++++++++--------------- 1 file changed, 581 insertions(+), 308 deletions(-) diff --git a/types/p2/index.d.ts b/types/p2/index.d.ts index 88dde55025..95082f836d 100644 --- a/types/p2/index.d.ts +++ b/types/p2/index.d.ts @@ -7,18 +7,26 @@ export = p2; export as namespace p2; declare namespace p2 { + export interface AABBOptions { + + upperBound?: [number, number]; + lowerBound?: [number, number]; + + } export class AABB { - constructor(options?: { - upperBound?: number[]; - lowerBound?: number[]; - }); + constructor(options?: AABBOptions); - setFromPoints(points: number[][], position: number[], angle: number, skinSize: number): void; + lowerBound: [number, number]; + upperBound: [number, number]; + + setFromPoints(points: [number, number][], position: [number, number], angle?: number, skinSize?: number): void; copy(aabb: AABB): void; extend(aabb: AABB): void; overlaps(aabb: AABB): boolean; + containsPoint(point: [number, number]): boolean; + overlapsRay(ray: Ray): number; } @@ -43,34 +51,15 @@ declare namespace p2 { setWorld(world: World): void; getCollisionPairs(world: World): Body[]; + boundingRadiusCheck(bodyA: Body, bodyB: Body): boolean; boundingVolumeCheck(bodyA: Body, bodyB: Body): boolean; + aabbCheck(bodyA: Body, bodyB: Body): boolean; + canCollide(bodyA: Body, bodyB: Body): boolean; + aabbQuery(world?: World, aabb?: AABB, result?: Body[]): Body[]; } - export class GridBroadphase extends Broadphase { - - constructor(options?: { - xmin?: number; - xmax?: number; - ymin?: number; - ymax?: number; - nx?: number; - ny?: number; - }); - - xmin: number; - xmax: number; - ymin: number; - ymax: number; - nx: number; - ny: number; - binsizeX: number; - binsizeY: number; - - } - - export class NativeBroadphase extends Broadphase { - + export class NaiveBroadphase extends Broadphase { } export class Narrowphase { @@ -78,70 +67,104 @@ declare namespace p2 { contactEquations: ContactEquation[]; frictionEquations: FrictionEquation[]; enableFriction: boolean; - enableEquations: boolean; + enabledEquations: boolean; slipForce: number; - frictionCoefficient: number; - surfaceVelocity: number; - reuseObjects: boolean; - resuableContactEquations: any[]; - reusableFrictionEquations: any[]; - restitution: number; - stiffness: number; - relaxation: number; - frictionStiffness: number; - frictionRelaxation: number; + contactEquationPool: ContactEquationPool; + frictionEquationPool: FrictionEquationPool; enableFrictionReduction: boolean; - contactSkinSize: number; + collidingBodiesLastStep: TupleDictionary; + currentContactMaterial: ContactMaterial; + bodiesOverlap(bodyA: Body, bodyB: Body, checkCollisionMasks?: boolean): boolean; collidedLastStep(bodyA: Body, bodyB: Body): boolean; reset(): void; createContactEquation(bodyA: Body, bodyB: Body, shapeA: Shape, shapeB: Shape): ContactEquation; + createFrictionEquation(bodyA: Body, bodyB: Body, shapeA: Shape, shapeB: Shape): FrictionEquation; createFrictionFromContact(c: ContactEquation): FrictionEquation; } + export interface RayOptions { + + from: [number, number], + to: [number, number], + checkCollisionResponse?: boolean; + skipBackfaces?: boolean; + collisionMask?: number; + collisionGroup?: number; + mode?: number; + callback?: (result: RaycastResult) => void; + + } + + export class Ray { + + static CLOSEST: number; + static ANY: number; + static ALL: number; + + constructor(options?: RayOptions); + + from: [number, number]; + to: [number, number]; + checkCollisionResponse: boolean; + skipBackfaces: boolean; + collisionMask: number; + collisionGroup: number; + mode: number; + callback: (result: RaycastResult) => void; + direction: [number, number]; + length: number; + + update(): void; + intersectBodies(result: RaycastResult, bodies: Body[]): void; + getAABB(): AABB; + + } + + export class RaycastResult { + + normal: [number, number]; + shape: Shape; + body: Body; + faceIndex: number; + fraction: number; + isStopped: boolean; + + reset(): void; + getHitDistance(ray: Ray): number; + hasHit(): boolean; + getHitPoint(out: [number, number], ray: Ray): void; + stop(): void; + shouldStop(ray: Ray): boolean; + set(normal: [number, number], shape: Shape, body: Body, friction: number, faceIndex: number): void; + + } + export class SAPBroadphase extends Broadphase { axisList: Body[]; axisIndex: number; + setWorld(world: World): void; + } - export class Constraint { + export interface DistanceConstraintOptions extends ConstraintOptions { - static DISTANCE: number; - static GEAR: number; - static LOCK: number; - static PRISMATIC: number; - static REVOLUTE: number; - - constructor(bodyA: Body, bodyB: Body, type: number, options?: { - collideConnected?: boolean; - }); - - type: number; - equeations: Equation[]; - bodyA: Body; - bodyB: Body; - collideConnected: boolean; - - update(): void; - setStiffness(stiffness: number): void; - setRelaxation(relaxation: number): void; + distance?: number; + localAnchorA?: [number, number]; + localAnchorB?: [number, number]; + maxForce?: number; } export class DistanceConstraint extends Constraint { - constructor(bodyA: Body, bodyB: Body, options?: { - distance?: number; - localAnchorA?: number[]; - localAnchorB?: number[]; - maxForce?: number; - }); + constructor(bodyA: Body, bodyB: Body, type: number, options?: DistanceConstraintOptions); - localAnchorA: number[]; - localAnchorB: number[]; + localAnchorA: [number, number]; + localAnchorB: [number, number]; distance: number; maxForce: number; upperLimitEnabled: boolean; @@ -150,55 +173,70 @@ declare namespace p2 { lowerLimit: number; position: number; - setMaxForce(f: number): void; + setMaxForce(maxForce: number): void; getMaxForce(): number; + update(): void; + + } + + export interface GearConstraintOptions extends ConstraintOptions { + + angle?: number; + ratio?: number; + maxTorque?: number; } export class GearConstraint extends Constraint { - constructor(bodyA: Body, bodyB: Body, options?: { - angle?: number; - ratio?: number; - maxTorque?: number; - }); + constructor(bodyA: Body, bodyB: Body, options?: GearConstraintOptions); ratio: number; angle: number; setMaxTorque(torque: number): void; getMaxTorque(): number; + update(): void; + + } + + export interface LockConstraintOptions extends ConstraintOptions { + + localOffsetB?: [number, number]; + localAngleB?: number; + maxForce?: number; } export class LockConstraint extends Constraint { - constructor(bodyA: Body, bodyB: Body, options?: { - localOffsetB?: number[]; - localAngleB?: number; - maxForce?: number; - }); + constructor(bodyA: Body, bodyB: Body, type: number, options?: LockConstraintOptions); setMaxForce(force: number): void; getMaxForce(): number; + update(): void; + + } + + export interface PrismaticConstraintOptions extends ConstraintOptions { + + maxForce?: number; + localAnchorA?: [number, number]; + localAnchorB?: [number, number]; + localAxisA?: [number, number]; + disableRotationalLock?: boolean; + upperLimit?: number; + lowerLimit?: number; } export class PrismaticConstraint extends Constraint { - constructor(bodyA: Body, bodyB: Body, options?: { - maxForce?: number; - localAnchorA?: number[]; - localAnchorB?: number[]; - localAxisA?: number[]; - disableRotationalLock?: boolean; - upperLimit?: number; - lowerLimit?: number; - }); + constructor(bodyA: Body, bodyB: Body, options?: PrismaticConstraintOptions); - localAnchorA: number[]; - localAnchorB: number[]; - localAxisA: number[]; + localAnchorA: [number, number]; + localAnchorB: [number, number]; + localAxisA: [number, number]; position: number; velocity: number; lowerLimitEnabled: boolean; @@ -214,49 +252,89 @@ declare namespace p2 { enableMotor(): void; disableMotor(): void; setLimits(lower: number, upper: number): void; + update(): void; + + } + + export interface RevoluteConstraintOptions extends ConstraintOptions { + + worldPivot?: [number, number]; + localPivotA?: [number, number]; + localPivotB?: [number, number]; + maxForce?: number; } export class RevoluteConstraint extends Constraint { - constructor(bodyA: Body, bodyB: Body, options?: { - worldPivot?: number[]; - localPivotA?: number[]; - localPivotB?: number[]; - maxForce?: number; - }); + constructor(bodyA: Body, bodyB: Body, type: number, options?: RevoluteConstraintOptions); - pivotA: number[]; - pivotB: number[]; - motorEquation: RotationalVelocityEquation; - motorEnabled: boolean; angle: number; lowerLimitEnabled: boolean; upperLimitEnabled: boolean; lowerLimit: number; upperLimit: number; - upperLimitEquation: ContactEquation; - lowerLimitEquation: ContactEquation; + + setLimits(lower: number, upper: number): void; + update(): void; + + motorEnabled: boolean; + motorSpeed: number; + motorMaxForce: number; enableMotor(): void; disableMotor(): void; motorIsEnabled(): boolean; - setLimits(lower: number, upper: number): void; setMotorSpeed(speed: number): void; getMotorSpeed(): number; } + export interface ConstraintOptions { + + collideConnected?: boolean; + wakeUpBodies?: boolean; + + } + + export class Constraint { + + static DISTANCE: number; + static GEAR: number; + static LOCK: number; + static PRISMATIC: number; + static REVOLUTE: number; + + constructor(bodyA: Body, bodyB: Body, type: number, options?: ConstraintOptions); + + type: number; + equeations: Equation[]; + bodyA: Body; + bodyB: Body; + collideConnected: boolean; + + update(): void; + setStiffness(stiffness: number): void; + setRelaxation(relaxation: number): void; + + } + + export interface AngleLockEquationOptions { + + angle?: number; + ratio?: number; + + } + export class AngleLockEquation extends Equation { - constructor(bodyA: Body, bodyB: Body, options?: { - angle?: number; - ratio?: number; - }); + constructor(bodyA: Body, bodyB: Body, options?: AngleLockEquationOptions); + + angle: number; + ratio: number; - computeGq(): number; setRatio(ratio: number): number; - setMaxTorque(torque: number): number; + setMaxTorque(torque: number): void; } @@ -264,16 +342,17 @@ declare namespace p2 { constructor(bodyA: Body, bodyB: Body); - contactPointA: number[]; - penetrationVec: number[]; - contactPointB: number[]; - normalA: number[]; + contactPointA: [number, number]; + penetrationVec: [number, number]; + contactPointB: [number, number]; + normalA: [number, number]; restitution: number; firstImpact: boolean; shapeA: Shape; shapeB: Shape; computeB(a: number, b: number, h: number): number; + getVelocityAlongNormal(): number; } @@ -290,10 +369,7 @@ declare namespace p2 { bodyB: Body; stiffness: number; relaxation: number; - G: number[]; - offset: number; - a: number; - b: number; + G: [number, number]; epsilon: number; timeStep: number; needsUpdate: boolean; @@ -301,7 +377,7 @@ declare namespace p2 { relativeVelocity: number; enabled: boolean; - gmult(G: number[], vi: number[], wi: number[], vj: number[], wj: number[]): number; + gmult(G: [number, number], vi: [number, number], wi: [number, number], vj: [number, number], wj: [number, number]): number; computeB(a: number, b: number, h: number): number; computeGq(): number; computeGW(): number; @@ -310,6 +386,7 @@ declare namespace p2 { computeGiMGt(): number; addToWlambda(deltalambda: number): number; computeInvC(eps: number): number; + update(): void; } @@ -317,29 +394,31 @@ declare namespace p2 { constructor(bodyA: Body, bodyB: Body, slipForce: number); - contactPointA: number[]; - contactPointB: number[]; - t: number[]; + contactPointA: [number, number]; + contactPointB: [number, number]; + t: [number, number]; + contactEquations: ContactEquation[]; shapeA: Shape; shapeB: Shape; frictionCoefficient: number; - setSlipForce(slipForce: number): number; + setSlipForce(slipForce: number): void; getSlipForce(): number; - computeB(a: number, b: number, h: number): number; + + } + + export interface RotationalLockEquationOptions { + + angle?: number; } export class RotationalLockEquation extends Equation { - constructor(bodyA: Body, bodyB: Body, options?: { - angle?: number; - }); + constructor(bodyA: Body, bodyB: Body, options?: RotationalLockEquationOptions); angle: number; - computeGq(): number; - } export class RotationalVelocityEquation extends Equation { @@ -359,7 +438,7 @@ declare namespace p2 { } - export class ContactMaterialOptions { + export interface ContactMaterialOptions { friction?: number; restitution?: number; @@ -384,7 +463,7 @@ declare namespace p2 { restitution: number; stiffness: number; relaxation: number; - frictionStiffness: number; + frictionStuffness: number; frictionRelaxation: number; surfaceVelocity: number; contactSkinSize: number; @@ -395,7 +474,7 @@ declare namespace p2 { static idCounter: number; - constructor(id: number); + constructor(id?: number); id: number; @@ -403,52 +482,67 @@ declare namespace p2 { export class vec2 { - static crossLength(a: number[], b: number[]): number; - static crossVZ(out: number[], vec: number[], zcomp: number): number; - static crossZV(out: number[], zcomp: number, vec: number[]): number; - static rotate(out: number[], a: number[], angle: number): void; - static rotate90cw(out: number[], a: number[]): number; - static centroid(out: number[], a: number[], b: number[], c: number[]): number[]; - static create(): number[]; - static clone(a: number[]): number[]; - static fromValues(x: number, y: number): number[]; - static copy(out: number[], a: number[]): number[]; - static set(out: number[], x: number, y: number): number[]; - static toLocalFrame(out: number[], worldPoint: number[], framePosition: number[], frameAngle: number): void; - static toGlobalFrame(out: number[], localPoint: number[], framePosition: number[], frameAngle: number): void; - static add(out: number[], a: number[], b: number[]): number[]; - static subtract(out: number[], a: number[], b: number[]): number[]; - static sub(out: number[], a: number[], b: number[]): number[]; - static multiply(out: number[], a: number[], b: number[]): number[]; - static mul(out: number[], a: number[], b: number[]): number[]; - static divide(out: number[], a: number[], b: number[]): number[]; - static div(out: number[], a: number[], b: number[]): number[]; - static scale(out: number[], a: number[], b: number): number[]; - static distance(a: number[], b: number[]): number; - static dist(a: number[], b: number[]): number; - static squaredDistance(a: number[], b: number[]): number; - static sqrDist(a: number[], b: number[]): number; - static length(a: number[]): number; - static len(a: number[]): number; - static squaredLength(a: number[]): number; - static sqrLen(a: number[]): number; - static negate(out: number[], a: number[]): number[]; - static normalize(out: number[], a: number[]): number[]; - static dot(a: number[], b: number[]): number; - static str(a: number[]): string; + static crossLength(a: [number, number], b: [number, number]): number; + static crossVZ(out: [number, number], vec: [number, number], zcomp: number): [number, number]; + static crossZV(out: [number, number], zcomp: number, vec: [number, number]): [number, number]; + static rotate(out: [number, number], a: [number, number], angle: number): void; + static rotate90cw(out: [number, number], a: [number, number]): void; + static toLocalFrame(out: [number, number], worldPoint: [number, number], framePosition: [number, number], frameAngle: number): void; + static toGlobalFrame(out: [number, number], localPoint: [number, number], framePosition: [number, number], frameAngle: number): void; + static vectorToLocalFrame(out: [number, number], worldVector: [number, number], frameAngle: number): void; + static centroid(out: [number, number], a: [number, number], b: [number, number], c: [number, number]): [number, number]; + static create(): [number, number]; + static clone(a: [number, number]): [number, number]; + static fromValues(x: number, y: number): [number, number]; + static copy(out: [number, number], a: [number, number]): [number, number]; + static set(out: [number, number], x: number, y: number): [number, number]; + static add(out: [number, number], a: [number, number], b: [number, number]): [number, number]; + static subtract(out: [number, number], a: [number, number], b: [number, number]): [number, number]; + static sub(out: [number, number], a: [number, number], b: [number, number]): [number, number]; + static multiply(out: [number, number], a: [number, number], b: [number, number]): [number, number]; + static mul(out: [number, number], a: [number, number], b: [number, number]): [number, number]; + static divide(out: [number, number], a: [number, number], b: [number, number]): [number, number]; + static div(out: [number, number], a: [number, number], b: [number, number]): [number, number]; + static scale(out: [number, number], a: [number, number], b: number): [number, number]; + static distance(a: [number, number], b: [number, number]): number; + static dist(a: [number, number], b: [number, number]): number; + static squaredDistance(a: [number, number], b: [number, number]): number; + static sqrDist(a: [number, number], b: [number, number]): number; + static length(a: [number, number]): number; + static len(a: [number, number]): number; + static squaredLength(a: [number, number]): number; + static sqrLen(a: [number, number]): number; + static negate(out: [number, number], a: [number, number]): [number, number]; + static normalize(out: [number, number], a: [number, number]): [number, number]; + static dot(a: [number, number], b: [number, number]): number; + static str(a: [number, number]): string; + static lerp(out: [number, number], a: [number, number], b: [number, number], t: number): [number, number]; + static reflect(out: [number, number], vector: [number, number], normal: [number, number]): void; + static getLineSegmentsIntersection(out: [number, number], p1: [number, number], p2: [number, number], p3: [number, number], p4: [number, number]): boolean; + static getLineSegmentsIntersectionFraction(p1: [number, number], p2: [number, number], p3: [number, number], p4: [number, number]): number; } export interface BodyOptions { - mass?: number; - position?: number[]; - velocity?: number[]; + force?: [number, number]; + position?: [number, number]; + velocity?: [number, number]; + allowSleep?: boolean; + collisionResponse?: boolean; angle?: number; - angularVelocity?: number; - force?: number[]; angularForce?: number; + angularVelocity?: number; + ccdIterations?: number; + ccdSpeedThreshold?: number; fixedRotation?: boolean; + gravityScale?: number; + id?: number; + mass?: number; + sleepSpeedLimit?: number; + sleepTimeLimit?: number; + fixedX?: boolean; + fixedY?: boolean; } @@ -484,18 +578,20 @@ declare namespace p2 { invInertia: number; invMassSolve: number; invInertiaSolve: number; - fixedRotation: number; - position: number[]; - interpolatedPosition: number[]; - interpolatedAngle: number; - previousPosition: number[]; - previousAngle: number; - velocity: number[]; - vlambda: number[]; - wlambda: number[]; + fixedRotation: boolean; + fixedX: boolean; + fixedY: boolean; + position: [number, number]; + interpolatedPosition: [number, number]; + previousPosition: [number, number]; + velocity: [number, number]; + vlambda: [number, number]; + wlambda: [number, number]; angle: number; + previousAngle: number; + interpolatedAngle: number; angularVelocity: number; - force: number[]; + force: [number, number]; angularForce: number; damping: number; angularDamping: number; @@ -504,12 +600,14 @@ declare namespace p2 { aabb: AABB; aabbNeedsUpdate: boolean; allowSleep: boolean; - wantsToSleep: boolean; sleepState: number; sleepSpeedLimit: number; sleepTimeLimit: number; gravityScale: number; collisionResponse: boolean; + idleTime: number; + ccdSpeedThreshold: number; + ccdIterations: number; updateSolveMassProperties(): void; setDensity(density: number): void; @@ -517,45 +615,84 @@ declare namespace p2 { getAABB(): AABB; updateAABB(): void; updateBoundingRadius(): void; - addShape(shape: Shape, offset?: number[], angle?: number): void; + addShape(shape: Shape, offset?: [number, number], angle?: number): void; removeShape(shape: Shape): boolean; updateMassProperties(): void; - applyForce(force: number[], relativePoint?: number[]): void; - applyForceLocal(localforce: number[], localPoint?: number[]): void; - applyImpulse(impulse: number[], relativePoint?: number[]): void; - applyImpulseLocal(impulse: number[], localPoint?: number[]): void; - toLocalFrame(out: number[], worldPoint: number[]): void; - toWorldFrame(out: number[], localPoint: number[]): void; - fromPolygon(path: number[][], options?: { + applyForce(force: [number, number], relativePoint?: [number, number]): void; + applyForceLocal(localForce: [number, number], localPoint?: [number, number]): void; + applyImpulse(impulseVector: [number, number], relativePoint?: [number, number]): void; + applyImpulseLocal(localImpulse: [number, number], localPoint?: [number, number]): void; + toLocalFrame(out: [number, number], worldPoint: [number, number]): void; + toWorldFrame(out: [number, number], localPoint: [number, number]): void; + vectorToLocalFrame(out: [number, number], worldVector: [number, number]): void; + vectorToWorldFrame(out: [number, number], localVector: [number, number]): void; + fromPolygon(path: [number, number][], options?: { optimalDecomp?: boolean; skipSimpleCheck?: boolean; - removeCollinearPoints?: any; //boolean | number + removeCollinearPoints?: boolean | number; }): boolean; adjustCenterOfMass(): void; setZeroForce(): void; - resetConstraintVelocity(): void; - applyDamping(dy: number): void; + applyDamping(dt: number): void; wakeUp(): void; sleep(): void; sleepTick(time: number, dontSleep: boolean, dt: number): void; - getVelocityFromPosition(story: number[], dt: number): number[]; - getAngularVelocityFromPosition(timeStep: number): number; overlaps(body: Body): boolean; + integrate(dy: number): void; + getVelocityAtPoint(result: [number, number], relativePoint: [number, number]): [number, number]; + + } + + export interface LinearSpringOptions extends SpringOptions { + + restLength?: number; + + } + + export class LinearSpring extends Spring { + + constructor(bodyA: Body, bodyB: Body, options?: LinearSpringOptions); + + localAnchorA: [number, number]; + localAnchorB: [number, number]; + restLength: number; + + setWorldAnchorA(worldAnchorA: [number, number]): void; + setWorldAnchorB(worldAnchorB: [number, number]): void; + getWorldAnchorA(result: [number, number]): [number, number]; + getWorldAnchorB(result: [number, number]): [number, number]; + applyForce(): void; + + } + + export interface RotationalSpringOptions extends SpringOptions { + + restAngle?: number + + } + + export class RotationalSpring extends Spring { + + constructor(bodyA: Body, bodyB: Body, options?: RotationalSpringOptions); + + restAngle: number; + + } + + export interface SpringOptions { + + stiffness?: number; + damping?: number; + localAnchorA?: [number, number]; + localAnchorB?: [number, number]; + worldAnchorA?: [number, number]; + worldAnchorB?: [number, number]; } export class Spring { - constructor(bodyA: Body, bodyB: Body, options?: { - - stiffness?: number; - damping?: number; - localAnchorA?: number[]; - localAnchorB?: number[]; - worldAnchorA?: number[]; - worldAnchorB?: number[]; - - }); + constructor(bodyA: Body, bodyB: Body, options?: SpringOptions); stiffness: number; damping: number; @@ -566,36 +703,78 @@ declare namespace p2 { } - export class LinearSpring extends Spring { + export interface WheelConstraintOptions { - localAnchorA: number[]; - localAnchorB: number[]; - restLength: number; - - setWorldAnchorA(worldAnchorA: number[]): void; - setWorldAnchorB(worldAnchorB: number[]): void; - getWorldAnchorA(result: number[]): number[]; - getWorldAnchorB(result: number[]): number[]; - applyForce(): void; + localForwardVector?: [number, number]; + localPosition?: [number, number]; + sideFriction?: number; } - export class RotationalSpring extends Spring { + export class WheelConstraint extends Constraint { - constructor(bodyA: Body, bodyB: Body, options?: { - restAngle?: number; - stiffness?: number; - damping?: number; - }); + constructor(vehicle: TopDownVehicle, options?: WheelConstraintOptions); - restAngle: number; + protected vehicle: TopDownVehicle; + protected forwardEquation: FrictionEquation; + protected sideEquation: FrictionEquation; + + steerValue: number; + engineForce: number; + localForwardVector: [number, number]; + localPosition: [number, number]; + + setBrakeForce(force: number): void; + setSideFriction(force: number): void; + + getSpeed(): number; + + update(): void; + + } + + export interface TopDownVehicleOptions { + } + + export class TopDownVehicle { + + constructor(chasisBody: Body, options?: TopDownVehicleOptions); + + chasisBody: Body; + wheels: WheelConstraint[]; + world: World; + + addToWorld(world: World): void; + removeFromWorld(): void; + addWheel(wheelOptions?: WheelConstraintOptions): WheelConstraint; + + update(): void; + + } + + export interface BoxOptions { + + width?: number; + height?: number; + + } + + export class Box extends Shape { + + constructor(options?: BoxOptions); + + width: number; + height: number; + + computeMomentOfInertia(mass: number): number; + updateArea(): void; } export interface CapsuleOptions extends SharedShapeOptions { - length?: number; - radius?: number; + length?: number; + radius?: number; } @@ -606,11 +785,14 @@ declare namespace p2 { length: number; radius: number; + computeMomentOfInertia(mass: number): number; + updateArea(): void; + } export interface CircleOptions extends SharedShapeOptions { - radius?: number; + radius?: number; } @@ -619,13 +801,17 @@ declare namespace p2 { constructor(options?: CircleOptions); radius: number; + computeMomentOfInertia(mass: number): number; + updateArea(): void; + computeAABB(out: AABB, position: [number, number]): void; + raycast(result: RaycastResult, ray: Ray, position: [number, number]): void; } export interface ConvexOptions extends SharedShapeOptions { - vertices?: ArrayLike<number>[]; - axes?: ArrayLike<number>[]; + vertices: [number, number]|ArrayLike<number>[]; + axes: [number, number]|ArrayLike<number>[]; } @@ -635,16 +821,21 @@ declare namespace p2 { constructor(options?: ConvexOptions); - vertices: number[][]; - axes: number[][]; - centerOfMass: number[]; - triangles: number[]; + vertices: [number, number][]; + axes: [number, number][]; + centerOfMass: [number, number]; + triangles: [[number, number], [number, number], [number, number]]; boundingRadius: number; projectOntoLocalAxis(localAxis: number[], result: number[]): void; projectOntoWorldAxis(localAxis: number[], shapeOffset: number[], shapeAngle: number, result: number[]): void; updateCenterOfMass(): void; + updateNormals(): void; + updateTriangles(): void; + computeMomentOfInertia(mass: number): number; + updateArea(): void; + computeAABB(out: AABB, position: [number, number], angle: number): void; } @@ -661,11 +852,50 @@ declare namespace p2 { constructor(options?: HeightfieldOptions); - data: number[]; + heights: number[]; maxValue: number; minValue: number; elementWidth: number; + updateMaxMinValues(): void; + computeMomentOfInertia(): number; + updateArea(): void; + computeAABB(out: AABB, position: [number, number], angle: number): void; + + } + + export interface LineOptions extends SharedShapeOptions { + + length?: number; + + } + + export class Line extends Shape { + + constructor(options?: LineOptions); + + length: number; + + computeMomentOfInertia(mass: number): number; + computeAABB(out: AABB, position: [number, number], angle: number): void; + + } + + export class Particle extends Shape { + + constructor(options?: SharedShapeOptions); + + computeMomentOfInertia(): number; + computeAABB(out: AABB, position: [number, number]): void; + + } + + export class Plane extends Shape { + + constructor(options?: SharedShapeOptions); + + updateArea(): void; + } export interface SharedShapeOptions { @@ -673,9 +903,9 @@ declare namespace p2 { position?: number[]; angle?: number; collisionGroup?: number; - collisionResponse?: boolean; collisionMask?: number; sensor?: boolean; + collisionResponse?: boolean; } @@ -699,10 +929,11 @@ declare namespace p2 { constructor(options?: ShapeOptions); + body: Body; + position: [number, number]; + angle: number; type: number; id: number; - position: number[]; - angle: number; boundingRadius: number; collisionGroup: number; collisionResponse: boolean; @@ -711,52 +942,30 @@ declare namespace p2 { area: number; sensor: boolean; - computeMomentOfInertia(mass: number): number; + computeMomentOfInertia(mass?: number): number; updateBoundingRadius(): number; updateArea(): void; - computeAABB(out: AABB, position: number[], angle: number): void; + computeAABB(out?: AABB, position?: [number, number], angle?: number): void; + raycast(result?: RaycastResult, ray?: Ray, position?: [number, number], angle?: number): void; + } + + export interface GSSolverOptions { + + iterations?: number; + tolerance?: number; } - export interface LineOptions extends SharedShapeOptions { + export class GSSolver extends Solver { - length?: number; + constructor(options?: GSSolverOptions); - } + iterations: number; + tolerance: number; + frictionIterations: number; + usedIterations: number; - export class Line extends Shape { - - constructor(options?: LineOptions); - - length: number; - - } - - export class Particle extends Shape { - - constructor(options?: SharedShapeOptions); - - } - - export class Plane extends Shape { - - constructor(options?: SharedShapeOptions); - - } - - export interface BoxOptions { - - width?: number; - height?: number; - - } - - export class Box extends Shape { - - constructor(options?: BoxOptions); - - width: number; - height: number; + solve(h: number, world: World): void; } @@ -769,10 +978,10 @@ declare namespace p2 { type: number; equations: Equation[]; - equationSortFunction: Equation; //Equation | boolean + equationSortFunction: Equation | boolean - solve(dy: number, world: World): void; - solveIsland(dy: number, island: Island): void; + solve(dt: number, world: World): void; + solveIsland(dt: number, island: Island): void; sortEquations(): void; addEquation(eq: Equation): void; addEquations(eqs: Equation[]): void; @@ -781,26 +990,43 @@ declare namespace p2 { } - export class GSSolver extends Solver { + export class ContactEquationPool extends Pool { - constructor(options?: { - iterations?: number; - tolerance?: number; - }); + create(): ContactEquation; + destroy(equation: ContactEquation): ContactEquationPool; - iterations: number; - tolerance: number; - useZeroRHS: boolean; - frictionIterations: number; - usedIterations: number; + } - solve(h: number, world: World): void; + export class FrictionEquationPool extends Pool { + + create(): FrictionEquation; + destroy(equation: FrictionEquation): FrictionEquationPool; + + } + + export class IslandNodePool extends Pool { + + create(): IslandNode; + destroy(node: IslandNode): IslandNodePool; + + } + + export class IslandPool extends Pool { + + create(): Island; + destroy(island: Island): IslandPool; } export class OverlapKeeper { - constructor(bodyA: Body, shapeA: Shape, bodyB: Body, shapeB: Shape); + constructor(); + + overlappingShapesLastState: TupleDictionary; + overlappingShapesCurrentState: TupleDictionary; + OverlapKeeperRecordPool: OverlapKeeperRecordPool; + tmpDict: TupleDictionary; + tmpArray1: any[]; shapeA: Shape; shapeB: Shape; @@ -810,17 +1036,51 @@ declare namespace p2 { tick(): void; setOverlapping(bodyA: Body, shapeA: Shape, bodyB: Body, shapeB: Body): void; bodiesAreOverlapping(bodyA: Body, bodyB: Body): boolean; + } + + export class OverlapKeeperRecord { + + shapeA: Shape; + shapeB: Shape; + bodyA: Body; + bodyB: Body; + + constructor(bodyA: Body, shapeA: Shape, bodyB: Body, shapeB: Shape); + set(bodyA: Body, shapeA: Shape, bodyB: Body, shapeB: Shape): void; } + export class OverlapKeeperRecordPool extends Pool { + + create(): OverlapKeeperRecord; + destroy(record: OverlapKeeperRecord): OverlapKeeperRecordPool; + + } + + export interface PoolOptions { + size?: number; + } + + export class Pool { + + objects: any[]; + + constructor(options?: PoolOptions); + + resize(size: number): Pool; + get(): any; + release(object: any): Pool; + + } + export class TupleDictionary { - data: number[]; + data: any; keys: number[]; getKey(id1: number, id2: number): string; - getByKey(key: number): number; + getByKey(key: number): any; get(i: number, j: number): number; set(i: number, j: number, value: number): number; reset(): void; @@ -832,8 +1092,10 @@ declare namespace p2 { static appendArray<T>(a: Array<T>, b: Array<T>): Array<T>; static splice<T>(array: Array<T>, index: number, howMany: number): void; + static arrayRemove<T>(array: Array<T>, element: number): void; static extend(a: any, b: any): void; static defaults(options: any, defaults: any): any; + static shallowClone<T>(obj: T): T; } @@ -843,15 +1105,20 @@ declare namespace p2 { bodies: Body[]; reset(): void; - getBodies(result: any): Body[]; + getBodies(result: any[]): Body[]; wantsToSleep(): boolean; sleep(): boolean; } + export interface IslandManagerOptions { + } + export class IslandManager extends Solver { - static getUnvisitedNode(nodes: IslandNode[]): IslandNode; // IslandNode | boolean + static getUnvisitedNode(nodes: IslandNode[]): IslandNode | Boolean; + + constructor(options?: IslandManagerOptions); equations: Equation[]; islands: Island[]; @@ -876,6 +1143,13 @@ declare namespace p2 { } + export interface WorldOptions { + solver?: Solver; + gravity?: [number, number]; + broadphase?: Broadphase; + islandSplit?: boolean; + } + export class World extends EventEmitter { postStepEvent: { @@ -884,14 +1158,17 @@ declare namespace p2 { addBodyEvent: { type: string; + body: Body; }; removeBodyEvent: { type: string; + body: Body; }; addSpringEvent: { type: string; + spring: Spring; }; impactEvent: { @@ -935,22 +1212,16 @@ declare namespace p2 { static BODY_SLEEPING: number; static ISLAND_SLEEPING: number; - static integrateBody(body: Body, dy: number): void; + //static integrateBody(body: Body, dy: number): void; - constructor(options?: { - solver?: Solver; - gravity?: number[]; - broadphase?: Broadphase; - islandSplit?: boolean; - doProfiling?: boolean; - }); + constructor(options?: WorldOptions); springs: Spring[]; bodies: Body[]; solver: Solver; narrowphase: Narrowphase; islandManager: IslandManager; - gravity: number[]; + gravity: [number, number]; frictionGravity: number; useWorldGravityAsFrictionGravity: boolean; useFrictionGravityOnZeroGravity: boolean; @@ -967,6 +1238,7 @@ declare namespace p2 { solveConstraints: boolean; contactMaterials: ContactMaterial[]; time: number; + accumulator: number; stepping: boolean; islandSplit: boolean; emitImpactEvent: boolean; @@ -974,13 +1246,12 @@ declare namespace p2 { addConstraint(c: Constraint): void; addContactMaterial(contactMaterial: ContactMaterial): void; - removeContactMaterial(cm: ContactMaterial): void; getContactMaterial(materialA: Material, materialB: Material): ContactMaterial; // ContactMaterial | boolean - removeConstraint(c: Constraint): void; - step(dy: number, timeSinceLastCalled?: number, maxSubSteps?: number): void; - runNarrowphase(np: Narrowphase, bi: Body, si: Shape, xi: any[], ai: number, bj: Body, sj: Shape, xj: any[], aj: number, cm: number, glen: number): void; - addSpring(s: Spring): void; - removeSpring(s: Spring): void; + removeConstraint(constraint: Constraint): void; + removeContactMaterial(cm: ContactMaterial): void; + step(dt: number, timeSinceLastCalled?: number, maxSubSteps?: number): void; + addSpring(spring: Spring): void; + removeSpring(spring: Spring): void; addBody(body: Body): void; removeBody(body: Body): void; getBodyByID(id: number): Body; //Body | boolean @@ -988,13 +1259,15 @@ declare namespace p2 { enableBodyCollision(bodyA: Body, bodyB: Body): void; clear(): void; clone(): World; - hitTest(worldPoint: number[], bodies: Body[], precision: number): Body[]; + hitTest(worldPoint: [number, number], bodies: Body[], precision: number): Body[]; setGlobalEquationParameters(parameters: { relaxation?: number; stiffness?: number; }): void; setGlobalStiffness(stiffness: number): void; setGlobalRelaxation(relaxation: number): void; + raycast(result: RaycastResult, ray: Ray): boolean; + } } From a97fdbad6911b384e08fd6bc98e4f8d8c2ee8fa5 Mon Sep 17 00:00:00 2001 From: Janne Ramstedt <janne.ramstedt@aniway.fi> Date: Sat, 9 Feb 2019 03:46:18 +0200 Subject: [PATCH 171/197] Context is optional, uses "this" as fallback. --- types/p2/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/p2/index.d.ts b/types/p2/index.d.ts index 95082f836d..7a3715c7c7 100644 --- a/types/p2/index.d.ts +++ b/types/p2/index.d.ts @@ -431,7 +431,7 @@ declare namespace p2 { export class EventEmitter { - on(type: string, listener: Function, context: any): EventEmitter; + on(type: string, listener: Function, context?: any): EventEmitter; has(type: string, listener: Function): boolean; off(type: string, listener: Function): EventEmitter; emit(event: any): EventEmitter; From 7a65cd8947ddbbbbc2097eb2040c0eee86a876d7 Mon Sep 17 00:00:00 2001 From: Janne Ramstedt <janne.ramstedt@aniway.fi> Date: Sat, 9 Feb 2019 04:06:15 +0200 Subject: [PATCH 172/197] ConvexOptions's parameters are all optional --- types/p2/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/p2/index.d.ts b/types/p2/index.d.ts index 7a3715c7c7..d1191aea2e 100644 --- a/types/p2/index.d.ts +++ b/types/p2/index.d.ts @@ -810,8 +810,8 @@ declare namespace p2 { export interface ConvexOptions extends SharedShapeOptions { - vertices: [number, number]|ArrayLike<number>[]; - axes: [number, number]|ArrayLike<number>[]; + vertices?: [number, number]|ArrayLike<number>[]; + axes?: [number, number]|ArrayLike<number>[]; } From b868afe0eb7d43ee5c5b0615acf5858f29acb457 Mon Sep 17 00:00:00 2001 From: Janne Ramstedt <janne.ramstedt@aniway.fi> Date: Sat, 9 Feb 2019 04:06:40 +0200 Subject: [PATCH 173/197] position is tuple --- types/p2/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/p2/index.d.ts b/types/p2/index.d.ts index d1191aea2e..fe76b0c420 100644 --- a/types/p2/index.d.ts +++ b/types/p2/index.d.ts @@ -900,7 +900,7 @@ declare namespace p2 { export interface SharedShapeOptions { - position?: number[]; + position?: [number, number]; angle?: number; collisionGroup?: number; collisionMask?: number; From 506639e85e1c97999f1aab19a8a6e1fe204d484b Mon Sep 17 00:00:00 2001 From: Janne Ramstedt <janne.ramstedt@aniway.fi> Date: Sat, 9 Feb 2019 04:07:19 +0200 Subject: [PATCH 174/197] added missing semicolon --- types/p2/p2-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/p2/p2-tests.ts b/types/p2/p2-tests.ts index c796cf8f79..6817ac4016 100644 --- a/types/p2/p2-tests.ts +++ b/types/p2/p2-tests.ts @@ -44,7 +44,7 @@ const convex = new p2.Convex({ new Int32Array([0, -1]), [1, 1] ] -}) +}); // To get the trajectories of the bodies, // we must step the world forward in time. From 8664c5efac32095a96b8f269b4574bf196385978 Mon Sep 17 00:00:00 2001 From: Janne Ramstedt <janne.ramstedt@aniway.fi> Date: Sat, 9 Feb 2019 04:30:22 +0200 Subject: [PATCH 175/197] Added myself --- types/p2/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/p2/index.d.ts b/types/p2/index.d.ts index fe76b0c420..8bde6c1a3b 100644 --- a/types/p2/index.d.ts +++ b/types/p2/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for p2.js v0.7.1 // Project: https://github.com/schteppe/p2.js/ -// Definitions by: Clark Stevenson <https://github.com/clark-stevenson> +// Definitions by: Clark Stevenson <https://github.com/clark-stevenson>, Janne Ramstedt <https://github.com/jramstedt> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = p2; From 66469de2630f121c4cba2de554deea2265f39836 Mon Sep 17 00:00:00 2001 From: David Edmondson <threehams@gmail.com> Date: Fri, 8 Feb 2019 19:25:08 -0800 Subject: [PATCH 176/197] Revert whitespace change --- types/styled-system/styled-system-tests.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/styled-system/styled-system-tests.tsx b/types/styled-system/styled-system-tests.tsx index ce7b8d24ff..1a008fa045 100644 --- a/types/styled-system/styled-system-tests.tsx +++ b/types/styled-system/styled-system-tests.tsx @@ -277,7 +277,7 @@ interface GridComponentProps GridAutoColumnsProps, GridAutoRowsProps, GridTemplatesRowsProps, - GridTemplatesColumnsProps{} + GridTemplatesColumnsProps {} const Grid: React.ComponentType<GridComponentProps> = styled` ${gridGap}; ${gridRowGap}; From c2f3f6bea6b28ef4e38b168b805349c90fe162d7 Mon Sep 17 00:00:00 2001 From: antoinebrault <antoinebrault@gmail.com> Date: Fri, 8 Feb 2019 22:40:15 -0500 Subject: [PATCH 177/197] move custom types to jest namespace --- types/jest/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index d5061a78d5..0cc1999096 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -37,9 +37,6 @@ declare var xtest: jest.It; declare const expect: jest.Expect; type ArgsType<T> = T extends (...args: infer A) => any ? A : never; -// see https://github.com/Microsoft/TypeScript/issues/25215 -type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends (...args: any[]) => any ? never : K }[keyof T] & string; -type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never }[keyof T] & string; interface NodeRequire { /** @@ -240,6 +237,9 @@ declare namespace jest { } type EmptyFunction = () => void; + // see https://github.com/Microsoft/TypeScript/issues/25215 + type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends (...args: any[]) => any ? never : K }[keyof T] & string; + type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never }[keyof T] & string; interface DoneCallback { (...args: any[]): any; From bade23979671bfca4dfb83c4d46cf72c431b85da Mon Sep 17 00:00:00 2001 From: Frank Wallis <fwallis@outlook.com> Date: Sat, 9 Feb 2019 08:50:39 +0000 Subject: [PATCH 178/197] add skipSetBlur parameter to setOpen --- types/react-datepicker/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-datepicker/index.d.ts b/types/react-datepicker/index.d.ts index 4ba65f420e..ce7ebcfab9 100644 --- a/types/react-datepicker/index.d.ts +++ b/types/react-datepicker/index.d.ts @@ -131,7 +131,7 @@ export interface ReactDatePickerProps { declare class ReactDatePicker extends React.Component<ReactDatePickerProps> { readonly setBlur: () => void; readonly setFocus: () => void; - readonly setOpen: (open: boolean) => void; + readonly setOpen: (open: boolean, skipSetBlur?: boolean) => void; readonly isCalendarOpen: () => boolean; } From f203e285940845f8047208532ad2840a8efbca8f Mon Sep 17 00:00:00 2001 From: Xiao Liang <yxliang01@users.noreply.github.com> Date: Mon, 11 Feb 2019 02:55:44 +0800 Subject: [PATCH 179/197] solidity-parser-antlr: fix multiple type definitions --- types/solidity-parser-antlr/index.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/types/solidity-parser-antlr/index.d.ts b/types/solidity-parser-antlr/index.d.ts index 062a4ed918..e0917b1fbd 100644 --- a/types/solidity-parser-antlr/index.d.ts +++ b/types/solidity-parser-antlr/index.d.ts @@ -18,7 +18,9 @@ export interface BaseASTNode { range?: [number, number]; loc?: Location; } -export interface SourceUnit extends BaseASTNode {} // tslint:disable-line:no-empty-interface +export interface SourceUnit extends BaseASTNode { + children: ASTNode[]; // TODO: Can be more precise +} // tslint:disable-line:no-empty-interface export interface PragmaDirective extends BaseASTNode {} // tslint:disable-line:no-empty-interface export interface PragmaName extends BaseASTNode {} // tslint:disable-line:no-empty-interface export interface PragmaValue extends BaseASTNode {} // tslint:disable-line:no-empty-interface @@ -29,6 +31,7 @@ export interface ImportDeclaration extends BaseASTNode {} // tslint:disable-line export interface ImportDirective extends BaseASTNode {} // tslint:disable-line:no-empty-interface export interface ContractDefinition extends BaseASTNode { name: string; + subNodes: ASTNode[]; // TODO: Can be more precise } export interface InheritanceSpecifier extends BaseASTNode {} // tslint:disable-line:no-empty-interface export interface ContractPart extends BaseASTNode {} // tslint:disable-line:no-empty-interface @@ -45,6 +48,8 @@ export interface ModifierInvocation extends BaseASTNode { } export interface FunctionDefinition extends BaseASTNode { name: string; + parameters: ParameterList; + body: Block | null; } export interface ReturnParameters extends BaseASTNode {} // tslint:disable-line:no-empty-interface export interface ModifierList extends BaseASTNode {} // tslint:disable-line:no-empty-interface From b45d238cece73e5528b27c60aaa781cfc6fcc72f Mon Sep 17 00:00:00 2001 From: Xiao Liang <yxliang01@users.noreply.github.com> Date: Mon, 11 Feb 2019 03:15:52 +0800 Subject: [PATCH 180/197] fix(solidity-parser-antlr): fix visitor definition The visitor's return value should really be that `false | any` which is equal to `any`. See https://github.com/federicobond/solidity-parser-antlr/blob/73c6818452ba2eb50338b6a857acb82e976c34be/src/index.js#L97 . Current master version of `solidity-parser-antlr` only cares whether it's `false`. --- types/solidity-parser-antlr/index.d.ts | 164 ++++++++++++------------- 1 file changed, 82 insertions(+), 82 deletions(-) diff --git a/types/solidity-parser-antlr/index.d.ts b/types/solidity-parser-antlr/index.d.ts index e0917b1fbd..7b92aefb22 100644 --- a/types/solidity-parser-antlr/index.d.ts +++ b/types/solidity-parser-antlr/index.d.ts @@ -246,88 +246,88 @@ export type ASTNode = | BinaryOperation | Conditional; export interface Visitor { - SourceUnit?: (node: SourceUnit) => void; - PragmaDirective?: (node: PragmaDirective) => void; - PragmaName?: (node: PragmaName) => void; - PragmaValue?: (node: PragmaValue) => void; - Version?: (node: Version) => void; - VersionOperator?: (node: VersionOperator) => void; - VersionConstraint?: (node: VersionConstraint) => void; - ImportDeclaration?: (node: ImportDeclaration) => void; - ImportDirective?: (node: ImportDirective) => void; - ContractDefinition?: (node: ContractDefinition) => void; - InheritanceSpecifier?: (node: InheritanceSpecifier) => void; - ContractPart?: (node: ContractPart) => void; - StateVariableDeclaration?: (node: StateVariableDeclaration) => void; - UsingForDeclaration?: (node: UsingForDeclaration) => void; - StructDefinition?: (node: StructDefinition) => void; - ModifierDefinition?: (node: ModifierDefinition) => void; - ModifierInvocation?: (node: ModifierInvocation) => void; - FunctionDefinition?: (node: FunctionDefinition) => void; - ReturnParameters?: (node: ReturnParameters) => void; - ModifierList?: (node: ModifierList) => void; - EventDefinition?: (node: EventDefinition) => void; - EnumValue?: (node: EnumValue) => void; - EnumDefinition?: (node: EnumDefinition) => void; - ParameterList?: (node: ParameterList) => void; - Parameter?: (node: Parameter) => void; - EventParameterList?: (node: EventParameterList) => void; - EventParameter?: (node: EventParameter) => void; - FunctionTypeParameterList?: (node: FunctionTypeParameterList) => void; - FunctionTypeParameter?: (node: FunctionTypeParameter) => void; - VariableDeclaration?: (node: VariableDeclaration) => void; - TypeName?: (node: TypeName) => void; - UserDefinedTypeName?: (node: UserDefinedTypeName) => void; - Mapping?: (node: Mapping) => void; - FunctionTypeName?: (node: FunctionTypeName) => void; - StorageLocation?: (node: StorageLocation) => void; - StateMutability?: (node: StateMutability) => void; - Block?: (node: Block) => void; - Statement?: (node: Statement) => void; - ExpressionStatement?: (node: ExpressionStatement) => void; - IfStatement?: (node: IfStatement) => void; - WhileStatement?: (node: WhileStatement) => void; - SimpleStatement?: (node: SimpleStatement) => void; - ForStatement?: (node: ForStatement) => void; - InlineAssemblyStatement?: (node: InlineAssemblyStatement) => void; - DoWhileStatement?: (node: DoWhileStatement) => void; - ContinueStatement?: (node: ContinueStatement) => void; - BreakStatement?: (node: BreakStatement) => void; - ReturnStatement?: (node: ReturnStatement) => void; - ThrowStatement?: (node: ThrowStatement) => void; - VariableDeclarationStatement?: (node: VariableDeclarationStatement) => void; - IdentifierList?: (node: IdentifierList) => void; - ElementaryTypeName?: (node: ElementaryTypeName) => void; - Expression?: (node: Expression) => void; - PrimaryExpression?: (node: PrimaryExpression) => void; - ExpressionList?: (node: ExpressionList) => void; - NameValueList?: (node: NameValueList) => void; - NameValue?: (node: NameValue) => void; - FunctionCallArguments?: (node: FunctionCallArguments) => void; - AssemblyBlock?: (node: AssemblyBlock) => void; - AssemblyItem?: (node: AssemblyItem) => void; - AssemblyExpression?: (node: AssemblyExpression) => void; - AssemblyCall?: (node: AssemblyCall) => void; - AssemblyLocalDefinition?: (node: AssemblyLocalDefinition) => void; - AssemblyAssignment?: (node: AssemblyAssignment) => void; - AssemblyIdentifierOrList?: (node: AssemblyIdentifierOrList) => void; - AssemblyIdentifierList?: (node: AssemblyIdentifierList) => void; - AssemblyStackAssignment?: (node: AssemblyStackAssignment) => void; - LabelDefinition?: (node: LabelDefinition) => void; - AssemblySwitch?: (node: AssemblySwitch) => void; - AssemblyCase?: (node: AssemblyCase) => void; - AssemblyFunctionDefinition?: (node: AssemblyFunctionDefinition) => void; - AssemblyFunctionReturns?: (node: AssemblyFunctionReturns) => void; - AssemblyFor?: (node: AssemblyFor) => void; - AssemblyIf?: (node: AssemblyIf) => void; - AssemblyLiteral?: (node: AssemblyLiteral) => void; - SubAssembly?: (node: SubAssembly) => void; - TupleExpression?: (node: TupleExpression) => void; - ElementaryTypeNameExpression?: (node: ElementaryTypeNameExpression) => void; - NumberLiteral?: (node: NumberLiteral) => void; - Identifier?: (node: Identifier) => void; - BinaryOperation?: (node: BinaryOperation) => void; - Conditional?: (node: Conditional) => void; + SourceUnit?: (node: SourceUnit) => any; + PragmaDirective?: (node: PragmaDirective) => any; + PragmaName?: (node: PragmaName) => any; + PragmaValue?: (node: PragmaValue) => any; + Version?: (node: Version) => any; + VersionOperator?: (node: VersionOperator) => any; + VersionConstraint?: (node: VersionConstraint) => any; + ImportDeclaration?: (node: ImportDeclaration) => any; + ImportDirective?: (node: ImportDirective) => any; + ContractDefinition?: (node: ContractDefinition) => any; + InheritanceSpecifier?: (node: InheritanceSpecifier) => any; + ContractPart?: (node: ContractPart) => any; + StateVariableDeclaration?: (node: StateVariableDeclaration) => any; + UsingForDeclaration?: (node: UsingForDeclaration) => any; + StructDefinition?: (node: StructDefinition) => any; + ModifierDefinition?: (node: ModifierDefinition) => any; + ModifierInvocation?: (node: ModifierInvocation) => any; + FunctionDefinition?: (node: FunctionDefinition) => any; + ReturnParameters?: (node: ReturnParameters) => any; + ModifierList?: (node: ModifierList) => any; + EventDefinition?: (node: EventDefinition) => any; + EnumValue?: (node: EnumValue) => any; + EnumDefinition?: (node: EnumDefinition) => any; + ParameterList?: (node: ParameterList) => any; + Parameter?: (node: Parameter) => any; + EventParameterList?: (node: EventParameterList) => any; + EventParameter?: (node: EventParameter) => any; + FunctionTypeParameterList?: (node: FunctionTypeParameterList) => any; + FunctionTypeParameter?: (node: FunctionTypeParameter) => any; + VariableDeclaration?: (node: VariableDeclaration) => any; + TypeName?: (node: TypeName) => any; + UserDefinedTypeName?: (node: UserDefinedTypeName) => any; + Mapping?: (node: Mapping) => any; + FunctionTypeName?: (node: FunctionTypeName) => any; + StorageLocation?: (node: StorageLocation) => any; + StateMutability?: (node: StateMutability) => any; + Block?: (node: Block) => any; + Statement?: (node: Statement) => any; + ExpressionStatement?: (node: ExpressionStatement) => any; + IfStatement?: (node: IfStatement) => any; + WhileStatement?: (node: WhileStatement) => any; + SimpleStatement?: (node: SimpleStatement) => any; + ForStatement?: (node: ForStatement) => any; + InlineAssemblyStatement?: (node: InlineAssemblyStatement) => any; + DoWhileStatement?: (node: DoWhileStatement) => any; + ContinueStatement?: (node: ContinueStatement) => any; + BreakStatement?: (node: BreakStatement) => any; + ReturnStatement?: (node: ReturnStatement) => any; + ThrowStatement?: (node: ThrowStatement) => any; + VariableDeclarationStatement?: (node: VariableDeclarationStatement) => any; + IdentifierList?: (node: IdentifierList) => any; + ElementaryTypeName?: (node: ElementaryTypeName) => any; + Expression?: (node: Expression) => any; + PrimaryExpression?: (node: PrimaryExpression) => any; + ExpressionList?: (node: ExpressionList) => any; + NameValueList?: (node: NameValueList) => any; + NameValue?: (node: NameValue) => any; + FunctionCallArguments?: (node: FunctionCallArguments) => any; + AssemblyBlock?: (node: AssemblyBlock) => any; + AssemblyItem?: (node: AssemblyItem) => any; + AssemblyExpression?: (node: AssemblyExpression) => any; + AssemblyCall?: (node: AssemblyCall) => any; + AssemblyLocalDefinition?: (node: AssemblyLocalDefinition) => any; + AssemblyAssignment?: (node: AssemblyAssignment) => any; + AssemblyIdentifierOrList?: (node: AssemblyIdentifierOrList) => any; + AssemblyIdentifierList?: (node: AssemblyIdentifierList) => any; + AssemblyStackAssignment?: (node: AssemblyStackAssignment) => any; + LabelDefinition?: (node: LabelDefinition) => any; + AssemblySwitch?: (node: AssemblySwitch) => any; + AssemblyCase?: (node: AssemblyCase) => any; + AssemblyFunctionDefinition?: (node: AssemblyFunctionDefinition) => any; + AssemblyFunctionReturns?: (node: AssemblyFunctionReturns) => any; + AssemblyFor?: (node: AssemblyFor) => any; + AssemblyIf?: (node: AssemblyIf) => any; + AssemblyLiteral?: (node: AssemblyLiteral) => any; + SubAssembly?: (node: SubAssembly) => any; + TupleExpression?: (node: TupleExpression) => any; + ElementaryTypeNameExpression?: (node: ElementaryTypeNameExpression) => any; + NumberLiteral?: (node: NumberLiteral) => any; + Identifier?: (node: Identifier) => any; + BinaryOperation?: (node: BinaryOperation) => any; + Conditional?: (node: Conditional) => any; } export interface ParserOpts { tolerant?: boolean; From 9828be0826d7844df3e597606a4392c3bc8b6d91 Mon Sep 17 00:00:00 2001 From: Hui He <hui.he@rea-group.com> Date: Mon, 11 Feb 2019 16:17:15 +1100 Subject: [PATCH 181/197] [express-winston] update RequestFilter and ResponseFilter types --- types/express-winston/express-winston-tests.ts | 6 +++--- types/express-winston/index.d.ts | 12 ++++++++++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/types/express-winston/express-winston-tests.ts b/types/express-winston/express-winston-tests.ts index f370abdb5d..5d48bdd897 100644 --- a/types/express-winston/express-winston-tests.ts +++ b/types/express-winston/express-winston-tests.ts @@ -18,7 +18,7 @@ app.use(expressWinston.logger({ meta: true, metaField: 'metaField', msg: 'msg', - requestFilter: (req, prop) => true, + requestFilter: (req, prop) => req[prop], requestWhitelist: ['foo', 'bar'], skip: (req, res) => false, statusLevels: ({ error: 'error', success: 'success', warn: 'warn' }), @@ -69,8 +69,8 @@ app.use(expressWinston.errorLogger({ expressWinston.bodyBlacklist.push('potato'); expressWinston.bodyWhitelist.push('apple'); -expressWinston.defaultRequestFilter = (req: express.Request, prop: string) => true; -expressWinston.defaultResponseFilter = (res: express.Response, prop: string) => true; +expressWinston.defaultRequestFilter = (req: expressWinston.FilterRequest, prop: string) => req[prop]; +expressWinston.defaultResponseFilter = (res: expressWinston.FilterResponse, prop: string) => res[prop]; expressWinston.defaultSkip = () => true; expressWinston.ignoredRoutes.push('/ignored'); expressWinston.responseWhitelist.push('body'); diff --git a/types/express-winston/index.d.ts b/types/express-winston/index.d.ts index 462f3df1b3..f7ae04319b 100644 --- a/types/express-winston/index.d.ts +++ b/types/express-winston/index.d.ts @@ -8,10 +8,18 @@ import { ErrorRequestHandler, Handler, Request, Response } from 'express'; import * as winston from 'winston'; import * as Transport from 'winston-transport'; +export interface FilterRequest extends Request { + [other: string]: any; +} + +export interface FilterResponse extends Response { + [other: string]: any; +} + export type DynamicMetaFunction = (req: Request, res: Response, err: Error) => object; export type DynamicLevelFunction = (req: Request, res: Response, err: Error) => string; -export type RequestFilter = (req: Request, propName: string) => boolean; -export type ResponseFilter = (res: Response, propName: string) => boolean; +export type RequestFilter = (req: FilterRequest, propName: string) => any; +export type ResponseFilter = (res: FilterResponse, propName: string) => any; export type RouteFilter = (req: Request, res: Response) => boolean; export interface BaseLoggerOptions { From a7a7e9acbdf03d006541b2e4494fd7a0d46ea243 Mon Sep 17 00:00:00 2001 From: Christian Rackerseder <git@echooff.de> Date: Mon, 11 Feb 2019 07:36:20 +0100 Subject: [PATCH 182/197] Update Giphy API response type Aligned with official API docs: https://developers.giphy.com/docs/ --- types/giphy-api/index.d.ts | 88 ++++++++++++++++---------------------- 1 file changed, 38 insertions(+), 50 deletions(-) diff --git a/types/giphy-api/index.d.ts b/types/giphy-api/index.d.ts index e179e2b99b..f6174543eb 100644 --- a/types/giphy-api/index.d.ts +++ b/types/giphy-api/index.d.ts @@ -45,25 +45,45 @@ interface BaseImage { interface Result { data: [ { - type: "gif"; + type: string; id: string; slug: string; url: string; - bitly_gif_url: string; bitly_url: string; embed_url: string; username: string; source: string; rating: Rating; content_url: string; + user?: { + avatar_url: string; + banner_url: string; + profile_url: string; + username: string; + display_name: string; + twitter: string; + }, source_tld: string; source_post_url: string; - is_sticker: number; + update_datetime: string; + create_datetime: string; import_datetime: string; trending_datetime: string; + title: string; images: { + fixed_height: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; fixed_height_still: BaseImage; - original_still: BaseImage; + fixed_height_downsampled: BaseImage & { + size: string; + webp: string; + webp_size: string; + }; fixed_width: BaseImage & { size: string; mp4: string; @@ -71,18 +91,13 @@ interface Result { webp: string; webp_size: string; }; - fixed_height_small_still: BaseImage; - fixed_height_downsampled: BaseImage & { + original_still: BaseImage; + fixed_width_still: BaseImage; + fixed_width_downsampled: BaseImage & { size: string; webp: string; webp_size: string; }; - preview: { - width: string; - height: string; - mp4: string; - mp4_size: string; - }; fixed_height_small: BaseImage & { size: string; mp4: string; @@ -90,20 +105,7 @@ interface Result { webp: string; webp_size: string; }; - downsized_still: BaseImage & { - size: string; - }; - downsized: BaseImage & { - size: string; - }; - downsized_large: BaseImage & { - size: string; - }; - fixed_width_small_still: BaseImage; - preview_webp: BaseImage & { - size: string; - }; - fixed_width_still: BaseImage; + fixed_height_small_still: BaseImage; fixed_width_small: BaseImage & { size: string; mp4: string; @@ -111,20 +113,20 @@ interface Result { webp: string; webp_size: string; }; - downsized_small: { - width: string; - height: string; - mp4: string; - mp4_size: string; + fixed_width_small_still: BaseImage; + downsized: BaseImage & { + size: string; }; - fixed_width_downsampled: BaseImage & { + downsized_still: BaseImage; + downsized_large: BaseImage & { size: string; - webp: string; - webp_size: string; }; downsized_medium: BaseImage & { size: string; }; + downsized_small: BaseImage & { + size: string; + }; original: BaseImage & { size: string; frames: string; @@ -133,15 +135,8 @@ interface Result { webp: string; webp_size: string; }; - fixed_height: BaseImage & { - size: string; - mp4: string; - mp4_size: string; - webp: string; - webp_size: string; - }; - looping: { mp4: string; mp4_size: string }; - original_mp4: { + looping: { mp4: string; }; + preview: { width: string; height: string; mp4: string; @@ -150,13 +145,6 @@ interface Result { preview_gif: BaseImage & { size: string; }; - title: string; - _score: number; - analytics: { - onload: { url: string }; - onclick: { url: string }; - onsent: { url: string }; - }; }; } ]; From 7d158f64f897b65d19f75a957550faa6bff8960f Mon Sep 17 00:00:00 2001 From: shinhwagk <shanghai_sl@hotmail.com> Date: Mon, 11 Feb 2019 15:31:06 +0800 Subject: [PATCH 183/197] addAll function parameters not necessary. https://github.com/nodegit/nodegit/search?q=addAll&unscoped_q=addAll https://github.com/nodegit/nodegit/blob/master/examples/index-add-and-remove.js addAll function parameters not necessary. --- types/nodegit/index_.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/nodegit/index_.d.ts b/types/nodegit/index_.d.ts index 932691a89c..1fce02c942 100644 --- a/types/nodegit/index_.d.ts +++ b/types/nodegit/index_.d.ts @@ -26,7 +26,7 @@ export class Index { static open(indexPath: string): Promise<Index>; add(sourceEntry: IndexEntry): number; - addAll(pathspec: Strarray | string | string[], flags: number, callback?: Function): Promise<number>; + addAll(pathspec?: Strarray | string | string[], flags?: number, callback?: Function): Promise<number>; addByPath(path: string): Promise<number>; caps(): number; checksum(): Oid; From 9fb56fc26d8c6aada2fa7e8975bc153b45b2066a Mon Sep 17 00:00:00 2001 From: Jiri Spac <capajj@gmail.com> Date: Mon, 11 Feb 2019 11:47:16 +0100 Subject: [PATCH 184/197] adds cubicInterpolationMode prop to ChartLineOptions charts do respect the property as documented here https://www.chartjs.org/docs/latest/charts/line.html#cubicinterpolationmode --- types/chart.js/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 8e795ed77c..0b78644a96 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -417,6 +417,7 @@ declare namespace Chart { } interface ChartLineOptions { + cubicInterpolationMode?: 'default' | 'monotone'; tension?: number; backgroundColor?: ChartColor; borderWidth?: number; From 2e8330c53ab072972a13a27b2693fbc0f8fd47df Mon Sep 17 00:00:00 2001 From: Xiao Liang <yxliang01@users.noreply.github.com> Date: Mon, 11 Feb 2019 21:30:12 +0800 Subject: [PATCH 185/197] solidity-parser-antlr: improve Visitor return type Making `Visitor` return type `=> false | any` rather than `=> any` would make it clearer that `false` is a special return value for the `Visitor`s, if it's not `false`, it doesn't really matter what the value is. --- types/solidity-parser-antlr/index.d.ts | 164 ++++++++++++------------- 1 file changed, 82 insertions(+), 82 deletions(-) diff --git a/types/solidity-parser-antlr/index.d.ts b/types/solidity-parser-antlr/index.d.ts index 7b92aefb22..2c50a971a1 100644 --- a/types/solidity-parser-antlr/index.d.ts +++ b/types/solidity-parser-antlr/index.d.ts @@ -246,88 +246,88 @@ export type ASTNode = | BinaryOperation | Conditional; export interface Visitor { - SourceUnit?: (node: SourceUnit) => any; - PragmaDirective?: (node: PragmaDirective) => any; - PragmaName?: (node: PragmaName) => any; - PragmaValue?: (node: PragmaValue) => any; - Version?: (node: Version) => any; - VersionOperator?: (node: VersionOperator) => any; - VersionConstraint?: (node: VersionConstraint) => any; - ImportDeclaration?: (node: ImportDeclaration) => any; - ImportDirective?: (node: ImportDirective) => any; - ContractDefinition?: (node: ContractDefinition) => any; - InheritanceSpecifier?: (node: InheritanceSpecifier) => any; - ContractPart?: (node: ContractPart) => any; - StateVariableDeclaration?: (node: StateVariableDeclaration) => any; - UsingForDeclaration?: (node: UsingForDeclaration) => any; - StructDefinition?: (node: StructDefinition) => any; - ModifierDefinition?: (node: ModifierDefinition) => any; - ModifierInvocation?: (node: ModifierInvocation) => any; - FunctionDefinition?: (node: FunctionDefinition) => any; - ReturnParameters?: (node: ReturnParameters) => any; - ModifierList?: (node: ModifierList) => any; - EventDefinition?: (node: EventDefinition) => any; - EnumValue?: (node: EnumValue) => any; - EnumDefinition?: (node: EnumDefinition) => any; - ParameterList?: (node: ParameterList) => any; - Parameter?: (node: Parameter) => any; - EventParameterList?: (node: EventParameterList) => any; - EventParameter?: (node: EventParameter) => any; - FunctionTypeParameterList?: (node: FunctionTypeParameterList) => any; - FunctionTypeParameter?: (node: FunctionTypeParameter) => any; - VariableDeclaration?: (node: VariableDeclaration) => any; - TypeName?: (node: TypeName) => any; - UserDefinedTypeName?: (node: UserDefinedTypeName) => any; - Mapping?: (node: Mapping) => any; - FunctionTypeName?: (node: FunctionTypeName) => any; - StorageLocation?: (node: StorageLocation) => any; - StateMutability?: (node: StateMutability) => any; - Block?: (node: Block) => any; - Statement?: (node: Statement) => any; - ExpressionStatement?: (node: ExpressionStatement) => any; - IfStatement?: (node: IfStatement) => any; - WhileStatement?: (node: WhileStatement) => any; - SimpleStatement?: (node: SimpleStatement) => any; - ForStatement?: (node: ForStatement) => any; - InlineAssemblyStatement?: (node: InlineAssemblyStatement) => any; - DoWhileStatement?: (node: DoWhileStatement) => any; - ContinueStatement?: (node: ContinueStatement) => any; - BreakStatement?: (node: BreakStatement) => any; - ReturnStatement?: (node: ReturnStatement) => any; - ThrowStatement?: (node: ThrowStatement) => any; - VariableDeclarationStatement?: (node: VariableDeclarationStatement) => any; - IdentifierList?: (node: IdentifierList) => any; - ElementaryTypeName?: (node: ElementaryTypeName) => any; - Expression?: (node: Expression) => any; - PrimaryExpression?: (node: PrimaryExpression) => any; - ExpressionList?: (node: ExpressionList) => any; - NameValueList?: (node: NameValueList) => any; - NameValue?: (node: NameValue) => any; - FunctionCallArguments?: (node: FunctionCallArguments) => any; - AssemblyBlock?: (node: AssemblyBlock) => any; - AssemblyItem?: (node: AssemblyItem) => any; - AssemblyExpression?: (node: AssemblyExpression) => any; - AssemblyCall?: (node: AssemblyCall) => any; - AssemblyLocalDefinition?: (node: AssemblyLocalDefinition) => any; - AssemblyAssignment?: (node: AssemblyAssignment) => any; - AssemblyIdentifierOrList?: (node: AssemblyIdentifierOrList) => any; - AssemblyIdentifierList?: (node: AssemblyIdentifierList) => any; - AssemblyStackAssignment?: (node: AssemblyStackAssignment) => any; - LabelDefinition?: (node: LabelDefinition) => any; - AssemblySwitch?: (node: AssemblySwitch) => any; - AssemblyCase?: (node: AssemblyCase) => any; - AssemblyFunctionDefinition?: (node: AssemblyFunctionDefinition) => any; - AssemblyFunctionReturns?: (node: AssemblyFunctionReturns) => any; - AssemblyFor?: (node: AssemblyFor) => any; - AssemblyIf?: (node: AssemblyIf) => any; - AssemblyLiteral?: (node: AssemblyLiteral) => any; - SubAssembly?: (node: SubAssembly) => any; - TupleExpression?: (node: TupleExpression) => any; - ElementaryTypeNameExpression?: (node: ElementaryTypeNameExpression) => any; - NumberLiteral?: (node: NumberLiteral) => any; - Identifier?: (node: Identifier) => any; - BinaryOperation?: (node: BinaryOperation) => any; - Conditional?: (node: Conditional) => any; + SourceUnit?: (node: SourceUnit) => false | any; + PragmaDirective?: (node: PragmaDirective) => false | any; + PragmaName?: (node: PragmaName) => false | any; + PragmaValue?: (node: PragmaValue) => false | any; + Version?: (node: Version) => false | any; + VersionOperator?: (node: VersionOperator) => false | any; + VersionConstraint?: (node: VersionConstraint) => false | any; + ImportDeclaration?: (node: ImportDeclaration) => false | any; + ImportDirective?: (node: ImportDirective) => false | any; + ContractDefinition?: (node: ContractDefinition) => false | any; + InheritanceSpecifier?: (node: InheritanceSpecifier) => false | any; + ContractPart?: (node: ContractPart) => false | any; + StateVariableDeclaration?: (node: StateVariableDeclaration) => false | any; + UsingForDeclaration?: (node: UsingForDeclaration) => false | any; + StructDefinition?: (node: StructDefinition) => false | any; + ModifierDefinition?: (node: ModifierDefinition) => false | any; + ModifierInvocation?: (node: ModifierInvocation) => false | any; + FunctionDefinition?: (node: FunctionDefinition) => false | any; + ReturnParameters?: (node: ReturnParameters) => false | any; + ModifierList?: (node: ModifierList) => false | any; + EventDefinition?: (node: EventDefinition) => false | any; + EnumValue?: (node: EnumValue) => false | any; + EnumDefinition?: (node: EnumDefinition) => false | any; + ParameterList?: (node: ParameterList) => false | any; + Parameter?: (node: Parameter) => false | any; + EventParameterList?: (node: EventParameterList) => false | any; + EventParameter?: (node: EventParameter) => false | any; + FunctionTypeParameterList?: (node: FunctionTypeParameterList) => false | any; + FunctionTypeParameter?: (node: FunctionTypeParameter) => false | any; + VariableDeclaration?: (node: VariableDeclaration) => false | any; + TypeName?: (node: TypeName) => false | any; + UserDefinedTypeName?: (node: UserDefinedTypeName) => false | any; + Mapping?: (node: Mapping) => false | any; + FunctionTypeName?: (node: FunctionTypeName) => false | any; + StorageLocation?: (node: StorageLocation) => false | any; + StateMutability?: (node: StateMutability) => false | any; + Block?: (node: Block) => false | any; + Statement?: (node: Statement) => false | any; + ExpressionStatement?: (node: ExpressionStatement) => false | any; + IfStatement?: (node: IfStatement) => false | any; + WhileStatement?: (node: WhileStatement) => false | any; + SimpleStatement?: (node: SimpleStatement) => false | any; + ForStatement?: (node: ForStatement) => false | any; + InlineAssemblyStatement?: (node: InlineAssemblyStatement) => false | any; + DoWhileStatement?: (node: DoWhileStatement) => false | any; + ContinueStatement?: (node: ContinueStatement) => false | any; + BreakStatement?: (node: BreakStatement) => false | any; + ReturnStatement?: (node: ReturnStatement) => false | any; + ThrowStatement?: (node: ThrowStatement) => false | any; + VariableDeclarationStatement?: (node: VariableDeclarationStatement) => false | any; + IdentifierList?: (node: IdentifierList) => false | any; + ElementaryTypeName?: (node: ElementaryTypeName) => false | any; + Expression?: (node: Expression) => false | any; + PrimaryExpression?: (node: PrimaryExpression) => false | any; + ExpressionList?: (node: ExpressionList) => false | any; + NameValueList?: (node: NameValueList) => false | any; + NameValue?: (node: NameValue) => false | any; + FunctionCallArguments?: (node: FunctionCallArguments) => false | any; + AssemblyBlock?: (node: AssemblyBlock) => false | any; + AssemblyItem?: (node: AssemblyItem) => false | any; + AssemblyExpression?: (node: AssemblyExpression) => false | any; + AssemblyCall?: (node: AssemblyCall) => false | any; + AssemblyLocalDefinition?: (node: AssemblyLocalDefinition) => false | any; + AssemblyAssignment?: (node: AssemblyAssignment) => false | any; + AssemblyIdentifierOrList?: (node: AssemblyIdentifierOrList) => false | any; + AssemblyIdentifierList?: (node: AssemblyIdentifierList) => false | any; + AssemblyStackAssignment?: (node: AssemblyStackAssignment) => false | any; + LabelDefinition?: (node: LabelDefinition) => false | any; + AssemblySwitch?: (node: AssemblySwitch) => false | any; + AssemblyCase?: (node: AssemblyCase) => false | any; + AssemblyFunctionDefinition?: (node: AssemblyFunctionDefinition) => false | any; + AssemblyFunctionReturns?: (node: AssemblyFunctionReturns) => false | any; + AssemblyFor?: (node: AssemblyFor) => false | any; + AssemblyIf?: (node: AssemblyIf) => false | any; + AssemblyLiteral?: (node: AssemblyLiteral) => false | any; + SubAssembly?: (node: SubAssembly) => false | any; + TupleExpression?: (node: TupleExpression) => false | any; + ElementaryTypeNameExpression?: (node: ElementaryTypeNameExpression) => false | any; + NumberLiteral?: (node: NumberLiteral) => false | any; + Identifier?: (node: Identifier) => false | any; + BinaryOperation?: (node: BinaryOperation) => false | any; + Conditional?: (node: Conditional) => false | any; } export interface ParserOpts { tolerant?: boolean; From 0e3d4f5e0a5073d3fef372b05bb83150b4cadbe8 Mon Sep 17 00:00:00 2001 From: Joosung Park <park012241@park012241.me> Date: Mon, 11 Feb 2019 22:32:25 +0900 Subject: [PATCH 186/197] Fix typo Issue Fixed typo issue in pygpio/index.d.ts In line 75 and line 77, It was "levle", I fixed to "level" --- types/pigpio/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/pigpio/index.d.ts b/types/pigpio/index.d.ts index 8eaa6491bb..cd9af3c838 100644 --- a/types/pigpio/index.d.ts +++ b/types/pigpio/index.d.ts @@ -72,9 +72,9 @@ export class Gpio extends NodeJS.EventEmitter { /** * Sets the GPIO level to 0 or 1. If PWM or servo pulses are active on the GPIO they are switched off. - * @param levle 0 or 1 + * @param level 0 or 1 */ - digitalWrite(levle: number): Gpio; + digitalWrite(level: number): Gpio; /** * Sends a trigger pulse to the GPIO. The GPIO is set to level for pulseLen microseconds and then reset to not level. From aa5e75ea959dd4d5594347639ff02d786c9face7 Mon Sep 17 00:00:00 2001 From: Joosung Park <park012241@park012241.me> Date: Mon, 11 Feb 2019 22:45:38 +0900 Subject: [PATCH 187/197] Add Definitions by add "Definitions by" --- types/pigpio/index.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/types/pigpio/index.d.ts b/types/pigpio/index.d.ts index cd9af3c838..b62528b17c 100644 --- a/types/pigpio/index.d.ts +++ b/types/pigpio/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for pigpio 1.2 // Project: https://github.com/fivdi/pigpio -// Definitions by: ManerFan <https://github.com/manerfan>, erikma <https://github.com/erikma> +// Definitions by: ManerFan <https://github.com/manerfan> +// erikma <https://github.com/erikma> +// park012241 <https://github.com/park012241> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="node" /> From ff81a175074a4662d4211e190d65a69b3fdbb06b Mon Sep 17 00:00:00 2001 From: Xiao Liang <yxliang01@users.noreply.github.com> Date: Mon, 11 Feb 2019 22:34:35 +0800 Subject: [PATCH 188/197] revert(solidity-parser-antlr): improve Visitor return type Since the official DefinitelyTyped/DefinitelyTyped build has `no-any-union` option enabled, changing back to `Visitor` returning `any`. --- types/solidity-parser-antlr/index.d.ts | 164 ++++++++++++------------- 1 file changed, 82 insertions(+), 82 deletions(-) diff --git a/types/solidity-parser-antlr/index.d.ts b/types/solidity-parser-antlr/index.d.ts index 2c50a971a1..7b92aefb22 100644 --- a/types/solidity-parser-antlr/index.d.ts +++ b/types/solidity-parser-antlr/index.d.ts @@ -246,88 +246,88 @@ export type ASTNode = | BinaryOperation | Conditional; export interface Visitor { - SourceUnit?: (node: SourceUnit) => false | any; - PragmaDirective?: (node: PragmaDirective) => false | any; - PragmaName?: (node: PragmaName) => false | any; - PragmaValue?: (node: PragmaValue) => false | any; - Version?: (node: Version) => false | any; - VersionOperator?: (node: VersionOperator) => false | any; - VersionConstraint?: (node: VersionConstraint) => false | any; - ImportDeclaration?: (node: ImportDeclaration) => false | any; - ImportDirective?: (node: ImportDirective) => false | any; - ContractDefinition?: (node: ContractDefinition) => false | any; - InheritanceSpecifier?: (node: InheritanceSpecifier) => false | any; - ContractPart?: (node: ContractPart) => false | any; - StateVariableDeclaration?: (node: StateVariableDeclaration) => false | any; - UsingForDeclaration?: (node: UsingForDeclaration) => false | any; - StructDefinition?: (node: StructDefinition) => false | any; - ModifierDefinition?: (node: ModifierDefinition) => false | any; - ModifierInvocation?: (node: ModifierInvocation) => false | any; - FunctionDefinition?: (node: FunctionDefinition) => false | any; - ReturnParameters?: (node: ReturnParameters) => false | any; - ModifierList?: (node: ModifierList) => false | any; - EventDefinition?: (node: EventDefinition) => false | any; - EnumValue?: (node: EnumValue) => false | any; - EnumDefinition?: (node: EnumDefinition) => false | any; - ParameterList?: (node: ParameterList) => false | any; - Parameter?: (node: Parameter) => false | any; - EventParameterList?: (node: EventParameterList) => false | any; - EventParameter?: (node: EventParameter) => false | any; - FunctionTypeParameterList?: (node: FunctionTypeParameterList) => false | any; - FunctionTypeParameter?: (node: FunctionTypeParameter) => false | any; - VariableDeclaration?: (node: VariableDeclaration) => false | any; - TypeName?: (node: TypeName) => false | any; - UserDefinedTypeName?: (node: UserDefinedTypeName) => false | any; - Mapping?: (node: Mapping) => false | any; - FunctionTypeName?: (node: FunctionTypeName) => false | any; - StorageLocation?: (node: StorageLocation) => false | any; - StateMutability?: (node: StateMutability) => false | any; - Block?: (node: Block) => false | any; - Statement?: (node: Statement) => false | any; - ExpressionStatement?: (node: ExpressionStatement) => false | any; - IfStatement?: (node: IfStatement) => false | any; - WhileStatement?: (node: WhileStatement) => false | any; - SimpleStatement?: (node: SimpleStatement) => false | any; - ForStatement?: (node: ForStatement) => false | any; - InlineAssemblyStatement?: (node: InlineAssemblyStatement) => false | any; - DoWhileStatement?: (node: DoWhileStatement) => false | any; - ContinueStatement?: (node: ContinueStatement) => false | any; - BreakStatement?: (node: BreakStatement) => false | any; - ReturnStatement?: (node: ReturnStatement) => false | any; - ThrowStatement?: (node: ThrowStatement) => false | any; - VariableDeclarationStatement?: (node: VariableDeclarationStatement) => false | any; - IdentifierList?: (node: IdentifierList) => false | any; - ElementaryTypeName?: (node: ElementaryTypeName) => false | any; - Expression?: (node: Expression) => false | any; - PrimaryExpression?: (node: PrimaryExpression) => false | any; - ExpressionList?: (node: ExpressionList) => false | any; - NameValueList?: (node: NameValueList) => false | any; - NameValue?: (node: NameValue) => false | any; - FunctionCallArguments?: (node: FunctionCallArguments) => false | any; - AssemblyBlock?: (node: AssemblyBlock) => false | any; - AssemblyItem?: (node: AssemblyItem) => false | any; - AssemblyExpression?: (node: AssemblyExpression) => false | any; - AssemblyCall?: (node: AssemblyCall) => false | any; - AssemblyLocalDefinition?: (node: AssemblyLocalDefinition) => false | any; - AssemblyAssignment?: (node: AssemblyAssignment) => false | any; - AssemblyIdentifierOrList?: (node: AssemblyIdentifierOrList) => false | any; - AssemblyIdentifierList?: (node: AssemblyIdentifierList) => false | any; - AssemblyStackAssignment?: (node: AssemblyStackAssignment) => false | any; - LabelDefinition?: (node: LabelDefinition) => false | any; - AssemblySwitch?: (node: AssemblySwitch) => false | any; - AssemblyCase?: (node: AssemblyCase) => false | any; - AssemblyFunctionDefinition?: (node: AssemblyFunctionDefinition) => false | any; - AssemblyFunctionReturns?: (node: AssemblyFunctionReturns) => false | any; - AssemblyFor?: (node: AssemblyFor) => false | any; - AssemblyIf?: (node: AssemblyIf) => false | any; - AssemblyLiteral?: (node: AssemblyLiteral) => false | any; - SubAssembly?: (node: SubAssembly) => false | any; - TupleExpression?: (node: TupleExpression) => false | any; - ElementaryTypeNameExpression?: (node: ElementaryTypeNameExpression) => false | any; - NumberLiteral?: (node: NumberLiteral) => false | any; - Identifier?: (node: Identifier) => false | any; - BinaryOperation?: (node: BinaryOperation) => false | any; - Conditional?: (node: Conditional) => false | any; + SourceUnit?: (node: SourceUnit) => any; + PragmaDirective?: (node: PragmaDirective) => any; + PragmaName?: (node: PragmaName) => any; + PragmaValue?: (node: PragmaValue) => any; + Version?: (node: Version) => any; + VersionOperator?: (node: VersionOperator) => any; + VersionConstraint?: (node: VersionConstraint) => any; + ImportDeclaration?: (node: ImportDeclaration) => any; + ImportDirective?: (node: ImportDirective) => any; + ContractDefinition?: (node: ContractDefinition) => any; + InheritanceSpecifier?: (node: InheritanceSpecifier) => any; + ContractPart?: (node: ContractPart) => any; + StateVariableDeclaration?: (node: StateVariableDeclaration) => any; + UsingForDeclaration?: (node: UsingForDeclaration) => any; + StructDefinition?: (node: StructDefinition) => any; + ModifierDefinition?: (node: ModifierDefinition) => any; + ModifierInvocation?: (node: ModifierInvocation) => any; + FunctionDefinition?: (node: FunctionDefinition) => any; + ReturnParameters?: (node: ReturnParameters) => any; + ModifierList?: (node: ModifierList) => any; + EventDefinition?: (node: EventDefinition) => any; + EnumValue?: (node: EnumValue) => any; + EnumDefinition?: (node: EnumDefinition) => any; + ParameterList?: (node: ParameterList) => any; + Parameter?: (node: Parameter) => any; + EventParameterList?: (node: EventParameterList) => any; + EventParameter?: (node: EventParameter) => any; + FunctionTypeParameterList?: (node: FunctionTypeParameterList) => any; + FunctionTypeParameter?: (node: FunctionTypeParameter) => any; + VariableDeclaration?: (node: VariableDeclaration) => any; + TypeName?: (node: TypeName) => any; + UserDefinedTypeName?: (node: UserDefinedTypeName) => any; + Mapping?: (node: Mapping) => any; + FunctionTypeName?: (node: FunctionTypeName) => any; + StorageLocation?: (node: StorageLocation) => any; + StateMutability?: (node: StateMutability) => any; + Block?: (node: Block) => any; + Statement?: (node: Statement) => any; + ExpressionStatement?: (node: ExpressionStatement) => any; + IfStatement?: (node: IfStatement) => any; + WhileStatement?: (node: WhileStatement) => any; + SimpleStatement?: (node: SimpleStatement) => any; + ForStatement?: (node: ForStatement) => any; + InlineAssemblyStatement?: (node: InlineAssemblyStatement) => any; + DoWhileStatement?: (node: DoWhileStatement) => any; + ContinueStatement?: (node: ContinueStatement) => any; + BreakStatement?: (node: BreakStatement) => any; + ReturnStatement?: (node: ReturnStatement) => any; + ThrowStatement?: (node: ThrowStatement) => any; + VariableDeclarationStatement?: (node: VariableDeclarationStatement) => any; + IdentifierList?: (node: IdentifierList) => any; + ElementaryTypeName?: (node: ElementaryTypeName) => any; + Expression?: (node: Expression) => any; + PrimaryExpression?: (node: PrimaryExpression) => any; + ExpressionList?: (node: ExpressionList) => any; + NameValueList?: (node: NameValueList) => any; + NameValue?: (node: NameValue) => any; + FunctionCallArguments?: (node: FunctionCallArguments) => any; + AssemblyBlock?: (node: AssemblyBlock) => any; + AssemblyItem?: (node: AssemblyItem) => any; + AssemblyExpression?: (node: AssemblyExpression) => any; + AssemblyCall?: (node: AssemblyCall) => any; + AssemblyLocalDefinition?: (node: AssemblyLocalDefinition) => any; + AssemblyAssignment?: (node: AssemblyAssignment) => any; + AssemblyIdentifierOrList?: (node: AssemblyIdentifierOrList) => any; + AssemblyIdentifierList?: (node: AssemblyIdentifierList) => any; + AssemblyStackAssignment?: (node: AssemblyStackAssignment) => any; + LabelDefinition?: (node: LabelDefinition) => any; + AssemblySwitch?: (node: AssemblySwitch) => any; + AssemblyCase?: (node: AssemblyCase) => any; + AssemblyFunctionDefinition?: (node: AssemblyFunctionDefinition) => any; + AssemblyFunctionReturns?: (node: AssemblyFunctionReturns) => any; + AssemblyFor?: (node: AssemblyFor) => any; + AssemblyIf?: (node: AssemblyIf) => any; + AssemblyLiteral?: (node: AssemblyLiteral) => any; + SubAssembly?: (node: SubAssembly) => any; + TupleExpression?: (node: TupleExpression) => any; + ElementaryTypeNameExpression?: (node: ElementaryTypeNameExpression) => any; + NumberLiteral?: (node: NumberLiteral) => any; + Identifier?: (node: Identifier) => any; + BinaryOperation?: (node: BinaryOperation) => any; + Conditional?: (node: Conditional) => any; } export interface ParserOpts { tolerant?: boolean; From ff55e4fa68a0210ae726a49c640632388d531eb7 Mon Sep 17 00:00:00 2001 From: Laurent Senta <laurent.senta@gmail.com> Date: Mon, 11 Feb 2019 15:21:00 +0100 Subject: [PATCH 189/197] react-avatar-editor: add optional className field --- types/react-avatar-editor/index.d.ts | 2 ++ types/react-avatar-editor/react-avatar-editor-tests.tsx | 1 + 2 files changed, 3 insertions(+) diff --git a/types/react-avatar-editor/index.d.ts b/types/react-avatar-editor/index.d.ts index c2aebc5e63..3d4135120c 100644 --- a/types/react-avatar-editor/index.d.ts +++ b/types/react-avatar-editor/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/mosch/react-avatar-editor // Definitions by: Diogo Corrêa <https://github.com/diogocorrea> // Gabriel Prates <https://github.com/gabsprates> +// Laurent Senta <https://github.com/lsenta> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -23,6 +24,7 @@ export interface CroppedRect { } export interface AvatarEditorProps { + className?: string; image: string | File; width?: number; height?: number; diff --git a/types/react-avatar-editor/react-avatar-editor-tests.tsx b/types/react-avatar-editor/react-avatar-editor-tests.tsx index 3abf24aae3..bee4ff6a56 100644 --- a/types/react-avatar-editor/react-avatar-editor-tests.tsx +++ b/types/react-avatar-editor/react-avatar-editor-tests.tsx @@ -25,6 +25,7 @@ class AvatarEditorTest extends React.Component { <div> <AvatarEditor image="" /> <AvatarEditor image={file} /> + <AvatarEditor image="" className="helloworld" /> <AvatarEditor image="" width={1} /> <AvatarEditor image="" height={1} /> <AvatarEditor image="" border={1} /> From a12c36639a7afa948a88648356f16a8dd8a84bde Mon Sep 17 00:00:00 2001 From: Roman Vyakhirev <roman.vyakhirev@mendix.com> Date: Mon, 11 Feb 2019 15:35:24 +0100 Subject: [PATCH 190/197] Include missing props for TabBar, align sort order with documentation --- types/react-native-tab-view/index.d.ts | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/types/react-native-tab-view/index.d.ts b/types/react-native-tab-view/index.d.ts index 8118239f8a..a6e6b27735 100644 --- a/types/react-native-tab-view/index.d.ts +++ b/types/react-native-tab-view/index.d.ts @@ -202,20 +202,25 @@ export type IndicatorProps< export type TabBarProps<T extends RouteBase = RouteBase> = SceneRendererProps< T > & { - scrollEnabled?: boolean + getLabelText?: (scene: Scene<T>) => string | undefined | null + getAccessible?: (scene: Scene<T>) => boolean + getAccessibilityLabel?: (scene: Scene<T>) => string | undefined | null + getTestID?: (scene: Scene<T>) => string | undefined | null + renderIcon?: (scene: Scene<T>) => ReactNode + renderLabel?: (scene: Scene<T>) => ReactNode + renderIndicator?: (props: IndicatorProps<T>) => ReactNode + renderBadge?: (scene: Scene<T>) => ReactNode + onTabPress?: (scene: Scene<T>) => void + onTabLongPress?: (scene: Scene<T>) => void pressColor?: string pressOpacity?: number - getLabelText?: (scene: Scene<T>) => string | undefined | null - renderLabel?: (scene: Scene<T>) => ReactNode - renderIcon?: (scene: Scene<T>) => ReactNode - renderBadge?: (scene: Scene<T>) => ReactNode - renderIndicator?: (props: IndicatorProps<T>) => ReactNode - onTabPress?: (scene: Scene<T>) => void + scrollEnabled?: boolean + bounces?: boolean + useNativeDriver?: boolean; tabStyle?: StyleProp<ViewStyle> indicatorStyle?: StyleProp<ViewStyle> labelStyle?: StyleProp<ViewStyle> style?: StyleProp<ViewStyle> - useNativeDriver?: boolean; } export class TabBar<T extends Route = Route> extends PureComponent<TabBarProps<T>> {} From ca5bde36c398dcd83933e085af75178ef0e889bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joa=CC=83o=20Vieira?= <joaoguerravieira@gmail.com> Date: Mon, 11 Feb 2019 15:03:09 +0000 Subject: [PATCH 191/197] Remove buildManifest from renderPage response for Next.js 8. --- types/next/document.d.ts | 7 +++++-- types/next/index.d.ts | 2 +- types/next/test/next-document-tests.tsx | 8 +++++--- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/types/next/document.d.ts b/types/next/document.d.ts index d0e6d2c91b..3933d8c117 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -2,10 +2,13 @@ import * as React from "react"; import { NextContext, NextComponentType } from "."; import { DefaultQuery } from "./router"; +/** + * Result from renderPage(). + * https://github.com/zeit/next.js/blob/v8.0.0/packages/next/pages/_document.js#L18 + */ export interface RenderPageResponse { - buildManifest: Record<string, any>; html?: string; - head?: Array<React.ReactElement<any>>; + head?: React.ReactNode; } export interface PageProps { diff --git a/types/next/index.d.ts b/types/next/index.d.ts index 8d911ab2c1..73d3d70800 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for next 7.0 +// Type definitions for next 8.0 // Project: https://github.com/zeit/next.js/packages/next // Definitions by: Drew Hays <https://github.com/dru89> // Brice BERNARD <https://github.com/brikou> diff --git a/types/next/test/next-document-tests.tsx b/types/next/test/next-document-tests.tsx index 1cd217a749..d5be842c4c 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -48,7 +48,7 @@ class MyDoc extends Document<WithUrlProps> { // with app and component enhancers const enhanceApp: Enhancer<PageProps, {}> = App => props => <App />; const enhanceComponent: Enhancer<PageProps, {}> = Component => props => <Component />; - const { html, head, buildManifest } = renderPage({ + const { html, head } = renderPage({ enhanceApp, enhanceComponent }); @@ -60,7 +60,7 @@ class MyDoc extends Document<WithUrlProps> { // Custom prop const url = req!.url; - return { html, head, buildManifest, styles, url }; + return { html, head, styles, url }; } constructor(props: WithUrlProps & DocumentProps) { @@ -73,12 +73,14 @@ class MyDoc extends Document<WithUrlProps> { render() { const { pathname, query } = this.props.__NEXT_DATA__; + const { head, styles } = this.props; return ( <html> <Head nonce="nonce" any="property" should="work" here> + {head} <title>My page - {this.props.styles} + {styles}
From 2381e666ff8959731ca8ebd355ebdc934c74bc60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joa=CC=83o=20Vieira?= Date: Mon, 11 Feb 2019 15:18:55 +0000 Subject: [PATCH 192/197] Add more specific links for reference. --- types/next/document.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/next/document.d.ts b/types/next/document.d.ts index 3933d8c117..4ccd54ad64 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -5,6 +5,8 @@ import { DefaultQuery } from "./router"; /** * Result from renderPage(). * https://github.com/zeit/next.js/blob/v8.0.0/packages/next/pages/_document.js#L18 + * https://github.com/zeit/next.js/blob/v8.0.0/packages/next-server/server/render.tsx#L159 + * https://github.com/zeit/next.js/blob/v8.0.0/packages/next-server/server/render.tsx#L44 */ export interface RenderPageResponse { html?: string; From 5bfd2436a79d6123a3ac5840e93cc5e60c527937 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joa=CC=83o=20Vieira?= Date: Mon, 11 Feb 2019 15:40:56 +0000 Subject: [PATCH 193/197] Allow Document styles to be a ReactNode again. --- types/next/document.d.ts | 4 ++-- types/next/test/next-document-tests.tsx | 7 ++++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/types/next/document.d.ts b/types/next/document.d.ts index 4ccd54ad64..f89e5d71e0 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -36,7 +36,7 @@ export interface NextDocumentContext exte E extends PageProps = AnyPageProps, P = E, EA extends PageProps = AnyPageProps, - PA = EA, + PA = EA >( enhancer?: | Enhancer // tslint:disable-line no-unnecessary-generics @@ -49,7 +49,7 @@ export interface NextDocumentContext exte * https://github.com/zeit/next.js/blob/7.0.0/server/document.js#L16 */ export interface DefaultDocumentIProps extends RenderPageResponse { - styles?: React.ReactNode[]; + styles?: React.ReactNode; } /** diff --git a/types/next/test/next-document-tests.tsx b/types/next/test/next-document-tests.tsx index d5be842c4c..7c50a03930 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -55,7 +55,12 @@ class MyDoc extends Document { const initialProps = await Document.getInitialProps(ctx); - const styles = [...(initialProps.styles ? initialProps.styles : []),