diff --git a/README.md b/README.md index bbf2a6f16e..746d9d9f3e 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 `` or an import? @@ -327,14 +327,60 @@ 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 [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: + +```js +// Type definitions for Node.js 10.12 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// 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 `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. +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 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: + +#### 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 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 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 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 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 [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`. +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 { @@ -352,10 +398,11 @@ 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 updated to the latest version. Also, `/// ` will not work with path mapping, so dependencies must use `import`. diff --git a/notNeededPackages.json b/notNeededPackages.json index 701978da24..f073197bf9 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -564,12 +564,24 @@ "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", "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.1" + }, { "libraryName": "fecha", "typingsPackageName": "fecha", 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 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// -/// 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, logger: Logger, options: Option): Acl; - new (backend: Backend, logger: Logger): Acl; - new (backend: Backend): Acl; - memoryBackend: MemoryBackendStatic; + new ( + backend: AclStatic.Backend, + 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; - removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise; - userRoles: (userId: Value, cb?: (err: Error, roles: string[]) => any) => Promise; - roleUsers: (role: Value, cb?: (err: Error, users: Values) => any) => Promise; - hasRole: (userId: Value, role: string, cb?: (err: Error, isInRole: boolean) => any) => Promise; - addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise; - removeRole: (role: string, cb?: Callback) => Promise; - removeResource: (resource: string, cb?: Callback) => Promise; - allow: { - (roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise; - (aclSets: AclSet | AclSet[]): Promise; +declare namespace AclStatic { + interface Logger { + debug: (msg: string) => any; } - removeAllow: (role: string, resources: strings, permissions: strings, cb?: Callback) => Promise; - removePermissions: (role: string, resources: strings, permissions: strings, cb?: Function) => Promise; - allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise; - isAllowed: (userId: Value, resources: strings, permissions: strings, cb?: AllowedCallback) => Promise; - areAnyRolesAllowed: (roles: strings, resource: strings, permissions: strings, cb?: AllowedCallback) => Promise; - whatResources: { - (roles: strings, cb?: AnyCallback): Promise; - (roles: strings, permissions: strings, cb?: AnyCallback): Promise; + + interface Acl { + addUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise; + removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise; + userRoles: (userId: Value, cb?: (err: Error, roles: string[]) => any) => Promise; + roleUsers: (role: Value, cb?: (err: Error, users: Values) => any) => Promise; + hasRole: ( + userId: Value, + role: string, + cb?: (err: Error, isInRole: boolean) => any + ) => Promise; + addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise; + removeRole: (role: string, cb?: Callback) => Promise; + removeResource: (resource: string, cb?: Callback) => Promise; + allow: { + (roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise; + (aclSets: AclSet | AclSet[]): Promise; + }; + removeAllow: ( + role: string, + resources: strings, + permissions: strings, + cb?: Callback + ) => Promise; + removePermissions: ( + role: string, + resources: strings, + permissions: strings, + cb?: Callback + ) => Promise; + allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise; + isAllowed: ( + userId: Value, + resources: strings, + permissions: strings, + cb?: AllowedCallback + ) => Promise; + areAnyRolesAllowed: ( + roles: strings, + resource: strings, + permissions: strings, + cb?: AllowedCallback + ) => Promise; + whatResources: { + (roles: strings, cb?: AnyCallback): Promise; + (roles: strings, permissions: strings, cb?: AnyCallback): Promise; + }; + permittedResources: (roles: strings, permissions: strings, cb?: Callback) => Promise; + 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 {} + interface MemoryBackendStatic { + new (): MemoryBackend; + } + + // + // For internal use + // + interface Backend { + 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; + getAsync: ( + bucket: string, + key: Value, + cb?: (err: Error | null, value: any) => void + ) => Promise; + cleanAsync: (cb?: (error?: Error) => void) => Promise; + unionAsync: ( + bucket: string, + keys: Value[], + cb?: (error: Error | undefined, results: any[]) => void + ) => Promise; + } + + 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 {} + interface RedisBackendStatic { + new (redis: redis.RedisClient, prefix?: string): RedisBackend; + } + + // for mongodb backend + interface MongodbBackend extends Backend {} + interface MongodbBackendStatic { + new (db: mongo.Db, prefix?: string, useSingle?: boolean): MongodbBackend; } - permittedResources: (roles: strings, permissions: strings, cb?: Function) => Promise; - 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 { } -interface MemoryBackendStatic { - new (): MemoryBackend; -} - -// -// For internal use -// -interface Backend { - 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 { } -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 { } -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 = (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" } 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) 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; + const ngStringPromise: ng.IPromise = + promiseInterop.then((num) => Promise.resolve(String(num))); + const caughtStringPromise: ng.IPromise = + 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( + successCallback?: + | ((value: T) => PromiseLike | PromiseLike | TResult1) + | null, + errorCallback?: + | ((reason: any) => PromiseLike | PromiseLike | TResult2) + | null, + notifyCallback?: (state: any) => any + ): IPromise; then( successCallback?: | ((value: T) => IPromise | IPromise | TResult1) @@ -1210,6 +1219,11 @@ declare namespace angular { /** * Shorthand for promise.then(null, errorCallback) */ + catch( + onRejected?: + | ((reason: any) => PromiseLike | PromiseLike | TResult) + | null + ): IPromise; catch( onRejected?: | ((reason: any) => IPromise | IPromise | 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 +} 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 // James Gregory // Erik Dalén +// Loïk Gaonac'h // 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" 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; +declare let promiseParamsResult: Promise; +declare let promiseParamsByPathResult: Promise; +declare let promiseAllParamResults: Promise; + +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 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import { SSM } from 'aws-sdk'; + +export function getParameter( + name: SSM.Types.PSParameterName, + options?: SSM.Types.ClientConfiguration +): Promise; + +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; + +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; + +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; + 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/fastify-cors/tslint.json b/types/aws-param-store/tslint.json similarity index 100% rename from types/fastify-cors/tslint.json rename to types/aws-param-store/tslint.json 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 +// Julian Gonggrijp // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// -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):void; + setRelated(related:Collection):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):void; + setKeyContents(keyContents:Collection):void; - onChange(model:Model, attr:any, options:any):void; + onChange(model:BModel, attr:any, options:any):void; - handleAddition(model:Model, coll:Collection, options:any):void; + handleAddition(model:BModel, coll:Collection, options:any):void; - handleRemoval(model:Model, coll:Collection, options:any):void; + handleRemoval(model:BModel, coll:Collection, options:any):void; - handleReset(coll:Collection, options:any):void; + handleReset(coll:Collection, 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; + retroFitRelation(relation:Model, create:boolean):Collection; - getCollection(type:RelationalModel, create:boolean):Collection; + getCollection(type:Model, create:boolean):Collection; 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, options:any):void; + unregister(model:Model, collection:Collection, options:any):void; reset():void; diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index bbafa0301c..aab2385ea4 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; + + /** + * Get job properties as Json Object + */ + toJSON(): { + id: JobId, + name: string, + data: T, + opts: JobOptions, + progress: number, + delay: number, + timestamp: number, + attemptsMade: number, + failedReason: any, + stacktrace: string[] | null, + returnvalue: any, + finishedOn: number | null, + processedOn: number | null + }; } type JobStatus = 'completed' | 'waiting' | 'active' | 'delayed' | 'failed'; 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 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// +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/fastify-cors/tsconfig.json b/types/bunyan-seq/tsconfig.json similarity index 93% rename from types/fastify-cors/tsconfig.json rename to types/bunyan-seq/tsconfig.json index 9e696b42e2..bd77368148 100644 --- a/types/fastify-cors/tsconfig.json +++ b/types/bunyan-seq/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "fastify-cors-tests.ts" + "bunyan-seq-tests.ts" ] } diff --git a/types/fastify-static/tslint.json b/types/bunyan-seq/tslint.json similarity index 100% rename from types/fastify-static/tslint.json rename to types/bunyan-seq/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 +// 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" } 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 +// 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" } diff --git a/types/carbon__motion/carbon__motion-tests.ts b/types/carbon__motion/carbon__motion-tests.ts new file mode 100644 index 0000000000..6bcc820f5d --- /dev/null +++ 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 new file mode 100644 index 0000000000..173687d04c --- /dev/null +++ b/types/carbon__motion/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for @carbon/motion 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/motion +// Definitions by: Vince Picone +// 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: string, mode: string): string; + +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" } 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 +// 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" } diff --git a/types/carbon__type/carbon__type-tests.ts b/types/carbon__type/carbon__type-tests.ts new file mode 100644 index 0000000000..a5d4cf7b8b --- /dev/null +++ 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 new file mode 100644 index 0000000000..7933f2e358 --- /dev/null +++ b/types/carbon__type/index.d.ts @@ -0,0 +1,726 @@ +// Type definitions for @carbon/type 0.0 +// Project: https://github.com/IBM/carbon-elements/tree/master/packages/type +// Definitions by: Vince Picone +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +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: string +): { + fontFamily: string; +}; + +export function fontWeight( + weight: string +): { + fontWeight: number; +}; + +export function getTypeSize(step: number): number; + +export function print(block: object): string; + +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" } 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 = 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"); diff --git a/types/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index 02853c66ba..18527ed8c5 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; } - 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 { @@ -499,8 +485,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 +595,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 +607,6 @@ export interface Host extends events.EventEmitter { isUp(): boolean; } -export interface HostMapStatic { - new (): HostMap; -} - export interface HostMap extends events.EventEmitter { length: number; @@ -742,19 +718,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; @@ -766,10 +733,6 @@ export namespace metadata { stateType: string; } - interface ClientStateStatic { - new (): ClientState; - } - interface ClientState { getConnectedHosts(): Host[]; getInFlightQueries(host: Host): number; @@ -822,13 +785,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; @@ -840,11 +796,19 @@ export namespace metadata { isKeysKind(): boolean; } - interface MaterializedViewStatic { - new (name: string): MaterializedView; + interface MaterializedView extends DataCollection { } + + 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 }>; } - interface MaterializedView extends DataCollection { } + type MetadataCallback = (err: any, retVal: T) => void; interface MetadataStatic { new (options: ClientOptions, controlConnection: any): Metadata; @@ -853,21 +817,34 @@ 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): void; + getAggregate(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>): Promise; + getAggregates(keyspaceName: string, name: string, callback: MetadataCallback): void; + getAggregates(keyspaceName: string, name: string): Promise; + getFunction(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: MetadataCallback): void; + getFunction(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>): Promise; + getFunctions(keyspaceName: string, name: string, callback: MetadataCallback): void; + getFunctions(keyspaceName: string, name: string): Promise; + getMaterializedView(keyspaceName: string, name: string, callback: MetadataCallback): void; + getMaterializedView(keyspaceName: string, name: string, callback: Callback): Promise; + getReplicas(keyspaceName: string, token: Buffer | token.Token | token.TokenRange): any[]; // TODO + getTable(keyspaceName: string, name: string, callback: MetadataCallback): void; + getTable(keyspaceName: string, name: string): Promise; + getTokenRanges(): Set; + getTokenRangesForHost(keyspaceName: string, host: Host): Set | null; + getTrace(traceId: types.Uuid, consistency: types.consistencies, callback: MetadataCallback): void; + getTrace(traceId: types.Uuid, consistency: types.consistencies, callback: Callback): Promise; + getTrace(traceId: types.Uuid, callback: MetadataCallback): void; + getTrace(traceId: types.Uuid): Promise; + getUdt(keyspaceName: string, name: string, callback: MetadataCallback): void; // TODO + getUdt(keyspaceName: string, name: string): Promise; // TODO + 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; + refreshKeyspaces(waitReconnect: boolean, callback: Callback): void; + refreshKeyspaces(waitReconnect?: boolean): Promise; + refreshKeyspaces(callback: Callback): void; } interface SchemaFunction { @@ -882,10 +859,6 @@ export namespace metadata { signature: string[]; } - interface TableMetadataStatic { - new (name: string): TableMetadata; - } - interface TableMetadata extends DataCollection { indexes: Index[]; indexInterval?: number; @@ -927,6 +900,7 @@ export interface ExecutionOptions { } export let ExecutionOptions: ExecutionOptionsStatic; +export let ExecutionProfile: ExecutionProfileStatic; export namespace mapping { let Mapper: MapperStatic; @@ -1136,3 +1110,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 function defaultOptions(): ClientOptions; +export const version: string; 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; diff --git a/types/color-support/color-support-tests.ts b/types/color-support/color-support-tests.ts new file mode 100644 index 0000000000..45bb6317cf --- /dev/null +++ b/types/color-support/color-support-tests.ts @@ -0,0 +1,48 @@ +import colorSupport = require('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 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +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" } 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..563ca925c3 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 +// Type definitions for D3JS d3-force module 1.2 // Project: https://github.com/d3/d3-force/ -// Definitions by: Tom Wanzek , Alex Ford , Boris Yankov +// Definitions by: Tom Wanzek +// Alex Ford +// Boris Yankov +// 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 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); -var error:debug.IDebugger = debug("DefinitelyTyped:error"); +const error: debug1.Debugger = debug1("DefinitelyTyped:error"); error.log = console.error.bind(console); error("This should be printed to stderr"); -var extendedLog: debug.IDebugger = log.extend('extended'); +const extendedLog: debug1.Debugger = 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: debug1.Debugger = log.extend('with-delim', '.'); +extendedWithCustomDelimiter("Testing this is an IDebugger, too."); diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index 2eca1c8fb8..2067b27222 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -1,40 +1,45 @@ -// 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; +declare var debug: debug.Debug & {debug: debug.Debug, default: debug.Debug}; 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): 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 + type IDebug = Debug; + + interface Formatters { + [formatter: string]: (v: any) => string; } - export interface IDebugger { + type IDebugger = Debugger; + + interface Debugger { (formatter: any, ...args: any[]): void; enabled: boolean; - log: Function; + log: (v: any) => string; namespace: string; - extend: (namespace: string, delimiter?: string) => debug.IDebugger; + extend: (namespace: string, delimiter?: string) => Debugger; } } 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" } 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; 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: { 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 { 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 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 -// 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-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, { - 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 -// 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 { - sendFile(filename: string): FastifyReply; - } -} - -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/feathersjs__errors/index.d.ts b/types/feathersjs__errors/index.d.ts index 056acff676..3994e2056c 100644 --- a/types/feathersjs__errors/index.d.ts +++ b/types/feathersjs__errors/index.d.ts @@ -1,11 +1,26 @@ -// Type definitions for @feathersjs/errors 3.2 +// Type definitions for @feathersjs/errors 3.3 // Project: http://feathersjs.com/ // Definitions by: Jan Lohage +// RazzM13 // 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 { - constructor(msg: string | Error, name: string, code: number, className: string, data: 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); + toJSON(): FeathersErrorJSON; } export class BadRequest extends FeathersError { diff --git a/types/generic-pool/generic-pool-tests.ts b/types/generic-pool/generic-pool-tests.ts index 28590def30..09a46ccf84 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 6bb537e9ba..14fea9497f 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; 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..f6174543eb --- /dev/null +++ b/types/giphy-api/index.d.ts @@ -0,0 +1,177 @@ +// Type definitions for giphy-api 2.0 +// Project: https://github.com/austinkelleher/giphy-api +// Definitions by: Christian Rackerseder +// 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: string; + id: string; + slug: string; + 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; + 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; + fixed_height_downsampled: BaseImage & { + size: string; + webp: string; + webp_size: string; + }; + fixed_width: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + original_still: BaseImage; + fixed_width_still: BaseImage; + fixed_width_downsampled: BaseImage & { + size: string; + webp: string; + webp_size: string; + }; + fixed_height_small: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + fixed_height_small_still: BaseImage; + fixed_width_small: BaseImage & { + size: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + fixed_width_small_still: BaseImage; + downsized: BaseImage & { + size: string; + }; + downsized_still: BaseImage; + downsized_large: BaseImage & { + size: string; + }; + downsized_medium: BaseImage & { + size: string; + }; + downsized_small: BaseImage & { + size: string; + }; + original: BaseImage & { + size: string; + frames: string; + mp4: string; + mp4_size: string; + webp: string; + webp_size: string; + }; + looping: { mp4: string; }; + preview: { + width: string; + height: string; + mp4: string; + mp4_size: string; + }; + preview_gif: BaseImage & { + size: 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; + id(ids: string | string[], cb: Callback): void; + id(ids: string | string[]): Promise; + translate(termOrOptions: string | TranslateOptions, cb: Callback): void; + translate(termOrOptions: string | TranslateOptions): Promise; + random(tagOrOptions: string | RandomOptions, cb: Callback): void; + random(tagOrOptions: string | RandomOptions): Promise; + trending(options: TrendingOptions, cb: Callback): void; + trending(cb: Callback): void; + trending(options?: TrendingOptions): Promise; +} + +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" } 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..0f3a9dcc78 --- /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|undefined) => 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|undefined) => 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/fastify-static/tsconfig.json b/types/hexo/tsconfig.json similarity index 65% rename from types/fastify-static/tsconfig.json rename to types/hexo/tsconfig.json index bdfa7d40c6..6e37a832a0 100644 --- a/types/fastify-static/tsconfig.json +++ b/types/hexo/tsconfig.json @@ -1,16 +1,23 @@ { "compilerOptions": { "module": "commonjs", - "lib": ["es6"], + "lib": [ + "es6" + ], "noImplicitAny": true, "noImplicitThis": true, - "strictFunctionTypes": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", - "typeRoots": ["../"], + "typeRoots": [ + "../" + ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, - "files": ["index.d.ts", "fastify-static-tests.ts"] + "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 + } + +} diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index 6beeccb08f..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. @@ -296,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 */ @@ -311,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; } @@ -335,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 { @@ -350,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 01ab0c6fc4..a2c89cb893 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); @@ -259,3 +259,30 @@ 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) => { + if (!obj || !obj.common) return; + if (obj.common.custom) { + const test1: ioBroker.StateCommon = obj.common; + } + obj + && obj.common + && 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) => { }); +} diff --git a/types/irc/index.d.ts b/types/irc/index.d.ts index a7b163ca6e..6c222c428d 100644 --- a/types/irc/index.d.ts +++ b/types/irc/index.d.ts @@ -8,8 +8,8 @@ /** This library provides IRC client functionality. */ import events = require('events'); -import crypto = require('crypto'); import net = require('net'); +import tls = require('tls'); /** This library provides IRC client functionality. */ declare namespace NodeIRC { @@ -287,7 +287,7 @@ declare namespace NodeIRC { * Should SSL be used? Can either be true or crypto credentials. * @default false */ - secure?: boolean | crypto.Credentials; + secure?: boolean | tls.SecureContext; /** * Should we accept self-signed certificates? diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 840d9b7fa0..d66e509c83 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -213,9 +213,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). @@ -238,6 +238,9 @@ declare namespace jest { type ArgsType<T> = T extends (...args: infer A) => any ? A : never; type RejectedValue<T> = T extends PromiseLike<any> ? any : never; type ResolvedValue<T> = T extends PromiseLike<infer U> ? U | T : 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 DoneCallback { (...args: any[]): any; diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index 00ccd38106..15702d45a4 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(() => "") diff --git a/types/jscodeshift/index.d.ts b/types/jscodeshift/index.d.ts new file mode 100644 index 0000000000..e19423d928 --- /dev/null +++ b/types/jscodeshift/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for jscodeshift 0.6 +// Project: https://github.com/facebook/jscodeshift#readme +// Definitions by: Brie Bunge <https://github.com/brieb> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import core = require("./src/core"); + +export = core; diff --git a/types/jscodeshift/package.json b/types/jscodeshift/package.json new file mode 100644 index 0000000000..a501c0f28d --- /dev/null +++ b/types/jscodeshift/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "dependencies": { + "ast-types": "0.12.1", + "recast": "0.17.2" + } +} diff --git a/types/jscodeshift/src/Collection.d.ts b/types/jscodeshift/src/Collection.d.ts new file mode 100644 index 0000000000..2cab87b153 --- /dev/null +++ b/types/jscodeshift/src/Collection.d.ts @@ -0,0 +1,131 @@ +import recast = require("recast"); +import JSXElement = require("./collections/JSXElement"); +import NodeCollection = require("./collections/Node"); +import VariableDeclarator = require("./collections/VariableDeclarator"); + +type ASTPath<N> = recast.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<recast.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 = recast.ASTNode>( + callback: ( + path: ASTPath<N>, + i: number, + paths: Array<ASTPath<N>> + ) => ASTPath<T> | Array<ASTPath<T>> | null | undefined, + type: recast.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?: recast.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: 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 + * 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?: recast.Type<any>): void; + +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 new file mode 100644 index 0000000000..0490e40f76 --- /dev/null +++ b/types/jscodeshift/src/collections/JSXElement.d.ts @@ -0,0 +1,71 @@ +import nodes = require("ast-types/gen/nodes"); +import recast = require("recast"); +import Collection = require("../Collection"); + +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.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.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.Collection<JSXElementChild>; + + /** + * Returns all children that are JSXElements. + * This method only applies to JSXElement typed collections. + */ + childElements(): Collection.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 {}; // 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..d1e74f314d --- /dev/null +++ b/types/jscodeshift/src/collections/Node.d.ts @@ -0,0 +1,57 @@ +import nodes = require("ast-types/gen/nodes"); +import recast = require("recast"); +import Collection = require("../Collection"); + +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: 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.Collection<nodes.ASTNode>; + + /** + * Traverse the AST up and finds the closest node of the provided type. + */ + 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 falsy value, the element is skipped. + */ + getVariableDeclarators(nameGetter: (...args: any[]) => any): Collection.Collection<nodes.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.Collection<T>; + + /** + * Inserts a new node before the current one. + */ + insertBefore(insert: any): Collection.Collection<N>; + + /** + * Inserts a new node after the current one. + */ + insertAfter(insert: any): Collection.Collection<N>; + + remove(): Collection.Collection<N>; +} + +export function register(): void; + +export {}; // 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..eb7c8bcdfd --- /dev/null +++ b/types/jscodeshift/src/collections/VariableDeclarator.d.ts @@ -0,0 +1,39 @@ +import nodes = require("ast-types/gen/nodes"); +import recast = require("recast"); +import Collection = require("../Collection"); + +type ASTPath<N> = recast.NodePath<N, N>; + +export interface GlobalMethods { + /** + * Finds all variable declarators, optionally filtered by name. + */ + findVariableDeclarators(name?: string): Collection.Collection<nodes.VariableDeclarator>; +} + +export interface TransformMethods<N> { + /** + * Renames a variable and all its occurrences. + * This method only applies to VariableDeclarator typed collections. + */ + renameTo(newName: string): Collection.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 {}; // 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 new file mode 100644 index 0000000000..cfc0a3c543 --- /dev/null +++ b/types/jscodeshift/src/template.d.ts @@ -0,0 +1,18 @@ +import recast = require("recast"); + +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; + } +} 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 new file mode 100644 index 0000000000..1c6d8cda56 --- /dev/null +++ b/types/jscodeshift/test/js-transforms/bind-this-to-bind-expression.ts @@ -0,0 +1,25 @@ +/** + * This transform converts stuff like: + * + * let x = this.foo.bind(this); + * + * to + * + * let x = ::this.foo; + * + */ +import j = require("jscodeshift"); + +const transform: j.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") + // We can now replace it with ::this.xyz + .replaceWith(p => j.bindExpression(null, (p.value.callee as j.MemberExpression).object)) + .toSource(); +}; + +export = transform; 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 new file mode 100644 index 0000000000..09cdf3f29e --- /dev/null +++ b/types/jscodeshift/test/js-transforms/call-expression-bind-this-to-arrow-function-expression.ts @@ -0,0 +1,60 @@ +/** + * 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; + * + */ +import { Transform, MemberExpression, FunctionExpression, ArrowFunctionExpression } from "jscodeshift"; + +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") + .replaceWith(p => { + 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. + 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; + 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(object.params, body, useExpression); + }) + .toSource(); +}; 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 new file mode 100644 index 0000000000..b960c920cd --- /dev/null +++ b/types/jscodeshift/test/js-transforms/function-expression-to-arrow-function-expression.ts @@ -0,0 +1,53 @@ +/** + * 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; + * } + */ +import { Transform, ArrowFunctionExpression } from "jscodeshift"; + +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) + .replaceWith(p => { + 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; + 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 new file mode 100644 index 0000000000..db4caff58c --- /dev/null +++ b/types/jscodeshift/test/js-transforms/props-to-destructuring.ts @@ -0,0 +1,142 @@ +/** + * 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} /> + * } + * } + * + */ +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'; +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 = (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: { [name: string]: boolean } = {}; + + // Figure out if the variable was defined from props, so that we can re-use that definition. + const isFromProps = (name: string, resolvedScope: any) => { + return resolvedScope.getBindings()[name].every( + (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: 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')) + 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 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 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 as Identifier).name)) + // Now, do the replacement, `this.props.xyz` => `xyz`. + .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 => { + // 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; + // 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; + } + + // 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.ts b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts new file mode 100644 index 0000000000..6d1a30c378 --- /dev/null +++ b/types/jscodeshift/test/js-transforms/pure-to-composite-component.ts @@ -0,0 +1,64 @@ +/** 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>; + * } + * } + */ + +import { Transform, ASTNode } from "jscodeshift"; + +const transform: Transform = (file, api) => { + const j = api.jscodeshift; + const {statement} = j.template; + + function hasJSXElement(ast: ASTNode) { + 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.type === "VariableDeclarator" && decl.init != null) { + if (decl.init.type !== 'ArrowFunctionExpression' || + (!hasJSXElement(decl.init.body) && decl.init.body.type !== "JSXElement")) + return p.value; + + 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} } + }`; + } + }) + .toSource(); +}; diff --git a/types/jscodeshift/test/jscodeshift-tests.ts b/types/jscodeshift/test/jscodeshift-tests.ts new file mode 100644 index 0000000000..f426eb37b7 --- /dev/null +++ b/types/jscodeshift/test/jscodeshift-tests.ts @@ -0,0 +1,75 @@ +import { ASTNode, FileInfo, API, Transform, Parser } 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(); +}; + +// 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") { + // $ExpectType CatchClause + node; + + if (node.param && node.param.type === "Identifier") { + // $ExpectType Identifier + node.param; + + if ( + node.param.typeAnnotation && + node.param.typeAnnotation.type === "TSTypeAnnotation" + ) { + // $ExpectType TSTypeAnnotation + node.param.typeAnnotation; + + if (node.param.typeAnnotation.typeAnnotation.type === "TSArrayType") { + // $ExpectType TSArrayType + node.param.typeAnnotation.typeAnnotation; + } + } + } + } +} diff --git a/types/jscodeshift/tsconfig.json b/types/jscodeshift/tsconfig.json new file mode 100644 index 0000000000..5937bd483a --- /dev/null +++ b/types/jscodeshift/tsconfig.json @@ -0,0 +1,34 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "src/core.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", + "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" + ] +} diff --git a/types/jscodeshift/tslint.json b/types/jscodeshift/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/jscodeshift/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} 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..9d89c7c329 100644 --- a/types/katex/index.d.ts +++ b/types/katex/index.d.ts @@ -2,24 +2,28 @@ // 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 +// TypeScript Version: 2.1 + +/// <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 +36,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); + } +} diff --git a/types/kissfft-js/index.d.ts b/types/kissfft-js/index.d.ts new file mode 100644 index 0000000000..dc745354ec --- /dev/null +++ b/types/kissfft-js/index.d.ts @@ -0,0 +1,18 @@ +// 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 + +export class FFT { + constructor(size: number); + forward(input: number[]): number[]; + inverse(input: number[]): number[]; + dispose(): void; +} + +export class FFTR { + constructor(size: number); + forward(input: number[]): number[]; + inverse(input: number[]): number[]; + dispose(): void; +} diff --git a/types/kissfft-js/kissfft-js-tests.ts b/types/kissfft-js/kissfft-js-tests.ts new file mode 100644 index 0000000000..7de3255660 --- /dev/null +++ b/types/kissfft-js/kissfft-js-tests.ts @@ -0,0 +1,11 @@ +import * as kissFFT from "kissfft-js"; + +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 kissFFT.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..5164a8f4bd --- /dev/null +++ b/types/kissfft-js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": 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" } 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(); + }); diff --git a/types/libxmljs/index.d.ts b/types/libxmljs/index.d.ts index a29a6adeda..6540561a07 100644 --- a/types/libxmljs/index.d.ts +++ b/types/libxmljs/index.d.ts @@ -14,12 +14,48 @@ 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 { + 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 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; @@ -113,6 +149,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[]; diff --git a/types/list.js/index.d.ts b/types/list.js/index.d.ts index 0c31e24e20..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,15 +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 = List; 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"). * diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index b5f1134fb5..eebf89497d 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 // 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 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..559308cc69 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; @@ -63,11 +71,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/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..db6815caf2 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 */ @@ -795,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 +}; 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/fastify-static/package.json b/types/moment-precise-range-plugin/package.json similarity index 64% rename from types/fastify-static/package.json rename to types/moment-precise-range-plugin/package.json index e8c68ab969..19e5fb0d14 100644 --- a/types/fastify-static/package.json +++ b/types/moment-precise-range-plugin/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "fastify": "^1.11.2" + "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" } diff --git a/types/next/document.d.ts b/types/next/document.d.ts index d0e6d2c91b..f89e5d71e0 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -2,10 +2,15 @@ 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 + * 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 { - buildManifest: Record<string, any>; html?: string; - head?: Array<React.ReactElement<any>>; + head?: React.ReactNode; } export interface PageProps { @@ -31,7 +36,7 @@ export interface NextDocumentContext<Q extends DefaultQuery = DefaultQuery> exte E extends PageProps = AnyPageProps, P = E, EA extends PageProps = AnyPageProps, - PA = EA, + PA = EA >( enhancer?: | Enhancer<E, P> // tslint:disable-line no-unnecessary-generics @@ -44,7 +49,7 @@ export interface NextDocumentContext<Q extends DefaultQuery = DefaultQuery> 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/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..7c50a03930 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -48,19 +48,24 @@ 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 }); const initialProps = await Document.getInitialProps(ctx); - const styles = [...(initialProps.styles ? initialProps.styles : []), <style />]; + const styles = ( + <> + {initialProps.styles} + <style /> + </> + ); // Custom prop const url = req!.url; - return { html, head, buildManifest, styles, url }; + return { html, head, styles, url }; } constructor(props: WithUrlProps & DocumentProps) { @@ -73,12 +78,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}
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 // Niklas Lindgren // Vinay Bedre +// Antonio Román // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -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 { 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 +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// 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/child_process.d.ts b/types/node/child_process.d.ts index c8d20b8249..8e10d4e0c7 100644 --- a/types/node/child_process.d.ts +++ b/types/node/child_process.d.ts @@ -77,32 +77,36 @@ 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; + /** + * @default 0 + */ + timeout?: number; + } + + 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, options?: SpawnOptions): ChildProcess; - interface ExecOptions { - cwd?: string; - env?: NodeJS.ProcessEnv; + interface ExecOptions extends CommonOptions { shell?: string; - timeout?: number; maxBuffer?: number; killSignal?: string; - uid?: number; - gid?: number; - windowsHide?: boolean; } interface ExecOptionsWithStringEncoding extends ExecOptions { @@ -152,15 +156,9 @@ 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; - timeout?: number; + interface ExecFileOptions extends CommonOptions { maxBuffer?: number; killSignal?: string; - uid?: number; - gid?: number; - windowsHide?: boolean; windowsVerbatimArguments?: boolean; } interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { @@ -264,21 +262,15 @@ declare module "child_process" { } function fork(modulePath: string, args?: ReadonlyArray, 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,13 @@ declare module "child_process" { function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; - 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; @@ -328,18 +314,12 @@ declare module "child_process" { function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; function execSync(command: string, options?: ExecSyncOptions): Buffer; - interface ExecFileSyncOptions { - cwd?: string; + interface ExecFileSyncOptions extends CommonOptions { 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..27f935d1c6 100644 --- a/types/node/crypto.d.ts +++ b/types/node/crypto.d.ts @@ -2,9 +2,9 @@ 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; + exportChallenge(spkac: BinaryLike): Buffer; + exportPublicKey(spkac: BinaryLike): Buffer; + verifySpkac(spkac: Binary): boolean; } const Certificate: { new(): Certificate; @@ -14,19 +14,8 @@ 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; + function createHmac(algorithm: string, key: BinaryLike, options?: stream.TransformOptions): Hmac; type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; @@ -35,19 +24,40 @@ declare module "crypto" { type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; interface Hash extends NodeJS.ReadWriteStream { - update(data: string | Buffer | NodeJS.TypedArray | DataView): Hash; + update(data: BinaryLike): 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: BinaryLike): Hmac; update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hmac; digest(): Buffer; digest(encoding: HexBase64Latin1Encoding): string; } + + export type KeyObjectType = 'secret' | 'public' | 'private'; + + interface KeyObject { + asymmetricKeyType?: KeyType; + export(options?: { + type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1', + format: KeyFormat, + cipher?: string, + passphrase?: string | Buffer + }): string | Buffer; + symmetricSize?: number; + type: KeyObjectType; + } + type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm'; type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; + + type Binary = Buffer | NodeJS.TypedArray | DataView; + type BinaryLike = string | Binary; + + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { authTagLength: number; } @@ -55,21 +65,33 @@ declare module "crypto" { authTagLength?: number; } /** @deprecated since v10.0.0 use createCipheriv() */ - function createCipher(algorithm: CipherCCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): CipherCCM; + function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; /** @deprecated since v10.0.0 use createCipheriv() */ - function createCipher(algorithm: CipherGCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): CipherGCM; + function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, 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 createCipher(algorithm: string, password: BinaryLike, 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; + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions + ): CipherCCM; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions + ): CipherGCM; + function createCipheriv( + algorithm: string, key: CipherKey, iv: BinaryLike, options?: stream.TransformOptions + ): Cipher; interface Cipher extends NodeJS.ReadWriteStream { - update(data: string | Buffer | NodeJS.TypedArray | DataView): Buffer; + update(data: BinaryLike): 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; + update(data: Binary, output_encoding: HexBase64BinaryEncoding): string; + update(data: Binary, input_encoding: any, output_encoding: HexBase64BinaryEncoding): string; // second arg ignored update(data: string, input_encoding: Utf8AsciiBinaryEncoding, output_encoding: HexBase64BinaryEncoding): string; final(): Buffer; @@ -87,74 +109,100 @@ declare module "crypto" { getAuthTag(): Buffer; } /** @deprecated since v10.0.0 use createCipheriv() */ - function createDecipher(algorithm: CipherCCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options: CipherCCMOptions): DecipherCCM; + function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; /** @deprecated since v10.0.0 use createCipheriv() */ - function createDecipher(algorithm: CipherGCMTypes, password: string | Buffer | NodeJS.TypedArray | DataView, options?: CipherGCMOptions): DecipherGCM; + function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, 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 createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; function createDecipheriv( algorithm: CipherCCMTypes, - key: string | Buffer | NodeJS.TypedArray | DataView, - iv: string | Buffer | NodeJS.TypedArray | DataView, + key: BinaryLike, + iv: BinaryLike, options: CipherCCMOptions, ): DecipherCCM; function createDecipheriv( algorithm: CipherGCMTypes, - key: string | Buffer | NodeJS.TypedArray | DataView, - iv: string | Buffer | NodeJS.TypedArray | DataView, + key: BinaryLike, + iv: BinaryLike, options?: CipherGCMOptions, ): DecipherGCM; - function createDecipheriv(algorithm: string, key: string | Buffer | NodeJS.TypedArray | DataView, iv: string | Buffer | NodeJS.TypedArray | DataView, options?: stream.TransformOptions): Decipher; + function createDecipheriv(algorithm: string, key: BinaryLike, iv: BinaryLike, options?: stream.TransformOptions): Decipher; interface Decipher extends NodeJS.ReadWriteStream { - update(data: Buffer | NodeJS.TypedArray | DataView): Buffer; + update(data: Binary): Buffer; update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; - update(data: Buffer | NodeJS.TypedArray | DataView, input_encoding: any, output_encoding: Utf8AsciiBinaryEncoding): string; + update(data: Binary, 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; + // setAuthTag(tag: Binary): this; + // setAAD(buffer: Binary): this; } interface DecipherCCM extends Decipher { - setAuthTag(buffer: Buffer | NodeJS.TypedArray | DataView): this; - setAAD(buffer: Buffer | NodeJS.TypedArray | DataView, options: { plaintextLength: number }): this; + setAuthTag(buffer: Binary): this; + setAAD(buffer: Binary, 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; + setAuthTag(buffer: Binary): this; + setAAD(buffer: Binary, 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; + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat; + type?: 'pkcs1' | 'pkcs8' | 'sec1'; + passphrase?: string | Buffer; } + + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat; + type?: 'pkcs1' | 'spki'; + } + + function createPrivateKey(key: PrivateKeyInput | string | Buffer): KeyObject; + function createPublicKey(key: PublicKeyInput | string | Buffer): KeyObject; + function createSecretKey(key: Buffer): KeyObject; + + function createSign(algorithm: string, options?: stream.WritableOptions): Signer; + + interface SignPrivateKeyInput extends PrivateKeyInput { + padding?: number; + saltLength?: number; + } + + type KeyLike = string | Buffer | KeyObject; + + interface Signer extends NodeJS.WritableStream { + update(data: BinaryLike): Signer; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Signer; + sign(private_key: SignPrivateKeyInput | KeyLike): Buffer; + sign(private_key: SignPrivateKeyInput | KeyLike, 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: BinaryLike): 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; + verify(object: Object | KeyLike, signature: Binary): boolean; + verify(object: Object | KeyLike, 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_length: number, generator?: number | Binary): DiffieHellman; + function createDiffieHellman(prime: Binary): 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: number | Binary): 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: Binary): 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: Binary, output_encoding: HexBase64Latin1Encoding): string; computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; getPrime(): Buffer; getPrime(encoding: HexBase64Latin1Encoding): string; @@ -164,32 +212,32 @@ declare module "crypto" { getPublicKey(encoding: HexBase64Latin1Encoding): string; getPrivateKey(): Buffer; getPrivateKey(encoding: HexBase64Latin1Encoding): string; - setPublicKey(public_key: Buffer | NodeJS.TypedArray | DataView): void; + setPublicKey(public_key: Binary): void; setPublicKey(public_key: string, encoding: string): void; - setPrivateKey(private_key: Buffer | NodeJS.TypedArray | DataView): void; + setPrivateKey(private_key: Binary): 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, + password: BinaryLike, + salt: BinaryLike, 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 pbkdf2Sync(password: BinaryLike, salt: BinaryLike, 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(buffer: T, offset?: number, size?: number): T; - function randomFill(buffer: T, callback: (err: Error | null, buf: T) => void): void; - function randomFill(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; - function randomFill(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; + function randomFillSync(buffer: T, offset?: number, size?: number): T; + function randomFill(buffer: T, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; interface ScryptOptions { N?: number; @@ -198,38 +246,38 @@ declare module "crypto" { maxmem?: number; } function scrypt( - password: string | Buffer | NodeJS.TypedArray | DataView, - salt: string | Buffer | NodeJS.TypedArray | DataView, + password: BinaryLike, + salt: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void, ): void; function scrypt( - password: string | Buffer | NodeJS.TypedArray | DataView, - salt: string | Buffer | NodeJS.TypedArray | DataView, + password: BinaryLike, + salt: BinaryLike, 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; + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; interface RsaPublicKey { - key: string; + key: KeyLike; padding?: number; } interface RsaPrivateKey { - key: string; + key: KeyLike; 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 publicEncrypt(public_key: RsaPublicKey | KeyLike, buffer: Binary): Buffer; + function privateDecrypt(private_key: RsaPrivateKey | KeyLike, buffer: Binary): Buffer; + function privateEncrypt(private_key: RsaPrivateKey | KeyLike, buffer: Binary): Buffer; + function publicDecrypt(public_key: RsaPublicKey | KeyLike, buffer: Binary): Buffer; function getCiphers(): string[]; function getCurves(): string[]; function getHashes(): string[]; class ECDH { static convertKey( - key: string | Buffer | NodeJS.TypedArray | DataView, + key: BinaryLike, curve: string, inputEncoding?: HexBase64Latin1Encoding, outputEncoding?: "latin1" | "hex" | "base64", @@ -237,19 +285,19 @@ declare module "crypto" { ): Buffer | string; generateKeys(): Buffer; generateKeys(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; - computeSecret(other_public_key: Buffer | NodeJS.TypedArray | DataView): Buffer; + computeSecret(other_public_key: Binary): 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: Binary, 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: Binary): 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; + function timingSafeEqual(a: Binary, b: Binary): boolean; /** @deprecated since v10.0.0 */ const DEFAULT_ENCODING: string; 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..105ce92036 100644 --- a/types/node/fs.d.ts +++ b/types/node/fs.d.ts @@ -1165,7 +1165,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 e4f6f40fd1..cd7d67bbdf 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 {} -interface ReadonlySet {} - -// Forward-declare needed types from lib.es2015.d.ts (in case users are using `--lib es5`) -interface Iterable { } -interface Iterator { - next(value?: any): IteratorResult; -} -interface IteratorResult { } -interface IterableIterator { } -interface AsyncIterableIterator {} 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 @@ -207,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 */ @@ -216,6 +195,9 @@ interface NodeRequireFunction { interface NodeRequire extends NodeRequireFunction { resolve: RequireResolve; cache: any; + /** + * @deprecated + */ extensions: NodeExtensions; main: NodeModule | undefined; } @@ -249,67 +231,59 @@ 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; + write(string: string, encoding?: string): number; + write(string: string, offset: number, encoding?: string): number; + write(string: string, offset: number, length: number, encoding?: string): number; toString(encoding?: string, start?: number, end?: number): string; - toJSON(): { type: 'Buffer', data: any[] }; + toJSON(): { type: 'Buffer', data: number[] }; 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; + 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; @@ -470,7 +444,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; @@ -486,6 +472,7 @@ declare namespace NodeJS { stderr?: WritableStream; ignoreErrors?: boolean; colorMode?: boolean | 'auto'; + inspectOptions?: InspectOptions; } interface ConsoleConstructor { @@ -733,7 +720,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; @@ -800,6 +793,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]; @@ -983,6 +979,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..4e726b6735 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; @@ -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 9126f5504b..0c5f2212ac 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.9 // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript // DefinitelyTyped @@ -6,6 +6,7 @@ // Alexander T. // Alvis HT Tang // Andrew Makarov +// Benjamin Toueg // Bruno Scheufler // Chigozirim C. // Christian Vaagland Tellnes @@ -35,43 +36,52 @@ // Kyle Uehlein // 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: +/// + +// 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 {} +interface ReadonlySet {} +interface IteratorResult { } +interface Iterable { } +interface Iterator { + next(value?: any): IteratorResult; +} +interface IterableIterator { } +interface AsyncIterableIterator {} +interface SymbolConstructor { + readonly iterator: symbol; + readonly asyncIterator: symbol; +} +declare var Symbol: SymbolConstructor; +declare class SharedArrayBuffer { + constructor(byteSize: number); + 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/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 3a8622802a..902a95d088 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -5,19 +5,14 @@ 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"; @@ -34,22 +29,6 @@ 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 /// ////////////////////////////////////////////////////////// @@ -65,7 +44,7 @@ import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buff assert.doesNotThrow(() => { const b = false; if (b) { throw new Error("a hammer at your face"); } - }, undefined, "What the...*crunch*"); + }, () => 1, "What the...*crunch*"); assert.equal(3, "3", "uses == comparator"); @@ -88,7 +67,7 @@ import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buff assert.strictEqual(1, 1, "uses === comparator"); - assert.throws(() => { throw new Error("a hammer at your face"); }, undefined, "DODGED IT"); + assert.throws(() => { throw new Error("a hammer at your face"); }, Error, "DODGED IT"); assert.strict.strict.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); } @@ -254,7 +233,7 @@ import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buff 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', { encoding: undefined }) as string[]; listS = fs.readdirSync('path', 'utf8'); listS = fs.readdirSync('path', null); listS = fs.readdirSync('path', undefined); @@ -320,7 +299,7 @@ import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buff } { - let s: string; + let s = '123'; let b: Buffer; fs.readlink('/path/to/folder', (err, linkString) => s = linkString); fs.readlink('/path/to/folder', undefined, (err, linkString) => s = linkString); @@ -349,7 +328,7 @@ import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buff } { - let s: string; + let s = '123'; let b: Buffer; fs.realpath('/path/to/folder', (err, resolvedPath) => s = resolvedPath); fs.realpath('/path/to/folder', undefined, (err, resolvedPath) => s = resolvedPath); @@ -431,213 +410,6 @@ import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buff } } -/////////////////////////////////////////////////////// -/// 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 sharedArrayBuffer: SharedArrayBuffer = { - byteLength: 10, - slice: (begin?: number, end?: number) => sharedArrayBuffer - }; - const buf7: Buffer = Buffer.from(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 //////////////////////////////////////////////////// @@ -666,10 +438,10 @@ function bufferTests() { assert.equal(helloUrl.query['hello'], 'world'); let strUrl = url.parse('http://example.com/?hello=world'); - let queryStr: string = strUrl.query; + let queryStr: string = strUrl.query!; strUrl = url.parse('http://example.com/?hello=world', false); - queryStr = strUrl.query; + queryStr = strUrl.query!; function getBoolean(): boolean { return false; } const urlUrl = url.parse('http://example.com/?hello=world', getBoolean()); @@ -774,8 +546,10 @@ function bufferTests() { const params = new url.URLSearchParams([ ['user', 'abc'], ['query', 'first'], - ['query', 'second'] - ]); + ['query', 'second'], + // ts 2.1/2.* compatibility + // tslint:disable-next-line no-unnecessary-type-assertion + ] as Array<[string, string]>); assert.equal(params.toString(), 'user=abc&query=first&query=second'); } @@ -789,176 +563,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 { - assert(arguments.length === 0); - - return Promise.resolve(); - } - - static fnE(): Promise { - assert(arguments.length === 0); - - return Promise.reject(new Error('fail')); - } - - static fnT1(arg1: string): Promise { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.resolve(); - } - - static fnT1E(arg1: string): Promise { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.reject(new Error('fail')); - } - - static fnTResult(): Promise { - assert(arguments.length === 0); - - return Promise.resolve('result'); - } - - static fnTResultE(): Promise { - assert(arguments.length === 0); - - return Promise.reject(new Error('fail')); - } - - static fnT1TResult(arg1: string): Promise { - assert(arguments.length === 1 && arg1 === 'parameter'); - - return Promise.resolve('result'); - } - - static fnT1TResultE(arg1: string): Promise { - 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 = readPromised(__filename).then((data: Buffer): void => { }).catch((error: Error): void => { }); - const arg0: () => Promise = util.promisify((cb: (err: Error, result: number) => void): void => { }); - const arg0NoResult: () => Promise = util.promisify((cb: (err: Error) => void): void => { }); - const arg1: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error, result: number) => void): void => { }); - const arg1NoResult: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error) => void): void => { }); - const cbOptionalError: () => Promise = 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 (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 //////////////////////////////////////////////////// @@ -987,30 +591,60 @@ function stream_readable_pipe_test() { 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)); +zlib.deflate(compressMe, (err: Error | null, result: Buffer) => zlib.inflate(result, (err: Error | null, result: Buffer) => result)); +zlib.deflate( + compressMe, + { finishFlush: zlib.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => zlib.inflate( + result, + { finishFlush: zlib.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => result + ) +); +zlib.deflate(compressMeString, (err: Error | null, result: Buffer) => zlib.inflate(result, (err: Error | null, result: Buffer) => result)); +zlib.deflate( + compressMeString, + { finishFlush: zlib.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => zlib.inflate( + result, + { finishFlush: zlib.Z_SYNC_FLUSH }, + (err: Error | null, 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(compressMe, (err: Error | null, result: Buffer) => zlib.inflateRaw(result, (err: Error | null, result: Buffer) => result)); +zlib.deflateRaw( + compressMe, + { finishFlush: zlib.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => zlib.inflateRaw( + result, { finishFlush: zlib.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => result + ) +); +zlib.deflateRaw(compressMeString, (err: Error | null, result: Buffer) => zlib.inflateRaw(result, (err: Error | null, 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), + (err: Error | null, result: Buffer) => zlib.inflateRaw(result, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error | null, 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)); +zlib.gzip(compressMe, (err: Error | null, result: Buffer) => zlib.gunzip(result, (err: Error | null, result: Buffer) => result)); +zlib.gzip( + compressMe, + { finishFlush: zlib.Z_SYNC_FLUSH }, + (err: Error | null, result: Buffer) => zlib.gunzip( + result, { finishFlush: zlib.Z_SYNC_FLUSH }, + (err: Error | null, 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); +zlib.unzip(compressMe, (err: Error | null, result: Buffer) => result); +zlib.unzip(compressMe, { finishFlush: zlib.Z_SYNC_FLUSH }, (err: Error | null, result: Buffer) => result); const unzipped: Buffer = zlib.unzipSync(compressMe); // Simplified constructors @@ -1023,9 +657,9 @@ function simplified_stream_ctor_test() { size; }, destroy(error, cb) { - // $ExpectType Error + // $ExpectType Error | null error; - // $ExpectType (error: Error) => void + // $ExpectType (error: Error | null) => void cb; } }); @@ -1038,7 +672,7 @@ function simplified_stream_ctor_test() { chunk; // $ExpectType string enc; - // $ExpectType (error?: Error) => void + // $ExpectType (error?: Error | null | undefined) => void cb; }, writev(chunks, cb) { @@ -1046,21 +680,21 @@ function simplified_stream_ctor_test() { this; // $ExpectType { chunk: any; encoding: string; }[] chunks; - // $ExpectType (error?: Error) => void + // $ExpectType (error?: Error | null | undefined) => void cb; }, destroy(error, cb) { // $ExpectType Writable this; - // $ExpectType Error + // $ExpectType Error | null error; - // $ExpectType (error: Error) => void + // $ExpectType (error: Error | null) => void cb; }, final(cb) { // $ExpectType Writable this; - // $ExpectType (error?: Error) => void + // $ExpectType (error?: Error | null | undefined) => void cb; } }); @@ -1079,7 +713,7 @@ function simplified_stream_ctor_test() { chunk; // $ExpectType string enc; - // $ExpectType (error?: Error) => void + // $ExpectType (error?: Error | null | undefined) => void cb; }, writev(chunks, cb) { @@ -1087,21 +721,21 @@ function simplified_stream_ctor_test() { this; // $ExpectType { chunk: any; encoding: string; }[] chunks; - // $ExpectType (error?: Error) => void + // $ExpectType (error?: Error | null | undefined) => void cb; }, destroy(error, cb) { // $ExpectType Duplex this; - // $ExpectType Error + // $ExpectType Error | null error; - // $ExpectType (error: Error) => void + // $ExpectType (error: Error | null) => void cb; }, final(cb) { // $ExpectType Duplex this; - // $ExpectType (error?: Error) => void + // $ExpectType (error?: Error | null | undefined) => void cb; }, readableObjectMode: true, @@ -1122,7 +756,7 @@ function simplified_stream_ctor_test() { chunk; // $ExpectType string enc; - // $ExpectType (error?: Error) => void + // $ExpectType (error?: Error | null | undefined) => void cb; }, writev(chunks, cb) { @@ -1130,21 +764,21 @@ function simplified_stream_ctor_test() { this; // $ExpectType { chunk: any; encoding: string; }[] chunks; - // $ExpectType (error?: Error) => void + // $ExpectType (error?: Error | null | undefined) => void cb; }, destroy(error, cb) { // $ExpectType Transform this; - // $ExpectType Error + // $ExpectType Error | null error; - // $ExpectType (error: Error) => void + // $ExpectType (error: Error | null) => void cb; }, final(cb) { // $ExpectType Transform this; - // $ExpectType (error?: Error) => void + // $ExpectType (error?: Error | null | undefined) => void cb; }, transform(chunk, enc, cb) { @@ -1182,484 +816,6 @@ async function asyncStreamPipelineFinished() { 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 /// ////////////////////////////////////////////////// @@ -1683,7 +839,7 @@ async function asyncStreamPipelineFinished() { } { - let _server: tls.Server; + let _server = tls.createServer({}); let _boolean: boolean; const _func1 = (err: Error, resp: Buffer) => { }; const _func2 = (err: Error, sessionData: any) => { }; @@ -1827,7 +983,8 @@ async function asyncStreamPipelineFinished() { } { - let _TLSSocket: tls.TLSSocket; + let _TLSSocket = tls.connect({ + }); let _boolean: boolean; /** * events.EventEmitter @@ -1868,179 +1025,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 /// ////////////////////////////////////////////////////// @@ -2099,134 +1083,6 @@ async function asyncStreamPipelineFinished() { } } -//////////////////////////////////////////////////// -/// 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 //////////////////////////////////////////////////// @@ -2360,7 +1216,7 @@ async function asyncStreamPipelineFinished() { // returns // ['foo', 'bar', 'baz'] - process.env["PATH"]; // $ExpectType string + process.env["PATH"]; // $ExpectType string | undefined path.parse('/home/user/dir/file.txt'); // returns @@ -2442,180 +1298,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 //////////////////////////////////////////////////// @@ -2677,7 +1359,7 @@ async function asyncStreamPipelineFinished() { } { - let _cp: childProcess.ChildProcess; + let _cp = childProcess.spawn('asd'); const _socket: net.Socket = net.createConnection(1); const _server: net.Server = net.createServer(); let _boolean: boolean; @@ -2805,8 +1487,8 @@ async function asyncStreamPipelineFinished() { const _err: Error = err; }); _cp = _cp.addListener("exit", (code, signal) => { - const _code: number = code; - const _signal: string = signal; + const _code: number | null = code; + const _signal: string | null = signal; }); _cp = _cp.addListener("message", (message, sendHandle) => { const _message: any = message; @@ -2828,8 +1510,8 @@ async function asyncStreamPipelineFinished() { const _err: Error = err; }); _cp = _cp.on("exit", (code, signal) => { - const _code: number = code; - const _signal: string = signal; + const _code: number | null = code; + const _signal: string | null = signal; }); _cp = _cp.on("message", (message, sendHandle) => { const _message: any = message; @@ -2845,8 +1527,8 @@ async function asyncStreamPipelineFinished() { const _err: Error = err; }); _cp = _cp.once("exit", (code, signal) => { - const _code: number = code; - const _signal: string = signal; + const _code: number | null = code; + const _signal: string | null = signal; }); _cp = _cp.once("message", (message, sendHandle) => { const _message: any = message; @@ -2862,8 +1544,8 @@ async function asyncStreamPipelineFinished() { const _err: Error = err; }); _cp = _cp.prependListener("exit", (code, signal) => { - const _code: number = code; - const _signal: string = signal; + const _code: number | null = code; + const _signal: string | null = signal; }); _cp = _cp.prependListener("message", (message, sendHandle) => { const _message: any = message; @@ -2879,8 +1561,8 @@ async function asyncStreamPipelineFinished() { const _err: Error = err; }); _cp = _cp.prependOnceListener("exit", (code, signal) => { - const _code: number = code; - const _signal: string = signal; + const _code: number | null = code; + const _signal: string | null = signal; }); _cp = _cp.prependOnceListener("message", (message, sendHandle) => { const _message: any = message; @@ -2928,63 +1610,13 @@ async function asyncStreamPipelineFinished() { cluster.fork(); Object.keys(cluster.workers).forEach(key => { const worker = cluster.workers[key]; - if (worker.isDead()) { + if (worker && 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 //////////////////////////////////////////////////// @@ -3270,19 +1902,19 @@ async function asyncStreamPipelineFinished() { } { const frames: NodeJS.CallSite[] = []; - Error.prepareStackTrace(new Error(), frames); + Error.prepareStackTrace!(new Error(), frames); } { - const frame: NodeJS.CallSite = null; + 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 typeName: string | null = frame.getTypeName(); + const func: Function | undefined = frame.getFunction(); + const funcName: string | null = frame.getFunctionName(); + const meth: string | null = frame.getMethodName(); + const fname: string | null = frame.getFileName(); + const lineno: number | null = frame.getLineNumber(); + const colno: number | null = frame.getColumnNumber(); + const evalOrigin: string | undefined = frame.getEvalOrigin(); const isTop: boolean = frame.isToplevel(); const isEval: boolean = frame.isEval(); const isNative: boolean = frame.isNative(); @@ -3431,306 +2063,13 @@ 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 /// ///////////////////////////////////////////////////// { { - let _server: repl.REPLServer; + let _server = repl.start(); let _boolean: boolean; const _ctx: vm.Context = {}; @@ -4221,10 +2560,10 @@ import * as constants from 'constants'; http2Session.destroy(); - const alpnProtocol: string = http2Session.alpnProtocol; - const destroyed: boolean = http2Session.destroyed; - const encrypted: boolean = http2Session.encrypted; - const originSet: string[] = http2Session.originSet; + const alpnProtocol: string | undefined = http2Session.alpnProtocol; + const destroyed: boolean | undefined = http2Session.destroyed; + const encrypted: boolean | undefined = http2Session.encrypted; + const originSet: string[] | undefined = http2Session.originSet; const pendingSettingsAck: boolean = http2Session.pendingSettingsAck; let settings: http2.Settings = http2Session.localSettings; const closed: boolean = http2Session.closed; @@ -4330,7 +2669,7 @@ import * as constants from 'constants'; 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']; + const s: number = headers[':status']!; }); // ServerHttp2Stream @@ -4392,7 +2731,8 @@ import * as constants from 'constants'; // Public API (except constants) { - let settings: http2.Settings; + let settings: http2.Settings = { + }; const serverOptions: http2.ServerOptions = { maxDeflateDynamicTableSize: 0, maxReservedRemoteStreams: 0, @@ -4425,7 +2765,8 @@ import * as constants from 'constants'; // Http2ServerResponse - let outgoingHeaders: http2.OutgoingHttpHeaders; + let outgoingHeaders: http2.OutgoingHttpHeaders = { + }; response.addTrailers(outgoingHeaders); socket = response.connection; const finished: boolean = response.finished; @@ -4773,10 +3114,10 @@ import * as constants from 'constants'; // Known post method const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' }; session.post('Runtime.evaluate', parameter, - (err: Error, params: inspector.Runtime.EvaluateReturnType) => {}); + (err: Error | null, 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; + const exceptionDetails: inspector.Runtime.ExceptionDetails = params.exceptionDetails!; + const resultClassName: string = params.result.className!; }); session.post('Runtime.evaluate'); 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/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; } type ReadLine = Interface; // type forwarded for backwards compatiblity diff --git a/types/node/test/buffer.ts b/types/node/test/buffer.ts new file mode 100644 index 0000000000..37b02ef708 --- /dev/null +++ b/types/node/test/buffer.ts @@ -0,0 +1,203 @@ +// Specifically test buffer module regression. +import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buffer"; + +const utf8Buffer = new Buffer('test'); +const base64Buffer = new Buffer('', 'base64'); +const octets: Uint8Array = new Uint8Array(123); +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(new SharedArrayBuffer(123)); +} + +// 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); +result = b.write('asd'); +result = b.write('asd', 'hex'); +result = b.write('asd', 123, 'hex'); +result = b.write('asd', 123, 123, 'hex'); + +// 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); +} diff --git a/types/node/test/crypto.ts b/types/node/test/crypto.ts new file mode 100644 index 0000000000..8f7ffe86f5 --- /dev/null +++ b/types/node/test/crypto.ts @@ -0,0 +1,487 @@ +import * as crypto from 'crypto'; +import * as assert from 'assert'; +import { promisify } from 'util'; + +{ + // 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 | null, buf: Buffer) => void {}); + crypto.randomFill(buffer, 2, (err: Error | null, buf: Buffer) => void {}); + crypto.randomFill(buffer, 2, 3, (err: Error | null, 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 | null, buf: Uint8Array) => void {}); + crypto.randomFill(ui8arr, 2, (err: Error | null, buf: Uint8Array) => void {}); + crypto.randomFill(ui8arr, 2, 3, (err: Error | null, 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 | null, buf: Int32Array) => void {}); + crypto.randomFill(i32arr, 2, (err: Error | null, buf: Int32Array) => void {}); + crypto.randomFill(i32arr, 2, 3, (err: Error | null, 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 = 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', + }, + }); +} + +{ + crypto.createPrivateKey(Buffer.from('asdf')); + crypto.createPrivateKey({ + key: 'asd', + format: 'der', + }); +} + +{ + crypto.createSecretKey(Buffer.from('asdf')); +} diff --git a/types/node/test/dgram.ts b/types/node/test/dgram.ts new file mode 100644 index 0000000000..8749f79743 --- /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 | null, 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 = new 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..e29fdf3e25 --- /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..9cd5c7d0b2 --- /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..a2276654c8 --- /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 | null = 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 = true; + let buffer = Buffer.from('123'); + let error = new Error('asd'); + let str = '123'; + let num = 123; + + 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.createServer(); + + let _socket = net.connect(''); + let bool: boolean; + let error = new 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..a49eead8ec --- /dev/null +++ b/types/node/test/readline.ts @@ -0,0 +1,185 @@ +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('asd', 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.createInterface({ + input: process.stdin, + }); + 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/tty.ts b/types/node/test/tty.ts new file mode 100644 index 0000000000..fdbbee9230 --- /dev/null +++ b/types/node/test/tty.ts @@ -0,0 +1,25 @@ +import * as tty from 'tty'; + +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; + +ws.clearLine(-1); +ws.clearLine(0); +ws.clearLine(1); +ws.clearScreenDown(); +ws.cursorTo(42, 42); +ws.addListener('resize', () => { +}); +ws.getColorDepth(); +ws.getColorDepth({ +}); +ws.clearScreenDown(); +ws.getWindowSize(); + +const isTTY: boolean = tty.isatty(1); 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 { + assert(arguments.length === 0); + + return Promise.resolve(); + } + + static fnE(): Promise { + assert(arguments.length === 0); + + return Promise.reject(new Error('fail')); + } + + static fnT1(arg1: string): Promise { + assert(arguments.length === 1 && arg1 === 'parameter'); + + return Promise.resolve(); + } + + static fnT1E(arg1: string): Promise { + assert(arguments.length === 1 && arg1 === 'parameter'); + + return Promise.reject(new Error('fail')); + } + + static fnTResult(): Promise { + assert(arguments.length === 0); + + return Promise.resolve('result'); + } + + static fnTResultE(): Promise { + assert(arguments.length === 0); + + return Promise.reject(new Error('fail')); + } + + static fnT1TResult(arg1: string): Promise { + assert(arguments.length === 1 && arg1 === 'parameter'); + + return Promise.resolve('result'); + } + + static fnT1TResultE(arg1: string): Promise { + 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 = readPromised(__filename).then((data: Buffer): void => { }).catch((error: Error): void => { }); + const arg0: () => Promise = util.promisify((cb: (err: Error, result: number) => void): void => { }); + const arg0NoResult: () => Promise = util.promisify((cb: (err: Error) => void): void => { }); + const arg1: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error, result: number) => void): void => { }); + const arg1NoResult: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error) => void): void => { }); + const cbOptionalError: () => Promise = 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 (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..d55304a619 --- /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..e7222b5a5b 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; key?: string | Buffer | Array; @@ -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 { @@ -363,7 +382,7 @@ declare module "tls" { 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 createSecurePair(credentials?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; function createSecureContext(details: SecureContextOptions): SecureContext; function getCiphers(): string[]; 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: +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +// tslint:disable-next-line:no-bad-reference +/// + +// TypeScript 3.1-specific augmentations: +/// 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..c2b32a1695 --- /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": true, + "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 +/// +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..e16d482b6f 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", @@ -41,7 +42,17 @@ "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", + "test/buffer.ts", + "test/tty.ts", + "test/crypto.ts" ], "compilerOptions": { "module": "commonjs", @@ -52,7 +63,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/node/tty.d.ts b/types/node/tty.d.ts index 7d75c89f58..5fadbc2d39 100644 --- a/types/node/tty.d.ts +++ b/types/node/tty.d.ts @@ -7,7 +7,39 @@ 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; + /** + * @default `process.env` + */ + 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 f918286559..1adf10059f 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; function promisify(fn: Function): Function; - namespace promisify { - const custom: symbol; - } namespace types { function isAnyArrayBuffer(object: any): boolean; @@ -167,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, message?: string | Error): Promise; + function rejects(block: Function | Promise, error: RegExp | Function | Object | Error, message?: string | Error): Promise; + function doesNotReject(block: Function | Promise, message?: string | Error): Promise; + function doesNotReject(block: Function | Promise, error: RegExp | Function, message?: string | Error): Promise; + + 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(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 +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/types/node/v10/buffer.d.ts b/types/node/v10/buffer.d.ts new file mode 100644 index 0000000000..1d618f2c4b --- /dev/null +++ b/types/node/v10/buffer.d.ts @@ -0,0 +1,12 @@ +declare module "buffer" { + export const INSPECT_MAX_BYTES: number; + const BuffType: typeof Buffer; + + 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/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, 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 | null): ChildProcess; + function execFile(file: string, args: ReadonlyArray | 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 | 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 | 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 | 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 | 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 | 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 | 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, 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 { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number; + signal: string; + error: Error; + } + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; + + 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, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(command: string, args?: ReadonlyArray, 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(buffer: T, offset?: number, size?: number): T; + function randomFill(buffer: T, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; + function randomFill(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 { + format: T; + cipher: string; + passphrase: string; + } + + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * @default 0x10001 + */ + publicExponent?: number; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs1' | 'pkcs8'; + }; + } + + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + + interface ECKeyPairOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'sec1' | 'pkcs8'; + }; + } + + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + + 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; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__(hostname: string, rrtype: string): Promise; + } + + 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; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + + 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; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + + function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + + function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; + namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + + function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; + namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + + function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + + function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; + namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + + function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException, address: SoaRecord) => void): void; + namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + + function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: SrvRecord[]) => void): void; + namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + + function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; + namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + + function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: AnyRecord[]) => void): void; + namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + + 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; + 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + + 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; + + /** + * 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; + + /** + * 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; + } + + /** + * 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; + + /** + * 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; + + /** + * 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; + + 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + + /** + * 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; + + /** + * 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; + } + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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( + 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( + 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(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(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__( + 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( + 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__(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; + + /** + * 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; + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + */ + chown(uid: number, gid: number): Promise; + + /** + * 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; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + */ + datasync(): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + */ + sync(): Promise; + + /** + * 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(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; + + /** + * 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; + + /** + * 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; + + /** + * Asynchronous fstat(2) - Get file status. + */ + stat(): Promise; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param len If not specified, defaults to `0`. + */ + truncate(len?: number): Promise; + + /** + * 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; + + /** + * 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(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; + + /** + * Asynchronous close(2) - close a `FileHandle`. + */ + close(): Promise; + } + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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( + 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( + 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param handle A `FileHandle`. + */ + function fdatasync(handle: FileHandle): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param handle A `FileHandle`. + */ + function fsync(handle: FileHandle): Promise; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * Asynchronous fstat(2) - Get file status. + * @param handle A `FileHandle`. + */ + function fstat(handle: FileHandle): Promise; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param handle A `FileHandle`. + */ + function fchown(handle: FileHandle, uid: number, gid: number): Promise; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + + /** + * 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; + } +} diff --git a/types/node/v10/globals.d.ts b/types/node/v10/globals.d.ts new file mode 100644 index 0000000000..23cab2f1f8 --- /dev/null +++ b/types/node/v10/globals.d.ts @@ -0,0 +1,995 @@ +// 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; + function __promisify__(ms: number, value: T): Promise; +} +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; + function __promisify__(value: T): Promise; +} +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; + +// 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; + values(): IterableIterator; +} + +/** + * 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; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(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; + } + + 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) => void; + type UncaughtExceptionListener = (error: Error) => void; + type UnhandledRejectionListener = (reason: any, promise: Promise) => 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, 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): 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; + + /** + * EventEmitter + * 1. beforeExit + * 2. disconnect + * 3. exit + * 4. message + * 5. rejectionHandled + * 6. uncaughtException + * 7. unhandledRejection + * 8. warning + * 9. message + * 10. + * 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): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "unhandledRejection", reason: any, promise: Promise): 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..696c687268 --- /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-patch'?: string; + 'accept-ranges'?: string; + 'accept'?: 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; + '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; + 'tk'?: string; + 'trailer'?: string; + 'transfer-encoding'?: 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 +// DefinitelyTyped +// Alberto Schiabel +// Alexander T. +// Alvis HT Tang +// Andrew Makarov +// Bruno Scheufler +// Chigozirim C. +// Christian Vaagland Tellnes +// Deividas Bakanas +// Eugene Y. Q. Shen +// Flarna +// Hannes Magnusson +// Hoàng Văn Khải +// Huw +// Kelvin Jin +// Klaus Meinhardt +// Lishude +// Mariusz Wiktorczyk +// Matthieu Sieben +// Mohsen Azimi +// Nicolas Even +// Nicolas Voigt +// Parambir Singh +// Sebastian Silbermann +// Simon Schick +// Thomas den Hollander +// Wilco Bakker +// wwwy3y3 +// Zane Hannan AU +// Jeremie Rodriguez +// Samuel Ainsworth +// Kyle Uehlein +// 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: +/// + +// 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 {} +interface ReadonlySet {} +interface IteratorResult { } +interface Iterable { } +interface Iterator { + next(value?: any): IteratorResult; +} +interface IterableIterator { } +interface AsyncIterableIterator {} +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 { + 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) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => 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) => 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) => void): this; + + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => 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) => 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) => void): this; + + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => 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) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => 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) => void): this; + + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => 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) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification<{}>): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): 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) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => 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) => 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) => void): this; + + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => 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) => 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) => void): this; + + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => 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) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => 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) => void): this; + + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => 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) => 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) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => 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) => 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) => void): this; + + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => 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) => 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) => void): this; + + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => 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) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => 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) => void): this; + + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => 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) => 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) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => 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) => 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) => void): this; + + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => 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) => 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) => void): this; + + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => 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) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => 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) => void): this; + + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => 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) => 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) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => 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) => 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) => void): this; + + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => 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) => 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) => void): this; + + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => 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) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => 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) => void): this; + + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => 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) => 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; + + 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 { + assert(arguments.length === 0); + + return Promise.resolve(); + } + + static fnE(): Promise { + assert(arguments.length === 0); + + return Promise.reject(new Error('fail')); + } + + static fnT1(arg1: string): Promise { + assert(arguments.length === 1 && arg1 === 'parameter'); + + return Promise.resolve(); + } + + static fnT1E(arg1: string): Promise { + assert(arguments.length === 1 && arg1 === 'parameter'); + + return Promise.reject(new Error('fail')); + } + + static fnTResult(): Promise { + assert(arguments.length === 0); + + return Promise.resolve('result'); + } + + static fnTResultE(): Promise { + assert(arguments.length === 0); + + return Promise.reject(new Error('fail')); + } + + static fnT1TResult(arg1: string): Promise { + assert(arguments.length === 1 && arg1 === 'parameter'); + + return Promise.resolve('result'); + } + + static fnT1TResultE(arg1: string): Promise { + 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 = readPromised(__filename).then((data: Buffer): void => { }).catch((error: Error): void => { }); + const arg0: () => Promise = util.promisify((cb: (err: Error, result: number) => void): void => { }); + const arg0NoResult: () => Promise = util.promisify((cb: (err: Error) => void): void => { }); + const arg1: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error, result: number) => void): void => { }); + const arg1NoResult: (arg: string) => Promise = util.promisify((arg: string, cb: (err: Error) => void): void => { }); + const cbOptionalError: () => Promise = 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 (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) => { }); + process.on("uncaughtException", (error: Error) => { }); + process.addListener("unhandledRejection", (reason: any, promise: Promise) => { }); + 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, 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) => { + 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) => { + 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 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(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; + } + + 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; + } + + function pipeline(stream1: NodeJS.ReadableStream, stream2: T, callback?: (err: NodeJS.ErrnoException) => void): T; + function pipeline(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: T, callback?: (err: NodeJS.ErrnoException) => void): T; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: T, + callback?: (err: NodeJS.ErrnoException) => void, + ): T; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: NodeJS.ReadWriteStream, + stream5: T, + callback?: (err: NodeJS.ErrnoException) => void, + ): T; + function pipeline(streams: Array, callback?: (err: NodeJS.ErrnoException) => void): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array void)>, + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.WritableStream): Promise; + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.WritableStream): Promise; + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: NodeJS.WritableStream): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: NodeJS.ReadWriteStream, + stream5: NodeJS.WritableStream, + ): Promise; + function __promisify__(streams: Array): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array, + ): Promise; + } + } + + 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; + function __promisify__(ms: number, value: T): Promise; + } + 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; + function __promisify__(value: T): Promise; + } + 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) 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; + key?: string | Buffer | Array; + passphrase?: string; + cert?: string | Buffer | Array; + ca?: string | Buffer | Array; + ciphers?: string; + honorCipherOrder?: boolean; + ecdhCurve?: string; + clientCertEngine?: string; + crl?: string | Buffer | Array; + 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: +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +// tslint:disable-next-line:no-bad-reference +/// + +// TypeScript 3.1-specific augmentations: +/// 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 +/// +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; + set(name: string, value: string): void; + sort(): void; + toString(): string; + values(): IterableIterator; + [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(fn: T, message: string): T; + function isDeepStrictEqual(val1: any, val2: any): boolean; + + interface CustomPromisify extends Function { + __promisify__: TCustom; + } + + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + + function promisify(fn: CustomPromisify): TCustom; + function promisify(fn: (callback: (err: Error | null, result: TResult) => void) => void): () => Promise; + function promisify(fn: (callback: (err?: Error | null) => void) => void): () => Promise; + function promisify(fn: (arg1: T1, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, callback: (err?: Error | null) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify( + 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; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: Error | null) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify( + 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; + function promisify( + 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; + 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): 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): 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/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; 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/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; add(sourceEntry: IndexEntry): number; - addAll(pathspec: Strarray | string | string[], flags: number, callback?: Function): Promise; + addAll(pathspec?: Strarray | string | string[], flags?: number, callback?: Function): Promise; addByPath(path: string): Promise; caps(): number; checksum(): Oid; diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index ffb686b3d2..be6822cf36 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 { * * * An {@link Office.TableData} object, and the shape of the table matches the bound table. - * 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". + * 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". * * * @@ -2654,7 +2654,7 @@ declare namespace Office { * * * An {@link Office.TableData} object, and the shape of the table matches the bound table. - * 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". + * 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". * * * @@ -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 { * * * - * + * * * * @@ -4659,7 +4659,7 @@ declare namespace Office { *
WordIf there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion pointIf `data` is a string, the specified text is inserted.
If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.
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).
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).
If `data` is Office Open XML, the specified XML is inserted.
If `data` is a base64 encoded image stream, the specified image is inserted.
If there is a selectionIt will be replaced with the specified `data` following the same rules as above.
* * - * + * * * * @@ -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. @@ -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] * @@ -11741,16 +11741,18 @@ 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. + * **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. */ interface Appointment extends Item { } /** * 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. + * **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. */ interface AppointmentCompose extends Appointment, ItemCompose { /** @@ -11765,32 +11767,6 @@ declare namespace Office { *
WordIf there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion pointIf `data` is a string, the specified text is inserted.
If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.
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).
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).
If `data` is Office Open XML, the specified XML is inserted.
If `data` is a base64 encoded image stream, the specified image is inserted.
If there is a selectionIt will be replaced with the specified `data` following the same rules as above.
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Organizer
*/ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Organizer
- */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Organizer
- * - * 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. * @@ -11904,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] @@ -11938,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}. @@ -12295,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] @@ -12330,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] * @@ -12590,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. * @@ -12634,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. * @@ -12667,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. * @@ -12701,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. * @@ -12842,8 +12818,9 @@ 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. + * **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. */ interface AppointmentRead extends Appointment, ItemRead { /** @@ -12857,7 +12834,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Attendee * - * 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}. * */ @@ -12875,7 +12852,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] * @@ -12887,7 +12864,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] * @@ -12897,7 +12874,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Attendee * - * 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; /** @@ -12985,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}. @@ -13087,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] @@ -13137,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}. @@ -13232,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] * @@ -13257,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] * @@ -13275,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] @@ -13304,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] * @@ -13326,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] * @@ -13340,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] * @@ -13408,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] * @@ -13438,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] * @@ -13464,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] * @@ -13483,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] * @@ -13510,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] * @@ -13622,32 +13599,6 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read */ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Read
- */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Read
- * - * 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,36 +13627,13 @@ 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 - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
- */ - recurrence: Recurrence; - /** * Gets the id of the series that an instance belongs to. * * 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}. @@ -13774,7 +13702,7 @@ declare namespace Office { addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: Office.AsyncResult) => 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 @@ -13806,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] @@ -13950,8 +13878,9 @@ 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. + * **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. */ interface ItemCompose extends Item { /** @@ -14237,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] @@ -14272,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] * @@ -14467,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. * @@ -14513,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. * @@ -14546,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. * @@ -14581,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. * @@ -14724,8 +14653,9 @@ 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. + * **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. */ interface ItemRead extends Item { /** @@ -14738,7 +14668,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Read * - * 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}. * @@ -14788,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}. @@ -14845,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] * @@ -14870,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] * @@ -14888,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] @@ -14917,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] @@ -14940,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] * @@ -14954,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] * @@ -15023,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] * @@ -15053,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] * @@ -15079,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] * @@ -15098,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] * @@ -15123,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] * @@ -15143,8 +15073,9 @@ 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. + * **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. */ interface Message extends Item { /** @@ -15171,8 +15102,9 @@ 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. + * **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. */ interface MessageCompose extends Message, ItemCompose { /** @@ -15234,32 +15166,6 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose */ conversationId: string; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose
- */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose
- * - * 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,35 +15226,13 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose */ 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 - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose
- */ - recurrence: Recurrence; /** * Gets the id of the series that an instance belongs to. * * 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}. @@ -15708,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] @@ -15743,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] @@ -16007,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. * @@ -16052,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. * @@ -16084,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. * @@ -16119,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. * @@ -16259,8 +16143,9 @@ 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. + * **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. */ interface MessageRead extends Message, ItemRead { /** @@ -16274,7 +16159,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Read * - * 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}. * @@ -16328,7 +16213,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] * @@ -16340,7 +16225,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] * @@ -16350,7 +16235,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Read * - * 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; /** @@ -16359,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. * @@ -16444,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}. @@ -16509,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] @@ -16529,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}. @@ -16552,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] * @@ -16657,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] * @@ -16682,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] * @@ -16701,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] @@ -16731,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] @@ -16754,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] * @@ -16768,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] * @@ -16838,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] * @@ -16868,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] * @@ -16894,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] * @@ -16913,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] * @@ -16940,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] * @@ -17278,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; /** @@ -17339,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] * @@ -17380,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] * @@ -17431,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] * @@ -17457,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] * @@ -17486,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] * @@ -17568,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] * @@ -17690,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* @@ -17779,7 +17664,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. */ @@ -18577,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] * @@ -18604,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] * @@ -18746,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. @@ -19386,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 0b4346ef8b..caafa47822 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 { * * * An {@link Office.TableData} object, and the shape of the table matches the bound table. - * 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". + * 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". * * * @@ -2654,7 +2654,7 @@ declare namespace Office { * * * An {@link Office.TableData} object, and the shape of the table matches the bound table. - * 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". + * 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". * * * @@ -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 { * * * - * + * * * * @@ -4659,7 +4659,7 @@ declare namespace Office { *
WordIf there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion pointIf `data` is a string, the specified text is inserted.
If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.
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).
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).
If `data` is Office Open XML, the specified XML is inserted.
If `data` is a base64 encoded image stream, the specified image is inserted.
If there is a selectionIt will be replaced with the specified `data` following the same rules as above.
* * - * + * * * * @@ -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. @@ -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] * @@ -11741,16 +11741,18 @@ 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. + * **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. */ interface Appointment extends Item { } /** * 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. + * **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. */ interface AppointmentCompose extends Appointment, ItemCompose { /** @@ -11765,32 +11767,6 @@ declare namespace Office { *
WordIf there is no selection and the insertion point is at a valid location, the specified `data` is inserted at the insertion pointIf `data` is a string, the specified text is inserted.
If `data` is an array of arrays ("matrix") or a TableData object, a new Word table is inserted.
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).
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).
If `data` is Office Open XML, the specified XML is inserted.
If `data` is a base64 encoded image stream, the specified image is inserted.
If there is a selectionIt will be replaced with the specified `data` following the same rules as above.
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Organizer
*/ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Organizer
- */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Organizer
- * - * 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. * @@ -11904,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] @@ -11938,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}. @@ -12295,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] @@ -12330,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] * @@ -12590,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. * @@ -12634,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. * @@ -12667,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. * @@ -12701,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. * @@ -12842,8 +12818,9 @@ 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. + * **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. */ interface AppointmentRead extends Appointment, ItemRead { /** @@ -12857,7 +12834,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Attendee * - * 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}. * */ @@ -12875,7 +12852,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] * @@ -12887,7 +12864,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] * @@ -12897,7 +12874,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Attendee * - * 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; /** @@ -12985,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}. @@ -13087,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] @@ -13137,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}. @@ -13232,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] * @@ -13257,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] * @@ -13275,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] @@ -13304,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] * @@ -13326,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] * @@ -13340,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] * @@ -13408,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] * @@ -13438,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] * @@ -13464,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] * @@ -13483,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] * @@ -13510,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] * @@ -13622,32 +13599,6 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read */ body: Body; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Read
- */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Read
- * - * 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,36 +13627,13 @@ 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 - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
- */ - recurrence: Recurrence; - /** * Gets the id of the series that an instance belongs to. * * 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}. @@ -13774,7 +13702,7 @@ declare namespace Office { addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: Office.AsyncResult) => 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 @@ -13806,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] @@ -13950,8 +13878,9 @@ 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. + * **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. */ interface ItemCompose extends Item { /** @@ -14237,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] @@ -14272,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] * @@ -14467,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. * @@ -14513,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. * @@ -14546,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. * @@ -14581,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. * @@ -14724,8 +14653,9 @@ 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. + * **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. */ interface ItemRead extends Item { /** @@ -14738,7 +14668,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Read * - * 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}. * @@ -14788,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}. @@ -14845,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] * @@ -14870,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] * @@ -14888,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] @@ -14917,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] @@ -14940,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] * @@ -14954,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] * @@ -15023,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] * @@ -15053,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] * @@ -15079,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] * @@ -15098,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] * @@ -15123,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] * @@ -15143,8 +15073,9 @@ 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. + * **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. */ interface Message extends Item { /** @@ -15171,8 +15102,9 @@ 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. + * **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. */ interface MessageCompose extends Message, ItemCompose { /** @@ -15234,32 +15166,6 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose */ conversationId: string; - /** - * Gets the date and time that an item was created. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose
- */ - dateTimeCreated: Date; - /** - * Gets the date and time that an item was last modified. Read mode only. - * - * [Api set: Mailbox 1.0] - * - * @remarks - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose
- * - * 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,35 +15226,13 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose */ 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 - * - * - * - *
{@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
{@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose
- */ - recurrence: Recurrence; /** * Gets the id of the series that an instance belongs to. * * 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}. @@ -15708,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] @@ -15743,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] @@ -16007,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. * @@ -16052,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. * @@ -16084,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. * @@ -16119,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. * @@ -16259,8 +16143,9 @@ 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. + * **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. */ interface MessageRead extends Message, ItemRead { /** @@ -16274,7 +16159,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Read * - * 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}. * @@ -16328,7 +16213,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] * @@ -16340,7 +16225,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] * @@ -16350,7 +16235,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Read * - * 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; /** @@ -16359,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. * @@ -16444,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}. @@ -16509,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] @@ -16529,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}. @@ -16552,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] * @@ -16657,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] * @@ -16682,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] * @@ -16701,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] @@ -16731,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] @@ -16754,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] * @@ -16768,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] * @@ -16838,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] * @@ -16868,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] * @@ -16894,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] * @@ -16913,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] * @@ -16940,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] * @@ -17278,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; /** @@ -17339,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] * @@ -17380,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] * @@ -17431,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] * @@ -17457,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] * @@ -17486,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] * @@ -17568,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] * @@ -17690,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* @@ -17779,7 +17664,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. */ @@ -18577,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] * @@ -18604,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] * @@ -18746,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. @@ -19386,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] * @@ -20747,22 +20632,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; diff --git a/types/p2/index.d.ts b/types/p2/index.d.ts index 88dde55025..8bde6c1a3b 100644 --- a/types/p2/index.d.ts +++ b/types/p2/index.d.ts @@ -1,24 +1,32 @@ // Type definitions for p2.js v0.7.1 // Project: https://github.com/schteppe/p2.js/ -// Definitions by: Clark Stevenson +// Definitions by: Clark Stevenson , Janne Ramstedt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped 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 { @@ -352,14 +431,14 @@ 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; } - 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[]; - axes?: ArrayLike[]; + vertices?: [number, number]|ArrayLike[]; + axes?: [number, number]|ArrayLike[]; } @@ -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,21 +852,60 @@ 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 { - position?: number[]; + position?: [number, 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(a: Array, b: Array): Array; static splice(array: Array, index: number, howMany: number): void; + static arrayRemove(array: Array, element: number): void; static extend(a: any, b: any): void; static defaults(options: any, defaults: any): any; + static shallowClone(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; + } } 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. diff --git a/types/pigpio/index.d.ts b/types/pigpio/index.d.ts index 8eaa6491bb..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 , erikma +// Definitions by: ManerFan +// erikma +// park012241 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -72,9 +74,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. 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; 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()} } }; 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 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -21,7 +21,9 @@ export interface FastPath { export type BuiltInParser = (text: string, options?: any) => AST; export type BuiltInParserName = - | 'babylon' + | 'babylon' // deprecated + | 'babel' + | 'babel-flow' | 'flow' | 'typescript' | 'postcss' // deprecated 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..459a351c33 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -26,6 +26,7 @@ // Drew Wyatt // John Ottenlips // Nitesh Phadatare +// Krantisinh Deshmukh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -163,6 +164,7 @@ /// /// /// +/// /// /// /// @@ -1575,6 +1577,17 @@ 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(from: number, to: number, list: ReadonlyArray): T[]; + move(from: number, to: number): (list: ReadonlyArray) => T[]; + move(from: number): { + (to: number, list: ReadonlyArray): T[]; + (to: number): (list: ReadonlyArray) => T[]; + }; + /** * 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..e4039483da 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 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 // Gabriel Prates +// Laurent Senta // 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 {
+ diff --git a/types/react-datepicker/index.d.ts b/types/react-datepicker/index.d.ts index e2870092dc..ce7ebcfab9 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; + +declare class ReactDatePicker extends React.Component { + readonly setBlur: () => void; + readonly setFocus: () => void; + readonly setOpen: (open: boolean, skipSetBlur?: 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();
; + +function handleRef(ref: DatePicker | null) { + if (ref) { + ref.setBlur(); + ref.setFocus(); + if (ref.isCalendarOpen()) { + ref.setOpen(false); + } + } +} 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 // AssureSign // Microsoft // MartynasZilinskas // Josh Rutherford +// Jessica Franco // 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..46274e3ffd 100644 --- a/types/react-dom/react-dom-tests.tsx +++ b/types/react-dom/react-dom-tests.tsx @@ -178,4 +178,23 @@ 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); + }); + 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 f60d088515..8730dc9447 100644 --- a/types/react-dom/test-utils/index.d.ts +++ b/types/react-dom/test-utils/index.d.ts @@ -278,3 +278,26 @@ export function findRenderedComponentWithType, 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. +// 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. +// Ideally this should be as hard to accidentally use as possible. +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-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-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"; { }} />; 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 { } + +export function withOptions(handler: (this: TThis, ev: T) => any, options: EventOptions): (this: TThis, ev: T) => any; + +export type EventListenerThisType = T extends keyof Window ? Window[T] : T; + +export type OnErrorEventHandlerArgs = OnErrorEventHandlerNonNull extends (...args: infer A) => any ? A : []; + +export interface EventListenerProps { + // Global events + onPointerCancel?(this: EventListenerThisType, ev: PointerEvent): any; + onPointerCancelCapture?(this: EventListenerThisType, ev: PointerEvent): any; + onPointerDown?(this: EventListenerThisType, ev: PointerEvent): any; + onPointerDownCapture?(this: EventListenerThisType, ev: PointerEvent): any; + onPointerEnter?(this: EventListenerThisType, ev: PointerEvent): any; + onPointerEnterCapture?(this: EventListenerThisType, ev: PointerEvent): any; + onPointerLeave?(this: EventListenerThisType, ev: PointerEvent): any; + onPointerLeaveCapture?(this: EventListenerThisType, ev: PointerEvent): any; + onPointerMove?(this: EventListenerThisType, ev: PointerEvent): any; + onPointerMoveCapture?(this: EventListenerThisType, ev: PointerEvent): any; + onPointerOut?(this: EventListenerThisType, ev: PointerEvent): any; + onPointerOutCapture?(this: EventListenerThisType, ev: PointerEvent): any; + onPointerOver?(this: EventListenerThisType, ev: PointerEvent): any; + onPointerOverCapture?(this: EventListenerThisType, ev: PointerEvent): any; + onPointerUp?(this: EventListenerThisType, ev: PointerEvent): any; + onPointerUpCapture?(this: EventListenerThisType, ev: PointerEvent): any; + onWheel?(this: EventListenerThisType, ev: WheelEvent): any; + onWheelCapture?(this: EventListenerThisType, ev: WheelEvent): any; + onAbort?(this: EventListenerThisType, ev: Event): any; + onAbortCapture?(this: EventListenerThisType, ev: Event): any; + onAfterPrint?(this: EventListenerThisType, ev: Event): any; + onAfterPrintCapture?(this: EventListenerThisType, ev: Event): any; + onBeforePrint?(this: EventListenerThisType, ev: Event): any; + onBeforePrintCapture?(this: EventListenerThisType, ev: Event): any; + onBeforeUnload?(this: EventListenerThisType, ev: BeforeUnloadEvent): any; + onBeforeUnloadCapture?(this: EventListenerThisType, ev: BeforeUnloadEvent): any; + onBlur?(this: EventListenerThisType, ev: FocusEvent): any; + onBlurCapture?(this: EventListenerThisType, ev: FocusEvent): any; + onCanPlay?(this: EventListenerThisType, ev: Event): any; + onCanPlayCapture?(this: EventListenerThisType, ev: Event): any; + onCanPlayThrough?(this: EventListenerThisType, ev: Event): any; + onCanPlayThroughCapture?(this: EventListenerThisType, ev: Event): any; + onChange?(this: EventListenerThisType, ev: Event): any; + onChangeCapture?(this: EventListenerThisType, ev: Event): any; + onClick?(this: EventListenerThisType, ev: MouseEvent): any; + onClickCapture?(this: EventListenerThisType, ev: MouseEvent): any; + onCompassNeedsCalibration?(this: EventListenerThisType, ev: Event): any; + onCompassNeedsCalibrationCapture?(this: EventListenerThisType, ev: Event): any; + onContextMenu?(this: EventListenerThisType, ev: PointerEvent): any; + onContextMenuCapture?(this: EventListenerThisType, ev: PointerEvent): any; + onDblClick?(this: EventListenerThisType, ev: MouseEvent): any; + onDblClickCapture?(this: EventListenerThisType, ev: MouseEvent): any; + onDeviceMotion?(this: EventListenerThisType, ev: DeviceMotionEvent): any; + onDeviceMotionCapture?(this: EventListenerThisType, ev: DeviceMotionEvent): any; + onDeviceOrientation?(this: EventListenerThisType, ev: DeviceOrientationEvent): any; + onDeviceOrientationCapture?(this: EventListenerThisType, ev: DeviceOrientationEvent): any; + onDrag?(this: EventListenerThisType, ev: DragEvent): any; + onDragCapture?(this: EventListenerThisType, ev: DragEvent): any; + onDragEnd?(this: EventListenerThisType, ev: DragEvent): any; + onDragEndCapture?(this: EventListenerThisType, ev: DragEvent): any; + onDragEnter?(this: EventListenerThisType, ev: DragEvent): any; + onDragEnterCapture?(this: EventListenerThisType, ev: DragEvent): any; + onDragLeave?(this: EventListenerThisType, ev: DragEvent): any; + onDragLeaveCapture?(this: EventListenerThisType, ev: DragEvent): any; + onDragOver?(this: EventListenerThisType, ev: DragEvent): any; + onDragOverCapture?(this: EventListenerThisType, ev: DragEvent): any; + onDragStart?(this: EventListenerThisType, ev: DragEvent): any; + onDragStartCapture?(this: EventListenerThisType, ev: DragEvent): any; + onDrop?(this: EventListenerThisType, ev: DragEvent): any; + onDropCapture?(this: EventListenerThisType, ev: DragEvent): any; + onDurationChange?(this: EventListenerThisType, ev: Event): any; + onDurationChangeCapture?(this: EventListenerThisType, ev: Event): any; + onEmptied?(this: EventListenerThisType, ev: Event): any; + onEmptiedCapture?(this: EventListenerThisType, ev: Event): any; + onEnded?(this: EventListenerThisType, ev: Event): any; + onEndedCapture?(this: EventListenerThisType, ev: Event): any; + onError?(this: EventListenerThisType, ...args: OnErrorEventHandlerArgs): any; + onErrorCapture?(this: EventListenerThisType, ...args: OnErrorEventHandlerArgs): any; + onFocus?(this: EventListenerThisType, ev: FocusEvent): any; + onFocusCapture?(this: EventListenerThisType, ev: FocusEvent): any; + onHashChange?(this: EventListenerThisType, ev: HashChangeEvent): any; + onHashChangeCapture?(this: EventListenerThisType, ev: HashChangeEvent): any; + onInput?(this: EventListenerThisType, ev: Event): any; + onInputCapture?(this: EventListenerThisType, ev: Event): any; + onKeyDown?(this: EventListenerThisType, ev: KeyboardEvent): any; + onKeyDownCapture?(this: EventListenerThisType, ev: KeyboardEvent): any; + onKeyPress?(this: EventListenerThisType, ev: KeyboardEvent): any; + onKeyPressCapture?(this: EventListenerThisType, ev: KeyboardEvent): any; + onKeyUp?(this: EventListenerThisType, ev: KeyboardEvent): any; + onKeyUpCapture?(this: EventListenerThisType, ev: KeyboardEvent): any; + onLoad?(this: EventListenerThisType, ev: Event): any; + onLoadCapture?(this: EventListenerThisType, ev: Event): any; + onLoadedData?(this: EventListenerThisType, ev: Event): any; + onLoadedDataCapture?(this: EventListenerThisType, ev: Event): any; + onLoadedMetadata?(this: EventListenerThisType, ev: Event): any; + onLoadedMetadataCapture?(this: EventListenerThisType, ev: Event): any; + onLoadStart?(this: EventListenerThisType, ev: Event): any; + onLoadStartCapture?(this: EventListenerThisType, ev: Event): any; + onMessage?(this: EventListenerThisType, ev: MessageEvent): any; + onMessageCapture?(this: EventListenerThisType, ev: MessageEvent): any; + onMouseDown?(this: EventListenerThisType, ev: MouseEvent): any; + onMouseDownCapture?(this: EventListenerThisType, ev: MouseEvent): any; + onMouseEnter?(this: EventListenerThisType, ev: MouseEvent): any; + onMouseEnterCapture?(this: EventListenerThisType, ev: MouseEvent): any; + onMouseLeave?(this: EventListenerThisType, ev: MouseEvent): any; + onMouseLeaveCapture?(this: EventListenerThisType, ev: MouseEvent): any; + onMouseMove?(this: EventListenerThisType, ev: MouseEvent): any; + onMouseMoveCapture?(this: EventListenerThisType, ev: MouseEvent): any; + onMouseOut?(this: EventListenerThisType, ev: MouseEvent): any; + onMouseOutCapture?(this: EventListenerThisType, ev: MouseEvent): any; + onMouseOver?(this: EventListenerThisType, ev: MouseEvent): any; + onMouseOverCapture?(this: EventListenerThisType, ev: MouseEvent): any; + onMouseUp?(this: EventListenerThisType, ev: MouseEvent): any; + onMouseUpCapture?(this: EventListenerThisType, ev: MouseEvent): any; + onMouseWheel?(this: EventListenerThisType, ev: WheelEvent): any; + onMouseWheelCapture?(this: EventListenerThisType, ev: WheelEvent): any; + onMsGestureChange?(this: EventListenerThisType, ev: MSGestureEvent): any; + onMsGestureChangeCapture?(this: EventListenerThisType, ev: MSGestureEvent): any; + onMsGestureDoubleTap?(this: EventListenerThisType, ev: MSGestureEvent): any; + onMsGestureDoubleTapCapture?(this: EventListenerThisType, ev: MSGestureEvent): any; + onMsGestureEnd?(this: EventListenerThisType, ev: MSGestureEvent): any; + onMsGestureEndCapture?(this: EventListenerThisType, ev: MSGestureEvent): any; + onMsGestureHold?(this: EventListenerThisType, ev: MSGestureEvent): any; + onMsGestureHoldCapture?(this: EventListenerThisType, ev: MSGestureEvent): any; + onMsGestureStart?(this: EventListenerThisType, ev: MSGestureEvent): any; + onMsGestureStartCapture?(this: EventListenerThisType, ev: MSGestureEvent): any; + onMsGestureTap?(this: EventListenerThisType, ev: MSGestureEvent): any; + onMsGestureTapCapture?(this: EventListenerThisType, ev: MSGestureEvent): any; + onMsInertiaStart?(this: EventListenerThisType, ev: MSGestureEvent): any; + onMsInertiaStartCapture?(this: EventListenerThisType, ev: MSGestureEvent): any; + onMsPointerCancel?(this: EventListenerThisType, ev: MSPointerEvent): any; + onMsPointerCancelCapture?(this: EventListenerThisType, ev: MSPointerEvent): any; + onMsPointerDown?(this: EventListenerThisType, ev: MSPointerEvent): any; + onMsPointerDownCapture?(this: EventListenerThisType, ev: MSPointerEvent): any; + onMsPointerEnter?(this: EventListenerThisType, ev: MSPointerEvent): any; + onMsPointerEnterCapture?(this: EventListenerThisType, ev: MSPointerEvent): any; + onMsPointerLeave?(this: EventListenerThisType, ev: MSPointerEvent): any; + onMsPointerLeaveCapture?(this: EventListenerThisType, ev: MSPointerEvent): any; + onMsPointerMove?(this: EventListenerThisType, ev: MSPointerEvent): any; + onMsPointerMoveCapture?(this: EventListenerThisType, ev: MSPointerEvent): any; + onMsPointerOut?(this: EventListenerThisType, ev: MSPointerEvent): any; + onMsPointerOutCapture?(this: EventListenerThisType, ev: MSPointerEvent): any; + onMsPointerOver?(this: EventListenerThisType, ev: MSPointerEvent): any; + onMsPointerOverCapture?(this: EventListenerThisType, ev: MSPointerEvent): any; + oNmsPointerUp?(this: EventListenerThisType, ev: MSPointerEvent): any; + oNmsPointerUpCapture?(this: EventListenerThisType, ev: MSPointerEvent): any; + onOffline?(this: EventListenerThisType, ev: Event): any; + onOfflineCapture?(this: EventListenerThisType, ev: Event): any; + onOnline?(this: EventListenerThisType, ev: Event): any; + onOnlineCapture?(this: EventListenerThisType, ev: Event): any; + onOrientationChange?(this: EventListenerThisType, ev: Event): any; + onOrientationChangeCapture?(this: EventListenerThisType, ev: Event): any; + onPageHide?(this: EventListenerThisType, ev: PageTransitionEvent): any; + onPageHideCapture?(this: EventListenerThisType, ev: PageTransitionEvent): any; + onPageShow?(this: EventListenerThisType, ev: PageTransitionEvent): any; + onPageShowCapture?(this: EventListenerThisType, ev: PageTransitionEvent): any; + onPause?(this: EventListenerThisType, ev: Event): any; + onPauseCapture?(this: EventListenerThisType, ev: Event): any; + onPlay?(this: EventListenerThisType, ev: Event): any; + onPlayCapture?(this: EventListenerThisType, ev: Event): any; + onPlaying?(this: EventListenerThisType, ev: Event): any; + onPlayingCapture?(this: EventListenerThisType, ev: Event): any; + onPopState?(this: EventListenerThisType, ev: PopStateEvent): any; + onPopStateCapture?(this: EventListenerThisType, ev: PopStateEvent): any; + onProgress?(this: EventListenerThisType, ev: ProgressEvent): any; + onProgressCapture?(this: EventListenerThisType, ev: ProgressEvent): any; + onRateChange?(this: EventListenerThisType, ev: Event): any; + onRateChangeCapture?(this: EventListenerThisType, ev: Event): any; + onReadyStateChange?(this: EventListenerThisType, ev: ProgressEvent): any; + onReadyStateChangeCapture?(this: EventListenerThisType, ev: ProgressEvent): any; + onReset?(this: EventListenerThisType, ev: Event): any; + onResetCapture?(this: EventListenerThisType, ev: Event): any; + onResize?(this: EventListenerThisType, ev: UIEvent): any; + onResizeCapture?(this: EventListenerThisType, ev: UIEvent): any; + onScroll?(this: EventListenerThisType, ev: UIEvent): any; + onScrollCapture?(this: EventListenerThisType, ev: UIEvent): any; + onSeeked?(this: EventListenerThisType, ev: Event): any; + onSeekedCapture?(this: EventListenerThisType, ev: Event): any; + onSeeking?(this: EventListenerThisType, ev: Event): any; + onSeekingCapture?(this: EventListenerThisType, ev: Event): any; + onSelect?(this: EventListenerThisType, ev: UIEvent): any; + onSelectCapture?(this: EventListenerThisType, ev: UIEvent): any; + onSelectionChange?(this: EventListenerThisType, ev: Event): any; + onSelectionChangeCapture?(this: EventListenerThisType, ev: Event): any; + onStalled?(this: EventListenerThisType, ev: Event): any; + onStalledCapture?(this: EventListenerThisType, ev: Event): any; + onStorage?(this: EventListenerThisType, ev: StorageEvent): any; + onStorageCapture?(this: EventListenerThisType, ev: StorageEvent): any; + onSubmit?(this: EventListenerThisType, ev: Event): any; + onSubmitCapture?(this: EventListenerThisType, ev: Event): any; + onSuspend?(this: EventListenerThisType, ev: Event): any; + onSuspendCapture?(this: EventListenerThisType, ev: Event): any; + onTimeUpdate?(this: EventListenerThisType, ev: Event): any; + onTimeUpdateCapture?(this: EventListenerThisType, ev: Event): any; + onTouchCancel?(this: EventListenerThisType, ev: TouchEvent): any; + onTouchCancelCapture?(this: EventListenerThisType, ev: TouchEvent): any; + onTouchEnd?(this: EventListenerThisType, ev: TouchEvent): any; + onTouchEndCapture?(this: EventListenerThisType, ev: TouchEvent): any; + onTouchMove?(this: EventListenerThisType, ev: TouchEvent): any; + onTouchMoveCapture?(this: EventListenerThisType, ev: TouchEvent): any; + onTouchStart?(this: EventListenerThisType, ev: TouchEvent): any; + onTouchStartCapture?(this: EventListenerThisType, ev: TouchEvent): any; + onUnload?(this: EventListenerThisType, ev: Event): any; + onUnloadCapture?(this: EventListenerThisType, ev: Event): any; + onVolumeChange?(this: EventListenerThisType, ev: Event): any; + onVolumeChangeCapture?(this: EventListenerThisType, ev: Event): any; + onWaiting?(this: EventListenerThisType, ev: Event): any; + onWaitingCapture?(this: EventListenerThisType, 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 extends React.PureComponent> { } 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"; + + { }} />; + { }, { passive: true, capture: true })} />; + { }}/>; + { }} />; +; +; 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" } 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 // Diogo Corrêa @@ -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; /** * Process each search word and text to highlight before comparing (eg remove accents); signature * (text: string): string diff --git a/types/react-highlight-words/react-highlight-words-tests.tsx b/types/react-highlight-words/react-highlight-words-tests.tsx index de63c6d9ec..de1100e0de 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}) => ({children}); + class HighlighterTest extends React.Component { render() { return (
text} searchWords={["el", "or"]} textToHighlight="Hello World" 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 { 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; 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; } -export interface DialogActionListProps { +export interface DialogFooterProps { bordered?: boolean; style?: StyleProp; } @@ -70,9 +70,7 @@ export interface DialogProps { onDismiss?: () => void; onTouchOutside?: () => void; onHardwareBackPress?: () => boolean; - actions?: any[]; - actionContainerStyle?: StyleProp; - actionsBordered?: boolean; + footer?: any; useNativeDriver?: boolean; } @@ -97,7 +95,7 @@ export class SlideAnimation { } export class DialogContent extends React.Component { } -export class DialogActionList extends React.Component { } +export class DialogFooter extends React.Component { } export class DialogButton extends React.Component { } export class DialogTitle extends React.Component { } export class Overlay extends React.Component { } 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 { this.scalingPopupDialog = popupDialog} dialogTitle={} dialogAnimation={scaleAnimation} - actions={[ - this.dismissPopupDialog(this.scalingPopupDialog)} - textStyle={{ color: "red" }} - key="button-1" - />, - ]} + footer={ + + this.dismissPopupDialog(this.scalingPopupDialog)} + textStyle={{ color: "red" }} + bordered + key="button-1" + /> + {}} + key="button-2" + /> + + } /> this.slidingPopupDialog = popupDialog} dialogTitle={} diff --git a/types/react-native-tab-view/index.d.ts b/types/react-native-tab-view/index.d.ts index 078247e97d..a6e6b27735 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 // Kyle Roach // Tim Wang +// Gerardo Pacheco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { PureComponent, ReactNode, ComponentType } from 'react' @@ -201,15 +202,21 @@ export type IndicatorProps< export type TabBarProps = SceneRendererProps< T > & { - scrollEnabled?: boolean + getLabelText?: (scene: Scene) => string | undefined | null + getAccessible?: (scene: Scene) => boolean + getAccessibilityLabel?: (scene: Scene) => string | undefined | null + getTestID?: (scene: Scene) => string | undefined | null + renderIcon?: (scene: Scene) => ReactNode + renderLabel?: (scene: Scene) => ReactNode + renderIndicator?: (props: IndicatorProps) => ReactNode + renderBadge?: (scene: Scene) => ReactNode + onTabPress?: (scene: Scene) => void + onTabLongPress?: (scene: Scene) => void pressColor?: string pressOpacity?: number - getLabelText?: (scene: Scene) => string | undefined | null - renderLabel?: (scene: Scene) => ReactNode - renderIcon?: (scene: Scene) => ReactNode - renderBadge?: (scene: Scene) => ReactNode - renderIndicator?: (props: IndicatorProps) => ReactNode - onTabPress?: (scene: Scene) => void + scrollEnabled?: boolean + bounces?: boolean + useNativeDriver?: boolean; tabStyle?: StyleProp indicatorStyle?: StyleProp labelStyle?: StyleProp diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 4b06119df2..ad641ce049 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -16,6 +16,7 @@ // Kacper Wiszczuk // Ryan Nickel // Souvik Ghosh +// Cheng Gibson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -6296,21 +6297,6 @@ export interface ScrollViewPropsIOS { */ scrollsToTop?: boolean; - /** - * When snapToInterval is set, snapToAlignment will define the relationship of the the snapping to the scroll view. - * - start (the default) will align the snap at the left (horizontal) or top (vertical) - * - center will align the snap in the center - * - end will align the snap at the right (horizontal) or bottom (vertical) - */ - snapToAlignment?: "start" | "center" | "end"; - - /** - * When set, causes the scroll view to stop at multiples of the value of snapToInterval. - * This can be used for paginating through children that have lengths smaller than the scroll view. - * Used in combination with snapToAlignment. - */ - snapToInterval?: number; - /** * An array of child indices determining which children get docked to the * top of the screen when scrolling. For example passing @@ -6483,6 +6469,44 @@ export interface ScrollViewProps extends ViewProps, ScrollViewPropsIOS, ScrollVi * functionality for the ScrollView. */ refreshControl?: React.ReactElement; + + /** + * When `snapToInterval` is set, `snapToAlignment` will define the relationship of the the snapping to the scroll view. + * - `start` (the default) will align the snap at the left (horizontal) or top (vertical) + * - `center` will align the snap in the center + * - `end` will align the snap at the right (horizontal) or bottom (vertical) + */ + snapToAlignment?: "start" | "center" | "end"; + + /** + * When set, causes the scroll view to stop at multiples of the value of `snapToInterval`. + * This can be used for paginating through children that have lengths smaller than the scroll view. + * Used in combination with `snapToAlignment` and `decelerationRate="fast"`. Overrides less + * configurable `pagingEnabled` prop. + */ + snapToInterval?: number; + + /** + * When set, causes the scroll view to stop at the defined offsets. This can be used for + * paginating through variously sized children that have lengths smaller than the scroll view. + * Typically used in combination with `decelerationRate="fast"`. Overrides less configurable + * `pagingEnabled` and `snapToInterval` props. + */ + snapToOffsets?: number[]; + + /** + * Use in conjuction with `snapToOffsets`. By default, the beginning of the list counts as a + * snap offset. Set `snapToStart` to false to disable this behavior and allow the list to scroll + * freely between its start and the first `snapToOffsets` offset. The default value is true. + */ + snapToStart?: boolean; + + /** + * Use in conjuction with `snapToOffsets`. By default, the end of the list counts as a snap + * offset. Set `snapToEnd` to false to disable this behavior and allow the list to scroll freely + * between its end and the last `snapToOffsets` offset. The default value is true. + */ + snapToEnd?: boolean; } declare class ScrollViewComponent extends React.Component {} @@ -8995,8 +9019,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..622e2b28c8 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" { @@ -453,6 +454,9 @@ class ScrollerListComponentTest extends React.Component<{}, { dataSource: ListVi nestedScrollEnabled={true} invertStickyHeaders={true} contentOffset={{ x: 0, y: 0 }} + snapToStart={false} + snapToEnd={false} + snapToOffsets={[100, 300, 500]} {...props} style={[scrollViewStyle1.scrollView, scrollViewStyle2]} /> @@ -843,3 +847,8 @@ const ShareTest = () => { } }); }; + +const KeyboardTest = () => { + const subscriber = Keyboard.addListener("keyboardDidHide", (event) => {event}); + subscriber.remove(); +} 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 // Shingo Sato // SPWizard01 +// Kevin Rambaud // 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 // Simon Archer // Yasunori Ohoka +// Kevin Rambaud // 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-test-renderer/index.d.ts b/types/react-test-renderer/index.d.ts index c147d5c190..abdae1c908 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 // Lochbrunner // John Reilly // John Gozde +// Jessica Franco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -50,3 +51,26 @@ export interface TestRendererOptions { createNodeMock(element: ReactElement): any; } export function create(nextElement: ReactElement, 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. +// 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. +// Ideally this should be as hard to accidentally use as possible. +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/react-test-renderer-tests.ts b/types/react-test-renderer/react-test-renderer-tests.ts index 83dc510e2b..48d861cf62 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,12 @@ 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); +// $ExpectError +Promise.resolve(act(() => {})); 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 type DependencyList = ReadonlyArray; - // 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 { 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>( reducer: R, initialState: ReducerState, 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); 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 // ryee-dev // jamesmckenzie +// sara f-p // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -10,7 +11,7 @@ import * as React from "react"; export interface BaseProps extends React.ClassAttributes { className?: string; - as?: string; + as?: any; } export interface SpaceProps extends BaseProps { 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 '../'; diff --git a/types/redux-form/index.d.ts b/types/redux-form/index.d.ts index 6915032138..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 7.4 +// Type definitions for redux-form 7.5 // Project: https://github.com/erikras/redux-form // Definitions by: Carson Full // Daniel Lytkin @@ -12,6 +12,7 @@ // Maddi Joyce // Kamil Wojcik // Mohamed Shaaban +// Ethan Setnik // 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, { 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. */ diff --git a/types/solidity-parser-antlr/index.d.ts b/types/solidity-parser-antlr/index.d.ts index 062a4ed918..7b92aefb22 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 @@ -241,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; diff --git a/types/spellchecker/index.d.ts b/types/spellchecker/index.d.ts new file mode 100644 index 0000000000..01064d0688 --- /dev/null +++ b/types/spellchecker/index.d.ts @@ -0,0 +1,61 @@ +// Type definitions for spellchecker 3.5 +// Project: http://atom.github.io/node-spellchecker +// Definitions by: Dale Fenton +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/* --------------------------------------------------------------------------- + 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; + +/** + * 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" } 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); diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index 5eebdd2ff0..2b46cbb3af 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; diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index 19b9afcd5f..788e8c305f 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -421,6 +421,8 @@ export interface JustifyItemsProps { justifyItems?: ResponsiveValue; } +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..1a008fa045 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, @@ -253,7 +255,8 @@ interface FlexComponentProps JustifyContentProps, FlexWrapProps, FlexBasisProps, - FlexDirectionProps {} + FlexDirectionProps, + JustifyItemsProps {} const Flex: React.ComponentType = styled` ${alignItems}; ${alignContent}; @@ -261,6 +264,7 @@ const Flex: React.ComponentType = styled` ${flexWrap}; ${flexBasis}; ${flexDirection}; + ${justifyItems}; `; interface GridComponentProps @@ -427,6 +431,10 @@ const test = () => ( + // justifyItems + + + // gridGap diff --git a/types/url-parse/index.d.ts b/types/url-parse/index.d.ts index 8fc22dbfc0..cb3bc75dd5 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; }; }; 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 +// Naveen Kumar Sangi +// 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(); diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index c6909a4886..e2f1cb8111 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -33,17 +33,20 @@ 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; + type VictoryStyleObject = { [K in keyof React.CSSProperties]: StringOrNumberOrCallback }; /** * Style interface used in components/themeing */ export interface VictoryStyleInterface { - parent?: React.CSSProperties; - data?: React.CSSProperties; - labels?: React.CSSProperties; - tickLabels?: React.CSSProperties; + parent?: VictoryStyleObject; + data?: VictoryStyleObject; + labels?: VictoryStyleObject; } export interface VictoryAnimationProps { @@ -122,16 +125,19 @@ declare module "victory" { * Event handlers are currently only called with their corresponding events. */ events?: React.DOMAttributes; - /** - * 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 +147,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 `` 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 + * elements. When text is given as an array, separate 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. */ @@ -568,7 +595,7 @@ declare module "victory" { /** * The style prop applies SVG style properties to the rendered flyout container. These props will be passed to the flyoutComponent. */ - flyoutStyle?: React.CSSProperties; + 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, @@ -1002,65 +1029,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 +1175,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"axis" | "axisLabel" | "grid" | "ticks" | "tickLabels" | "parent", number | string>[]; /** @@ -1198,20 +1226,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 + * element with standalone={false} parent styles will be applied to the enclosing tag. + * Many styles that can be applied to a parent will not be expressed when applied to a . + * + * 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 +1387,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; /** @@ -1373,16 +1420,16 @@ declare module "victory" { 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 @@ -1449,7 +1496,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface[]; /** @@ -1580,7 +1626,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface[]; /** @@ -1685,7 +1730,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** @@ -1752,7 +1796,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", number | string>[]; /** @@ -1995,7 +2038,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** @@ -2113,7 +2155,6 @@ declare module "victory" { * } * } * ]} - *}} */ events?: EventPropTypeInterface<"data" | "labels" | "parent", StringOrNumberOrCallback>[]; /** @@ -2220,7 +2261,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 = ; +test = ( + datum.label} + labelPlacement='perpendicular' + renderInPortal={true} + > + {"data viz \n is \n fun!"} + +); + +test = ( + + {"data viz \n is \n fun!"} + +); + // VictoryArea test test = ( + "Mercury", + "Venus", + "Earth", + "Mars", + "Jupiter" + ]} /> ); test = ( 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 = ( d.x, + stroke: (datum, active) => active ? datum.x : datum.y, + strokeWidth: 3 + } + }} x={"amount"} y={(data) => (data.yield + data.error)} /> diff --git a/types/video.js/index.d.ts b/types/video.js/index.d.ts index 62bbf83362..2c2457e3ea 100644 --- a/types/video.js/index.d.ts +++ b/types/video.js/index.d.ts @@ -3713,6 +3713,21 @@ declare namespace videojs { new (player: Player, options?: ComponentOptions): MouseTimeDisplay }; + enum ReadyState { + HaveNothing = 0, + HaveMetadata = 1, + HaveCurrentData = 2, + HaveFutureData = 3, + 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. @@ -4249,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 @@ -4342,6 +4364,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. @@ -4609,6 +4637,7 @@ declare namespace videojs { fluid?: boolean; height?: number; html5?: any; + inactivityTimeout?: number; language?: string; languages?: { [code: string]: LanguageTranslations }; loop?: boolean; diff --git a/types/video.js/video.js-tests.ts b/types/video.js/video.js-tests.ts index 378a7150f3..e21d7fe581 100644 --- a/types/video.js/video.js-tests.ts +++ b/types/video.js/video.js-tests.ts @@ -57,8 +57,12 @@ videojs("example_video_1").ready(function() { this.height(480); + const readyState: videojs.ReadyState = this.readyState(); + this.requestFullscreen(); + const networkState: videojs.NetworkState = this.networkState(); + testEvents(this); testComponents(this); diff --git a/types/webappsec-credential-management/index.d.ts b/types/webappsec-credential-management/index.d.ts index 4c47ee7cc8..ce3e7ef26c 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 +// Joao Peixoto // 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 | null; } /** diff --git a/types/webappsec-credential-management/webappsec-credential-management-tests.ts b/types/webappsec-credential-management/webappsec-credential-management-tests.ts index 2afa9f8785..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) { @@ -352,3 +354,17 @@ 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), + userHandle: null, + }; + sampleResponse.userHandle === undefined; +} 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 // Alan Agius // Artur Androsovych +// Dave Cardwell // 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); 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; + captureImage(imageOptions?: Device.CaptureImageOptions): Async.PromiseLike; /** * Invokes the device camera to capture video. diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 9f3cb687a2..dc73ae6bd9 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -26,6 +26,7 @@ export function addMethod>( export function ref(path: string, options?: { contextPrefix: string }): Ref; export function lazy(fn: (value: T) => Schema): Lazy; export function setLocale(customLocale: LocaleObject): void; +export function isSchema(obj: any): obj is Schema; export const mixed: MixedSchemaConstructor; export const string: StringSchemaConstructor; @@ -227,7 +228,7 @@ export interface TestContext { parent: any; schema: Schema; resolve: (value: any) => any; - createError: (params: { path: string; message: string }) => ValidationError; + createError: (params?: { path?: string; message?: string }) => ValidationError; } export interface ValidateOptions { diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index a90a7df25d..c6717e95ad 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(yup.number, "minimum", function( this, @@ -199,6 +204,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);