From 5b6137d6c9a16c9da2523bd33028986fdd254f08 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 19 Aug 2020 11:30:57 -0700 Subject: [PATCH] flip node typesVersions --- types/node/assert.d.ts | 20 +- types/node/base.d.ts | 61 +- types/node/index.d.ts | 92 +- types/node/node-tests.ts | 366 +- types/node/package.json | 12 +- types/node/{v13/ts3.7 => ts3.1}/assert.d.ts | 20 +- types/node/ts3.1/base.d.ts | 41 + types/node/{ => ts3.1}/fs.d.ts | 0 types/node/{ => ts3.1}/globals.d.ts | 0 types/node/{ => ts3.1}/globals.global.d.ts | 0 types/node/ts3.1/index.d.ts | 91 + types/node/ts3.1/node-tests.ts | 351 ++ types/node/{ts3.2 => ts3.1}/tsconfig.json | 0 types/node/ts3.1/tslint.json | 10 + types/node/{ => ts3.1}/util.d.ts | 0 types/node/{ts3.2 => ts3.4}/base.d.ts | 0 types/node/{ts3.2 => ts3.4}/fs.d.ts | 0 types/node/{ts3.2 => ts3.4}/globals.d.ts | 0 types/node/{ts3.2 => ts3.4}/index.d.ts | 0 types/node/{ts3.2 => ts3.4}/node-tests.ts | 0 types/node/{ts3.2 => ts3.4}/process.d.ts | 0 types/node/{ts3.7 => ts3.4}/tsconfig.json | 0 types/node/{ts3.2 => ts3.4}/tslint.json | 0 types/node/{ts3.2 => ts3.4}/util.d.ts | 0 types/node/{ts3.5 => ts3.6}/base.d.ts | 0 .../node/{ts3.5 => ts3.6}/globals.global.d.ts | 0 types/node/{ts3.5 => ts3.6}/index.d.ts | 0 types/node/{ts3.5 => ts3.6}/node-tests.ts | 0 types/node/{ts3.5 => ts3.6}/test/globals.ts | 0 types/node/{ts3.5 => ts3.6}/tsconfig.json | 0 types/node/{ts3.5 => ts3.6}/tslint.json | 0 types/node/{ts3.5 => ts3.6}/wasi.d.ts | 0 types/node/ts3.7/base.d.ts | 20 - types/node/ts3.7/index.d.ts | 5 - types/node/ts3.7/node-tests.ts | 59 - types/node/tslint.json | 16 +- types/node/v10/assert.d.ts | 10 +- types/node/v10/base.d.ts | 60 +- types/node/v10/index.d.ts | 95 +- types/node/v10/node-tests.ts | 5068 +---------------- types/node/v10/package.json | 8 +- types/node/v10/{ts3.7 => ts3.1}/assert.d.ts | 10 +- types/node/v10/ts3.1/base.d.ts | 40 + types/node/v10/{ => ts3.1}/globals.d.ts | 0 types/node/v10/ts3.1/index.d.ts | 94 + types/node/v10/ts3.1/node-tests.ts | 5061 ++++++++++++++++ types/node/v10/{ts3.2 => ts3.1}/tsconfig.json | 0 types/node/v10/ts3.1/tslint.json | 10 + types/node/v10/{ => ts3.1}/util.d.ts | 0 types/node/v10/{ts3.2 => ts3.6}/base.d.ts | 0 types/node/v10/{ts3.2 => ts3.6}/globals.d.ts | 0 types/node/v10/{ts3.2 => ts3.6}/index.d.ts | 0 types/node/v10/{ts3.2 => ts3.6}/node-tests.ts | 0 types/node/v10/{ts3.7 => ts3.6}/tsconfig.json | 0 types/node/v10/{ts3.2 => ts3.6}/tslint.json | 0 types/node/v10/{ts3.2 => ts3.6}/util.d.ts | 0 types/node/v10/ts3.7/base.d.ts | 20 - types/node/v10/ts3.7/index.d.ts | 5 - types/node/v10/ts3.7/node-tests.ts | 59 - types/node/v10/ts3.7/tslint.json | 10 - types/node/v10/tslint.json | 16 +- types/node/v11/assert.d.ts | 10 +- types/node/v11/base.d.ts | 60 +- types/node/v11/index.d.ts | 104 +- types/node/v11/node-tests.ts | 1219 +--- types/node/v11/package.json | 8 +- .../node/{v12/ts3.7 => v11/ts3.1}/assert.d.ts | 10 +- types/node/v11/ts3.1/base.d.ts | 40 + types/node/v11/{ => ts3.1}/globals.d.ts | 0 types/node/v11/ts3.1/index.d.ts | 103 + types/node/v11/ts3.1/node-tests.ts | 1204 ++++ types/node/v11/{ts3.2 => ts3.1}/tsconfig.json | 0 types/node/v11/ts3.1/tslint.json | 10 + types/node/v11/{ => ts3.1}/util.d.ts | 0 types/node/v11/{ts3.2 => ts3.6}/base.d.ts | 0 types/node/v11/{ts3.2 => ts3.6}/globals.d.ts | 0 types/node/v11/{ts3.2 => ts3.6}/index.d.ts | 0 types/node/v11/{ts3.2 => ts3.6}/node-tests.ts | 0 types/node/v11/{ts3.7 => ts3.6}/tsconfig.json | 0 types/node/v11/{ts3.2 => ts3.6}/tslint.json | 0 types/node/v11/{ts3.2 => ts3.6}/util.d.ts | 0 types/node/v11/ts3.7/base.d.ts | 20 - types/node/v11/ts3.7/index.d.ts | 5 - types/node/v11/ts3.7/node-tests.ts | 59 - types/node/v11/ts3.7/tslint.json | 10 - types/node/v11/tslint.json | 16 +- types/node/v12/assert.d.ts | 10 +- types/node/v12/base.d.ts | 60 +- types/node/v12/index.d.ts | 111 +- types/node/v12/node-tests.ts | 913 +-- types/node/v12/package.json | 12 +- .../node/{v11/ts3.7 => v12/ts3.1}/assert.d.ts | 10 +- types/node/v12/ts3.1/base.d.ts | 40 + types/node/v12/{ => ts3.1}/fs.d.ts | 0 types/node/v12/{ => ts3.1}/globals.d.ts | 0 types/node/v12/ts3.1/index.d.ts | 110 + types/node/v12/ts3.1/node-tests.ts | 898 +++ types/node/v12/{ts3.2 => ts3.1}/tsconfig.json | 0 types/node/v12/ts3.1/tslint.json | 9 + types/node/v12/{ => ts3.1}/util.d.ts | 0 types/node/v12/{ts3.2 => ts3.3}/base.d.ts | 0 types/node/v12/{ts3.2 => ts3.3}/fs.d.ts | 0 types/node/v12/{ts3.2 => ts3.3}/globals.d.ts | 0 types/node/v12/{ts3.2 => ts3.3}/index.d.ts | 0 types/node/v12/{ts3.2 => ts3.3}/node-tests.ts | 0 types/node/v12/{ts3.7 => ts3.3}/tsconfig.json | 0 types/node/v12/{ts3.2 => ts3.3}/tslint.json | 0 types/node/v12/{ts3.2 => ts3.3}/util.d.ts | 0 types/node/v12/{ts3.4 => ts3.6}/base.d.ts | 0 .../v12/{ts3.4 => ts3.6}/globals.global.d.ts | 0 types/node/v12/{ts3.4 => ts3.6}/index.d.ts | 0 types/node/v12/{ts3.4 => ts3.6}/node-tests.ts | 0 .../node/v12/{ts3.4 => ts3.6}/test/globals.ts | 0 types/node/v12/{ts3.4 => ts3.6}/tsconfig.json | 0 types/node/v12/{ts3.4 => ts3.6}/tslint.json | 0 types/node/v12/ts3.7/base.d.ts | 20 - types/node/v12/ts3.7/index.d.ts | 5 - types/node/v12/ts3.7/node-tests.ts | 59 - types/node/v12/ts3.7/tslint.json | 10 - types/node/v12/tslint.json | 15 +- types/node/v13/assert.d.ts | 10 +- types/node/v13/base.d.ts | 60 +- types/node/v13/index.d.ts | 92 +- types/node/v13/node-tests.ts | 362 +- types/node/v13/package.json | 12 +- types/node/{ts3.7 => v13/ts3.1}/assert.d.ts | 10 +- types/node/v13/ts3.1/base.d.ts | 40 + types/node/v13/{ => ts3.1}/fs.d.ts | 0 types/node/v13/{ => ts3.1}/globals.d.ts | 0 .../node/v13/{ => ts3.1}/globals.global.d.ts | 0 types/node/v13/ts3.1/index.d.ts | 91 + types/node/v13/ts3.1/node-tests.ts | 347 ++ types/node/v13/{ts3.2 => ts3.1}/tsconfig.json | 0 types/node/v13/ts3.1/tslint.json | 10 + types/node/v13/{ => ts3.1}/util.d.ts | 0 types/node/v13/ts3.2/tslint.json | 10 - types/node/v13/{ts3.2 => ts3.4}/base.d.ts | 0 types/node/v13/{ts3.2 => ts3.4}/fs.d.ts | 0 types/node/v13/{ts3.2 => ts3.4}/globals.d.ts | 0 types/node/v13/{ts3.2 => ts3.4}/index.d.ts | 0 types/node/v13/{ts3.2 => ts3.4}/node-tests.ts | 0 types/node/v13/{ts3.7 => ts3.4}/tsconfig.json | 0 types/node/{ts3.7 => v13/ts3.4}/tslint.json | 0 types/node/v13/{ts3.2 => ts3.4}/util.d.ts | 0 types/node/v13/{ts3.5 => ts3.6}/base.d.ts | 0 .../v13/{ts3.5 => ts3.6}/globals.global.d.ts | 0 types/node/v13/{ts3.5 => ts3.6}/index.d.ts | 0 types/node/v13/{ts3.5 => ts3.6}/node-tests.ts | 0 .../node/v13/{ts3.5 => ts3.6}/test/globals.ts | 0 types/node/v13/{ts3.5 => ts3.6}/tsconfig.json | 0 types/node/v13/{ts3.5 => ts3.6}/tslint.json | 0 types/node/v13/{ts3.5 => ts3.6}/wasi.d.ts | 0 types/node/v13/ts3.7/base.d.ts | 20 - types/node/v13/ts3.7/index.d.ts | 5 - types/node/v13/ts3.7/node-tests.ts | 59 - types/node/v13/ts3.7/tslint.json | 10 - types/node/v13/tslint.json | 16 +- types/node/v6/index.d.ts | 47 +- types/node/v6/node-tests.ts | 22 + types/node/v6/package.json | 4 +- types/node/v6/ts3.1/index.d.ts | 48 + types/node/v6/{ts3.2 => ts3.1}/node-tests.ts | 22 - types/node/v6/{ts3.2 => ts3.1}/tsconfig.json | 0 types/node/v6/ts3.1/tslint.json | 40 + types/node/v6/ts3.2/index.d.ts | 15 - types/node/v6/ts3.2/tslint.json | 6 - types/node/v6/tslint.json | 36 +- types/node/v7/index.d.ts | 46 +- types/node/v7/node-tests.ts | 22 + types/node/v7/package.json | 4 +- types/node/v7/ts3.1/index.d.ts | 47 + types/node/v7/{ts3.2 => ts3.1}/node-tests.ts | 22 - types/node/v7/{ts3.2 => ts3.1}/tsconfig.json | 0 types/node/v7/ts3.1/tslint.json | 40 + types/node/v7/ts3.2/index.d.ts | 15 - types/node/v7/ts3.2/tslint.json | 6 - types/node/v7/tslint.json | 36 +- types/node/v8/index.d.ts | 62 +- types/node/v8/node-tests.ts | 33 +- types/node/v8/package.json | 4 +- types/node/v8/ts3.1/index.d.ts | 67 + types/node/v8/{ts3.2 => ts3.1}/node-tests.ts | 33 +- types/node/v8/{ts3.2 => ts3.1}/tsconfig.json | 0 types/node/v8/ts3.1/tslint.json | 18 + types/node/v8/ts3.2/index.d.ts | 23 - types/node/v8/ts3.2/tslint.json | 7 - types/node/v8/tslint.json | 13 +- types/node/v9/index.d.ts | 65 +- types/node/v9/node-tests.ts | 2 +- types/node/v9/package.json | 4 +- types/node/v9/ts3.1/index.d.ts | 70 + types/node/v9/{ts3.2 => ts3.1}/node-tests.ts | 2 +- types/node/v9/{ts3.2 => ts3.1}/tsconfig.json | 0 types/node/v9/ts3.1/tslint.json | 18 + types/node/v9/ts3.2/index.d.ts | 23 - types/node/v9/ts3.2/tslint.json | 7 - types/node/v9/tslint.json | 13 +- 197 files changed, 9493 insertions(+), 9493 deletions(-) rename types/node/{v13/ts3.7 => ts3.1}/assert.d.ts (74%) create mode 100644 types/node/ts3.1/base.d.ts rename types/node/{ => ts3.1}/fs.d.ts (100%) rename types/node/{ => ts3.1}/globals.d.ts (100%) rename types/node/{ => ts3.1}/globals.global.d.ts (100%) create mode 100644 types/node/ts3.1/index.d.ts create mode 100644 types/node/ts3.1/node-tests.ts rename types/node/{ts3.2 => ts3.1}/tsconfig.json (100%) create mode 100644 types/node/ts3.1/tslint.json rename types/node/{ => ts3.1}/util.d.ts (100%) rename types/node/{ts3.2 => ts3.4}/base.d.ts (100%) rename types/node/{ts3.2 => ts3.4}/fs.d.ts (100%) rename types/node/{ts3.2 => ts3.4}/globals.d.ts (100%) rename types/node/{ts3.2 => ts3.4}/index.d.ts (100%) rename types/node/{ts3.2 => ts3.4}/node-tests.ts (100%) rename types/node/{ts3.2 => ts3.4}/process.d.ts (100%) rename types/node/{ts3.7 => ts3.4}/tsconfig.json (100%) rename types/node/{ts3.2 => ts3.4}/tslint.json (100%) rename types/node/{ts3.2 => ts3.4}/util.d.ts (100%) rename types/node/{ts3.5 => ts3.6}/base.d.ts (100%) rename types/node/{ts3.5 => ts3.6}/globals.global.d.ts (100%) rename types/node/{ts3.5 => ts3.6}/index.d.ts (100%) rename types/node/{ts3.5 => ts3.6}/node-tests.ts (100%) rename types/node/{ts3.5 => ts3.6}/test/globals.ts (100%) rename types/node/{ts3.5 => ts3.6}/tsconfig.json (100%) rename types/node/{ts3.5 => ts3.6}/tslint.json (100%) rename types/node/{ts3.5 => ts3.6}/wasi.d.ts (100%) delete mode 100644 types/node/ts3.7/base.d.ts delete mode 100644 types/node/ts3.7/index.d.ts delete mode 100644 types/node/ts3.7/node-tests.ts rename types/node/v10/{ts3.7 => ts3.1}/assert.d.ts (85%) create mode 100644 types/node/v10/ts3.1/base.d.ts rename types/node/v10/{ => ts3.1}/globals.d.ts (100%) create mode 100644 types/node/v10/ts3.1/index.d.ts create mode 100644 types/node/v10/ts3.1/node-tests.ts rename types/node/v10/{ts3.2 => ts3.1}/tsconfig.json (100%) create mode 100644 types/node/v10/ts3.1/tslint.json rename types/node/v10/{ => ts3.1}/util.d.ts (100%) rename types/node/v10/{ts3.2 => ts3.6}/base.d.ts (100%) rename types/node/v10/{ts3.2 => ts3.6}/globals.d.ts (100%) rename types/node/v10/{ts3.2 => ts3.6}/index.d.ts (100%) rename types/node/v10/{ts3.2 => ts3.6}/node-tests.ts (100%) rename types/node/v10/{ts3.7 => ts3.6}/tsconfig.json (100%) rename types/node/v10/{ts3.2 => ts3.6}/tslint.json (100%) rename types/node/v10/{ts3.2 => ts3.6}/util.d.ts (100%) delete mode 100644 types/node/v10/ts3.7/base.d.ts delete mode 100644 types/node/v10/ts3.7/index.d.ts delete mode 100644 types/node/v10/ts3.7/node-tests.ts delete mode 100644 types/node/v10/ts3.7/tslint.json rename types/node/{v12/ts3.7 => v11/ts3.1}/assert.d.ts (85%) create mode 100644 types/node/v11/ts3.1/base.d.ts rename types/node/v11/{ => ts3.1}/globals.d.ts (100%) create mode 100644 types/node/v11/ts3.1/index.d.ts create mode 100644 types/node/v11/ts3.1/node-tests.ts rename types/node/v11/{ts3.2 => ts3.1}/tsconfig.json (100%) create mode 100644 types/node/v11/ts3.1/tslint.json rename types/node/v11/{ => ts3.1}/util.d.ts (100%) rename types/node/v11/{ts3.2 => ts3.6}/base.d.ts (100%) rename types/node/v11/{ts3.2 => ts3.6}/globals.d.ts (100%) rename types/node/v11/{ts3.2 => ts3.6}/index.d.ts (100%) rename types/node/v11/{ts3.2 => ts3.6}/node-tests.ts (100%) rename types/node/v11/{ts3.7 => ts3.6}/tsconfig.json (100%) rename types/node/v11/{ts3.2 => ts3.6}/tslint.json (100%) rename types/node/v11/{ts3.2 => ts3.6}/util.d.ts (100%) delete mode 100644 types/node/v11/ts3.7/base.d.ts delete mode 100644 types/node/v11/ts3.7/index.d.ts delete mode 100644 types/node/v11/ts3.7/node-tests.ts delete mode 100644 types/node/v11/ts3.7/tslint.json rename types/node/{v11/ts3.7 => v12/ts3.1}/assert.d.ts (85%) create mode 100644 types/node/v12/ts3.1/base.d.ts rename types/node/v12/{ => ts3.1}/fs.d.ts (100%) rename types/node/v12/{ => ts3.1}/globals.d.ts (100%) create mode 100644 types/node/v12/ts3.1/index.d.ts create mode 100644 types/node/v12/ts3.1/node-tests.ts rename types/node/v12/{ts3.2 => ts3.1}/tsconfig.json (100%) create mode 100644 types/node/v12/ts3.1/tslint.json rename types/node/v12/{ => ts3.1}/util.d.ts (100%) rename types/node/v12/{ts3.2 => ts3.3}/base.d.ts (100%) rename types/node/v12/{ts3.2 => ts3.3}/fs.d.ts (100%) rename types/node/v12/{ts3.2 => ts3.3}/globals.d.ts (100%) rename types/node/v12/{ts3.2 => ts3.3}/index.d.ts (100%) rename types/node/v12/{ts3.2 => ts3.3}/node-tests.ts (100%) rename types/node/v12/{ts3.7 => ts3.3}/tsconfig.json (100%) rename types/node/v12/{ts3.2 => ts3.3}/tslint.json (100%) rename types/node/v12/{ts3.2 => ts3.3}/util.d.ts (100%) rename types/node/v12/{ts3.4 => ts3.6}/base.d.ts (100%) rename types/node/v12/{ts3.4 => ts3.6}/globals.global.d.ts (100%) rename types/node/v12/{ts3.4 => ts3.6}/index.d.ts (100%) rename types/node/v12/{ts3.4 => ts3.6}/node-tests.ts (100%) rename types/node/v12/{ts3.4 => ts3.6}/test/globals.ts (100%) rename types/node/v12/{ts3.4 => ts3.6}/tsconfig.json (100%) rename types/node/v12/{ts3.4 => ts3.6}/tslint.json (100%) delete mode 100644 types/node/v12/ts3.7/base.d.ts delete mode 100644 types/node/v12/ts3.7/index.d.ts delete mode 100644 types/node/v12/ts3.7/node-tests.ts delete mode 100644 types/node/v12/ts3.7/tslint.json rename types/node/{ts3.7 => v13/ts3.1}/assert.d.ts (86%) create mode 100644 types/node/v13/ts3.1/base.d.ts rename types/node/v13/{ => ts3.1}/fs.d.ts (100%) rename types/node/v13/{ => ts3.1}/globals.d.ts (100%) rename types/node/v13/{ => ts3.1}/globals.global.d.ts (100%) create mode 100644 types/node/v13/ts3.1/index.d.ts create mode 100644 types/node/v13/ts3.1/node-tests.ts rename types/node/v13/{ts3.2 => ts3.1}/tsconfig.json (100%) create mode 100644 types/node/v13/ts3.1/tslint.json rename types/node/v13/{ => ts3.1}/util.d.ts (100%) delete mode 100644 types/node/v13/ts3.2/tslint.json rename types/node/v13/{ts3.2 => ts3.4}/base.d.ts (100%) rename types/node/v13/{ts3.2 => ts3.4}/fs.d.ts (100%) rename types/node/v13/{ts3.2 => ts3.4}/globals.d.ts (100%) rename types/node/v13/{ts3.2 => ts3.4}/index.d.ts (100%) rename types/node/v13/{ts3.2 => ts3.4}/node-tests.ts (100%) rename types/node/v13/{ts3.7 => ts3.4}/tsconfig.json (100%) rename types/node/{ts3.7 => v13/ts3.4}/tslint.json (100%) rename types/node/v13/{ts3.2 => ts3.4}/util.d.ts (100%) rename types/node/v13/{ts3.5 => ts3.6}/base.d.ts (100%) rename types/node/v13/{ts3.5 => ts3.6}/globals.global.d.ts (100%) rename types/node/v13/{ts3.5 => ts3.6}/index.d.ts (100%) rename types/node/v13/{ts3.5 => ts3.6}/node-tests.ts (100%) rename types/node/v13/{ts3.5 => ts3.6}/test/globals.ts (100%) rename types/node/v13/{ts3.5 => ts3.6}/tsconfig.json (100%) rename types/node/v13/{ts3.5 => ts3.6}/tslint.json (100%) rename types/node/v13/{ts3.5 => ts3.6}/wasi.d.ts (100%) delete mode 100644 types/node/v13/ts3.7/base.d.ts delete mode 100644 types/node/v13/ts3.7/index.d.ts delete mode 100644 types/node/v13/ts3.7/node-tests.ts delete mode 100644 types/node/v13/ts3.7/tslint.json create mode 100644 types/node/v6/ts3.1/index.d.ts rename types/node/v6/{ts3.2 => ts3.1}/node-tests.ts (99%) rename types/node/v6/{ts3.2 => ts3.1}/tsconfig.json (100%) create mode 100644 types/node/v6/ts3.1/tslint.json delete mode 100644 types/node/v6/ts3.2/index.d.ts delete mode 100644 types/node/v6/ts3.2/tslint.json create mode 100644 types/node/v7/ts3.1/index.d.ts rename types/node/v7/{ts3.2 => ts3.1}/node-tests.ts (99%) rename types/node/v7/{ts3.2 => ts3.1}/tsconfig.json (100%) create mode 100644 types/node/v7/ts3.1/tslint.json delete mode 100644 types/node/v7/ts3.2/index.d.ts delete mode 100644 types/node/v7/ts3.2/tslint.json create mode 100644 types/node/v8/ts3.1/index.d.ts rename types/node/v8/{ts3.2 => ts3.1}/node-tests.ts (99%) rename types/node/v8/{ts3.2 => ts3.1}/tsconfig.json (100%) create mode 100644 types/node/v8/ts3.1/tslint.json delete mode 100644 types/node/v8/ts3.2/index.d.ts delete mode 100644 types/node/v8/ts3.2/tslint.json create mode 100644 types/node/v9/ts3.1/index.d.ts rename types/node/v9/{ts3.2 => ts3.1}/node-tests.ts (99%) rename types/node/v9/{ts3.2 => ts3.1}/tsconfig.json (100%) create mode 100644 types/node/v9/ts3.1/tslint.json delete mode 100644 types/node/v9/ts3.2/index.d.ts delete mode 100644 types/node/v9/ts3.2/tslint.json diff --git a/types/node/assert.d.ts b/types/node/assert.d.ts index 3f01820b2d..9750dae7de 100644 --- a/types/node/assert.d.ts +++ b/types/node/assert.d.ts @@ -1,5 +1,5 @@ declare module "assert" { - function assert(value: any, message?: string | Error): void; + function assert(value: any, message?: string | Error): asserts value; namespace assert { class AssertionError implements Error { name: string; @@ -19,20 +19,20 @@ declare module "assert" { type AssertPredicate = RegExp | (new() => object) | ((thrown: any) => boolean) | object | Error; function fail(message?: string | Error): never; - /** @deprecated since v10.0.0 - use `fail([message])` or other assert functions instead. */ + /** @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 ok(value: any, message?: string | Error): asserts value; + /** @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. */ + /** @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. */ + /** @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. */ + /** @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 strictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; function notStrictEqual(actual: any, expected: any, message?: string | Error): void; - function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; + function deepStrictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; function throws(block: () => any, message?: string | Error): void; @@ -40,7 +40,7 @@ declare module "assert" { function doesNotThrow(block: () => any, message?: string | Error): void; function doesNotThrow(block: () => any, error: RegExp | Function, message?: string | Error): void; - function ifError(value: any): void; + function ifError(value: any): asserts value is null | undefined; function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; function rejects(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; diff --git a/types/node/base.d.ts b/types/node/base.d.ts index 2abdd0f33a..201cd5678b 100644 --- a/types/node/base.d.ts +++ b/types/node/base.d.ts @@ -1,41 +1,20 @@ -// base definitions for all NodeJS modules that are not specific to any version of TypeScript -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +// NOTE: These definitions support NodeJS and TypeScript 3.7. + +// 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.7/base.d.ts - Definitions specific to TypeScript 3.7 +// - ~/ts3.7/index.d.ts - Definitions specific to TypeScript 3.7 with assert pulled in + +// 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.7-specific augmentations: +/// diff --git a/types/node/index.d.ts b/types/node/index.d.ts index e917b54655..2cd553b853 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1,91 +1,5 @@ -// Type definitions for non-npm package Node.js 14.6 -// Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped -// Alberto Schiabel -// Alexander T. -// Alvis HT Tang -// Andrew Makarov -// Benjamin Toueg -// Bruno Scheufler -// Chigozirim C. -// David Junger -// Deividas Bakanas -// Eugene Y. Q. Shen -// Flarna -// Hannes Magnusson -// Hoàng Văn Khải -// Huw -// Kelvin Jin -// Klaus Meinhardt -// Lishude -// Mariusz Wiktorczyk -// Mohsen Azimi -// Nicolas Even -// Nikita Galkin -// Parambir Singh -// Sebastian Silbermann -// Simon Schick -// Thomas den Hollander -// Wilco Bakker -// wwwy3y3 -// Samuel Ainsworth -// Kyle Uehlein -// Jordi Oliveras Rovira -// Thanik Bhongbhibhat -// Marcin Kopacz -// Trivikram Kamat -// Minh Son Nguyen -// Junxiao Shi -// Ilia Baryshnikov -// ExE Boss -// Surasak Chaisurin -// Piotr Błażejewicz -// Anna Henningsen -// Jason Kwok -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// NOTE: These definitions support NodeJS and TypeScript 3.7. +// This isn't strictly needed since 3.7 has the assert module, but this way we're consistent. +// Typically type modificatons should be made in base.d.ts instead of here -// NOTE: These definitions support NodeJS and TypeScript 3.5. - -// 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.8 -// - ~/ts3.5/index.d.ts - Definitions specific to TypeScript 3.5 - -// NOTE: Augmentations for TypeScript 3.5 and later should use individual files for overrides -// within the respective ~/ts3.5 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.5, so the older definitions will be found here. - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: /// - -// We can't include globals.global.d.ts in globals.d.ts, as it'll cause duplication errors in TypeScript 3.5+ -/// - -// We can't include assert.d.ts in base.d.ts, as it'll cause duplication errors in TypeScript 3.7+ -/// - -// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) -// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files -// just to ensure the names are known and node typings can be used without importing these libs. -// if someone really needs these types the libs need to be added via --lib or in tsconfig.json -interface AsyncIterable { } -interface IterableIterator { } -interface AsyncIterableIterator {} -interface SymbolConstructor { - readonly asyncIterator: symbol; -} -declare var Symbol: SymbolConstructor; -// even this is just a forward declaration some properties are added otherwise -// it would be allowed to pass anything to e.g. Buffer.from() -interface SharedArrayBuffer { - readonly byteLength: number; - slice(begin?: number, end?: number): SharedArrayBuffer; -} - -declare module "util" { - namespace types { - function isBigInt64Array(value: any): boolean; - function isBigUint64Array(value: any): boolean; - } -} diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 7c42658076..983748c1fd 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -1,351 +1,59 @@ -import * as fs from "fs"; -import * as url from "url"; -import * as util from "util"; -import * as http from "http"; -import * as https from "https"; -import * as net from "net"; -import * as console2 from "console"; -import * as timers from "timers"; -import * as inspector from "inspector"; -import * as trace_events from "trace_events"; +import * as assert from 'assert'; -////////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html /// -////////////////////////////////////////////////////// +assert(true, "it's working"); + +assert.ok(true, 'inner functions work as well'); + +assert.throws(() => {}); +assert.throws(() => {}, /Regex test/); +assert.throws( + () => {}, + () => {}, + 'works wonderfully', +); + +assert['fail'](true, true, 'works like a charm'); { - let agent: https.Agent = new https.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256, - maxCachedSessions: 100, - timeout: 15000 - }); - - agent = https.globalAgent; - - let sockets: NodeJS.ReadOnlyDict = agent.sockets; - sockets = agent.freeSockets; - - 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 = []; - - { - function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} - - class MyIncomingMessage extends http.IncomingMessage { - foo: number; - } - - class MyServerResponse extends http.ServerResponse { - foo: string; - } - - let server: https.Server; - - server = new https.Server(); - server = new https.Server(reqListener); - server = new https.Server({ IncomingMessage: MyIncomingMessage}); - - server = new https.Server({ - IncomingMessage: MyIncomingMessage, - ServerResponse: MyServerResponse - }, reqListener); - - server = https.createServer(); - server = https.createServer(reqListener); - server = https.createServer({ IncomingMessage: MyIncomingMessage }); - server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); - - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - const maxHeadersCount: number | null = server.maxHeadersCount; - const headersTimeout: number = server.headersTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } + const a = null as any; + assert.ifError(a); + a; // $ExpectType null | undefined } -///////////////////////////////////////////////////// -/// Timers tests : https://nodejs.org/api/timers.html -///////////////////////////////////////////////////// - { - { - const immediate = timers - .setImmediate(() => { - console.log('immediate'); - }) - .unref() - .ref(); - const b: boolean = immediate.hasRef(); - timers.clearImmediate(immediate); - } - { - const timeout = timers - .setInterval(() => { - console.log('interval'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - timers.clearInterval(timeout); - } - { - const timeout = timers - .setTimeout(() => { - console.log('timeout'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - timers.clearTimeout(timeout); - } - async function testPromisify(doSomething: { - (foo: any, onSuccessCallback: (result: string) => void, onErrorCallback: (reason: any) => void): void; - [util.promisify.custom](foo: any): Promise; - }) { - 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(""); - - // $ExpectType (foo: any) => Promise - const doSomethingPromise = util.promisify(doSomething); - - // $ExpectType string - s = await doSomethingPromise('foo'); - } + const a = true as boolean; + assert(a); + a; // $ExpectType true } -///////////////////////////////////////////////////////// -/// 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 | 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(); - const isConstr: boolean = frame.isConstructor(); - } + // tslint:disable-next-line: no-null-undefined-union + const a = 13 as number | null | undefined; + assert(a); + a; // $ExpectType number } -/////////////////////////////////////////////////////////// -/// 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.profile(); - console.profile('label'); - console.profileEnd(); - console.profileEnd('label'); - console.timeStamp(); - console.timeStamp('label'); - } + const a = true as boolean; + assert.ok(a); + a; // $ExpectType true } -/***************************************************************************** - * * - * The following tests are the modules not mentioned in document but existed * - * * - *****************************************************************************/ - -/////////////////////////////////////////////////////////// -/// 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 | undefined = 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 | 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!; - }); - 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; - }); - } + // tslint:disable-next-line: no-null-undefined-union + const a = 13 as number | null | undefined; + assert.ok(a); + a; // $ExpectType number } -/////////////////////////////////////////////////////////// -/// Trace Events Tests /// -/////////////////////////////////////////////////////////// - { - const enabledCategories: string | undefined = 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(); + const a = 'test' as any; + assert.strictEqual(a, 'test'); + a; // $ExpectType string } -//////////////////////////////////////////////////// -/// Node.js ESNEXT Support -//////////////////////////////////////////////////// - { - const s = 'foo'; - const s1: string = s.trimLeft(); - const s2: string = s.trimRight(); + const a = { b: 2 } as any; + assert.deepStrictEqual(a, { b: 2 }); + a; // $ExpectType { b: number; } } diff --git a/types/node/package.json b/types/node/package.json index f791e46a8a..dd84e4f705 100644 --- a/types/node/package.json +++ b/types/node/package.json @@ -2,19 +2,19 @@ "private": true, "types": "index", "typesVersions": { - ">=3.7.0-0": { + "<=3.1": { "*": [ - "ts3.7/*" + "ts3.1/*" ] }, - ">=3.5.0-0": { + "<=3.4": { "*": [ - "ts3.5/*" + "ts3.4/*" ] }, - ">=3.2.0-0": { + "<=3.6": { "*": [ - "ts3.2/*" + "ts3.6/*" ] } } diff --git a/types/node/v13/ts3.7/assert.d.ts b/types/node/ts3.1/assert.d.ts similarity index 74% rename from types/node/v13/ts3.7/assert.d.ts rename to types/node/ts3.1/assert.d.ts index 9750dae7de..3f01820b2d 100644 --- a/types/node/v13/ts3.7/assert.d.ts +++ b/types/node/ts3.1/assert.d.ts @@ -1,5 +1,5 @@ declare module "assert" { - function assert(value: any, message?: string | Error): asserts value; + function assert(value: any, message?: string | Error): void; namespace assert { class AssertionError implements Error { name: string; @@ -19,20 +19,20 @@ declare module "assert" { type AssertPredicate = RegExp | (new() => object) | ((thrown: any) => boolean) | object | Error; function fail(message?: string | Error): never; - /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + /** @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): asserts value; - /** @deprecated since v9.9.0 - use strictEqual() instead. */ + 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. */ + /** @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. */ + /** @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. */ + /** @deprecated since v9.9.0 - use `notDeepStrictEqual()` instead. */ function notDeepEqual(actual: any, expected: any, message?: string | Error): void; - function strictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; + 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: T, message?: string | Error): asserts actual is T; + function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; function throws(block: () => any, message?: string | Error): void; @@ -40,7 +40,7 @@ declare module "assert" { function doesNotThrow(block: () => any, message?: string | Error): void; function doesNotThrow(block: () => any, error: RegExp | Function, message?: string | Error): void; - function ifError(value: any): asserts value is null | undefined; + function ifError(value: any): void; function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; function rejects(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; diff --git a/types/node/ts3.1/base.d.ts b/types/node/ts3.1/base.d.ts new file mode 100644 index 0000000000..2abdd0f33a --- /dev/null +++ b/types/node/ts3.1/base.d.ts @@ -0,0 +1,41 @@ +// base definitions for all NodeJS modules that are not specific to any version of TypeScript +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/types/node/fs.d.ts b/types/node/ts3.1/fs.d.ts similarity index 100% rename from types/node/fs.d.ts rename to types/node/ts3.1/fs.d.ts diff --git a/types/node/globals.d.ts b/types/node/ts3.1/globals.d.ts similarity index 100% rename from types/node/globals.d.ts rename to types/node/ts3.1/globals.d.ts diff --git a/types/node/globals.global.d.ts b/types/node/ts3.1/globals.global.d.ts similarity index 100% rename from types/node/globals.global.d.ts rename to types/node/ts3.1/globals.global.d.ts diff --git a/types/node/ts3.1/index.d.ts b/types/node/ts3.1/index.d.ts new file mode 100644 index 0000000000..e917b54655 --- /dev/null +++ b/types/node/ts3.1/index.d.ts @@ -0,0 +1,91 @@ +// Type definitions for non-npm package Node.js 14.6 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +// Alexander T. +// Alvis HT Tang +// Andrew Makarov +// Benjamin Toueg +// Bruno Scheufler +// Chigozirim C. +// David Junger +// Deividas Bakanas +// Eugene Y. Q. Shen +// Flarna +// Hannes Magnusson +// Hoàng Văn Khải +// Huw +// Kelvin Jin +// Klaus Meinhardt +// Lishude +// Mariusz Wiktorczyk +// Mohsen Azimi +// Nicolas Even +// Nikita Galkin +// Parambir Singh +// Sebastian Silbermann +// Simon Schick +// Thomas den Hollander +// Wilco Bakker +// wwwy3y3 +// Samuel Ainsworth +// Kyle Uehlein +// Jordi Oliveras Rovira +// Thanik Bhongbhibhat +// Marcin Kopacz +// Trivikram Kamat +// Minh Son Nguyen +// Junxiao Shi +// Ilia Baryshnikov +// ExE Boss +// Surasak Chaisurin +// Piotr Błażejewicz +// Anna Henningsen +// Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// NOTE: These definitions support NodeJS and TypeScript 3.5. + +// 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.8 +// - ~/ts3.5/index.d.ts - Definitions specific to TypeScript 3.5 + +// NOTE: Augmentations for TypeScript 3.5 and later should use individual files for overrides +// within the respective ~/ts3.5 (or later) folder. However, this is disallowed for versions +// prior to TypeScript 3.5, so the older definitions will be found here. + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// + +// We can't include globals.global.d.ts in globals.d.ts, as it'll cause duplication errors in TypeScript 3.5+ +/// + +// We can't include assert.d.ts in base.d.ts, as it'll cause duplication errors in TypeScript 3.7+ +/// + +// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) +// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files +// just to ensure the names are known and node typings can be used without importing these libs. +// if someone really needs these types the libs need to be added via --lib or in tsconfig.json +interface AsyncIterable { } +interface IterableIterator { } +interface AsyncIterableIterator {} +interface SymbolConstructor { + readonly asyncIterator: symbol; +} +declare var Symbol: SymbolConstructor; +// even this is just a forward declaration some properties are added otherwise +// it would be allowed to pass anything to e.g. Buffer.from() +interface SharedArrayBuffer { + readonly byteLength: number; + slice(begin?: number, end?: number): SharedArrayBuffer; +} + +declare module "util" { + namespace types { + function isBigInt64Array(value: any): boolean; + function isBigUint64Array(value: any): boolean; + } +} diff --git a/types/node/ts3.1/node-tests.ts b/types/node/ts3.1/node-tests.ts new file mode 100644 index 0000000000..7c42658076 --- /dev/null +++ b/types/node/ts3.1/node-tests.ts @@ -0,0 +1,351 @@ +import * as fs from "fs"; +import * as url from "url"; +import * as util from "util"; +import * as http from "http"; +import * as https from "https"; +import * as net from "net"; +import * as console2 from "console"; +import * as timers from "timers"; +import * as inspector from "inspector"; +import * as trace_events from "trace_events"; + +////////////////////////////////////////////////////// +/// 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; + + let sockets: NodeJS.ReadOnlyDict = agent.sockets; + sockets = agent.freeSockets; + + 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 = []; + + { + function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} + + class MyIncomingMessage extends http.IncomingMessage { + foo: number; + } + + class MyServerResponse extends http.ServerResponse { + foo: string; + } + + let server: https.Server; + + server = new https.Server(); + server = new https.Server(reqListener); + server = new https.Server({ IncomingMessage: MyIncomingMessage}); + + server = new https.Server({ + IncomingMessage: MyIncomingMessage, + ServerResponse: MyServerResponse + }, reqListener); + + server = https.createServer(); + server = https.createServer(reqListener); + server = https.createServer({ IncomingMessage: MyIncomingMessage }); + server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); + + const timeout: number = server.timeout; + const listening: boolean = server.listening; + const keepAliveTimeout: number = server.keepAliveTimeout; + const maxHeadersCount: number | null = server.maxHeadersCount; + const headersTimeout: number = server.headersTimeout; + server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); + } +} + +///////////////////////////////////////////////////// +/// Timers tests : https://nodejs.org/api/timers.html +///////////////////////////////////////////////////// + +{ + { + const immediate = timers + .setImmediate(() => { + console.log('immediate'); + }) + .unref() + .ref(); + const b: boolean = immediate.hasRef(); + timers.clearImmediate(immediate); + } + { + const timeout = timers + .setInterval(() => { + console.log('interval'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + timers.clearInterval(timeout); + } + { + const timeout = timers + .setTimeout(() => { + console.log('timeout'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + timers.clearTimeout(timeout); + } + async function testPromisify(doSomething: { + (foo: any, onSuccessCallback: (result: string) => void, onErrorCallback: (reason: any) => void): void; + [util.promisify.custom](foo: any): Promise; + }) { + 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(""); + + // $ExpectType (foo: any) => Promise + const doSomethingPromise = util.promisify(doSomething); + + // $ExpectType string + s = await doSomethingPromise('foo'); + } +} + +///////////////////////////////////////////////////////// +/// 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 | 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(); + const isConstr: boolean = frame.isConstructor(); + } +} + +/////////////////////////////////////////////////////////// +/// 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.profile(); + console.profile('label'); + console.profileEnd(); + console.profileEnd('label'); + console.timeStamp(); + console.timeStamp('label'); + } +} + +/***************************************************************************** + * * + * The following tests are the modules not mentioned in document but existed * + * * + *****************************************************************************/ + +/////////////////////////////////////////////////////////// +/// 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 | undefined = 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 | 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!; + }); + 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 | undefined = 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(); +} + +//////////////////////////////////////////////////// +/// Node.js ESNEXT Support +//////////////////////////////////////////////////// + +{ + const s = 'foo'; + const s1: string = s.trimLeft(); + const s2: string = s.trimRight(); +} diff --git a/types/node/ts3.2/tsconfig.json b/types/node/ts3.1/tsconfig.json similarity index 100% rename from types/node/ts3.2/tsconfig.json rename to types/node/ts3.1/tsconfig.json diff --git a/types/node/ts3.1/tslint.json b/types/node/ts3.1/tslint.json new file mode 100644 index 0000000000..464f610b93 --- /dev/null +++ b/types/node/ts3.1/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "no-unnecessary-class": false, + "unified-signatures": false + } +} diff --git a/types/node/util.d.ts b/types/node/ts3.1/util.d.ts similarity index 100% rename from types/node/util.d.ts rename to types/node/ts3.1/util.d.ts diff --git a/types/node/ts3.2/base.d.ts b/types/node/ts3.4/base.d.ts similarity index 100% rename from types/node/ts3.2/base.d.ts rename to types/node/ts3.4/base.d.ts diff --git a/types/node/ts3.2/fs.d.ts b/types/node/ts3.4/fs.d.ts similarity index 100% rename from types/node/ts3.2/fs.d.ts rename to types/node/ts3.4/fs.d.ts diff --git a/types/node/ts3.2/globals.d.ts b/types/node/ts3.4/globals.d.ts similarity index 100% rename from types/node/ts3.2/globals.d.ts rename to types/node/ts3.4/globals.d.ts diff --git a/types/node/ts3.2/index.d.ts b/types/node/ts3.4/index.d.ts similarity index 100% rename from types/node/ts3.2/index.d.ts rename to types/node/ts3.4/index.d.ts diff --git a/types/node/ts3.2/node-tests.ts b/types/node/ts3.4/node-tests.ts similarity index 100% rename from types/node/ts3.2/node-tests.ts rename to types/node/ts3.4/node-tests.ts diff --git a/types/node/ts3.2/process.d.ts b/types/node/ts3.4/process.d.ts similarity index 100% rename from types/node/ts3.2/process.d.ts rename to types/node/ts3.4/process.d.ts diff --git a/types/node/ts3.7/tsconfig.json b/types/node/ts3.4/tsconfig.json similarity index 100% rename from types/node/ts3.7/tsconfig.json rename to types/node/ts3.4/tsconfig.json diff --git a/types/node/ts3.2/tslint.json b/types/node/ts3.4/tslint.json similarity index 100% rename from types/node/ts3.2/tslint.json rename to types/node/ts3.4/tslint.json diff --git a/types/node/ts3.2/util.d.ts b/types/node/ts3.4/util.d.ts similarity index 100% rename from types/node/ts3.2/util.d.ts rename to types/node/ts3.4/util.d.ts diff --git a/types/node/ts3.5/base.d.ts b/types/node/ts3.6/base.d.ts similarity index 100% rename from types/node/ts3.5/base.d.ts rename to types/node/ts3.6/base.d.ts diff --git a/types/node/ts3.5/globals.global.d.ts b/types/node/ts3.6/globals.global.d.ts similarity index 100% rename from types/node/ts3.5/globals.global.d.ts rename to types/node/ts3.6/globals.global.d.ts diff --git a/types/node/ts3.5/index.d.ts b/types/node/ts3.6/index.d.ts similarity index 100% rename from types/node/ts3.5/index.d.ts rename to types/node/ts3.6/index.d.ts diff --git a/types/node/ts3.5/node-tests.ts b/types/node/ts3.6/node-tests.ts similarity index 100% rename from types/node/ts3.5/node-tests.ts rename to types/node/ts3.6/node-tests.ts diff --git a/types/node/ts3.5/test/globals.ts b/types/node/ts3.6/test/globals.ts similarity index 100% rename from types/node/ts3.5/test/globals.ts rename to types/node/ts3.6/test/globals.ts diff --git a/types/node/ts3.5/tsconfig.json b/types/node/ts3.6/tsconfig.json similarity index 100% rename from types/node/ts3.5/tsconfig.json rename to types/node/ts3.6/tsconfig.json diff --git a/types/node/ts3.5/tslint.json b/types/node/ts3.6/tslint.json similarity index 100% rename from types/node/ts3.5/tslint.json rename to types/node/ts3.6/tslint.json diff --git a/types/node/ts3.5/wasi.d.ts b/types/node/ts3.6/wasi.d.ts similarity index 100% rename from types/node/ts3.5/wasi.d.ts rename to types/node/ts3.6/wasi.d.ts diff --git a/types/node/ts3.7/base.d.ts b/types/node/ts3.7/base.d.ts deleted file mode 100644 index 201cd5678b..0000000000 --- a/types/node/ts3.7/base.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.7. - -// 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.7/base.d.ts - Definitions specific to TypeScript 3.7 -// - ~/ts3.7/index.d.ts - Definitions specific to TypeScript 3.7 with assert pulled in - -// 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.7-specific augmentations: -/// diff --git a/types/node/ts3.7/index.d.ts b/types/node/ts3.7/index.d.ts deleted file mode 100644 index 2cd553b853..0000000000 --- a/types/node/ts3.7/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.7. -// This isn't strictly needed since 3.7 has the assert module, but this way we're consistent. -// Typically type modificatons should be made in base.d.ts instead of here - -/// diff --git a/types/node/ts3.7/node-tests.ts b/types/node/ts3.7/node-tests.ts deleted file mode 100644 index 983748c1fd..0000000000 --- a/types/node/ts3.7/node-tests.ts +++ /dev/null @@ -1,59 +0,0 @@ -import * as assert from 'assert'; - -assert(true, "it's working"); - -assert.ok(true, 'inner functions work as well'); - -assert.throws(() => {}); -assert.throws(() => {}, /Regex test/); -assert.throws( - () => {}, - () => {}, - 'works wonderfully', -); - -assert['fail'](true, true, 'works like a charm'); - -{ - const a = null as any; - assert.ifError(a); - a; // $ExpectType null | undefined -} - -{ - const a = true as boolean; - assert(a); - a; // $ExpectType true -} - -{ - // tslint:disable-next-line: no-null-undefined-union - const a = 13 as number | null | undefined; - assert(a); - a; // $ExpectType number -} - -{ - const a = true as boolean; - assert.ok(a); - a; // $ExpectType true -} - -{ - // tslint:disable-next-line: no-null-undefined-union - const a = 13 as number | null | undefined; - assert.ok(a); - a; // $ExpectType number -} - -{ - const a = 'test' as any; - assert.strictEqual(a, 'test'); - a; // $ExpectType string -} - -{ - const a = { b: 2 } as any; - assert.deepStrictEqual(a, { b: 2 }); - a; // $ExpectType { b: number; } -} diff --git a/types/node/tslint.json b/types/node/tslint.json index 464f610b93..1a8ddd9863 100644 --- a/types/node/tslint.json +++ b/types/node/tslint.json @@ -1,10 +1,10 @@ { - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "no-empty-interface": false, - "no-single-declare-module": false, - "no-unnecessary-class": false, - "unified-signatures": false - } + "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/assert.d.ts b/types/node/v10/assert.d.ts index 1415f043ac..6abce89efe 100644 --- a/types/node/v10/assert.d.ts +++ b/types/node/v10/assert.d.ts @@ -1,5 +1,5 @@ declare module "assert" { - function assert(value: any, message?: string | Error): void; + function assert(value: any, message?: string | Error): asserts value; namespace assert { class AssertionError implements Error { name: string; @@ -19,7 +19,7 @@ declare module "assert" { 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; + function ok(value: any, message?: string | Error): asserts value; /** @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. */ @@ -28,9 +28,9 @@ declare module "assert" { 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 strictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; function notStrictEqual(actual: any, expected: any, message?: string | Error): void; - function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; + function deepStrictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; function throws(block: Function, message?: string | Error): void; @@ -38,7 +38,7 @@ declare module "assert" { 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 ifError(value: any): asserts value is null | undefined; function rejects(block: Function | Promise, message?: string | Error): Promise; function rejects(block: Function | Promise, error: RegExp | Function | Object | Error, message?: string | Error): Promise; diff --git a/types/node/v10/base.d.ts b/types/node/v10/base.d.ts index f9bc0b3d91..e0fc9c98f6 100644 --- a/types/node/v10/base.d.ts +++ b/types/node/v10/base.d.ts @@ -1,40 +1,20 @@ -// base definitions for all NodeJS modules that are not specific to any version of TypeScript -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +// NOTE: These definitions support NodeJS and TypeScript 3.7. + +// 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.7/base.d.ts - Definitions specific to TypeScript 3.7 +// - ~/ts3.7/index.d.ts - Definitions specific to TypeScript 3.7 with assert pulled in + +// 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.7-specific augmentations: +/// diff --git a/types/node/v10/index.d.ts b/types/node/v10/index.d.ts index e821ed792c..2cd553b853 100644 --- a/types/node/v10/index.d.ts +++ b/types/node/v10/index.d.ts @@ -1,94 +1,5 @@ -// Type definitions for Node.js 10.17 -// Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped -// Alberto Schiabel -// Alexander T. -// Alvis HT Tang -// Andrew Makarov -// Bruno Scheufler -// Chigozirim C. -// Deividas Bakanas -// Eugene Y. Q. Shen -// Flarna -// Hannes Magnusson -// Hoàng Văn Khải -// Huw -// Kelvin Jin -// Klaus Meinhardt -// Lishude -// Mariusz Wiktorczyk -// Mohsen Azimi -// Nicolas Even -// Nikita Galkin -// Parambir Singh -// Sebastian Silbermann -// Simon Schick -// Thomas den Hollander -// Wilco Bakker -// wwwy3y3 -// Zane Hannan AU -// Jeremie Rodriguez -// Samuel Ainsworth -// Kyle Uehlein -// Jordi Oliveras Rovira -// Thanik Bhongbhibhat -// Minh Son Nguyen -// ExE Boss -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// NOTE: These definitions support NodeJS and TypeScript 3.7. +// This isn't strictly needed since 3.7 has the assert module, but this way we're consistent. +// Typically type modificatons should be made in base.d.ts instead of here -// 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: /// - -// We can't include assert.d.ts in base.d.ts, as it'll cause duplication errors in +ts3.7 -/// - -// 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; - } - namespace types { - function isBigInt64Array(value: any): boolean; - function isBigUint64Array(value: any): boolean; - } -} diff --git a/types/node/v10/node-tests.ts b/types/node/v10/node-tests.ts index 5682949270..0527c46acf 100644 --- a/types/node/v10/node-tests.ts +++ b/types/node/v10/node-tests.ts @@ -1,5061 +1,59 @@ -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"); +import * as assert from 'assert'; -// Specifically test buffer module regression. -import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer, transcode, TranscodeEncoding } from "buffer"; +assert(true, "it's working"); -////////////////////////////////////////////////////////// -/// 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; - const hrtimeArray: [number, number] = process.hrtime(); - } -} +assert.ok(true, 'inner functions work as well'); -////////////////////////////////////////////////////////// -/// 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"); - - if (!!true) assert.fail('stuff broke'); - - if (!!true) assert.fail('actual', 'expected', 'message'); - - if (!!true) 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' }); - const listDir3: fs.Dirent[] = fs.readdirSync('path', { encoding: 'utf8', withFileTypes: true }); - - 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[]) => {}); - } - - async function testPromisify() { - const rd = util.promisify(fs.readdir); - let listS: string[]; - listS = await rd('path'); - listS = await rd('path', 'utf8'); - listS = await rd('path', null); - listS = await rd('path', undefined); - listS = await rd('path', { encoding: 'utf8' }); - listS = await rd('path', { encoding: null }); - listS = await rd('path', { encoding: null, withFileTypes: false }); - listS = await rd('path', { encoding: 'utf8', withFileTypes: false }); - const listDir: fs.Dirent[] = await rd('path', { withFileTypes: true }); - const listDir2: Buffer[] = await rd('path', { withFileTypes: false, encoding: 'buffer' }); - const listDir3: fs.Dirent[] = await rd('path', { encoding: 'utf8', withFileTypes: true }); - } - - { - 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, - }); - } - - { - let names: Promise; - let buffers: Promise; - let namesOrBuffers: Promise; - let entries: Promise; - - names = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: false }); - buffers = fs.promises.readdir('/path/to/dir', { encoding: 'buffer', withFileTypes: false }); - namesOrBuffers = fs.promises.readdir('/path/to/dir', { encoding: 'SOME OTHER', withFileTypes: false }); - entries = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: true }); - } -} - -/////////////////////////////////////////////////////// -/// 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); - } - - // Buffer module, transcode function - { - transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer - - const source: TranscodeEncoding = 'utf8'; - const target: TranscodeEncoding = 'ascii'; - transcode(Buffer.from('€'), source, target); // $ExpectType 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(callbackifyTest.fn); - const cfnE = util.callbackify(callbackifyTest.fnE); - const cfnT1 = util.callbackify(callbackifyTest.fnT1); - const cfnT1E = util.callbackify(callbackifyTest.fnT1E); - const cfnTResult = util.callbackify(callbackifyTest.fnTResult); - const cfnTResultE = util.callbackify(callbackifyTest.fnTResultE); - const cfnT1TResult = util.callbackify(callbackifyTest.fnT1TResult); - const cfnT1TResultE = util.callbackify(callbackifyTest.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, code?: string) => T - util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead'); - // $ExpectType (fn: T, message: string, code?: string) => T - util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead', 'DEP0001'); - - // 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 - let b: boolean; - b = util.types.isBigInt64Array(15); - b = util.types.isBigUint64Array(15); - b = util.types.isModuleNamespaceObject(15); - - // 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), +assert.throws(() => {}); +assert.throws(() => {}, /Regex test/); +assert.throws( + () => {}, + () => {}, + 'works wonderfully', ); -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, - readableHighWaterMark: 2048, - writableHighWaterMark: 1024 - }); - - 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, - readableHighWaterMark: 2048, - writableHighWaterMark: 1024 - }); -} - -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 /// -//////////////////////////////////////////////////////// +assert['fail'](true, true, 'works like a charm'); { - { - // 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(); - } - - { - const key: string | null = '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, 'binary', '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', - }, - }); - } + const a = null as any; + assert.ifError(a); + a; // $ExpectType null } -////////////////////////////////////////////////// -/// 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 can be either nothing (undefined) or an error - _server = _server.close(() => { }); - _server = _server.close((err) => { - if (typeof err !== 'undefined') { const _err: Error = err; } - }); - } - - { - 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", () => { }); - } + const a = true as boolean; + assert(a); + a; // $ExpectType true } -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html /// -//////////////////////////////////////////////////// - { - // http Server - { - function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} - - let server: http.Server = new http.Server(); - - class MyIncomingMessage extends http.IncomingMessage { - foo: number; - } - - class MyServerResponse extends http.ServerResponse { - foo: string; - } - - server = new http.Server({ IncomingMessage: MyIncomingMessage}); - - server = new http.Server({ - IncomingMessage: MyIncomingMessage, - ServerResponse: MyServerResponse - }, reqListener); - - server = http.createServer(reqListener); - server = http.createServer({ IncomingMessage: MyIncomingMessage }); - server = http.createServer({ ServerResponse: MyServerResponse }, reqListener); - - // 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' ] - }; - } + // tslint:disable-next-line: no-null-undefined-union + const a = 13 as number | null | undefined; + assert(a); + a; // $ExpectType number } -////////////////////////////////////////////////////// -/// 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 = []; - - { - function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} - - class MyIncomingMessage extends http.IncomingMessage { - foo: number; - } - - class MyServerResponse extends http.ServerResponse { - foo: string; - } - - let server = new https.Server({ IncomingMessage: MyIncomingMessage}); - - server = new https.Server({ - IncomingMessage: MyIncomingMessage, - ServerResponse: MyServerResponse - }, reqListener); - - server = https.createServer({ IncomingMessage: MyIncomingMessage }); - server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); - - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } + const a = true as boolean; + assert.ok(a); + a; // $ExpectType true } -//////////////////////////////////////////////////// -/// TTY tests : http://nodejs.org/api/tty.html -//////////////////////////////////////////////////// - { - const rs: tty.ReadStream = new tty.ReadStream(0); - const ws: tty.WriteStream = new tty.WriteStream(1); - - const rsIsRaw: boolean = rs.isRaw; - const rsRaw: tty.ReadStream = rs.setRawMode(true); - - const wsColumns: number = ws.columns; - const wsRows: number = ws.rows; - - const isTTY: boolean = tty.isatty(1); + // tslint:disable-next-line: no-null-undefined-union + const a = 13 as number | null | undefined; + assert.ok(a); + a; // $ExpectType number } -//////////////////////////////////////////////////// -/// 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); - } + const a = 'test' as any; + assert.strictEqual(a, 'test'); + a; // $ExpectType string } -//////////////////////////////////////////////////// -/// 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))}); - } - - { - const forked = childProcess.fork('./', ['asd'], { - windowsVerbatimArguments: true, - silent: false, - stdio: "inherit", - execPath: '', - execArgv: ['asda'] - }); - const exitCode: number | null = forked.exitCode; - const signalCode: number | null = forked.signalCode; - const ipc: stream.Pipe = forked.channel; - const hasRef: boolean = ipc.hasRef(); - ipc.close(); - ipc.unref(); - ipc.ref(); - } - - { - const forked = childProcess.fork('./', { - windowsVerbatimArguments: true, - silent: false, - stdio: ["inherit"], - execPath: '', - execArgv: ['asda'] - }); - } - - { - const forked = childProcess.fork('./'); - } - - 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; - } - - if (os.platform() === 'win32') { - let result: number; - - result = os.constants.errno.WSAEINTR; - result = os.constants.errno.WSAEBADF; - result = os.constants.errno.WSAEACCES; - result = os.constants.errno.WSAEFAULT; - result = os.constants.errno.WSAEINVAL; - result = os.constants.errno.WSAEMFILE; - result = os.constants.errno.WSAEWOULDBLOCK; - result = os.constants.errno.WSAEINPROGRESS; - result = os.constants.errno.WSAEALREADY; - result = os.constants.errno.WSAENOTSOCK; - result = os.constants.errno.WSAEDESTADDRREQ; - result = os.constants.errno.WSAEMSGSIZE; - result = os.constants.errno.WSAEPROTOTYPE; - result = os.constants.errno.WSAENOPROTOOPT; - result = os.constants.errno.WSAEPROTONOSUPPORT; - result = os.constants.errno.WSAESOCKTNOSUPPORT; - result = os.constants.errno.WSAEOPNOTSUPP; - result = os.constants.errno.WSAEPFNOSUPPORT; - result = os.constants.errno.WSAEAFNOSUPPORT; - result = os.constants.errno.WSAEADDRINUSE; - result = os.constants.errno.WSAEADDRNOTAVAIL; - result = os.constants.errno.WSAENETDOWN; - result = os.constants.errno.WSAENETUNREACH; - result = os.constants.errno.WSAENETRESET; - result = os.constants.errno.WSAECONNABORTED; - result = os.constants.errno.WSAECONNRESET; - result = os.constants.errno.WSAENOBUFS; - result = os.constants.errno.WSAEISCONN; - result = os.constants.errno.WSAENOTCONN; - result = os.constants.errno.WSAESHUTDOWN; - result = os.constants.errno.WSAETOOMANYREFS; - result = os.constants.errno.WSAETIMEDOUT; - result = os.constants.errno.WSAECONNREFUSED; - result = os.constants.errno.WSAELOOP; - result = os.constants.errno.WSAENAMETOOLONG; - result = os.constants.errno.WSAEHOSTDOWN; - result = os.constants.errno.WSAEHOSTUNREACH; - result = os.constants.errno.WSAENOTEMPTY; - result = os.constants.errno.WSAEPROCLIM; - result = os.constants.errno.WSAEUSERS; - result = os.constants.errno.WSAEDQUOT; - result = os.constants.errno.WSAESTALE; - result = os.constants.errno.WSAEREMOTE; - result = os.constants.errno.WSASYSNOTREADY; - result = os.constants.errno.WSAVERNOTSUPPORTED; - result = os.constants.errno.WSANOTINITIALISED; - result = os.constants.errno.WSAEDISCON; - result = os.constants.errno.WSAENOMORE; - result = os.constants.errno.WSAECANCELLED; - result = os.constants.errno.WSAEINVALIDPROCTABLE; - result = os.constants.errno.WSAEINVALIDPROVIDER; - result = os.constants.errno.WSAEPROVIDERFAILEDINIT; - result = os.constants.errno.WSASYSCALLFAILURE; - result = os.constants.errno.WSASERVICE_NOT_FOUND; - result = os.constants.errno.WSATYPE_NOT_FOUND; - result = os.constants.errno.WSA_E_NO_MORE; - result = os.constants.errno.WSA_E_CANCELLED; - result = os.constants.errno.WSAEREFUSED; - } - - { - 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 immediate = timers - .setImmediate(() => { - console.log('immediate'); - }) - .unref() - .ref(); - timers.clearImmediate(immediate); - } - { - const timeout = timers - .setInterval(() => { - console.log('interval'); - }, 20) - .unref() - .ref() - .refresh(); - timers.clearInterval(timeout); - } - { - const timeout = timers - .setTimeout(() => { - console.log('timeout'); - }, 20) - .unref() - .ref() - .refresh(); - 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) => {}); - process.on("customEvent", () => { }); - - 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 callback parameter can be either nothing (undefined) or an error - server = server.close(() => { }); - server = server.close((err) => { - if (typeof err !== 'undefined') { const _err: Error = err; } - }); - - // 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 - }; - // 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 | undefined = 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(); + const a = { b: 2 } as any; + assert.deepStrictEqual(a, { b: 2 }); + a; // $ExpectType { b: number; } } diff --git a/types/node/v10/package.json b/types/node/v10/package.json index 028f692acb..d70cf2b291 100644 --- a/types/node/v10/package.json +++ b/types/node/v10/package.json @@ -2,14 +2,14 @@ "private": true, "types": "index", "typesVersions": { - ">=3.7.0-0": { + "<=3.1": { "*": [ - "ts3.7/*" + "ts3.1/*" ] }, - ">=3.2.0-0": { + "<=3.6": { "*": [ - "ts3.2/*" + "ts3.6/*" ] } } diff --git a/types/node/v10/ts3.7/assert.d.ts b/types/node/v10/ts3.1/assert.d.ts similarity index 85% rename from types/node/v10/ts3.7/assert.d.ts rename to types/node/v10/ts3.1/assert.d.ts index 6abce89efe..1415f043ac 100644 --- a/types/node/v10/ts3.7/assert.d.ts +++ b/types/node/v10/ts3.1/assert.d.ts @@ -1,5 +1,5 @@ declare module "assert" { - function assert(value: any, message?: string | Error): asserts value; + function assert(value: any, message?: string | Error): void; namespace assert { class AssertionError implements Error { name: string; @@ -19,7 +19,7 @@ declare module "assert" { 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): asserts value; + 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. */ @@ -28,9 +28,9 @@ declare module "assert" { 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: T, message?: string | Error): asserts actual is T; + 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: T, message?: string | Error): asserts actual is T; + 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; @@ -38,7 +38,7 @@ declare module "assert" { function doesNotThrow(block: Function, message?: string | Error): void; function doesNotThrow(block: Function, error: RegExp | Function, message?: string | Error): void; - function ifError(value: any): asserts value is null | undefined; + 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; diff --git a/types/node/v10/ts3.1/base.d.ts b/types/node/v10/ts3.1/base.d.ts new file mode 100644 index 0000000000..f9bc0b3d91 --- /dev/null +++ b/types/node/v10/ts3.1/base.d.ts @@ -0,0 +1,40 @@ +// base definitions for all NodeJS modules that are not specific to any version of TypeScript +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/types/node/v10/globals.d.ts b/types/node/v10/ts3.1/globals.d.ts similarity index 100% rename from types/node/v10/globals.d.ts rename to types/node/v10/ts3.1/globals.d.ts 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..e821ed792c --- /dev/null +++ b/types/node/v10/ts3.1/index.d.ts @@ -0,0 +1,94 @@ +// Type definitions for Node.js 10.17 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +// Alexander T. +// Alvis HT Tang +// Andrew Makarov +// Bruno Scheufler +// Chigozirim C. +// Deividas Bakanas +// Eugene Y. Q. Shen +// Flarna +// Hannes Magnusson +// Hoàng Văn Khải +// Huw +// Kelvin Jin +// Klaus Meinhardt +// Lishude +// Mariusz Wiktorczyk +// Mohsen Azimi +// Nicolas Even +// Nikita Galkin +// Parambir Singh +// Sebastian Silbermann +// Simon Schick +// Thomas den Hollander +// Wilco Bakker +// wwwy3y3 +// Zane Hannan AU +// Jeremie Rodriguez +// Samuel Ainsworth +// Kyle Uehlein +// Jordi Oliveras Rovira +// Thanik Bhongbhibhat +// Minh Son Nguyen +// ExE Boss +// 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: +/// + +// We can't include assert.d.ts in base.d.ts, as it'll cause duplication errors in +ts3.7 +/// + +// 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; + } + namespace types { + function isBigInt64Array(value: any): boolean; + function isBigUint64Array(value: any): boolean; + } +} 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..5682949270 --- /dev/null +++ b/types/node/v10/ts3.1/node-tests.ts @@ -0,0 +1,5061 @@ +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, transcode, TranscodeEncoding } 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; + const hrtimeArray: [number, number] = process.hrtime(); + } +} + +////////////////////////////////////////////////////////// +/// 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"); + + if (!!true) assert.fail('stuff broke'); + + if (!!true) assert.fail('actual', 'expected', 'message'); + + if (!!true) 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' }); + const listDir3: fs.Dirent[] = fs.readdirSync('path', { encoding: 'utf8', withFileTypes: true }); + + 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[]) => {}); + } + + async function testPromisify() { + const rd = util.promisify(fs.readdir); + let listS: string[]; + listS = await rd('path'); + listS = await rd('path', 'utf8'); + listS = await rd('path', null); + listS = await rd('path', undefined); + listS = await rd('path', { encoding: 'utf8' }); + listS = await rd('path', { encoding: null }); + listS = await rd('path', { encoding: null, withFileTypes: false }); + listS = await rd('path', { encoding: 'utf8', withFileTypes: false }); + const listDir: fs.Dirent[] = await rd('path', { withFileTypes: true }); + const listDir2: Buffer[] = await rd('path', { withFileTypes: false, encoding: 'buffer' }); + const listDir3: fs.Dirent[] = await rd('path', { encoding: 'utf8', withFileTypes: true }); + } + + { + 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, + }); + } + + { + let names: Promise; + let buffers: Promise; + let namesOrBuffers: Promise; + let entries: Promise; + + names = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: false }); + buffers = fs.promises.readdir('/path/to/dir', { encoding: 'buffer', withFileTypes: false }); + namesOrBuffers = fs.promises.readdir('/path/to/dir', { encoding: 'SOME OTHER', withFileTypes: false }); + entries = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: true }); + } +} + +/////////////////////////////////////////////////////// +/// 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); + } + + // Buffer module, transcode function + { + transcode(Buffer.from('€'), 'utf8', 'ascii'); // $ExpectType Buffer + + const source: TranscodeEncoding = 'utf8'; + const target: TranscodeEncoding = 'ascii'; + transcode(Buffer.from('€'), source, target); // $ExpectType 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(callbackifyTest.fn); + const cfnE = util.callbackify(callbackifyTest.fnE); + const cfnT1 = util.callbackify(callbackifyTest.fnT1); + const cfnT1E = util.callbackify(callbackifyTest.fnT1E); + const cfnTResult = util.callbackify(callbackifyTest.fnTResult); + const cfnTResultE = util.callbackify(callbackifyTest.fnTResultE); + const cfnT1TResult = util.callbackify(callbackifyTest.fnT1TResult); + const cfnT1TResultE = util.callbackify(callbackifyTest.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, code?: string) => T + util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead'); + // $ExpectType (fn: T, message: string, code?: string) => T + util.deprecate(util.deprecate, 'deprecate() is deprecated, use bar() instead', 'DEP0001'); + + // 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 + let b: boolean; + b = util.types.isBigInt64Array(15); + b = util.types.isBigUint64Array(15); + b = util.types.isModuleNamespaceObject(15); + + // 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, + readableHighWaterMark: 2048, + writableHighWaterMark: 1024 + }); + + 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, + readableHighWaterMark: 2048, + writableHighWaterMark: 1024 + }); +} + +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(); + } + + { + const key: string | null = '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, 'binary', '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 can be either nothing (undefined) or an error + _server = _server.close(() => { }); + _server = _server.close((err) => { + if (typeof err !== 'undefined') { const _err: Error = err; } + }); + } + + { + 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 + { + function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} + + let server: http.Server = new http.Server(); + + class MyIncomingMessage extends http.IncomingMessage { + foo: number; + } + + class MyServerResponse extends http.ServerResponse { + foo: string; + } + + server = new http.Server({ IncomingMessage: MyIncomingMessage}); + + server = new http.Server({ + IncomingMessage: MyIncomingMessage, + ServerResponse: MyServerResponse + }, reqListener); + + server = http.createServer(reqListener); + server = http.createServer({ IncomingMessage: MyIncomingMessage }); + server = http.createServer({ ServerResponse: MyServerResponse }, reqListener); + + // 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 = []; + + { + function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} + + class MyIncomingMessage extends http.IncomingMessage { + foo: number; + } + + class MyServerResponse extends http.ServerResponse { + foo: string; + } + + let server = new https.Server({ IncomingMessage: MyIncomingMessage}); + + server = new https.Server({ + IncomingMessage: MyIncomingMessage, + ServerResponse: MyServerResponse + }, reqListener); + + server = https.createServer({ IncomingMessage: MyIncomingMessage }); + server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); + + 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(0); + const ws: tty.WriteStream = new tty.WriteStream(1); + + const rsIsRaw: boolean = rs.isRaw; + const rsRaw: tty.ReadStream = 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))}); + } + + { + const forked = childProcess.fork('./', ['asd'], { + windowsVerbatimArguments: true, + silent: false, + stdio: "inherit", + execPath: '', + execArgv: ['asda'] + }); + const exitCode: number | null = forked.exitCode; + const signalCode: number | null = forked.signalCode; + const ipc: stream.Pipe = forked.channel; + const hasRef: boolean = ipc.hasRef(); + ipc.close(); + ipc.unref(); + ipc.ref(); + } + + { + const forked = childProcess.fork('./', { + windowsVerbatimArguments: true, + silent: false, + stdio: ["inherit"], + execPath: '', + execArgv: ['asda'] + }); + } + + { + const forked = childProcess.fork('./'); + } + + 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; + } + + if (os.platform() === 'win32') { + let result: number; + + result = os.constants.errno.WSAEINTR; + result = os.constants.errno.WSAEBADF; + result = os.constants.errno.WSAEACCES; + result = os.constants.errno.WSAEFAULT; + result = os.constants.errno.WSAEINVAL; + result = os.constants.errno.WSAEMFILE; + result = os.constants.errno.WSAEWOULDBLOCK; + result = os.constants.errno.WSAEINPROGRESS; + result = os.constants.errno.WSAEALREADY; + result = os.constants.errno.WSAENOTSOCK; + result = os.constants.errno.WSAEDESTADDRREQ; + result = os.constants.errno.WSAEMSGSIZE; + result = os.constants.errno.WSAEPROTOTYPE; + result = os.constants.errno.WSAENOPROTOOPT; + result = os.constants.errno.WSAEPROTONOSUPPORT; + result = os.constants.errno.WSAESOCKTNOSUPPORT; + result = os.constants.errno.WSAEOPNOTSUPP; + result = os.constants.errno.WSAEPFNOSUPPORT; + result = os.constants.errno.WSAEAFNOSUPPORT; + result = os.constants.errno.WSAEADDRINUSE; + result = os.constants.errno.WSAEADDRNOTAVAIL; + result = os.constants.errno.WSAENETDOWN; + result = os.constants.errno.WSAENETUNREACH; + result = os.constants.errno.WSAENETRESET; + result = os.constants.errno.WSAECONNABORTED; + result = os.constants.errno.WSAECONNRESET; + result = os.constants.errno.WSAENOBUFS; + result = os.constants.errno.WSAEISCONN; + result = os.constants.errno.WSAENOTCONN; + result = os.constants.errno.WSAESHUTDOWN; + result = os.constants.errno.WSAETOOMANYREFS; + result = os.constants.errno.WSAETIMEDOUT; + result = os.constants.errno.WSAECONNREFUSED; + result = os.constants.errno.WSAELOOP; + result = os.constants.errno.WSAENAMETOOLONG; + result = os.constants.errno.WSAEHOSTDOWN; + result = os.constants.errno.WSAEHOSTUNREACH; + result = os.constants.errno.WSAENOTEMPTY; + result = os.constants.errno.WSAEPROCLIM; + result = os.constants.errno.WSAEUSERS; + result = os.constants.errno.WSAEDQUOT; + result = os.constants.errno.WSAESTALE; + result = os.constants.errno.WSAEREMOTE; + result = os.constants.errno.WSASYSNOTREADY; + result = os.constants.errno.WSAVERNOTSUPPORTED; + result = os.constants.errno.WSANOTINITIALISED; + result = os.constants.errno.WSAEDISCON; + result = os.constants.errno.WSAENOMORE; + result = os.constants.errno.WSAECANCELLED; + result = os.constants.errno.WSAEINVALIDPROCTABLE; + result = os.constants.errno.WSAEINVALIDPROVIDER; + result = os.constants.errno.WSAEPROVIDERFAILEDINIT; + result = os.constants.errno.WSASYSCALLFAILURE; + result = os.constants.errno.WSASERVICE_NOT_FOUND; + result = os.constants.errno.WSATYPE_NOT_FOUND; + result = os.constants.errno.WSA_E_NO_MORE; + result = os.constants.errno.WSA_E_CANCELLED; + result = os.constants.errno.WSAEREFUSED; + } + + { + 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 immediate = timers + .setImmediate(() => { + console.log('immediate'); + }) + .unref() + .ref(); + timers.clearImmediate(immediate); + } + { + const timeout = timers + .setInterval(() => { + console.log('interval'); + }, 20) + .unref() + .ref() + .refresh(); + timers.clearInterval(timeout); + } + { + const timeout = timers + .setTimeout(() => { + console.log('timeout'); + }, 20) + .unref() + .ref() + .refresh(); + 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) => {}); + process.on("customEvent", () => { }); + + 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 callback parameter can be either nothing (undefined) or an error + server = server.close(() => { }); + server = server.close((err) => { + if (typeof err !== 'undefined') { const _err: Error = err; } + }); + + // 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 + }; + // 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 | undefined = 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/ts3.2/tsconfig.json b/types/node/v10/ts3.1/tsconfig.json similarity index 100% rename from types/node/v10/ts3.2/tsconfig.json rename to types/node/v10/ts3.1/tsconfig.json diff --git a/types/node/v10/ts3.1/tslint.json b/types/node/v10/ts3.1/tslint.json new file mode 100644 index 0000000000..4d72445ea0 --- /dev/null +++ b/types/node/v10/ts3.1/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "strict-export-declare-modifiers": false, + "unified-signatures": false + } +} diff --git a/types/node/v10/util.d.ts b/types/node/v10/ts3.1/util.d.ts similarity index 100% rename from types/node/v10/util.d.ts rename to types/node/v10/ts3.1/util.d.ts diff --git a/types/node/v10/ts3.2/base.d.ts b/types/node/v10/ts3.6/base.d.ts similarity index 100% rename from types/node/v10/ts3.2/base.d.ts rename to types/node/v10/ts3.6/base.d.ts diff --git a/types/node/v10/ts3.2/globals.d.ts b/types/node/v10/ts3.6/globals.d.ts similarity index 100% rename from types/node/v10/ts3.2/globals.d.ts rename to types/node/v10/ts3.6/globals.d.ts diff --git a/types/node/v10/ts3.2/index.d.ts b/types/node/v10/ts3.6/index.d.ts similarity index 100% rename from types/node/v10/ts3.2/index.d.ts rename to types/node/v10/ts3.6/index.d.ts diff --git a/types/node/v10/ts3.2/node-tests.ts b/types/node/v10/ts3.6/node-tests.ts similarity index 100% rename from types/node/v10/ts3.2/node-tests.ts rename to types/node/v10/ts3.6/node-tests.ts diff --git a/types/node/v10/ts3.7/tsconfig.json b/types/node/v10/ts3.6/tsconfig.json similarity index 100% rename from types/node/v10/ts3.7/tsconfig.json rename to types/node/v10/ts3.6/tsconfig.json diff --git a/types/node/v10/ts3.2/tslint.json b/types/node/v10/ts3.6/tslint.json similarity index 100% rename from types/node/v10/ts3.2/tslint.json rename to types/node/v10/ts3.6/tslint.json diff --git a/types/node/v10/ts3.2/util.d.ts b/types/node/v10/ts3.6/util.d.ts similarity index 100% rename from types/node/v10/ts3.2/util.d.ts rename to types/node/v10/ts3.6/util.d.ts diff --git a/types/node/v10/ts3.7/base.d.ts b/types/node/v10/ts3.7/base.d.ts deleted file mode 100644 index e0fc9c98f6..0000000000 --- a/types/node/v10/ts3.7/base.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.7. - -// 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.7/base.d.ts - Definitions specific to TypeScript 3.7 -// - ~/ts3.7/index.d.ts - Definitions specific to TypeScript 3.7 with assert pulled in - -// 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.7-specific augmentations: -/// diff --git a/types/node/v10/ts3.7/index.d.ts b/types/node/v10/ts3.7/index.d.ts deleted file mode 100644 index 2cd553b853..0000000000 --- a/types/node/v10/ts3.7/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.7. -// This isn't strictly needed since 3.7 has the assert module, but this way we're consistent. -// Typically type modificatons should be made in base.d.ts instead of here - -/// diff --git a/types/node/v10/ts3.7/node-tests.ts b/types/node/v10/ts3.7/node-tests.ts deleted file mode 100644 index 0527c46acf..0000000000 --- a/types/node/v10/ts3.7/node-tests.ts +++ /dev/null @@ -1,59 +0,0 @@ -import * as assert from 'assert'; - -assert(true, "it's working"); - -assert.ok(true, 'inner functions work as well'); - -assert.throws(() => {}); -assert.throws(() => {}, /Regex test/); -assert.throws( - () => {}, - () => {}, - 'works wonderfully', -); - -assert['fail'](true, true, 'works like a charm'); - -{ - const a = null as any; - assert.ifError(a); - a; // $ExpectType null -} - -{ - const a = true as boolean; - assert(a); - a; // $ExpectType true -} - -{ - // tslint:disable-next-line: no-null-undefined-union - const a = 13 as number | null | undefined; - assert(a); - a; // $ExpectType number -} - -{ - const a = true as boolean; - assert.ok(a); - a; // $ExpectType true -} - -{ - // tslint:disable-next-line: no-null-undefined-union - const a = 13 as number | null | undefined; - assert.ok(a); - a; // $ExpectType number -} - -{ - const a = 'test' as any; - assert.strictEqual(a, 'test'); - a; // $ExpectType string -} - -{ - const a = { b: 2 } as any; - assert.deepStrictEqual(a, { b: 2 }); - a; // $ExpectType { b: number; } -} diff --git a/types/node/v10/ts3.7/tslint.json b/types/node/v10/ts3.7/tslint.json deleted file mode 100644 index 1a8ddd9863..0000000000 --- a/types/node/v10/ts3.7/tslint.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "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/tslint.json b/types/node/v10/tslint.json index 4d72445ea0..1a8ddd9863 100644 --- a/types/node/v10/tslint.json +++ b/types/node/v10/tslint.json @@ -1,10 +1,10 @@ { - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "no-empty-interface": false, - "no-single-declare-module": false, - "strict-export-declare-modifiers": false, - "unified-signatures": false - } + "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/v11/assert.d.ts b/types/node/v11/assert.d.ts index 10aa09956e..161d8def8e 100644 --- a/types/node/v11/assert.d.ts +++ b/types/node/v11/assert.d.ts @@ -1,5 +1,5 @@ declare module "assert" { - function assert(value: any, message?: string | Error): void; + function assert(value: any, message?: string | Error): asserts value; namespace assert { class AssertionError implements Error { name: string; @@ -19,7 +19,7 @@ declare module "assert" { 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; + function ok(value: any, message?: string | Error): asserts value; /** @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. */ @@ -28,9 +28,9 @@ declare module "assert" { 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 strictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; function notStrictEqual(actual: any, expected: any, message?: string | Error): void; - function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; + function deepStrictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; function throws(block: () => any, message?: string | Error): void; @@ -38,7 +38,7 @@ declare module "assert" { function doesNotThrow(block: () => any, message?: string | Error): void; function doesNotThrow(block: () => any, error: RegExp | Function, message?: string | Error): void; - function ifError(value: any): void; + function ifError(value: any): asserts value is null | undefined; function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; function rejects(block: (() => Promise) | Promise, error: RegExp | Function | Object | Error, message?: string | Error): Promise; diff --git a/types/node/v11/base.d.ts b/types/node/v11/base.d.ts index f9bc0b3d91..e0fc9c98f6 100644 --- a/types/node/v11/base.d.ts +++ b/types/node/v11/base.d.ts @@ -1,40 +1,20 @@ -// base definitions for all NodeJS modules that are not specific to any version of TypeScript -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +// NOTE: These definitions support NodeJS and TypeScript 3.7. + +// 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.7/base.d.ts - Definitions specific to TypeScript 3.7 +// - ~/ts3.7/index.d.ts - Definitions specific to TypeScript 3.7 with assert pulled in + +// 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.7-specific augmentations: +/// diff --git a/types/node/v11/index.d.ts b/types/node/v11/index.d.ts index e8b186b05e..2cd553b853 100644 --- a/types/node/v11/index.d.ts +++ b/types/node/v11/index.d.ts @@ -1,103 +1,5 @@ -// Type definitions for non-npm package Node.js 11.15 -// Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped -// Alberto Schiabel -// Alexander T. -// Alvis HT Tang -// Andrew Makarov -// Benjamin Toueg -// Bruno Scheufler -// Chigozirim C. -// David Junger -// Deividas Bakanas -// Eugene Y. Q. Shen -// Flarna -// Hannes Magnusson -// Hoàng Văn Khải -// Huw -// Kelvin Jin -// Klaus Meinhardt -// Lishude -// Mariusz Wiktorczyk -// Mohsen Azimi -// Nicolas Even -// Nikita Galkin -// Parambir Singh -// Sebastian Silbermann -// Simon Schick -// Thomas den Hollander -// Wilco Bakker -// wwwy3y3 -// Zane Hannan AU -// Jeremie Rodriguez -// Samuel Ainsworth -// Kyle Uehlein -// Jordi Oliveras Rovira -// Thanik Bhongbhibhat -// Ivan Sieder -// Minh Son Nguyen -// ExE Boss -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// NOTE: These definitions support NodeJS and TypeScript 3.7. +// This isn't strictly needed since 3.7 has the assert module, but this way we're consistent. +// Typically type modificatons should be made in base.d.ts instead of here -// NOTE: These definitions support NodeJS and TypeScript 3.2. - -// 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.2/index.d.ts - Definitions specific to TypeScript 3.2 - -// NOTE: Augmentations for TypeScript 3.2 and later should use individual files for overrides -// within the respective ~/ts3.2 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.2, so the older definitions will be found here. - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: /// - -// We can't include assert.d.ts in base.d.ts, as it'll cause duplication errors in +ts3.7 -/// - -// TypeScript 2.1-specific augmentations: - -// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) -// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files -// just to ensure the names are known and node typings can be used without importing these libs. -// if someone really needs these types the libs need to be added via --lib or in tsconfig.json -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } -interface Set {} -interface Map {} -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; -// even this is just a forward declaration some properties are added otherwise -// it would be allowed to pass anything to e.g. Buffer.from() -interface SharedArrayBuffer { - readonly byteLength: number; - slice(begin?: number, end?: number): SharedArrayBuffer; -} - -declare module "util" { - namespace inspect { - const custom: symbol; - } - namespace promisify { - const custom: symbol; - } - namespace types { - function isBigInt64Array(value: any): boolean; - function isBigUint64Array(value: any): boolean; - } -} diff --git a/types/node/v11/node-tests.ts b/types/node/v11/node-tests.ts index 048fef67ef..983748c1fd 100644 --- a/types/node/v11/node-tests.ts +++ b/types/node/v11/node-tests.ts @@ -1,1204 +1,59 @@ -import assert = require("assert"); -import * as fs from "fs"; -import * as url from "url"; -import * as util from "util"; -import * as http from "http"; -import * as https from "https"; -import * as vm from "vm"; -import * as console2 from "console"; -import * as string_decoder from "string_decoder"; -import * as timers from "timers"; -import * as dns from "dns"; -import * as async_hooks from "async_hooks"; -import * as inspector from "inspector"; -import * as trace_events from "trace_events"; -import Module = require("module"); +import * as assert from 'assert'; -//////////////////////////////////////////////////// -/// File system tests : http://nodejs.org/api/fs.html -//////////////////////////////////////////////////// +assert(true, "it's working"); + +assert.ok(true, 'inner functions work as well'); + +assert.throws(() => {}); +assert.throws(() => {}, /Regex test/); +assert.throws( + () => {}, + () => {}, + 'works wonderfully', +); + +assert['fail'](true, true, 'works like a charm'); { - { - 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 | null, 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 }) as string[]; - 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' }); - const listDir3: fs.Dirent[] = fs.readdirSync('path', { encoding: 'utf8', withFileTypes: true }); - - 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 | null, files: fs.Dirent[]) => {}); - } - - async function testPromisify() { - const rd = util.promisify(fs.readdir); - let listS: string[]; - listS = await rd('path'); - listS = await rd('path', 'utf8'); - listS = await rd('path', null); - listS = await rd('path', undefined); - listS = await rd('path', { encoding: 'utf8' }); - listS = await rd('path', { encoding: null }); - listS = await rd('path', { encoding: null, withFileTypes: false }); - listS = await rd('path', { encoding: 'utf8', withFileTypes: false }); - const listDir: fs.Dirent[] = await rd('path', { withFileTypes: true }); - const listDir2: Buffer[] = await rd('path', { withFileTypes: false, encoding: 'buffer' }); - const listDir3: fs.Dirent[] = await rd('path', { encoding: 'utf8', withFileTypes: true }); - } - - { - 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 = '123'; - 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 = '123'; - 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, - }); - } - - { - let names: Promise; - let buffers: Promise; - let namesOrBuffers: Promise; - let entries: Promise; - - names = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: false }); - buffers = fs.promises.readdir('/path/to/dir', { encoding: 'buffer', withFileTypes: false }); - namesOrBuffers = fs.promises.readdir('/path/to/dir', { encoding: 'SOME OTHER', withFileTypes: false }); - entries = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: true }); - } + const a = null as any; + assert.ifError(a); + a; // $ExpectType null | undefined } -//////////////////////////////////////////////////// -/// 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'], - // 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'); - } - - { - let path: string = url.fileURLToPath('file://test'); - path = url.fileURLToPath(new url.URL('file://test')); - } - - { - const path: url.URL = url.pathToFileURL('file://test'); - } + const a = true as boolean; + assert(a); + a; // $ExpectType true } -////////////////////////////////////////////////////// -/// 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 = []; - - { - function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} - - class MyIncomingMessage extends http.IncomingMessage { - foo: number; - } - - class MyServerResponse extends http.ServerResponse { - foo: string; - } - - let server: https.Server; - - server = new https.Server(); - server = new https.Server(reqListener); - server = new https.Server({ IncomingMessage: MyIncomingMessage}); - - server = new https.Server({ - IncomingMessage: MyIncomingMessage, - ServerResponse: MyServerResponse - }, reqListener); - - server = https.createServer(); - server = https.createServer(reqListener); - server = https.createServer({ IncomingMessage: MyIncomingMessage }); - server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); - - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - const maxHeadersCount: number | null = server.maxHeadersCount; - const headersTimeout: number = server.headersTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } + // tslint:disable-next-line: no-null-undefined-union + const a = 13 as number | null | undefined; + assert(a); + a; // $ExpectType number } -//////////////////////////////////////////////////// -/// 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')); + const a = true as boolean; + assert.ok(a); + a; // $ExpectType true } -//////////////////////////////////////////////////// -/// 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'), - }); - } + // tslint:disable-next-line: no-null-undefined-union + const a = 13 as number | null | undefined; + assert.ok(a); + a; // $ExpectType number } -///////////////////////////////////////////////////// -/// Timers tests : https://nodejs.org/api/timers.html -///////////////////////////////////////////////////// - { - { - const immediate = timers - .setImmediate(() => { - console.log('immediate'); - }) - .unref() - .ref(); - const b: boolean = immediate.hasRef(); - timers.clearImmediate(immediate); - } - { - const timeout = timers - .setInterval(() => { - console.log('interval'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - timers.clearInterval(timeout); - } - { - const timeout = timers - .setTimeout(() => { - console.log('timeout'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - 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(""); - } + const a = 'test' as any; + assert.strictEqual(a, 'test'); + a; // $ExpectType string } -///////////////////////////////////////////////////////// -/// 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 | 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(); - const isConstr: boolean = frame.isConstructor(); - } -} - -/////////////////////////////////////////////////////////// -/// 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'); - } -} - -/////////////////////////////////////////////////// -/// DNS Tests : https://nodejs.org/api/dns.html /// -/////////////////////////////////////////////////// - -{ - dns.lookup("nodejs.org", (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 4, (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 6, (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", {}, (err, address, family) => { - const _err: NodeJS.ErrnoException | null = 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 | null = err; - const _address: string = address; - const _family: number = family; - } - ); - dns.lookup("nodejs.org", { all: true }, (err, addresses) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: dns.LookupAddress[] = addresses; - }); - dns.lookup("nodejs.org", { all: true, verbatim: true }, (err, addresses) => { - const _err: NodeJS.ErrnoException | null = 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 | null = 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 | null = 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; -} - -//////////////////////////////////////////////////// -/// 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 - }); -} - -/////////////////////////////////////////////////////////// -/// 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 | undefined = 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 | 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!; - }); - 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(); + const a = { b: 2 } as any; + assert.deepStrictEqual(a, { b: 2 }); + a; // $ExpectType { b: number; } } diff --git a/types/node/v11/package.json b/types/node/v11/package.json index 028f692acb..d70cf2b291 100644 --- a/types/node/v11/package.json +++ b/types/node/v11/package.json @@ -2,14 +2,14 @@ "private": true, "types": "index", "typesVersions": { - ">=3.7.0-0": { + "<=3.1": { "*": [ - "ts3.7/*" + "ts3.1/*" ] }, - ">=3.2.0-0": { + "<=3.6": { "*": [ - "ts3.2/*" + "ts3.6/*" ] } } diff --git a/types/node/v12/ts3.7/assert.d.ts b/types/node/v11/ts3.1/assert.d.ts similarity index 85% rename from types/node/v12/ts3.7/assert.d.ts rename to types/node/v11/ts3.1/assert.d.ts index 161d8def8e..10aa09956e 100644 --- a/types/node/v12/ts3.7/assert.d.ts +++ b/types/node/v11/ts3.1/assert.d.ts @@ -1,5 +1,5 @@ declare module "assert" { - function assert(value: any, message?: string | Error): asserts value; + function assert(value: any, message?: string | Error): void; namespace assert { class AssertionError implements Error { name: string; @@ -19,7 +19,7 @@ declare module "assert" { 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): asserts value; + 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. */ @@ -28,9 +28,9 @@ declare module "assert" { 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: T, message?: string | Error): asserts actual is T; + 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: T, message?: string | Error): asserts actual is T; + function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; function throws(block: () => any, message?: string | Error): void; @@ -38,7 +38,7 @@ declare module "assert" { function doesNotThrow(block: () => any, message?: string | Error): void; function doesNotThrow(block: () => any, error: RegExp | Function, message?: string | Error): void; - function ifError(value: any): asserts value is null | undefined; + function ifError(value: any): void; function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; function rejects(block: (() => Promise) | Promise, error: RegExp | Function | Object | Error, message?: string | Error): Promise; diff --git a/types/node/v11/ts3.1/base.d.ts b/types/node/v11/ts3.1/base.d.ts new file mode 100644 index 0000000000..f9bc0b3d91 --- /dev/null +++ b/types/node/v11/ts3.1/base.d.ts @@ -0,0 +1,40 @@ +// base definitions for all NodeJS modules that are not specific to any version of TypeScript +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/types/node/v11/globals.d.ts b/types/node/v11/ts3.1/globals.d.ts similarity index 100% rename from types/node/v11/globals.d.ts rename to types/node/v11/ts3.1/globals.d.ts diff --git a/types/node/v11/ts3.1/index.d.ts b/types/node/v11/ts3.1/index.d.ts new file mode 100644 index 0000000000..e8b186b05e --- /dev/null +++ b/types/node/v11/ts3.1/index.d.ts @@ -0,0 +1,103 @@ +// Type definitions for non-npm package Node.js 11.15 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +// Alexander T. +// Alvis HT Tang +// Andrew Makarov +// Benjamin Toueg +// Bruno Scheufler +// Chigozirim C. +// David Junger +// Deividas Bakanas +// Eugene Y. Q. Shen +// Flarna +// Hannes Magnusson +// Hoàng Văn Khải +// Huw +// Kelvin Jin +// Klaus Meinhardt +// Lishude +// Mariusz Wiktorczyk +// Mohsen Azimi +// Nicolas Even +// Nikita Galkin +// Parambir Singh +// Sebastian Silbermann +// Simon Schick +// Thomas den Hollander +// Wilco Bakker +// wwwy3y3 +// Zane Hannan AU +// Jeremie Rodriguez +// Samuel Ainsworth +// Kyle Uehlein +// Jordi Oliveras Rovira +// Thanik Bhongbhibhat +// Ivan Sieder +// Minh Son Nguyen +// ExE Boss +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// NOTE: These definitions support NodeJS and TypeScript 3.2. + +// 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.2/index.d.ts - Definitions specific to TypeScript 3.2 + +// NOTE: Augmentations for TypeScript 3.2 and later should use individual files for overrides +// within the respective ~/ts3.2 (or later) folder. However, this is disallowed for versions +// prior to TypeScript 3.2, so the older definitions will be found here. + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// + +// We can't include assert.d.ts in base.d.ts, as it'll cause duplication errors in +ts3.7 +/// + +// TypeScript 2.1-specific augmentations: + +// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) +// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files +// just to ensure the names are known and node typings can be used without importing these libs. +// if someone really needs these types the libs need to be added via --lib or in tsconfig.json +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } +interface Set {} +interface Map {} +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; +// even this is just a forward declaration some properties are added otherwise +// it would be allowed to pass anything to e.g. Buffer.from() +interface SharedArrayBuffer { + readonly byteLength: number; + slice(begin?: number, end?: number): SharedArrayBuffer; +} + +declare module "util" { + namespace inspect { + const custom: symbol; + } + namespace promisify { + const custom: symbol; + } + namespace types { + function isBigInt64Array(value: any): boolean; + function isBigUint64Array(value: any): boolean; + } +} diff --git a/types/node/v11/ts3.1/node-tests.ts b/types/node/v11/ts3.1/node-tests.ts new file mode 100644 index 0000000000..048fef67ef --- /dev/null +++ b/types/node/v11/ts3.1/node-tests.ts @@ -0,0 +1,1204 @@ +import assert = require("assert"); +import * as fs from "fs"; +import * as url from "url"; +import * as util from "util"; +import * as http from "http"; +import * as https from "https"; +import * as vm from "vm"; +import * as console2 from "console"; +import * as string_decoder from "string_decoder"; +import * as timers from "timers"; +import * as dns from "dns"; +import * as async_hooks from "async_hooks"; +import * as inspector from "inspector"; +import * as trace_events from "trace_events"; +import Module = require("module"); + +//////////////////////////////////////////////////// +/// 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 | null, 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 }) as string[]; + 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' }); + const listDir3: fs.Dirent[] = fs.readdirSync('path', { encoding: 'utf8', withFileTypes: true }); + + 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 | null, files: fs.Dirent[]) => {}); + } + + async function testPromisify() { + const rd = util.promisify(fs.readdir); + let listS: string[]; + listS = await rd('path'); + listS = await rd('path', 'utf8'); + listS = await rd('path', null); + listS = await rd('path', undefined); + listS = await rd('path', { encoding: 'utf8' }); + listS = await rd('path', { encoding: null }); + listS = await rd('path', { encoding: null, withFileTypes: false }); + listS = await rd('path', { encoding: 'utf8', withFileTypes: false }); + const listDir: fs.Dirent[] = await rd('path', { withFileTypes: true }); + const listDir2: Buffer[] = await rd('path', { withFileTypes: false, encoding: 'buffer' }); + const listDir3: fs.Dirent[] = await rd('path', { encoding: 'utf8', withFileTypes: true }); + } + + { + 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 = '123'; + 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 = '123'; + 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, + }); + } + + { + let names: Promise; + let buffers: Promise; + let namesOrBuffers: Promise; + let entries: Promise; + + names = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: false }); + buffers = fs.promises.readdir('/path/to/dir', { encoding: 'buffer', withFileTypes: false }); + namesOrBuffers = fs.promises.readdir('/path/to/dir', { encoding: 'SOME OTHER', withFileTypes: false }); + entries = fs.promises.readdir('/path/to/dir', { encoding: 'utf8', withFileTypes: true }); + } +} + +//////////////////////////////////////////////////// +/// 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'], + // 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'); + } + + { + let path: string = url.fileURLToPath('file://test'); + path = url.fileURLToPath(new url.URL('file://test')); + } + + { + const path: url.URL = url.pathToFileURL('file://test'); + } +} + +////////////////////////////////////////////////////// +/// 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 = []; + + { + function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} + + class MyIncomingMessage extends http.IncomingMessage { + foo: number; + } + + class MyServerResponse extends http.ServerResponse { + foo: string; + } + + let server: https.Server; + + server = new https.Server(); + server = new https.Server(reqListener); + server = new https.Server({ IncomingMessage: MyIncomingMessage}); + + server = new https.Server({ + IncomingMessage: MyIncomingMessage, + ServerResponse: MyServerResponse + }, reqListener); + + server = https.createServer(); + server = https.createServer(reqListener); + server = https.createServer({ IncomingMessage: MyIncomingMessage }); + server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); + + const timeout: number = server.timeout; + const listening: boolean = server.listening; + const keepAliveTimeout: number = server.keepAliveTimeout; + const maxHeadersCount: number | null = server.maxHeadersCount; + const headersTimeout: number = server.headersTimeout; + server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); + } +} + +//////////////////////////////////////////////////// +/// 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')); +} + +//////////////////////////////////////////////////// +/// 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 immediate = timers + .setImmediate(() => { + console.log('immediate'); + }) + .unref() + .ref(); + const b: boolean = immediate.hasRef(); + timers.clearImmediate(immediate); + } + { + const timeout = timers + .setInterval(() => { + console.log('interval'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + timers.clearInterval(timeout); + } + { + const timeout = timers + .setTimeout(() => { + console.log('timeout'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + 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 | 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(); + const isConstr: boolean = frame.isConstructor(); + } +} + +/////////////////////////////////////////////////////////// +/// 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'); + } +} + +/////////////////////////////////////////////////// +/// DNS Tests : https://nodejs.org/api/dns.html /// +/////////////////////////////////////////////////// + +{ + dns.lookup("nodejs.org", (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 4, (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 6, (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", {}, (err, address, family) => { + const _err: NodeJS.ErrnoException | null = 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 | null = err; + const _address: string = address; + const _family: number = family; + } + ); + dns.lookup("nodejs.org", { all: true }, (err, addresses) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: dns.LookupAddress[] = addresses; + }); + dns.lookup("nodejs.org", { all: true, verbatim: true }, (err, addresses) => { + const _err: NodeJS.ErrnoException | null = 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 | null = 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 | null = 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; +} + +//////////////////////////////////////////////////// +/// 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 + }); +} + +/////////////////////////////////////////////////////////// +/// 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 | undefined = 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 | 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!; + }); + 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/v11/ts3.2/tsconfig.json b/types/node/v11/ts3.1/tsconfig.json similarity index 100% rename from types/node/v11/ts3.2/tsconfig.json rename to types/node/v11/ts3.1/tsconfig.json diff --git a/types/node/v11/ts3.1/tslint.json b/types/node/v11/ts3.1/tslint.json new file mode 100644 index 0000000000..4d72445ea0 --- /dev/null +++ b/types/node/v11/ts3.1/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "strict-export-declare-modifiers": false, + "unified-signatures": false + } +} diff --git a/types/node/v11/util.d.ts b/types/node/v11/ts3.1/util.d.ts similarity index 100% rename from types/node/v11/util.d.ts rename to types/node/v11/ts3.1/util.d.ts diff --git a/types/node/v11/ts3.2/base.d.ts b/types/node/v11/ts3.6/base.d.ts similarity index 100% rename from types/node/v11/ts3.2/base.d.ts rename to types/node/v11/ts3.6/base.d.ts diff --git a/types/node/v11/ts3.2/globals.d.ts b/types/node/v11/ts3.6/globals.d.ts similarity index 100% rename from types/node/v11/ts3.2/globals.d.ts rename to types/node/v11/ts3.6/globals.d.ts diff --git a/types/node/v11/ts3.2/index.d.ts b/types/node/v11/ts3.6/index.d.ts similarity index 100% rename from types/node/v11/ts3.2/index.d.ts rename to types/node/v11/ts3.6/index.d.ts diff --git a/types/node/v11/ts3.2/node-tests.ts b/types/node/v11/ts3.6/node-tests.ts similarity index 100% rename from types/node/v11/ts3.2/node-tests.ts rename to types/node/v11/ts3.6/node-tests.ts diff --git a/types/node/v11/ts3.7/tsconfig.json b/types/node/v11/ts3.6/tsconfig.json similarity index 100% rename from types/node/v11/ts3.7/tsconfig.json rename to types/node/v11/ts3.6/tsconfig.json diff --git a/types/node/v11/ts3.2/tslint.json b/types/node/v11/ts3.6/tslint.json similarity index 100% rename from types/node/v11/ts3.2/tslint.json rename to types/node/v11/ts3.6/tslint.json diff --git a/types/node/v11/ts3.2/util.d.ts b/types/node/v11/ts3.6/util.d.ts similarity index 100% rename from types/node/v11/ts3.2/util.d.ts rename to types/node/v11/ts3.6/util.d.ts diff --git a/types/node/v11/ts3.7/base.d.ts b/types/node/v11/ts3.7/base.d.ts deleted file mode 100644 index e0fc9c98f6..0000000000 --- a/types/node/v11/ts3.7/base.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.7. - -// 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.7/base.d.ts - Definitions specific to TypeScript 3.7 -// - ~/ts3.7/index.d.ts - Definitions specific to TypeScript 3.7 with assert pulled in - -// 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.7-specific augmentations: -/// diff --git a/types/node/v11/ts3.7/index.d.ts b/types/node/v11/ts3.7/index.d.ts deleted file mode 100644 index 2cd553b853..0000000000 --- a/types/node/v11/ts3.7/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.7. -// This isn't strictly needed since 3.7 has the assert module, but this way we're consistent. -// Typically type modificatons should be made in base.d.ts instead of here - -/// diff --git a/types/node/v11/ts3.7/node-tests.ts b/types/node/v11/ts3.7/node-tests.ts deleted file mode 100644 index 983748c1fd..0000000000 --- a/types/node/v11/ts3.7/node-tests.ts +++ /dev/null @@ -1,59 +0,0 @@ -import * as assert from 'assert'; - -assert(true, "it's working"); - -assert.ok(true, 'inner functions work as well'); - -assert.throws(() => {}); -assert.throws(() => {}, /Regex test/); -assert.throws( - () => {}, - () => {}, - 'works wonderfully', -); - -assert['fail'](true, true, 'works like a charm'); - -{ - const a = null as any; - assert.ifError(a); - a; // $ExpectType null | undefined -} - -{ - const a = true as boolean; - assert(a); - a; // $ExpectType true -} - -{ - // tslint:disable-next-line: no-null-undefined-union - const a = 13 as number | null | undefined; - assert(a); - a; // $ExpectType number -} - -{ - const a = true as boolean; - assert.ok(a); - a; // $ExpectType true -} - -{ - // tslint:disable-next-line: no-null-undefined-union - const a = 13 as number | null | undefined; - assert.ok(a); - a; // $ExpectType number -} - -{ - const a = 'test' as any; - assert.strictEqual(a, 'test'); - a; // $ExpectType string -} - -{ - const a = { b: 2 } as any; - assert.deepStrictEqual(a, { b: 2 }); - a; // $ExpectType { b: number; } -} diff --git a/types/node/v11/ts3.7/tslint.json b/types/node/v11/ts3.7/tslint.json deleted file mode 100644 index 1a8ddd9863..0000000000 --- a/types/node/v11/ts3.7/tslint.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "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/v11/tslint.json b/types/node/v11/tslint.json index 4d72445ea0..1a8ddd9863 100644 --- a/types/node/v11/tslint.json +++ b/types/node/v11/tslint.json @@ -1,10 +1,10 @@ { - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "no-empty-interface": false, - "no-single-declare-module": false, - "strict-export-declare-modifiers": false, - "unified-signatures": false - } + "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/v12/assert.d.ts b/types/node/v12/assert.d.ts index 10aa09956e..161d8def8e 100644 --- a/types/node/v12/assert.d.ts +++ b/types/node/v12/assert.d.ts @@ -1,5 +1,5 @@ declare module "assert" { - function assert(value: any, message?: string | Error): void; + function assert(value: any, message?: string | Error): asserts value; namespace assert { class AssertionError implements Error { name: string; @@ -19,7 +19,7 @@ declare module "assert" { 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; + function ok(value: any, message?: string | Error): asserts value; /** @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. */ @@ -28,9 +28,9 @@ declare module "assert" { 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 strictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; function notStrictEqual(actual: any, expected: any, message?: string | Error): void; - function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; + function deepStrictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; function throws(block: () => any, message?: string | Error): void; @@ -38,7 +38,7 @@ declare module "assert" { function doesNotThrow(block: () => any, message?: string | Error): void; function doesNotThrow(block: () => any, error: RegExp | Function, message?: string | Error): void; - function ifError(value: any): void; + function ifError(value: any): asserts value is null | undefined; function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; function rejects(block: (() => Promise) | Promise, error: RegExp | Function | Object | Error, message?: string | Error): Promise; diff --git a/types/node/v12/base.d.ts b/types/node/v12/base.d.ts index f9bc0b3d91..02556a1b59 100644 --- a/types/node/v12/base.d.ts +++ b/types/node/v12/base.d.ts @@ -1,40 +1,20 @@ -// base definitions for all NodeJS modules that are not specific to any version of TypeScript -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +// NOTE: These definitions support NodeJS and TypeScript 3.7. + +// 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.7/base.d.ts - Definitions specific to TypeScript 3.7 +// - ~/ts3.7/index.d.ts - Definitions specific to TypeScript 3.7 with assert pulled in + +// 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.7-specific augmentations: +/// diff --git a/types/node/v12/index.d.ts b/types/node/v12/index.d.ts index 55688802b0..2cd553b853 100644 --- a/types/node/v12/index.d.ts +++ b/types/node/v12/index.d.ts @@ -1,110 +1,5 @@ -// Type definitions for non-npm package Node.js 12.12 -// Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped -// Alberto Schiabel -// Alexander T. -// Alvis HT Tang -// Andrew Makarov -// Benjamin Toueg -// Bruno Scheufler -// Chigozirim C. -// David Junger -// Deividas Bakanas -// Eugene Y. Q. Shen -// Flarna -// Hannes Magnusson -// Hoàng Văn Khải -// Huw -// Kelvin Jin -// Klaus Meinhardt -// Lishude -// Mariusz Wiktorczyk -// Mohsen Azimi -// Nicolas Even -// Nikita Galkin -// Parambir Singh -// Sebastian Silbermann -// Simon Schick -// Thomas den Hollander -// Wilco Bakker -// wwwy3y3 -// Zane Hannan AU -// Samuel Ainsworth -// Kyle Uehlein -// Jordi Oliveras Rovira -// Thanik Bhongbhibhat -// Marcin Kopacz -// Trivikram Kamat -// Minh Son Nguyen -// Junxiao Shi -// Ilia Baryshnikov -// ExE Boss -// Jason Kwok -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// NOTE: These definitions support NodeJS and TypeScript 3.7. +// This isn't strictly needed since 3.7 has the assert module, but this way we're consistent. +// Typically type modificatons should be made in base.d.ts instead of here -// NOTE: These definitions support NodeJS and TypeScript 3.2. - -// 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.2/index.d.ts - Definitions specific to TypeScript 3.2 - -// NOTE: Augmentations for TypeScript 3.2 and later should use individual files for overrides -// within the respective ~/ts3.2 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.2, so the older definitions will be found here. - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: /// - -// We can't include globals.global.d.ts in globals.d.ts, as it'll cause duplication errors in TypeScript 3.4+ -/// - -// We can't include assert.d.ts in base.d.ts, as it'll cause duplication errors in TypeScript 3.7+ -/// - -// TypeScript 2.1-specific augmentations: - -// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) -// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files -// just to ensure the names are known and node typings can be used without importing these libs. -// if someone really needs these types the libs need to be added via --lib or in tsconfig.json -interface MapConstructor { } -interface WeakMapConstructor { } -interface SetConstructor { } -interface WeakSetConstructor { } -interface Set {} -interface Map {} -interface ReadonlySet {} -interface Iterable { } -interface IteratorResult { } -interface AsyncIterable { } -interface Iterator { - next(value?: any): IteratorResult; -} -interface IterableIterator { } -interface AsyncIterableIterator {} -interface SymbolConstructor { - readonly iterator: symbol; - readonly asyncIterator: symbol; -} -declare var Symbol: SymbolConstructor; -// even this is just a forward declaration some properties are added otherwise -// it would be allowed to pass anything to e.g. Buffer.from() -interface SharedArrayBuffer { - readonly byteLength: number; - slice(begin?: number, end?: number): SharedArrayBuffer; -} - -declare module "util" { - namespace inspect { - const custom: symbol; - } - namespace promisify { - const custom: symbol; - } - namespace types { - function isBigInt64Array(value: any): boolean; - function isBigUint64Array(value: any): boolean; - } -} diff --git a/types/node/v12/node-tests.ts b/types/node/v12/node-tests.ts index 8b1b8f41a1..983748c1fd 100644 --- a/types/node/v12/node-tests.ts +++ b/types/node/v12/node-tests.ts @@ -1,898 +1,59 @@ -import assert = require("assert"); -import * as fs from "fs"; -import * as url from "url"; -import * as util from "util"; -import * as http from "http"; -import * as https from "https"; -import * as console2 from "console"; -import * as timers from "timers"; -import * as dns from "dns"; -import * as inspector from "inspector"; -import * as trace_events from "trace_events"; -import * as dgram from "dgram"; -import Module = require("module"); +import * as assert from 'assert'; -//////////////////////////////////////////////////// -/// Url tests : http://nodejs.org/api/url.html -//////////////////////////////////////////////////// +assert(true, "it's working"); + +assert.ok(true, 'inner functions work as well'); + +assert.throws(() => {}); +assert.throws(() => {}, /Regex test/); +assert.throws( + () => {}, + () => {}, + 'works wonderfully', +); + +assert['fail'](true, true, 'works like a charm'); { - { - 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'], - // 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'); - } - - { - let path: string = url.fileURLToPath('file://test'); - path = url.fileURLToPath(new url.URL('file://test')); - } - - { - const path: url.URL = url.pathToFileURL('file://test'); - } + const a = null as any; + assert.ifError(a); + a; // $ExpectType null | undefined } -////////////////////////////////////////////////////// -/// 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 = []; - - { - function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} - - class MyIncomingMessage extends http.IncomingMessage { - foo: number; - } - - class MyServerResponse extends http.ServerResponse { - foo: string; - } - - let server: https.Server; - - server = new https.Server(); - server = new https.Server(reqListener); - server = new https.Server({ IncomingMessage: MyIncomingMessage}); - - server = new https.Server({ - IncomingMessage: MyIncomingMessage, - ServerResponse: MyServerResponse - }, reqListener); - - server = https.createServer(); - server = https.createServer(reqListener); - server = https.createServer({ IncomingMessage: MyIncomingMessage }); - server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); - - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - const maxHeadersCount: number | null = server.maxHeadersCount; - const headersTimeout: number = server.headersTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } + const a = true as boolean; + assert(a); + a; // $ExpectType true } -///////////////////////////////////////////////////// -/// Timers tests : https://nodejs.org/api/timers.html -///////////////////////////////////////////////////// - { - { - const immediate = timers - .setImmediate(() => { - console.log('immediate'); - }) - .unref() - .ref(); - const b: boolean = immediate.hasRef(); - timers.clearImmediate(immediate); - } - { - const timeout = timers - .setInterval(() => { - console.log('interval'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - timers.clearInterval(timeout); - } - { - const timeout = timers - .setTimeout(() => { - console.log('timeout'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - 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(""); - } + // tslint:disable-next-line: no-null-undefined-union + const a = 13 as number | null | undefined; + assert(a); + a; // $ExpectType number } -///////////////////////////////////////////////////////// -/// 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 | 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(); - const isConstr: boolean = frame.isConstructor(); - } + const a = true as boolean; + assert.ok(a); + a; // $ExpectType true } -/////////////////////////////////////////////////////////// -/// 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'); - } + // tslint:disable-next-line: no-null-undefined-union + const a = 13 as number | null | undefined; + assert.ok(a); + a; // $ExpectType number } -/////////////////////////////////////////////////// -/// DNS Tests : https://nodejs.org/api/dns.html /// -/////////////////////////////////////////////////// - { - dns.lookup("nodejs.org", (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 4, (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", 6, (err, address, family) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: string = address; - const _family: number = family; - }); - dns.lookup("nodejs.org", {}, (err, address, family) => { - const _err: NodeJS.ErrnoException | null = 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 | null = err; - const _address: string = address; - const _family: number = family; - } - ); - dns.lookup("nodejs.org", { all: true }, (err, addresses) => { - const _err: NodeJS.ErrnoException | null = err; - const _address: dns.LookupAddress[] = addresses; - }); - dns.lookup("nodejs.org", { all: true, verbatim: true }, (err, addresses) => { - const _err: NodeJS.ErrnoException | null = 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 | null = 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 | null = 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(); - } + const a = 'test' as any; + assert.strictEqual(a, 'test'); + a; // $ExpectType string } -/***************************************************************************** - * * - * 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.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; -} - -/////////////////////////////////////////////////////////// -/// 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 | undefined = 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 | 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!; - }); - 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 | undefined = 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; - const path: string = module.path; - paths = m1.paths; - - const customRequire1 = moduleModule.createRequireFromPath('./test'); - const customRequire2 = moduleModule.createRequire('./test'); - - customRequire1('test'); - customRequire2('test'); - - const resolved1: string = customRequire1.resolve('test'); - const resolved2: string = customRequire2.resolve('test'); - - const paths1: string[] | null = customRequire1.resolve.paths('test'); - const paths2: string[] | null = customRequire2.resolve.paths('test'); - - const cachedModule1: Module = customRequire1.cache['/path/to/module.js']; - const cachedModule2: Module = customRequire2.cache['/path/to/module.js']; - - const main1: Module | undefined = customRequire1.main; - const main2: Module | undefined = customRequire2.main; -} - -///////////////////////////////////////////////////////// -/// stream tests : https://nodejs.org/api/stream.html /// -///////////////////////////////////////////////////////// -import stream = require('stream'); -import tty = require('tty'); - -{ - const writeStream = fs.createWriteStream('./index.d.ts'); - const _wom = writeStream.writableObjectMode; // $ExpectType boolean - - const readStream = fs.createReadStream('./index.d.ts'); - const _rom = readStream.readableObjectMode; // $ExpectType boolean - - const x: stream.Readable = process.stdin; - const stdin: tty.ReadStream = process.stdin; - const stdout: tty.WriteStream = process.stdout; - const stderr: tty.WriteStream = process.stderr; -} - -///////////////////////////////////////////////////////// -/// dgram tests : https://nodejs.org/api/dgram.html /// -///////////////////////////////////////////////////////// -{ - let sock: dgram.Socket = dgram.createSocket("udp4"); - sock = dgram.createSocket({ type: "udp4" }); - sock = dgram.createSocket({ - type: "udp4", - reuseAddr: true, - ipv6Only: false, - recvBufferSize: 4096, - sendBufferSize: 4096, - lookup: dns.lookup, - }); - sock = dgram.createSocket("udp6", (msg, rinfo) => { - msg; // $ExpectType Buffer - rinfo; // $ExpectType RemoteInfo - }); - sock.addMembership("233.252.0.0"); - sock.addMembership("233.252.0.0", "192.0.2.1"); - sock.address().address; // $ExpectType string - sock.address().family; // $ExpectType string - sock.address().port; // $ExpectType number - sock.bind(); - sock.bind(() => undefined); - sock.bind(8000); - sock.bind(8000, () => undefined); - sock.bind(8000, "192.0.2.1"); - sock.bind(8000, "192.0.2.1", () => undefined); - sock.bind({}, () => undefined); - sock.bind({ port: 8000, address: "192.0.2.1", exclusive: true }); - sock.bind({ fd: 7, exclusive: true }); - sock.close(); - sock.close(() => undefined); - sock.connect(8000); - sock.connect(8000, "192.0.2.1"); - sock.connect(8000, () => undefined); - sock.connect(8000, "192.0.2.1", () => undefined); - sock.disconnect(); - sock.dropMembership("233.252.0.0"); - sock.dropMembership("233.252.0.0", "192.0.2.1"); - sock.getRecvBufferSize(); // $ExpectType number - sock.getSendBufferSize(); // $ExpectType number - sock = sock.ref(); - sock.remoteAddress().address; // $ExpectType string - sock.remoteAddress().family; // $ExpectType string - sock.remoteAddress().port; // $ExpectType number - sock.send("datagram"); - sock.send(new Uint8Array(256), 8000, (err) => { - err; // $ExpectType Error | null - }); - sock.send(Buffer.alloc(256), 8000, "192.0.2.1"); - sock.send(new Uint8Array(256), 128, 64); - sock.send("datagram", 128, 64, (err) => undefined); - sock.send(new Uint8Array(256), 128, 64, 8000); - sock.send(new Uint8Array(256), 128, 64, 8000, (err) => undefined); - sock.send(Buffer.alloc(256), 128, 64, 8000, "192.0.2.1"); - sock.send("datagram", 128, 64, 8000, "192.0.2.1", (err) => undefined); - sock.setBroadcast(true); - sock.setMulticastInterface("192.0.2.1"); - sock.setMulticastLoopback(false); - sock.setMulticastTTL(128); - sock.setRecvBufferSize(4096); - sock.setSendBufferSize(4096); - sock.setTTL(128); - sock = sock.unref(); - - sock.on("close", () => undefined); - sock.on("connect", () => undefined); - sock.on("error", (exception) => { - exception; // $ExpectType Error - }); - sock.on("listening", () => undefined); - sock.on("message", (msg, rinfo) => { - msg; // $ExpectType Buffer - rinfo.address; // $ExpectType string - rinfo.family; // $ExpectType "IPv4" | "IPv6" - rinfo.port; // $ExpectType number - rinfo.size; // $ExpectType number - }); -} - -//////////////////////////////////////////////////// -/// Node.js ESNEXT Support -//////////////////////////////////////////////////// - -{ - const s = 'foo'; - const s1: string = s.trimLeft(); - const s2: string = s.trimRight(); + const a = { b: 2 } as any; + assert.deepStrictEqual(a, { b: 2 }); + a; // $ExpectType { b: number; } } diff --git a/types/node/v12/package.json b/types/node/v12/package.json index f7555e8915..101c324555 100644 --- a/types/node/v12/package.json +++ b/types/node/v12/package.json @@ -2,19 +2,19 @@ "private": true, "types": "index", "typesVersions": { - ">=3.7.0-0": { + "<=3.1": { "*": [ - "ts3.7/*" + "ts3.1/*" ] }, - ">=3.4.0-0": { + "<=3.3": { "*": [ - "ts3.4/*" + "ts3.3/*" ] }, - ">=3.2.0-0": { + "<=3.6": { "*": [ - "ts3.2/*" + "ts3.6/*" ] } } diff --git a/types/node/v11/ts3.7/assert.d.ts b/types/node/v12/ts3.1/assert.d.ts similarity index 85% rename from types/node/v11/ts3.7/assert.d.ts rename to types/node/v12/ts3.1/assert.d.ts index 161d8def8e..10aa09956e 100644 --- a/types/node/v11/ts3.7/assert.d.ts +++ b/types/node/v12/ts3.1/assert.d.ts @@ -1,5 +1,5 @@ declare module "assert" { - function assert(value: any, message?: string | Error): asserts value; + function assert(value: any, message?: string | Error): void; namespace assert { class AssertionError implements Error { name: string; @@ -19,7 +19,7 @@ declare module "assert" { 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): asserts value; + 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. */ @@ -28,9 +28,9 @@ declare module "assert" { 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: T, message?: string | Error): asserts actual is T; + 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: T, message?: string | Error): asserts actual is T; + function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; function throws(block: () => any, message?: string | Error): void; @@ -38,7 +38,7 @@ declare module "assert" { function doesNotThrow(block: () => any, message?: string | Error): void; function doesNotThrow(block: () => any, error: RegExp | Function, message?: string | Error): void; - function ifError(value: any): asserts value is null | undefined; + function ifError(value: any): void; function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; function rejects(block: (() => Promise) | Promise, error: RegExp | Function | Object | Error, message?: string | Error): Promise; diff --git a/types/node/v12/ts3.1/base.d.ts b/types/node/v12/ts3.1/base.d.ts new file mode 100644 index 0000000000..f9bc0b3d91 --- /dev/null +++ b/types/node/v12/ts3.1/base.d.ts @@ -0,0 +1,40 @@ +// base definitions for all NodeJS modules that are not specific to any version of TypeScript +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/types/node/v12/fs.d.ts b/types/node/v12/ts3.1/fs.d.ts similarity index 100% rename from types/node/v12/fs.d.ts rename to types/node/v12/ts3.1/fs.d.ts diff --git a/types/node/v12/globals.d.ts b/types/node/v12/ts3.1/globals.d.ts similarity index 100% rename from types/node/v12/globals.d.ts rename to types/node/v12/ts3.1/globals.d.ts diff --git a/types/node/v12/ts3.1/index.d.ts b/types/node/v12/ts3.1/index.d.ts new file mode 100644 index 0000000000..55688802b0 --- /dev/null +++ b/types/node/v12/ts3.1/index.d.ts @@ -0,0 +1,110 @@ +// Type definitions for non-npm package Node.js 12.12 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +// Alexander T. +// Alvis HT Tang +// Andrew Makarov +// Benjamin Toueg +// Bruno Scheufler +// Chigozirim C. +// David Junger +// Deividas Bakanas +// Eugene Y. Q. Shen +// Flarna +// Hannes Magnusson +// Hoàng Văn Khải +// Huw +// Kelvin Jin +// Klaus Meinhardt +// Lishude +// Mariusz Wiktorczyk +// Mohsen Azimi +// Nicolas Even +// Nikita Galkin +// Parambir Singh +// Sebastian Silbermann +// Simon Schick +// Thomas den Hollander +// Wilco Bakker +// wwwy3y3 +// Zane Hannan AU +// Samuel Ainsworth +// Kyle Uehlein +// Jordi Oliveras Rovira +// Thanik Bhongbhibhat +// Marcin Kopacz +// Trivikram Kamat +// Minh Son Nguyen +// Junxiao Shi +// Ilia Baryshnikov +// ExE Boss +// Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// NOTE: These definitions support NodeJS and TypeScript 3.2. + +// 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.2/index.d.ts - Definitions specific to TypeScript 3.2 + +// NOTE: Augmentations for TypeScript 3.2 and later should use individual files for overrides +// within the respective ~/ts3.2 (or later) folder. However, this is disallowed for versions +// prior to TypeScript 3.2, so the older definitions will be found here. + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// + +// We can't include globals.global.d.ts in globals.d.ts, as it'll cause duplication errors in TypeScript 3.4+ +/// + +// We can't include assert.d.ts in base.d.ts, as it'll cause duplication errors in TypeScript 3.7+ +/// + +// TypeScript 2.1-specific augmentations: + +// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) +// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files +// just to ensure the names are known and node typings can be used without importing these libs. +// if someone really needs these types the libs need to be added via --lib or in tsconfig.json +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } +interface Set {} +interface Map {} +interface ReadonlySet {} +interface Iterable { } +interface IteratorResult { } +interface AsyncIterable { } +interface Iterator { + next(value?: any): IteratorResult; +} +interface IterableIterator { } +interface AsyncIterableIterator {} +interface SymbolConstructor { + readonly iterator: symbol; + readonly asyncIterator: symbol; +} +declare var Symbol: SymbolConstructor; +// even this is just a forward declaration some properties are added otherwise +// it would be allowed to pass anything to e.g. Buffer.from() +interface SharedArrayBuffer { + readonly byteLength: number; + slice(begin?: number, end?: number): SharedArrayBuffer; +} + +declare module "util" { + namespace inspect { + const custom: symbol; + } + namespace promisify { + const custom: symbol; + } + namespace types { + function isBigInt64Array(value: any): boolean; + function isBigUint64Array(value: any): boolean; + } +} diff --git a/types/node/v12/ts3.1/node-tests.ts b/types/node/v12/ts3.1/node-tests.ts new file mode 100644 index 0000000000..8b1b8f41a1 --- /dev/null +++ b/types/node/v12/ts3.1/node-tests.ts @@ -0,0 +1,898 @@ +import assert = require("assert"); +import * as fs from "fs"; +import * as url from "url"; +import * as util from "util"; +import * as http from "http"; +import * as https from "https"; +import * as console2 from "console"; +import * as timers from "timers"; +import * as dns from "dns"; +import * as inspector from "inspector"; +import * as trace_events from "trace_events"; +import * as dgram from "dgram"; +import Module = require("module"); + +//////////////////////////////////////////////////// +/// 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'], + // 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'); + } + + { + let path: string = url.fileURLToPath('file://test'); + path = url.fileURLToPath(new url.URL('file://test')); + } + + { + const path: url.URL = url.pathToFileURL('file://test'); + } +} + +////////////////////////////////////////////////////// +/// 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 = []; + + { + function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} + + class MyIncomingMessage extends http.IncomingMessage { + foo: number; + } + + class MyServerResponse extends http.ServerResponse { + foo: string; + } + + let server: https.Server; + + server = new https.Server(); + server = new https.Server(reqListener); + server = new https.Server({ IncomingMessage: MyIncomingMessage}); + + server = new https.Server({ + IncomingMessage: MyIncomingMessage, + ServerResponse: MyServerResponse + }, reqListener); + + server = https.createServer(); + server = https.createServer(reqListener); + server = https.createServer({ IncomingMessage: MyIncomingMessage }); + server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); + + const timeout: number = server.timeout; + const listening: boolean = server.listening; + const keepAliveTimeout: number = server.keepAliveTimeout; + const maxHeadersCount: number | null = server.maxHeadersCount; + const headersTimeout: number = server.headersTimeout; + server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); + } +} + +///////////////////////////////////////////////////// +/// Timers tests : https://nodejs.org/api/timers.html +///////////////////////////////////////////////////// + +{ + { + const immediate = timers + .setImmediate(() => { + console.log('immediate'); + }) + .unref() + .ref(); + const b: boolean = immediate.hasRef(); + timers.clearImmediate(immediate); + } + { + const timeout = timers + .setInterval(() => { + console.log('interval'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + timers.clearInterval(timeout); + } + { + const timeout = timers + .setTimeout(() => { + console.log('timeout'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + 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 | 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(); + const isConstr: boolean = frame.isConstructor(); + } +} + +/////////////////////////////////////////////////////////// +/// 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'); + } +} + +/////////////////////////////////////////////////// +/// DNS Tests : https://nodejs.org/api/dns.html /// +/////////////////////////////////////////////////// + +{ + dns.lookup("nodejs.org", (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 4, (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 6, (err, address, family) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", {}, (err, address, family) => { + const _err: NodeJS.ErrnoException | null = 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 | null = err; + const _address: string = address; + const _family: number = family; + } + ); + dns.lookup("nodejs.org", { all: true }, (err, addresses) => { + const _err: NodeJS.ErrnoException | null = err; + const _address: dns.LookupAddress[] = addresses; + }); + dns.lookup("nodejs.org", { all: true, verbatim: true }, (err, addresses) => { + const _err: NodeJS.ErrnoException | null = 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 | null = 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 | null = 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.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; +} + +/////////////////////////////////////////////////////////// +/// 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 | undefined = 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 | 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!; + }); + 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 | undefined = 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; + const path: string = module.path; + paths = m1.paths; + + const customRequire1 = moduleModule.createRequireFromPath('./test'); + const customRequire2 = moduleModule.createRequire('./test'); + + customRequire1('test'); + customRequire2('test'); + + const resolved1: string = customRequire1.resolve('test'); + const resolved2: string = customRequire2.resolve('test'); + + const paths1: string[] | null = customRequire1.resolve.paths('test'); + const paths2: string[] | null = customRequire2.resolve.paths('test'); + + const cachedModule1: Module = customRequire1.cache['/path/to/module.js']; + const cachedModule2: Module = customRequire2.cache['/path/to/module.js']; + + const main1: Module | undefined = customRequire1.main; + const main2: Module | undefined = customRequire2.main; +} + +///////////////////////////////////////////////////////// +/// stream tests : https://nodejs.org/api/stream.html /// +///////////////////////////////////////////////////////// +import stream = require('stream'); +import tty = require('tty'); + +{ + const writeStream = fs.createWriteStream('./index.d.ts'); + const _wom = writeStream.writableObjectMode; // $ExpectType boolean + + const readStream = fs.createReadStream('./index.d.ts'); + const _rom = readStream.readableObjectMode; // $ExpectType boolean + + const x: stream.Readable = process.stdin; + const stdin: tty.ReadStream = process.stdin; + const stdout: tty.WriteStream = process.stdout; + const stderr: tty.WriteStream = process.stderr; +} + +///////////////////////////////////////////////////////// +/// dgram tests : https://nodejs.org/api/dgram.html /// +///////////////////////////////////////////////////////// +{ + let sock: dgram.Socket = dgram.createSocket("udp4"); + sock = dgram.createSocket({ type: "udp4" }); + sock = dgram.createSocket({ + type: "udp4", + reuseAddr: true, + ipv6Only: false, + recvBufferSize: 4096, + sendBufferSize: 4096, + lookup: dns.lookup, + }); + sock = dgram.createSocket("udp6", (msg, rinfo) => { + msg; // $ExpectType Buffer + rinfo; // $ExpectType RemoteInfo + }); + sock.addMembership("233.252.0.0"); + sock.addMembership("233.252.0.0", "192.0.2.1"); + sock.address().address; // $ExpectType string + sock.address().family; // $ExpectType string + sock.address().port; // $ExpectType number + sock.bind(); + sock.bind(() => undefined); + sock.bind(8000); + sock.bind(8000, () => undefined); + sock.bind(8000, "192.0.2.1"); + sock.bind(8000, "192.0.2.1", () => undefined); + sock.bind({}, () => undefined); + sock.bind({ port: 8000, address: "192.0.2.1", exclusive: true }); + sock.bind({ fd: 7, exclusive: true }); + sock.close(); + sock.close(() => undefined); + sock.connect(8000); + sock.connect(8000, "192.0.2.1"); + sock.connect(8000, () => undefined); + sock.connect(8000, "192.0.2.1", () => undefined); + sock.disconnect(); + sock.dropMembership("233.252.0.0"); + sock.dropMembership("233.252.0.0", "192.0.2.1"); + sock.getRecvBufferSize(); // $ExpectType number + sock.getSendBufferSize(); // $ExpectType number + sock = sock.ref(); + sock.remoteAddress().address; // $ExpectType string + sock.remoteAddress().family; // $ExpectType string + sock.remoteAddress().port; // $ExpectType number + sock.send("datagram"); + sock.send(new Uint8Array(256), 8000, (err) => { + err; // $ExpectType Error | null + }); + sock.send(Buffer.alloc(256), 8000, "192.0.2.1"); + sock.send(new Uint8Array(256), 128, 64); + sock.send("datagram", 128, 64, (err) => undefined); + sock.send(new Uint8Array(256), 128, 64, 8000); + sock.send(new Uint8Array(256), 128, 64, 8000, (err) => undefined); + sock.send(Buffer.alloc(256), 128, 64, 8000, "192.0.2.1"); + sock.send("datagram", 128, 64, 8000, "192.0.2.1", (err) => undefined); + sock.setBroadcast(true); + sock.setMulticastInterface("192.0.2.1"); + sock.setMulticastLoopback(false); + sock.setMulticastTTL(128); + sock.setRecvBufferSize(4096); + sock.setSendBufferSize(4096); + sock.setTTL(128); + sock = sock.unref(); + + sock.on("close", () => undefined); + sock.on("connect", () => undefined); + sock.on("error", (exception) => { + exception; // $ExpectType Error + }); + sock.on("listening", () => undefined); + sock.on("message", (msg, rinfo) => { + msg; // $ExpectType Buffer + rinfo.address; // $ExpectType string + rinfo.family; // $ExpectType "IPv4" | "IPv6" + rinfo.port; // $ExpectType number + rinfo.size; // $ExpectType number + }); +} + +//////////////////////////////////////////////////// +/// Node.js ESNEXT Support +//////////////////////////////////////////////////// + +{ + const s = 'foo'; + const s1: string = s.trimLeft(); + const s2: string = s.trimRight(); +} diff --git a/types/node/v12/ts3.2/tsconfig.json b/types/node/v12/ts3.1/tsconfig.json similarity index 100% rename from types/node/v12/ts3.2/tsconfig.json rename to types/node/v12/ts3.1/tsconfig.json diff --git a/types/node/v12/ts3.1/tslint.json b/types/node/v12/ts3.1/tslint.json new file mode 100644 index 0000000000..f1ded3562e --- /dev/null +++ b/types/node/v12/ts3.1/tslint.json @@ -0,0 +1,9 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "unified-signatures": false + } +} diff --git a/types/node/v12/util.d.ts b/types/node/v12/ts3.1/util.d.ts similarity index 100% rename from types/node/v12/util.d.ts rename to types/node/v12/ts3.1/util.d.ts diff --git a/types/node/v12/ts3.2/base.d.ts b/types/node/v12/ts3.3/base.d.ts similarity index 100% rename from types/node/v12/ts3.2/base.d.ts rename to types/node/v12/ts3.3/base.d.ts diff --git a/types/node/v12/ts3.2/fs.d.ts b/types/node/v12/ts3.3/fs.d.ts similarity index 100% rename from types/node/v12/ts3.2/fs.d.ts rename to types/node/v12/ts3.3/fs.d.ts diff --git a/types/node/v12/ts3.2/globals.d.ts b/types/node/v12/ts3.3/globals.d.ts similarity index 100% rename from types/node/v12/ts3.2/globals.d.ts rename to types/node/v12/ts3.3/globals.d.ts diff --git a/types/node/v12/ts3.2/index.d.ts b/types/node/v12/ts3.3/index.d.ts similarity index 100% rename from types/node/v12/ts3.2/index.d.ts rename to types/node/v12/ts3.3/index.d.ts diff --git a/types/node/v12/ts3.2/node-tests.ts b/types/node/v12/ts3.3/node-tests.ts similarity index 100% rename from types/node/v12/ts3.2/node-tests.ts rename to types/node/v12/ts3.3/node-tests.ts diff --git a/types/node/v12/ts3.7/tsconfig.json b/types/node/v12/ts3.3/tsconfig.json similarity index 100% rename from types/node/v12/ts3.7/tsconfig.json rename to types/node/v12/ts3.3/tsconfig.json diff --git a/types/node/v12/ts3.2/tslint.json b/types/node/v12/ts3.3/tslint.json similarity index 100% rename from types/node/v12/ts3.2/tslint.json rename to types/node/v12/ts3.3/tslint.json diff --git a/types/node/v12/ts3.2/util.d.ts b/types/node/v12/ts3.3/util.d.ts similarity index 100% rename from types/node/v12/ts3.2/util.d.ts rename to types/node/v12/ts3.3/util.d.ts diff --git a/types/node/v12/ts3.4/base.d.ts b/types/node/v12/ts3.6/base.d.ts similarity index 100% rename from types/node/v12/ts3.4/base.d.ts rename to types/node/v12/ts3.6/base.d.ts diff --git a/types/node/v12/ts3.4/globals.global.d.ts b/types/node/v12/ts3.6/globals.global.d.ts similarity index 100% rename from types/node/v12/ts3.4/globals.global.d.ts rename to types/node/v12/ts3.6/globals.global.d.ts diff --git a/types/node/v12/ts3.4/index.d.ts b/types/node/v12/ts3.6/index.d.ts similarity index 100% rename from types/node/v12/ts3.4/index.d.ts rename to types/node/v12/ts3.6/index.d.ts diff --git a/types/node/v12/ts3.4/node-tests.ts b/types/node/v12/ts3.6/node-tests.ts similarity index 100% rename from types/node/v12/ts3.4/node-tests.ts rename to types/node/v12/ts3.6/node-tests.ts diff --git a/types/node/v12/ts3.4/test/globals.ts b/types/node/v12/ts3.6/test/globals.ts similarity index 100% rename from types/node/v12/ts3.4/test/globals.ts rename to types/node/v12/ts3.6/test/globals.ts diff --git a/types/node/v12/ts3.4/tsconfig.json b/types/node/v12/ts3.6/tsconfig.json similarity index 100% rename from types/node/v12/ts3.4/tsconfig.json rename to types/node/v12/ts3.6/tsconfig.json diff --git a/types/node/v12/ts3.4/tslint.json b/types/node/v12/ts3.6/tslint.json similarity index 100% rename from types/node/v12/ts3.4/tslint.json rename to types/node/v12/ts3.6/tslint.json diff --git a/types/node/v12/ts3.7/base.d.ts b/types/node/v12/ts3.7/base.d.ts deleted file mode 100644 index 02556a1b59..0000000000 --- a/types/node/v12/ts3.7/base.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.7. - -// 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.7/base.d.ts - Definitions specific to TypeScript 3.7 -// - ~/ts3.7/index.d.ts - Definitions specific to TypeScript 3.7 with assert pulled in - -// 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.7-specific augmentations: -/// diff --git a/types/node/v12/ts3.7/index.d.ts b/types/node/v12/ts3.7/index.d.ts deleted file mode 100644 index 2cd553b853..0000000000 --- a/types/node/v12/ts3.7/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.7. -// This isn't strictly needed since 3.7 has the assert module, but this way we're consistent. -// Typically type modificatons should be made in base.d.ts instead of here - -/// diff --git a/types/node/v12/ts3.7/node-tests.ts b/types/node/v12/ts3.7/node-tests.ts deleted file mode 100644 index 983748c1fd..0000000000 --- a/types/node/v12/ts3.7/node-tests.ts +++ /dev/null @@ -1,59 +0,0 @@ -import * as assert from 'assert'; - -assert(true, "it's working"); - -assert.ok(true, 'inner functions work as well'); - -assert.throws(() => {}); -assert.throws(() => {}, /Regex test/); -assert.throws( - () => {}, - () => {}, - 'works wonderfully', -); - -assert['fail'](true, true, 'works like a charm'); - -{ - const a = null as any; - assert.ifError(a); - a; // $ExpectType null | undefined -} - -{ - const a = true as boolean; - assert(a); - a; // $ExpectType true -} - -{ - // tslint:disable-next-line: no-null-undefined-union - const a = 13 as number | null | undefined; - assert(a); - a; // $ExpectType number -} - -{ - const a = true as boolean; - assert.ok(a); - a; // $ExpectType true -} - -{ - // tslint:disable-next-line: no-null-undefined-union - const a = 13 as number | null | undefined; - assert.ok(a); - a; // $ExpectType number -} - -{ - const a = 'test' as any; - assert.strictEqual(a, 'test'); - a; // $ExpectType string -} - -{ - const a = { b: 2 } as any; - assert.deepStrictEqual(a, { b: 2 }); - a; // $ExpectType { b: number; } -} diff --git a/types/node/v12/ts3.7/tslint.json b/types/node/v12/ts3.7/tslint.json deleted file mode 100644 index 1a8ddd9863..0000000000 --- a/types/node/v12/ts3.7/tslint.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "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/v12/tslint.json b/types/node/v12/tslint.json index f1ded3562e..1a8ddd9863 100644 --- a/types/node/v12/tslint.json +++ b/types/node/v12/tslint.json @@ -1,9 +1,10 @@ { - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "no-empty-interface": false, - "no-single-declare-module": false, - "unified-signatures": false - } + "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/v13/assert.d.ts b/types/node/v13/assert.d.ts index 6a6f43dc55..9750dae7de 100644 --- a/types/node/v13/assert.d.ts +++ b/types/node/v13/assert.d.ts @@ -1,5 +1,5 @@ declare module "assert" { - function assert(value: any, message?: string | Error): void; + function assert(value: any, message?: string | Error): asserts value; namespace assert { class AssertionError implements Error { name: string; @@ -21,7 +21,7 @@ declare module "assert" { 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; + function ok(value: any, message?: string | Error): asserts value; /** @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. */ @@ -30,9 +30,9 @@ declare module "assert" { 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 strictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; function notStrictEqual(actual: any, expected: any, message?: string | Error): void; - function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; + function deepStrictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; function throws(block: () => any, message?: string | Error): void; @@ -40,7 +40,7 @@ declare module "assert" { function doesNotThrow(block: () => any, message?: string | Error): void; function doesNotThrow(block: () => any, error: RegExp | Function, message?: string | Error): void; - function ifError(value: any): void; + function ifError(value: any): asserts value is null | undefined; function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; function rejects(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; diff --git a/types/node/v13/base.d.ts b/types/node/v13/base.d.ts index f9bc0b3d91..201cd5678b 100644 --- a/types/node/v13/base.d.ts +++ b/types/node/v13/base.d.ts @@ -1,40 +1,20 @@ -// base definitions for all NodeJS modules that are not specific to any version of TypeScript -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +// NOTE: These definitions support NodeJS and TypeScript 3.7. + +// 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.7/base.d.ts - Definitions specific to TypeScript 3.7 +// - ~/ts3.7/index.d.ts - Definitions specific to TypeScript 3.7 with assert pulled in + +// 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.7-specific augmentations: +/// diff --git a/types/node/v13/index.d.ts b/types/node/v13/index.d.ts index d414bcafb3..2cd553b853 100644 --- a/types/node/v13/index.d.ts +++ b/types/node/v13/index.d.ts @@ -1,91 +1,5 @@ -// Type definitions for non-npm package Node.js 13.13 -// Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped -// Alberto Schiabel -// Alexander T. -// Alvis HT Tang -// Andrew Makarov -// Benjamin Toueg -// Bruno Scheufler -// Chigozirim C. -// Christian Vaagland Tellnes -// David Junger -// Deividas Bakanas -// Eugene Y. Q. Shen -// Flarna -// Hannes Magnusson -// Hoàng Văn Khải -// Huw -// Kelvin Jin -// Klaus Meinhardt -// Lishude -// Mariusz Wiktorczyk -// Mohsen Azimi -// Nicolas Even -// Nikita Galkin -// Parambir Singh -// Sebastian Silbermann -// Simon Schick -// Thomas den Hollander -// Wilco Bakker -// wwwy3y3 -// Samuel Ainsworth -// Kyle Uehlein -// Jordi Oliveras Rovira -// Thanik Bhongbhibhat -// Marcin Kopacz -// Trivikram Kamat -// Minh Son Nguyen -// Junxiao Shi -// Ilia Baryshnikov -// ExE Boss -// Surasak Chaisurin -// Piotr Błażejewicz -// Jason Kwok -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// NOTE: These definitions support NodeJS and TypeScript 3.7. +// This isn't strictly needed since 3.7 has the assert module, but this way we're consistent. +// Typically type modificatons should be made in base.d.ts instead of here -// NOTE: These definitions support NodeJS and TypeScript 3.5. - -// 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.8 -// - ~/ts3.5/index.d.ts - Definitions specific to TypeScript 3.5 - -// NOTE: Augmentations for TypeScript 3.5 and later should use individual files for overrides -// within the respective ~/ts3.5 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.5, so the older definitions will be found here. - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: /// - -// We can't include globals.global.d.ts in globals.d.ts, as it'll cause duplication errors in TypeScript 3.5+ -/// - -// We can't include assert.d.ts in base.d.ts, as it'll cause duplication errors in TypeScript 3.7+ -/// - -// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) -// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files -// just to ensure the names are known and node typings can be used without importing these libs. -// if someone really needs these types the libs need to be added via --lib or in tsconfig.json -interface AsyncIterable { } -interface IterableIterator { } -interface AsyncIterableIterator {} -interface SymbolConstructor { - readonly asyncIterator: symbol; -} -declare var Symbol: SymbolConstructor; -// even this is just a forward declaration some properties are added otherwise -// it would be allowed to pass anything to e.g. Buffer.from() -interface SharedArrayBuffer { - readonly byteLength: number; - slice(begin?: number, end?: number): SharedArrayBuffer; -} - -declare module "util" { - namespace types { - function isBigInt64Array(value: any): boolean; - function isBigUint64Array(value: any): boolean; - } -} diff --git a/types/node/v13/node-tests.ts b/types/node/v13/node-tests.ts index 559c7c62d6..983748c1fd 100644 --- a/types/node/v13/node-tests.ts +++ b/types/node/v13/node-tests.ts @@ -1,347 +1,59 @@ -import * as fs from "fs"; -import * as url from "url"; -import * as util from "util"; -import * as http from "http"; -import * as https from "https"; -import * as console2 from "console"; -import * as timers from "timers"; -import * as inspector from "inspector"; -import * as trace_events from "trace_events"; +import * as assert from 'assert'; -////////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html /// -////////////////////////////////////////////////////// +assert(true, "it's working"); + +assert.ok(true, 'inner functions work as well'); + +assert.throws(() => {}); +assert.throws(() => {}, /Regex test/); +assert.throws( + () => {}, + () => {}, + 'works wonderfully', +); + +assert['fail'](true, true, 'works like a charm'); { - 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 = []; - - { - function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} - - class MyIncomingMessage extends http.IncomingMessage { - foo: number; - } - - class MyServerResponse extends http.ServerResponse { - foo: string; - } - - let server: https.Server; - - server = new https.Server(); - server = new https.Server(reqListener); - server = new https.Server({ IncomingMessage: MyIncomingMessage}); - - server = new https.Server({ - IncomingMessage: MyIncomingMessage, - ServerResponse: MyServerResponse - }, reqListener); - - server = https.createServer(); - server = https.createServer(reqListener); - server = https.createServer({ IncomingMessage: MyIncomingMessage }); - server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); - - const timeout: number = server.timeout; - const listening: boolean = server.listening; - const keepAliveTimeout: number = server.keepAliveTimeout; - const maxHeadersCount: number | null = server.maxHeadersCount; - const headersTimeout: number = server.headersTimeout; - server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); - } + const a = null as any; + assert.ifError(a); + a; // $ExpectType null | undefined } -///////////////////////////////////////////////////// -/// Timers tests : https://nodejs.org/api/timers.html -///////////////////////////////////////////////////// - { - { - const immediate = timers - .setImmediate(() => { - console.log('immediate'); - }) - .unref() - .ref(); - const b: boolean = immediate.hasRef(); - timers.clearImmediate(immediate); - } - { - const timeout = timers - .setInterval(() => { - console.log('interval'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - timers.clearInterval(timeout); - } - { - const timeout = timers - .setTimeout(() => { - console.log('timeout'); - }, 20) - .unref() - .ref() - .refresh(); - const b: boolean = timeout.hasRef(); - timers.clearTimeout(timeout); - } - async function testPromisify(doSomething: { - (foo: any, onSuccessCallback: (result: string) => void, onErrorCallback: (reason: any) => void): void; - [util.promisify.custom](foo: any): Promise; - }) { - 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(""); - - // $ExpectType (foo: any) => Promise - const doSomethingPromise = util.promisify(doSomething); - - // $ExpectType string - s = await doSomethingPromise('foo'); - } + const a = true as boolean; + assert(a); + a; // $ExpectType true } -///////////////////////////////////////////////////////// -/// 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 | 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(); - const isConstr: boolean = frame.isConstructor(); - } + // tslint:disable-next-line: no-null-undefined-union + const a = 13 as number | null | undefined; + assert(a); + a; // $ExpectType number } -/////////////////////////////////////////////////////////// -/// 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.profile(); - console.profile('label'); - console.profileEnd(); - console.profileEnd('label'); - console.timeStamp(); - console.timeStamp('label'); - } + const a = true as boolean; + assert.ok(a); + a; // $ExpectType true } -/***************************************************************************** - * * - * The following tests are the modules not mentioned in document but existed * - * * - *****************************************************************************/ - -/////////////////////////////////////////////////////////// -/// 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 | undefined = 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 | 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!; - }); - 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; - }); - } + // tslint:disable-next-line: no-null-undefined-union + const a = 13 as number | null | undefined; + assert.ok(a); + a; // $ExpectType number } -/////////////////////////////////////////////////////////// -/// Trace Events Tests /// -/////////////////////////////////////////////////////////// - { - const enabledCategories: string | undefined = 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(); + const a = 'test' as any; + assert.strictEqual(a, 'test'); + a; // $ExpectType string } -//////////////////////////////////////////////////// -/// Node.js ESNEXT Support -//////////////////////////////////////////////////// - { - const s = 'foo'; - const s1: string = s.trimLeft(); - const s2: string = s.trimRight(); + const a = { b: 2 } as any; + assert.deepStrictEqual(a, { b: 2 }); + a; // $ExpectType { b: number; } } diff --git a/types/node/v13/package.json b/types/node/v13/package.json index f791e46a8a..dd84e4f705 100644 --- a/types/node/v13/package.json +++ b/types/node/v13/package.json @@ -2,19 +2,19 @@ "private": true, "types": "index", "typesVersions": { - ">=3.7.0-0": { + "<=3.1": { "*": [ - "ts3.7/*" + "ts3.1/*" ] }, - ">=3.5.0-0": { + "<=3.4": { "*": [ - "ts3.5/*" + "ts3.4/*" ] }, - ">=3.2.0-0": { + "<=3.6": { "*": [ - "ts3.2/*" + "ts3.6/*" ] } } diff --git a/types/node/ts3.7/assert.d.ts b/types/node/v13/ts3.1/assert.d.ts similarity index 86% rename from types/node/ts3.7/assert.d.ts rename to types/node/v13/ts3.1/assert.d.ts index 9750dae7de..6a6f43dc55 100644 --- a/types/node/ts3.7/assert.d.ts +++ b/types/node/v13/ts3.1/assert.d.ts @@ -1,5 +1,5 @@ declare module "assert" { - function assert(value: any, message?: string | Error): asserts value; + function assert(value: any, message?: string | Error): void; namespace assert { class AssertionError implements Error { name: string; @@ -21,7 +21,7 @@ declare module "assert" { 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): asserts value; + 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. */ @@ -30,9 +30,9 @@ declare module "assert" { 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: T, message?: string | Error): asserts actual is T; + 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: T, message?: string | Error): asserts actual is T; + function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; function throws(block: () => any, message?: string | Error): void; @@ -40,7 +40,7 @@ declare module "assert" { function doesNotThrow(block: () => any, message?: string | Error): void; function doesNotThrow(block: () => any, error: RegExp | Function, message?: string | Error): void; - function ifError(value: any): asserts value is null | undefined; + function ifError(value: any): void; function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; function rejects(block: (() => Promise) | Promise, error: AssertPredicate, message?: string | Error): Promise; diff --git a/types/node/v13/ts3.1/base.d.ts b/types/node/v13/ts3.1/base.d.ts new file mode 100644 index 0000000000..f9bc0b3d91 --- /dev/null +++ b/types/node/v13/ts3.1/base.d.ts @@ -0,0 +1,40 @@ +// base definitions for all NodeJS modules that are not specific to any version of TypeScript +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/types/node/v13/fs.d.ts b/types/node/v13/ts3.1/fs.d.ts similarity index 100% rename from types/node/v13/fs.d.ts rename to types/node/v13/ts3.1/fs.d.ts diff --git a/types/node/v13/globals.d.ts b/types/node/v13/ts3.1/globals.d.ts similarity index 100% rename from types/node/v13/globals.d.ts rename to types/node/v13/ts3.1/globals.d.ts diff --git a/types/node/v13/globals.global.d.ts b/types/node/v13/ts3.1/globals.global.d.ts similarity index 100% rename from types/node/v13/globals.global.d.ts rename to types/node/v13/ts3.1/globals.global.d.ts diff --git a/types/node/v13/ts3.1/index.d.ts b/types/node/v13/ts3.1/index.d.ts new file mode 100644 index 0000000000..d414bcafb3 --- /dev/null +++ b/types/node/v13/ts3.1/index.d.ts @@ -0,0 +1,91 @@ +// Type definitions for non-npm package Node.js 13.13 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +// Alexander T. +// Alvis HT Tang +// Andrew Makarov +// Benjamin Toueg +// Bruno Scheufler +// Chigozirim C. +// Christian Vaagland Tellnes +// David Junger +// Deividas Bakanas +// Eugene Y. Q. Shen +// Flarna +// Hannes Magnusson +// Hoàng Văn Khải +// Huw +// Kelvin Jin +// Klaus Meinhardt +// Lishude +// Mariusz Wiktorczyk +// Mohsen Azimi +// Nicolas Even +// Nikita Galkin +// Parambir Singh +// Sebastian Silbermann +// Simon Schick +// Thomas den Hollander +// Wilco Bakker +// wwwy3y3 +// Samuel Ainsworth +// Kyle Uehlein +// Jordi Oliveras Rovira +// Thanik Bhongbhibhat +// Marcin Kopacz +// Trivikram Kamat +// Minh Son Nguyen +// Junxiao Shi +// Ilia Baryshnikov +// ExE Boss +// Surasak Chaisurin +// Piotr Błażejewicz +// Jason Kwok +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// NOTE: These definitions support NodeJS and TypeScript 3.5. + +// 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.8 +// - ~/ts3.5/index.d.ts - Definitions specific to TypeScript 3.5 + +// NOTE: Augmentations for TypeScript 3.5 and later should use individual files for overrides +// within the respective ~/ts3.5 (or later) folder. However, this is disallowed for versions +// prior to TypeScript 3.5, so the older definitions will be found here. + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// + +// We can't include globals.global.d.ts in globals.d.ts, as it'll cause duplication errors in TypeScript 3.5+ +/// + +// We can't include assert.d.ts in base.d.ts, as it'll cause duplication errors in TypeScript 3.7+ +/// + +// Forward-declarations for needed types from es2015 and later (in case users are using `--lib es5`) +// Empty interfaces are used here which merge fine with the real declarations in the lib XXX files +// just to ensure the names are known and node typings can be used without importing these libs. +// if someone really needs these types the libs need to be added via --lib or in tsconfig.json +interface AsyncIterable { } +interface IterableIterator { } +interface AsyncIterableIterator {} +interface SymbolConstructor { + readonly asyncIterator: symbol; +} +declare var Symbol: SymbolConstructor; +// even this is just a forward declaration some properties are added otherwise +// it would be allowed to pass anything to e.g. Buffer.from() +interface SharedArrayBuffer { + readonly byteLength: number; + slice(begin?: number, end?: number): SharedArrayBuffer; +} + +declare module "util" { + namespace types { + function isBigInt64Array(value: any): boolean; + function isBigUint64Array(value: any): boolean; + } +} diff --git a/types/node/v13/ts3.1/node-tests.ts b/types/node/v13/ts3.1/node-tests.ts new file mode 100644 index 0000000000..559c7c62d6 --- /dev/null +++ b/types/node/v13/ts3.1/node-tests.ts @@ -0,0 +1,347 @@ +import * as fs from "fs"; +import * as url from "url"; +import * as util from "util"; +import * as http from "http"; +import * as https from "https"; +import * as console2 from "console"; +import * as timers from "timers"; +import * as inspector from "inspector"; +import * as trace_events from "trace_events"; + +////////////////////////////////////////////////////// +/// 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 = []; + + { + function reqListener(req: http.IncomingMessage, res: http.ServerResponse): void {} + + class MyIncomingMessage extends http.IncomingMessage { + foo: number; + } + + class MyServerResponse extends http.ServerResponse { + foo: string; + } + + let server: https.Server; + + server = new https.Server(); + server = new https.Server(reqListener); + server = new https.Server({ IncomingMessage: MyIncomingMessage}); + + server = new https.Server({ + IncomingMessage: MyIncomingMessage, + ServerResponse: MyServerResponse + }, reqListener); + + server = https.createServer(); + server = https.createServer(reqListener); + server = https.createServer({ IncomingMessage: MyIncomingMessage }); + server = https.createServer({ ServerResponse: MyServerResponse }, reqListener); + + const timeout: number = server.timeout; + const listening: boolean = server.listening; + const keepAliveTimeout: number = server.keepAliveTimeout; + const maxHeadersCount: number | null = server.maxHeadersCount; + const headersTimeout: number = server.headersTimeout; + server.setTimeout().setTimeout(1000).setTimeout(() => {}).setTimeout(100, () => {}); + } +} + +///////////////////////////////////////////////////// +/// Timers tests : https://nodejs.org/api/timers.html +///////////////////////////////////////////////////// + +{ + { + const immediate = timers + .setImmediate(() => { + console.log('immediate'); + }) + .unref() + .ref(); + const b: boolean = immediate.hasRef(); + timers.clearImmediate(immediate); + } + { + const timeout = timers + .setInterval(() => { + console.log('interval'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + timers.clearInterval(timeout); + } + { + const timeout = timers + .setTimeout(() => { + console.log('timeout'); + }, 20) + .unref() + .ref() + .refresh(); + const b: boolean = timeout.hasRef(); + timers.clearTimeout(timeout); + } + async function testPromisify(doSomething: { + (foo: any, onSuccessCallback: (result: string) => void, onErrorCallback: (reason: any) => void): void; + [util.promisify.custom](foo: any): Promise; + }) { + 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(""); + + // $ExpectType (foo: any) => Promise + const doSomethingPromise = util.promisify(doSomething); + + // $ExpectType string + s = await doSomethingPromise('foo'); + } +} + +///////////////////////////////////////////////////////// +/// 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 | 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(); + const isConstr: boolean = frame.isConstructor(); + } +} + +/////////////////////////////////////////////////////////// +/// 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.profile(); + console.profile('label'); + console.profileEnd(); + console.profileEnd('label'); + console.timeStamp(); + console.timeStamp('label'); + } +} + +/***************************************************************************** + * * + * The following tests are the modules not mentioned in document but existed * + * * + *****************************************************************************/ + +/////////////////////////////////////////////////////////// +/// 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 | undefined = 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 | 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!; + }); + 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 | undefined = 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(); +} + +//////////////////////////////////////////////////// +/// Node.js ESNEXT Support +//////////////////////////////////////////////////// + +{ + const s = 'foo'; + const s1: string = s.trimLeft(); + const s2: string = s.trimRight(); +} diff --git a/types/node/v13/ts3.2/tsconfig.json b/types/node/v13/ts3.1/tsconfig.json similarity index 100% rename from types/node/v13/ts3.2/tsconfig.json rename to types/node/v13/ts3.1/tsconfig.json diff --git a/types/node/v13/ts3.1/tslint.json b/types/node/v13/ts3.1/tslint.json new file mode 100644 index 0000000000..464f610b93 --- /dev/null +++ b/types/node/v13/ts3.1/tslint.json @@ -0,0 +1,10 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "no-empty-interface": false, + "no-single-declare-module": false, + "no-unnecessary-class": false, + "unified-signatures": false + } +} diff --git a/types/node/v13/util.d.ts b/types/node/v13/ts3.1/util.d.ts similarity index 100% rename from types/node/v13/util.d.ts rename to types/node/v13/ts3.1/util.d.ts diff --git a/types/node/v13/ts3.2/tslint.json b/types/node/v13/ts3.2/tslint.json deleted file mode 100644 index 1a8ddd9863..0000000000 --- a/types/node/v13/ts3.2/tslint.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "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/v13/ts3.2/base.d.ts b/types/node/v13/ts3.4/base.d.ts similarity index 100% rename from types/node/v13/ts3.2/base.d.ts rename to types/node/v13/ts3.4/base.d.ts diff --git a/types/node/v13/ts3.2/fs.d.ts b/types/node/v13/ts3.4/fs.d.ts similarity index 100% rename from types/node/v13/ts3.2/fs.d.ts rename to types/node/v13/ts3.4/fs.d.ts diff --git a/types/node/v13/ts3.2/globals.d.ts b/types/node/v13/ts3.4/globals.d.ts similarity index 100% rename from types/node/v13/ts3.2/globals.d.ts rename to types/node/v13/ts3.4/globals.d.ts diff --git a/types/node/v13/ts3.2/index.d.ts b/types/node/v13/ts3.4/index.d.ts similarity index 100% rename from types/node/v13/ts3.2/index.d.ts rename to types/node/v13/ts3.4/index.d.ts diff --git a/types/node/v13/ts3.2/node-tests.ts b/types/node/v13/ts3.4/node-tests.ts similarity index 100% rename from types/node/v13/ts3.2/node-tests.ts rename to types/node/v13/ts3.4/node-tests.ts diff --git a/types/node/v13/ts3.7/tsconfig.json b/types/node/v13/ts3.4/tsconfig.json similarity index 100% rename from types/node/v13/ts3.7/tsconfig.json rename to types/node/v13/ts3.4/tsconfig.json diff --git a/types/node/ts3.7/tslint.json b/types/node/v13/ts3.4/tslint.json similarity index 100% rename from types/node/ts3.7/tslint.json rename to types/node/v13/ts3.4/tslint.json diff --git a/types/node/v13/ts3.2/util.d.ts b/types/node/v13/ts3.4/util.d.ts similarity index 100% rename from types/node/v13/ts3.2/util.d.ts rename to types/node/v13/ts3.4/util.d.ts diff --git a/types/node/v13/ts3.5/base.d.ts b/types/node/v13/ts3.6/base.d.ts similarity index 100% rename from types/node/v13/ts3.5/base.d.ts rename to types/node/v13/ts3.6/base.d.ts diff --git a/types/node/v13/ts3.5/globals.global.d.ts b/types/node/v13/ts3.6/globals.global.d.ts similarity index 100% rename from types/node/v13/ts3.5/globals.global.d.ts rename to types/node/v13/ts3.6/globals.global.d.ts diff --git a/types/node/v13/ts3.5/index.d.ts b/types/node/v13/ts3.6/index.d.ts similarity index 100% rename from types/node/v13/ts3.5/index.d.ts rename to types/node/v13/ts3.6/index.d.ts diff --git a/types/node/v13/ts3.5/node-tests.ts b/types/node/v13/ts3.6/node-tests.ts similarity index 100% rename from types/node/v13/ts3.5/node-tests.ts rename to types/node/v13/ts3.6/node-tests.ts diff --git a/types/node/v13/ts3.5/test/globals.ts b/types/node/v13/ts3.6/test/globals.ts similarity index 100% rename from types/node/v13/ts3.5/test/globals.ts rename to types/node/v13/ts3.6/test/globals.ts diff --git a/types/node/v13/ts3.5/tsconfig.json b/types/node/v13/ts3.6/tsconfig.json similarity index 100% rename from types/node/v13/ts3.5/tsconfig.json rename to types/node/v13/ts3.6/tsconfig.json diff --git a/types/node/v13/ts3.5/tslint.json b/types/node/v13/ts3.6/tslint.json similarity index 100% rename from types/node/v13/ts3.5/tslint.json rename to types/node/v13/ts3.6/tslint.json diff --git a/types/node/v13/ts3.5/wasi.d.ts b/types/node/v13/ts3.6/wasi.d.ts similarity index 100% rename from types/node/v13/ts3.5/wasi.d.ts rename to types/node/v13/ts3.6/wasi.d.ts diff --git a/types/node/v13/ts3.7/base.d.ts b/types/node/v13/ts3.7/base.d.ts deleted file mode 100644 index 201cd5678b..0000000000 --- a/types/node/v13/ts3.7/base.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.7. - -// 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.7/base.d.ts - Definitions specific to TypeScript 3.7 -// - ~/ts3.7/index.d.ts - Definitions specific to TypeScript 3.7 with assert pulled in - -// 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.7-specific augmentations: -/// diff --git a/types/node/v13/ts3.7/index.d.ts b/types/node/v13/ts3.7/index.d.ts deleted file mode 100644 index 2cd553b853..0000000000 --- a/types/node/v13/ts3.7/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.7. -// This isn't strictly needed since 3.7 has the assert module, but this way we're consistent. -// Typically type modificatons should be made in base.d.ts instead of here - -/// diff --git a/types/node/v13/ts3.7/node-tests.ts b/types/node/v13/ts3.7/node-tests.ts deleted file mode 100644 index 983748c1fd..0000000000 --- a/types/node/v13/ts3.7/node-tests.ts +++ /dev/null @@ -1,59 +0,0 @@ -import * as assert from 'assert'; - -assert(true, "it's working"); - -assert.ok(true, 'inner functions work as well'); - -assert.throws(() => {}); -assert.throws(() => {}, /Regex test/); -assert.throws( - () => {}, - () => {}, - 'works wonderfully', -); - -assert['fail'](true, true, 'works like a charm'); - -{ - const a = null as any; - assert.ifError(a); - a; // $ExpectType null | undefined -} - -{ - const a = true as boolean; - assert(a); - a; // $ExpectType true -} - -{ - // tslint:disable-next-line: no-null-undefined-union - const a = 13 as number | null | undefined; - assert(a); - a; // $ExpectType number -} - -{ - const a = true as boolean; - assert.ok(a); - a; // $ExpectType true -} - -{ - // tslint:disable-next-line: no-null-undefined-union - const a = 13 as number | null | undefined; - assert.ok(a); - a; // $ExpectType number -} - -{ - const a = 'test' as any; - assert.strictEqual(a, 'test'); - a; // $ExpectType string -} - -{ - const a = { b: 2 } as any; - assert.deepStrictEqual(a, { b: 2 }); - a; // $ExpectType { b: number; } -} diff --git a/types/node/v13/ts3.7/tslint.json b/types/node/v13/ts3.7/tslint.json deleted file mode 100644 index 1a8ddd9863..0000000000 --- a/types/node/v13/ts3.7/tslint.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "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/v13/tslint.json b/types/node/v13/tslint.json index 464f610b93..1a8ddd9863 100644 --- a/types/node/v13/tslint.json +++ b/types/node/v13/tslint.json @@ -1,10 +1,10 @@ { - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "no-empty-interface": false, - "no-single-declare-module": false, - "no-unnecessary-class": false, - "unified-signatures": false - } + "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/v6/index.d.ts b/types/node/v6/index.d.ts index 5b4d19c087..de94dab76a 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -1,48 +1,15 @@ -// Type definitions for Node.js 6.14 -// Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped -// Wilco Bakker -// Thomas Bouldin -// Sebastian Silbermann -// Alorel -// Hoàng Văn Khải -// Sander Koenders -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/************************************************ -* * -* Node.js v6.x API * -* * -************************************************/ -// NOTE: These definitions support NodeJS and TypeScript 3.1. +// NOTE: These definitions support NodeJS and TypeScript 3.2. // 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 +// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2 -// 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. +// 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 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 Iterable { } -interface Iterator { - next(value?: any): IteratorResult; -} -interface IterableIterator { } -interface IteratorResult { } -interface AsyncIterableIterator {} -interface SymbolConstructor { - readonly iterator: symbol; -} -declare var Symbol: SymbolConstructor; +// TypeScript 3.2-specific augmentations: diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index 5ca32d660c..7c3dca38f0 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -1,3 +1,25 @@ +// NOTE: Disabled to preserve existing tests file +// tslint:disable:array-type +// tslint:disable:comment-format +// tslint:disable:import-spacing +// tslint:disable:interface-over-type-literal +// tslint:disable:jsdoc-format +// tslint:disable:max-line-length +// tslint:disable:no-consecutive-blank-lines +// tslint:disable:no-duplicate-imports +// tslint:disable:no-duplicate-variable +// tslint:disable:no-inferrable-types +// tslint:disable:no-namespace +// tslint:disable:no-padding +// tslint:disable:no-string-throw +// tslint:disable:no-var-keyword +// tslint:disable:object-literal-shorthand +// tslint:disable:one-line +// tslint:disable:only-arrow-functions +// tslint:disable:prefer-const +// tslint:disable:semicolon +// tslint:disable:typedef-whitespace +// tslint:disable:whitespace import assert = require("assert"); import * as fs from "fs"; import * as events from "events"; diff --git a/types/node/v6/package.json b/types/node/v6/package.json index cda6cc6dc8..54d5b8743e 100644 --- a/types/node/v6/package.json +++ b/types/node/v6/package.json @@ -2,9 +2,9 @@ "private": true, "types": "index", "typesVersions": { - ">=3.2.0-0": { + "<=3.1": { "*": [ - "ts3.2/*" + "ts3.1/*" ] } } diff --git a/types/node/v6/ts3.1/index.d.ts b/types/node/v6/ts3.1/index.d.ts new file mode 100644 index 0000000000..5b4d19c087 --- /dev/null +++ b/types/node/v6/ts3.1/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for Node.js 6.14 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Wilco Bakker +// Thomas Bouldin +// Sebastian Silbermann +// Alorel +// Hoàng Văn Khải +// Sander Koenders +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/************************************************ +* * +* Node.js v6.x API * +* * +************************************************/ +// 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 Iterable { } +interface Iterator { + next(value?: any): IteratorResult; +} +interface IterableIterator { } +interface IteratorResult { } +interface AsyncIterableIterator {} +interface SymbolConstructor { + readonly iterator: symbol; +} +declare var Symbol: SymbolConstructor; diff --git a/types/node/v6/ts3.2/node-tests.ts b/types/node/v6/ts3.1/node-tests.ts similarity index 99% rename from types/node/v6/ts3.2/node-tests.ts rename to types/node/v6/ts3.1/node-tests.ts index 7c3dca38f0..5ca32d660c 100644 --- a/types/node/v6/ts3.2/node-tests.ts +++ b/types/node/v6/ts3.1/node-tests.ts @@ -1,25 +1,3 @@ -// NOTE: Disabled to preserve existing tests file -// tslint:disable:array-type -// tslint:disable:comment-format -// tslint:disable:import-spacing -// tslint:disable:interface-over-type-literal -// tslint:disable:jsdoc-format -// tslint:disable:max-line-length -// tslint:disable:no-consecutive-blank-lines -// tslint:disable:no-duplicate-imports -// tslint:disable:no-duplicate-variable -// tslint:disable:no-inferrable-types -// tslint:disable:no-namespace -// tslint:disable:no-padding -// tslint:disable:no-string-throw -// tslint:disable:no-var-keyword -// tslint:disable:object-literal-shorthand -// tslint:disable:one-line -// tslint:disable:only-arrow-functions -// tslint:disable:prefer-const -// tslint:disable:semicolon -// tslint:disable:typedef-whitespace -// tslint:disable:whitespace import assert = require("assert"); import * as fs from "fs"; import * as events from "events"; diff --git a/types/node/v6/ts3.2/tsconfig.json b/types/node/v6/ts3.1/tsconfig.json similarity index 100% rename from types/node/v6/ts3.2/tsconfig.json rename to types/node/v6/ts3.1/tsconfig.json diff --git a/types/node/v6/ts3.1/tslint.json b/types/node/v6/ts3.1/tslint.json new file mode 100644 index 0000000000..f862895f2b --- /dev/null +++ b/types/node/v6/ts3.1/tslint.json @@ -0,0 +1,40 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "align": false, + "array-type": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "import-spacing": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "no-consecutive-blank-lines": false, + "no-const-enum": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-namespace": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-string-throw": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-var-keyword": false, + "object-literal-shorthand": false, + "one-line": false, + "only-arrow-functions": false, + "prefer-const": false, + "prefer-method-signature": false, + "semicolon": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "typedef-whitespace": false, + "unified-signatures": false, + "whitespace": false + } +} diff --git a/types/node/v6/ts3.2/index.d.ts b/types/node/v6/ts3.2/index.d.ts deleted file mode 100644 index de94dab76a..0000000000 --- a/types/node/v6/ts3.2/index.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.2. - -// 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.2/index.d.ts - Definitions specific to TypeScript 3.2 - -// 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.2-specific augmentations: diff --git a/types/node/v6/ts3.2/tslint.json b/types/node/v6/ts3.2/tslint.json deleted file mode 100644 index a62d0d4e68..0000000000 --- a/types/node/v6/ts3.2/tslint.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false - } -} diff --git a/types/node/v6/tslint.json b/types/node/v6/tslint.json index f862895f2b..a62d0d4e68 100644 --- a/types/node/v6/tslint.json +++ b/types/node/v6/tslint.json @@ -1,40 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "align": false, - "array-type": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "import-spacing": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "no-consecutive-blank-lines": false, - "no-const-enum": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-namespace": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-string-throw": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-var-keyword": false, - "object-literal-shorthand": false, - "one-line": false, - "only-arrow-functions": false, - "prefer-const": false, - "prefer-method-signature": false, - "semicolon": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "typedef-whitespace": false, - "unified-signatures": false, - "whitespace": false + "ban-types": false } } diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index 559d3cf696..154ea68bed 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -1,47 +1,15 @@ -// Type definitions for Node.js 7.10 -// Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped -// Parambir Singh -// Wilco Bakker -// Sebastian Silbermann -// Hoàng Văn Khải -// Sander Koenders -// Jordi Oliveras Rovira -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/************************************************ -* * -* Node.js v7.x API * -* * -************************************************/ -// NOTE: These definitions support NodeJS and TypeScript 3.1. +// NOTE: These definitions support NodeJS and TypeScript 3.2. // 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 +// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2 -// 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. +// 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 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 IteratorResult {} -interface Iterable {} -interface Iterator { - next(value?: any): IteratorResult; -} -interface IterableIterator { } -interface SymbolConstructor { - readonly iterator: symbol; -} -declare var Symbol: SymbolConstructor; +// TypeScript 3.2-specific augmentations: diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index 81c33d9658..987f394275 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -1,3 +1,25 @@ +// NOTE: Disabled to preserve existing tests file +// tslint:disable:array-type +// tslint:disable:comment-format +// tslint:disable:import-spacing +// tslint:disable:interface-over-type-literal +// tslint:disable:jsdoc-format +// tslint:disable:max-line-length +// tslint:disable:no-consecutive-blank-lines +// tslint:disable:no-duplicate-imports +// tslint:disable:no-duplicate-variable +// tslint:disable:no-inferrable-types +// tslint:disable:no-namespace +// tslint:disable:no-padding +// tslint:disable:no-string-throw +// tslint:disable:no-var-keyword +// tslint:disable:object-literal-shorthand +// tslint:disable:one-line +// tslint:disable:only-arrow-functions +// tslint:disable:prefer-const +// tslint:disable:semicolon +// tslint:disable:typedef-whitespace +// tslint:disable:whitespace import assert = require("assert"); import * as fs from "fs"; import * as events from "events"; diff --git a/types/node/v7/package.json b/types/node/v7/package.json index cda6cc6dc8..54d5b8743e 100644 --- a/types/node/v7/package.json +++ b/types/node/v7/package.json @@ -2,9 +2,9 @@ "private": true, "types": "index", "typesVersions": { - ">=3.2.0-0": { + "<=3.1": { "*": [ - "ts3.2/*" + "ts3.1/*" ] } } diff --git a/types/node/v7/ts3.1/index.d.ts b/types/node/v7/ts3.1/index.d.ts new file mode 100644 index 0000000000..559d3cf696 --- /dev/null +++ b/types/node/v7/ts3.1/index.d.ts @@ -0,0 +1,47 @@ +// Type definitions for Node.js 7.10 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Parambir Singh +// Wilco Bakker +// Sebastian Silbermann +// Hoàng Văn Khải +// Sander Koenders +// Jordi Oliveras Rovira +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/************************************************ +* * +* Node.js v7.x API * +* * +************************************************/ +// 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 IteratorResult {} +interface Iterable {} +interface Iterator { + next(value?: any): IteratorResult; +} +interface IterableIterator { } +interface SymbolConstructor { + readonly iterator: symbol; +} +declare var Symbol: SymbolConstructor; diff --git a/types/node/v7/ts3.2/node-tests.ts b/types/node/v7/ts3.1/node-tests.ts similarity index 99% rename from types/node/v7/ts3.2/node-tests.ts rename to types/node/v7/ts3.1/node-tests.ts index 987f394275..81c33d9658 100644 --- a/types/node/v7/ts3.2/node-tests.ts +++ b/types/node/v7/ts3.1/node-tests.ts @@ -1,25 +1,3 @@ -// NOTE: Disabled to preserve existing tests file -// tslint:disable:array-type -// tslint:disable:comment-format -// tslint:disable:import-spacing -// tslint:disable:interface-over-type-literal -// tslint:disable:jsdoc-format -// tslint:disable:max-line-length -// tslint:disable:no-consecutive-blank-lines -// tslint:disable:no-duplicate-imports -// tslint:disable:no-duplicate-variable -// tslint:disable:no-inferrable-types -// tslint:disable:no-namespace -// tslint:disable:no-padding -// tslint:disable:no-string-throw -// tslint:disable:no-var-keyword -// tslint:disable:object-literal-shorthand -// tslint:disable:one-line -// tslint:disable:only-arrow-functions -// tslint:disable:prefer-const -// tslint:disable:semicolon -// tslint:disable:typedef-whitespace -// tslint:disable:whitespace import assert = require("assert"); import * as fs from "fs"; import * as events from "events"; diff --git a/types/node/v7/ts3.2/tsconfig.json b/types/node/v7/ts3.1/tsconfig.json similarity index 100% rename from types/node/v7/ts3.2/tsconfig.json rename to types/node/v7/ts3.1/tsconfig.json diff --git a/types/node/v7/ts3.1/tslint.json b/types/node/v7/ts3.1/tslint.json new file mode 100644 index 0000000000..bfeeefc3d6 --- /dev/null +++ b/types/node/v7/ts3.1/tslint.json @@ -0,0 +1,40 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "align": false, + "array-type": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "import-spacing": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "no-consecutive-blank-lines": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-namespace": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-string-throw": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-var-keyword": false, + "object-literal-shorthand": false, + "one-line": false, + "only-arrow-functions": false, + "prefer-const": false, + "prefer-method-signature": false, + "semicolon": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "typedef-whitespace": false, + "unified-signatures": false, + "whitespace": false + } +} diff --git a/types/node/v7/ts3.2/index.d.ts b/types/node/v7/ts3.2/index.d.ts deleted file mode 100644 index 154ea68bed..0000000000 --- a/types/node/v7/ts3.2/index.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.2. - -// 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.2/index.d.ts - Definitions specific to TypeScript 3.2 - -// 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.2-specific augmentations: diff --git a/types/node/v7/ts3.2/tslint.json b/types/node/v7/ts3.2/tslint.json deleted file mode 100644 index a62d0d4e68..0000000000 --- a/types/node/v7/ts3.2/tslint.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false - } -} diff --git a/types/node/v7/tslint.json b/types/node/v7/tslint.json index bfeeefc3d6..a62d0d4e68 100644 --- a/types/node/v7/tslint.json +++ b/types/node/v7/tslint.json @@ -1,40 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "align": false, - "array-type": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "import-spacing": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "no-consecutive-blank-lines": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-namespace": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-string-throw": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-var-keyword": false, - "object-literal-shorthand": false, - "one-line": false, - "only-arrow-functions": false, - "prefer-const": false, - "prefer-method-signature": false, - "semicolon": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "typedef-whitespace": false, - "unified-signatures": false, - "whitespace": false + "ban-types": false } } diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index 4cfb6812b4..c354b5c0b3 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -1,67 +1,23 @@ -// Type definitions for Node.js 8.10 -// Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped -// Parambir Singh -// Wilco Bakker -// Chigozirim C. -// Flarna -// Mariusz Wiktorczyk -// wwwy3y3 -// Deividas Bakanas -// Kelvin Jin -// Alvis HT Tang -// Sebastian Silbermann -// Hannes Magnusson -// Alberto Schiabel -// Huw -// Nicolas Even -// Nikita Galkin -// Bruno Scheufler -// Hoàng Văn Khải -// Lishude -// Andrew Makarov -// Jordi Oliveras Rovira -// Thanik Bhongbhibhat -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 -// NOTE: These definitions support NodeJS and TypeScript 3.1. +// NOTE: These definitions support NodeJS and TypeScript 3.2. // 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 +// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2 -// 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. +// Reference required types from the default lib: +/// // 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 IteratorResult { } -interface Iterable { } -interface Iterator { - next(value?: any): IteratorResult; -} -interface IterableIterator { } -interface SymbolConstructor { - readonly iterator: symbol; -} -declare var Symbol: SymbolConstructor; +// tslint:disable-next-line:no-bad-reference +/// +// TypeScript 3.2-specific augmentations: declare module "util" { namespace inspect { - const custom: symbol; + const custom: unique symbol; } namespace promisify { - const custom: symbol; + const custom: unique symbol; } } diff --git a/types/node/v8/node-tests.ts b/types/node/v8/node-tests.ts index 95162307b5..191469bb65 100644 --- a/types/node/v8/node-tests.ts +++ b/types/node/v8/node-tests.ts @@ -2108,37 +2108,6 @@ namespace child_process_tests { childProcess.execFile("npm", { encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); } - { - const forked = childProcess.fork('./', ['asd'], { - windowsVerbatimArguments: true, - silent: false, - stdio: ["inherit"], - execPath: '', - execArgv: ['asda'] - }); - const exitCode: number | null = forked.exitCode; - const signalCode: number | null = forked.signalCode; - const ipc: stream.Pipe = forked.channel; - const hasRef: boolean = ipc.hasRef(); - ipc.close(); - ipc.unref(); - ipc.ref(); - } - - { - const forked = childProcess.fork('./', { - windowsVerbatimArguments: true, - silent: false, - stdio: ["inherit"], - execPath: '', - execArgv: ['asda'] - }); - } - - { - const forked = childProcess.fork('./'); - } - async function testPromisify() { const execFile = util.promisify(childProcess.execFile); let r: { stdout: string | Buffer, stderr: string | Buffer } = await execFile("npm"); @@ -4074,7 +4043,7 @@ namespace inspector_tests { inspector.open(0, 'localhost'); inspector.open(0, 'localhost', true); inspector.close(); - const inspectorUrl: string | undefined = inspector.url(); + const inspectorUrl: string = inspector.url(); const session = new inspector.Session(); session.connect(); diff --git a/types/node/v8/package.json b/types/node/v8/package.json index cda6cc6dc8..54d5b8743e 100644 --- a/types/node/v8/package.json +++ b/types/node/v8/package.json @@ -2,9 +2,9 @@ "private": true, "types": "index", "typesVersions": { - ">=3.2.0-0": { + "<=3.1": { "*": [ - "ts3.2/*" + "ts3.1/*" ] } } diff --git a/types/node/v8/ts3.1/index.d.ts b/types/node/v8/ts3.1/index.d.ts new file mode 100644 index 0000000000..4cfb6812b4 --- /dev/null +++ b/types/node/v8/ts3.1/index.d.ts @@ -0,0 +1,67 @@ +// Type definitions for Node.js 8.10 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Parambir Singh +// Wilco Bakker +// Chigozirim C. +// Flarna +// Mariusz Wiktorczyk +// wwwy3y3 +// Deividas Bakanas +// Kelvin Jin +// Alvis HT Tang +// Sebastian Silbermann +// Hannes Magnusson +// Alberto Schiabel +// Huw +// Nicolas Even +// Nikita Galkin +// Bruno Scheufler +// Hoàng Văn Khải +// Lishude +// Andrew Makarov +// Jordi Oliveras Rovira +// Thanik Bhongbhibhat +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 +// 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 IteratorResult { } +interface Iterable { } +interface Iterator { + next(value?: any): IteratorResult; +} +interface IterableIterator { } +interface SymbolConstructor { + readonly iterator: symbol; +} +declare var Symbol: SymbolConstructor; + +declare module "util" { + namespace inspect { + const custom: symbol; + } + namespace promisify { + const custom: symbol; + } +} diff --git a/types/node/v8/ts3.2/node-tests.ts b/types/node/v8/ts3.1/node-tests.ts similarity index 99% rename from types/node/v8/ts3.2/node-tests.ts rename to types/node/v8/ts3.1/node-tests.ts index 191469bb65..95162307b5 100644 --- a/types/node/v8/ts3.2/node-tests.ts +++ b/types/node/v8/ts3.1/node-tests.ts @@ -2108,6 +2108,37 @@ namespace child_process_tests { childProcess.execFile("npm", { encoding: 'buffer' }, (stdout, stderr) => { assert(stdout instanceof Buffer); }); } + { + const forked = childProcess.fork('./', ['asd'], { + windowsVerbatimArguments: true, + silent: false, + stdio: ["inherit"], + execPath: '', + execArgv: ['asda'] + }); + const exitCode: number | null = forked.exitCode; + const signalCode: number | null = forked.signalCode; + const ipc: stream.Pipe = forked.channel; + const hasRef: boolean = ipc.hasRef(); + ipc.close(); + ipc.unref(); + ipc.ref(); + } + + { + const forked = childProcess.fork('./', { + windowsVerbatimArguments: true, + silent: false, + stdio: ["inherit"], + execPath: '', + execArgv: ['asda'] + }); + } + + { + const forked = childProcess.fork('./'); + } + async function testPromisify() { const execFile = util.promisify(childProcess.execFile); let r: { stdout: string | Buffer, stderr: string | Buffer } = await execFile("npm"); @@ -4043,7 +4074,7 @@ namespace inspector_tests { inspector.open(0, 'localhost'); inspector.open(0, 'localhost', true); inspector.close(); - const inspectorUrl: string = inspector.url(); + const inspectorUrl: string | undefined = inspector.url(); const session = new inspector.Session(); session.connect(); diff --git a/types/node/v8/ts3.2/tsconfig.json b/types/node/v8/ts3.1/tsconfig.json similarity index 100% rename from types/node/v8/ts3.2/tsconfig.json rename to types/node/v8/ts3.1/tsconfig.json diff --git a/types/node/v8/ts3.1/tslint.json b/types/node/v8/ts3.1/tslint.json new file mode 100644 index 0000000000..8f9cf3a592 --- /dev/null +++ b/types/node/v8/ts3.1/tslint.json @@ -0,0 +1,18 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "dt-header": false, + "max-line-length": false, + "no-empty-interface": false, + "no-internal-module": false, + "no-redundant-jsdoc": false, + "no-single-declare-module": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-var-keyword": false, + "prefer-method-signature": false, + "strict-export-declare-modifiers": false, + "unified-signatures": false + } +} diff --git a/types/node/v8/ts3.2/index.d.ts b/types/node/v8/ts3.2/index.d.ts deleted file mode 100644 index c354b5c0b3..0000000000 --- a/types/node/v8/ts3.2/index.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.2. - -// 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.2/index.d.ts - Definitions specific to TypeScript 3.2 - -// 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.2-specific augmentations: -declare module "util" { - namespace inspect { - const custom: unique symbol; - } - namespace promisify { - const custom: unique symbol; - } -} diff --git a/types/node/v8/ts3.2/tslint.json b/types/node/v8/ts3.2/tslint.json deleted file mode 100644 index 67c323ed59..0000000000 --- a/types/node/v8/ts3.2/tslint.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "no-single-declare-module": false - } -} diff --git a/types/node/v8/tslint.json b/types/node/v8/tslint.json index 8f9cf3a592..67c323ed59 100644 --- a/types/node/v8/tslint.json +++ b/types/node/v8/tslint.json @@ -2,17 +2,6 @@ "extends": "dtslint/dt.json", "rules": { "ban-types": false, - "dt-header": false, - "max-line-length": false, - "no-empty-interface": false, - "no-internal-module": false, - "no-redundant-jsdoc": false, - "no-single-declare-module": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-var-keyword": false, - "prefer-method-signature": false, - "strict-export-declare-modifiers": false, - "unified-signatures": false + "no-single-declare-module": false } } diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index 1cd16a3443..c354b5c0b3 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -1,70 +1,23 @@ -// Type definitions for Node.js 9.6 -// Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped -// Parambir Singh -// Wilco Bakker -// Chigozirim C. -// Flarna -// Mariusz Wiktorczyk -// wwwy3y3 -// Deividas Bakanas -// Kelvin Jin -// Alvis HT Tang -// Sebastian Silbermann -// Hannes Magnusson -// Alberto Schiabel -// Klaus Meinhardt -// Huw -// Nicolas Even -// Nikita Galkin -// Bruno Scheufler -// Mohsen Azimi -// Hoàng Văn Khải -// Alexander T. -// Lishude -// Andrew Makarov -// Eugene Y. Q. Shen -// Jordi Oliveras Rovira -// Thanik Bhongbhibhat -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// NOTE: These definitions support NodeJS and TypeScript 3.1. +// NOTE: These definitions support NodeJS and TypeScript 3.2. // 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 +// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2 -// 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. +// Reference required types from the default lib: +/// // 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 IteratorResult { } -interface Iterable { } -interface Iterator { - next(value?: any): IteratorResult; -} -interface IterableIterator { } -interface SymbolConstructor { - readonly iterator: symbol; -} -declare var Symbol: SymbolConstructor; +// tslint:disable-next-line:no-bad-reference +/// +// TypeScript 3.2-specific augmentations: declare module "util" { namespace inspect { - const custom: symbol; + const custom: unique symbol; } namespace promisify { - const custom: symbol; + const custom: unique symbol; } } diff --git a/types/node/v9/node-tests.ts b/types/node/v9/node-tests.ts index d3e55de398..d51d13d655 100644 --- a/types/node/v9/node-tests.ts +++ b/types/node/v9/node-tests.ts @@ -4106,7 +4106,7 @@ namespace inspector_tests { inspector.open(0, 'localhost'); inspector.open(0, 'localhost', true); inspector.close(); - const inspectorUrl: string | undefined = inspector.url(); + const inspectorUrl: string = inspector.url(); const session = new inspector.Session(); session.connect(); diff --git a/types/node/v9/package.json b/types/node/v9/package.json index cda6cc6dc8..54d5b8743e 100644 --- a/types/node/v9/package.json +++ b/types/node/v9/package.json @@ -2,9 +2,9 @@ "private": true, "types": "index", "typesVersions": { - ">=3.2.0-0": { + "<=3.1": { "*": [ - "ts3.2/*" + "ts3.1/*" ] } } diff --git a/types/node/v9/ts3.1/index.d.ts b/types/node/v9/ts3.1/index.d.ts new file mode 100644 index 0000000000..1cd16a3443 --- /dev/null +++ b/types/node/v9/ts3.1/index.d.ts @@ -0,0 +1,70 @@ +// Type definitions for Node.js 9.6 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Parambir Singh +// Wilco Bakker +// Chigozirim C. +// Flarna +// Mariusz Wiktorczyk +// wwwy3y3 +// Deividas Bakanas +// Kelvin Jin +// Alvis HT Tang +// Sebastian Silbermann +// Hannes Magnusson +// Alberto Schiabel +// Klaus Meinhardt +// Huw +// Nicolas Even +// Nikita Galkin +// Bruno Scheufler +// Mohsen Azimi +// Hoàng Văn Khải +// Alexander T. +// Lishude +// Andrew Makarov +// Eugene Y. Q. Shen +// Jordi Oliveras Rovira +// Thanik Bhongbhibhat +// 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 IteratorResult { } +interface Iterable { } +interface Iterator { + next(value?: any): IteratorResult; +} +interface IterableIterator { } +interface SymbolConstructor { + readonly iterator: symbol; +} +declare var Symbol: SymbolConstructor; + +declare module "util" { + namespace inspect { + const custom: symbol; + } + namespace promisify { + const custom: symbol; + } +} diff --git a/types/node/v9/ts3.2/node-tests.ts b/types/node/v9/ts3.1/node-tests.ts similarity index 99% rename from types/node/v9/ts3.2/node-tests.ts rename to types/node/v9/ts3.1/node-tests.ts index d51d13d655..d3e55de398 100644 --- a/types/node/v9/ts3.2/node-tests.ts +++ b/types/node/v9/ts3.1/node-tests.ts @@ -4106,7 +4106,7 @@ namespace inspector_tests { inspector.open(0, 'localhost'); inspector.open(0, 'localhost', true); inspector.close(); - const inspectorUrl: string = inspector.url(); + const inspectorUrl: string | undefined = inspector.url(); const session = new inspector.Session(); session.connect(); diff --git a/types/node/v9/ts3.2/tsconfig.json b/types/node/v9/ts3.1/tsconfig.json similarity index 100% rename from types/node/v9/ts3.2/tsconfig.json rename to types/node/v9/ts3.1/tsconfig.json diff --git a/types/node/v9/ts3.1/tslint.json b/types/node/v9/ts3.1/tslint.json new file mode 100644 index 0000000000..8f9cf3a592 --- /dev/null +++ b/types/node/v9/ts3.1/tslint.json @@ -0,0 +1,18 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "dt-header": false, + "max-line-length": false, + "no-empty-interface": false, + "no-internal-module": false, + "no-redundant-jsdoc": false, + "no-single-declare-module": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-var-keyword": false, + "prefer-method-signature": false, + "strict-export-declare-modifiers": false, + "unified-signatures": false + } +} diff --git a/types/node/v9/ts3.2/index.d.ts b/types/node/v9/ts3.2/index.d.ts deleted file mode 100644 index c354b5c0b3..0000000000 --- a/types/node/v9/ts3.2/index.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.2. - -// 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.2/index.d.ts - Definitions specific to TypeScript 3.2 - -// 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.2-specific augmentations: -declare module "util" { - namespace inspect { - const custom: unique symbol; - } - namespace promisify { - const custom: unique symbol; - } -} diff --git a/types/node/v9/ts3.2/tslint.json b/types/node/v9/ts3.2/tslint.json deleted file mode 100644 index 67c323ed59..0000000000 --- a/types/node/v9/ts3.2/tslint.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "ban-types": false, - "no-single-declare-module": false - } -} diff --git a/types/node/v9/tslint.json b/types/node/v9/tslint.json index 8f9cf3a592..67c323ed59 100644 --- a/types/node/v9/tslint.json +++ b/types/node/v9/tslint.json @@ -2,17 +2,6 @@ "extends": "dtslint/dt.json", "rules": { "ban-types": false, - "dt-header": false, - "max-line-length": false, - "no-empty-interface": false, - "no-internal-module": false, - "no-redundant-jsdoc": false, - "no-single-declare-module": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-var-keyword": false, - "prefer-method-signature": false, - "strict-export-declare-modifiers": false, - "unified-signatures": false + "no-single-declare-module": false } }