diff --git a/.gitignore b/.gitignore index 7be817acce2349..ebeedeac6b8fe0 100644 --- a/.gitignore +++ b/.gitignore @@ -127,3 +127,4 @@ deps/v8/src/Debug/ deps/v8/src/Release/ deps/v8/src/inspector/Debug/ deps/v8/src/inspector/Release/ +deps/v8/third_party/eu-strip/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 8625b2026a093a..053e4381c1563c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,7 +33,8 @@ release. -10.0.0
+10.1.0
+10.0.0
9.11.1
diff --git a/COLLABORATOR_GUIDE.md b/COLLABORATOR_GUIDE.md index a7b1e68d7276a9..0cb03822c98947 100644 --- a/COLLABORATOR_GUIDE.md +++ b/COLLABORATOR_GUIDE.md @@ -416,14 +416,15 @@ longer be used. Node.js uses three Deprecation levels: -* *Documentation-Only Deprecation* refers to elements of the Public API that are - being staged for deprecation in a future Node.js major release. An explicit - notice indicating the deprecated status is added to the API documentation - but no functional changes are implemented in the code. There will be no - runtime deprecation warnings emitted for such deprecations by default. - Documentation-only deprecations may trigger a runtime warning when Node.js - is started with the [`--pending-deprecation`][] flag or the - `NODE_PENDING_DEPRECATION=1` environment variable is set. +* *Documentation-Only Deprecation* refers to elements of the Public API that + should be avoided by developers and that might be staged for a runtime + deprecation in a future Node.js major release. An explicit notice indicating + the deprecation status is added to the API documentation but no functional + changes are implemented in the code. By default there will be no deprecation + warnings emitted for such deprecations at runtime. Documentation-only + deprecations may trigger a runtime warning when Node.js is started with the + [`--pending-deprecation`][] flag or the `NODE_PENDING_DEPRECATION=1` + environment variable is set. * *Runtime Deprecation* refers to the use of process warnings emitted at runtime the first time that a deprecated API is used. A command-line @@ -489,8 +490,7 @@ The TSC should serve as the final arbiter where required. 1. Never use GitHub's green ["Merge Pull Request"][] button. Reasons for not using the web interface button: * The merge method will add an unnecessary merge commit. - * The squash & merge method has been known to add metadata to the commit - title (the PR #). + * The squash & merge method can add metadata (the PR #) to the commit title. * If more than one author has contributed to the PR, keep the most recent author when squashing. 1. Make sure the CI is done and the result is green. If the CI is not green, @@ -832,7 +832,6 @@ LTS working group and the Release team. | Subsystem | Maintainers | | --- | --- | | `benchmark/*` | @nodejs/benchmarking, @mscdex | -| `bootstrap_node.js` | @nodejs/process | | `doc/*`, `*.md` | @nodejs/documentation | | `lib/assert` | @nodejs/testing | | `lib/async_hooks` | @nodejs/async\_hooks for bugs/reviews (+ @nodejs/diagnostics for API) | @@ -845,6 +844,7 @@ LTS working group and the Release team. | `lib/fs`, `src/{fs,file}` | @nodejs/fs | | `lib/{_}http{*}` | @nodejs/http | | `lib/inspector.js`, `src/inspector_*` | @nodejs/V8-inspector | +| `lib/internal/bootstrap/*` | @nodejs/process | | `lib/internal/url`, `src/node_url` | @nodejs/url | | `lib/net` | @bnoordhuis, @indutny, @nodejs/streams | | `lib/repl` | @nodejs/repl | @@ -852,13 +852,13 @@ LTS working group and the Release team. | `lib/timers` | @nodejs/timers | | `lib/util` | @nodejs/util | | `lib/zlib` | @nodejs/zlib | -| `src/async-wrap.*` | @nodejs/async\_hooks | +| `src/async_wrap.*` | @nodejs/async\_hooks | | `src/node_api.*` | @nodejs/n-api | | `src/node_crypto.*` | @nodejs/crypto | | `test/*` | @nodejs/testing | | `tools/node_modules/eslint`, `.eslintrc` | @nodejs/linting | | build | @nodejs/build | -| `src/module_wrap.*`, `lib/internal/loader/*`, `lib/internal/vm/Module.js` | @nodejs/modules | +| `src/module_wrap.*`, `lib/internal/modules/*`, `lib/internal/vm/module.js` | @nodejs/modules | | GYP | @nodejs/gyp | | performance | @nodejs/performance | | platform specific | @nodejs/platform-{aix,arm,freebsd,macos,ppc,smartos,s390,windows} | diff --git a/CPP_STYLE_GUIDE.md b/CPP_STYLE_GUIDE.md index edc5f0f12e212c..41e1f082f87751 100644 --- a/CPP_STYLE_GUIDE.md +++ b/CPP_STYLE_GUIDE.md @@ -12,6 +12,7 @@ * [CamelCase for methods, functions, and classes](#camelcase-for-methods-functions-and-classes) * [snake\_case for local variables and parameters](#snake_case-for-local-variables-and-parameters) * [snake\_case\_ for private class fields](#snake_case_-for-private-class-fields) + * [snake\_case\_ for C-like structs](#snake_case_-for-c-like-structs) * [Space after `template`](#space-after-template) * [Memory Management](#memory-management) * [Memory allocation](#memory-allocation) @@ -147,6 +148,15 @@ class Foo { }; ``` +## snake\_case\_ for C-like structs +For plain C-like structs snake_case can be used. + +```c++ +struct foo_bar { + int name; +} +``` + ## Space after `template` ```c++ diff --git a/Makefile b/Makefile index f499788d9d86cc..02d97b633d87d6 100644 --- a/Makefile +++ b/Makefile @@ -393,7 +393,7 @@ clear-stalled: ps awwx | grep Release/node | grep -v grep | cat @PS_OUT=`ps awwx | grep Release/node | grep -v grep | awk '{print $$1}'`; \ if [ "$${PS_OUT}" ]; then \ - echo $${PS_OUT} | xargs kill; \ + echo $${PS_OUT} | xargs kill -9; \ fi .PHONY: test-gc @@ -439,7 +439,7 @@ test-ci-js: | clear-stalled ps awwx | grep Release/node | grep -v grep | cat @PS_OUT=`ps awwx | grep Release/node | grep -v grep | awk '{print $$1}'`; \ if [ "$${PS_OUT}" ]; then \ - echo $${PS_OUT} | xargs kill; exit 1; \ + echo $${PS_OUT} | xargs kill -9; exit 1; \ fi .PHONY: test-ci @@ -454,7 +454,7 @@ test-ci: | clear-stalled build-addons build-addons-napi doc-only ps awwx | grep Release/node | grep -v grep | cat @PS_OUT=`ps awwx | grep Release/node | grep -v grep | awk '{print $$1}'`; \ if [ "$${PS_OUT}" ]; then \ - echo $${PS_OUT} | xargs kill; exit 1; \ + echo $${PS_OUT} | xargs kill -9; exit 1; \ fi .PHONY: build-ci @@ -652,7 +652,7 @@ tools/doc/node_modules/js-yaml/package.json: gen-json = tools/doc/generate.js --format=json $< > $@ gen-html = tools/doc/generate.js --node-version=$(FULLVERSION) --format=html \ - --template=doc/template.html --analytics=$(DOCS_ANALYTICS) $< > $@ + --analytics=$(DOCS_ANALYTICS) $< > $@ out/doc/api/%.json: doc/api/%.md $(call available-node, $(gen-json)) @@ -813,8 +813,8 @@ release-only: exit 1 ; \ fi @if [ "$(DISTTYPE)" != "nightly" ] && [ "$(DISTTYPE)" != "next-nightly" ] && \ - `grep -q DEP00XX doc/api/deprecations.md`; then \ - echo 'Please update DEP00XX in doc/api/deprecations.md (See doc/releases.md)' ; \ + `grep -q DEP...X doc/api/deprecations.md`; then \ + echo 'Please update DEP...X in doc/api/deprecations.md (See doc/releases.md)' ; \ exit 1 ; \ fi @if [ "$(shell git status --porcelain | egrep -v '^\?\? ')" = "" ]; then \ diff --git a/README.md b/README.md index d39c7639e20d1a..df95961979edae 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,8 @@ search these unofficial resources: * [Questions tagged 'node.js' on StackOverflow][] * [#node.js channel on chat.freenode.net][]. See for more information. +* [Node.js Slack Community](https://node-js.slack.com/): Visit + [nodeslackers.com](http://www.nodeslackers.com/) to register. GitHub issues are meant for tracking enhancements and bugs, not general support. @@ -512,8 +514,6 @@ For more information about the governance of the Node.js project, see **Trivikram Kamat** <trivikr.dev@gmail.com> * [Trott](https://github.com/Trott) - **Rich Trott** <rtrott@gmail.com> (he/him) -* [tunniclm](https://github.com/tunniclm) - -**Mike Tunnicliffe** <m.j.tunnicliffe@gmail.com> * [vdeturckheim](https://github.com/vdeturckheim) - **Vladimir de Turckheim** <vlad2t@hotmail.com> (he/him) * [vkurchatkin](https://github.com/vkurchatkin) - @@ -557,6 +557,8 @@ For more information about the governance of the Node.js project, see **Alex Kocharin** <alex@kocharin.ru> * [tellnes](https://github.com/tellnes) - **Christian Tellnes** <christian@tellnes.no> +* [tunniclm](https://github.com/tunniclm) - +**Mike Tunnicliffe** <m.j.tunnicliffe@gmail.com> Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in maintaining the Node.js project. diff --git a/benchmark/events/ee-add-remove.js b/benchmark/events/ee-add-remove.js index eee8ff4524ed1a..54e680f74ae3e1 100644 --- a/benchmark/events/ee-add-remove.js +++ b/benchmark/events/ee-add-remove.js @@ -2,7 +2,7 @@ const common = require('../common.js'); const events = require('events'); -const bench = common.createBenchmark(main, { n: [25e4] }); +const bench = common.createBenchmark(main, { n: [1e6] }); function main({ n }) { const ee = new events.EventEmitter(); diff --git a/benchmark/fs/bench-stat-promise.js b/benchmark/fs/bench-stat-promise.js index b0317455728b46..96c7058fa6218a 100644 --- a/benchmark/fs/bench-stat-promise.js +++ b/benchmark/fs/bench-stat-promise.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); -const fsPromises = require('fs/promises'); +const fsPromises = require('fs').promises; const bench = common.createBenchmark(main, { n: [20e4], diff --git a/benchmark/http/headers.js b/benchmark/http/headers.js new file mode 100644 index 00000000000000..748865afbf3a04 --- /dev/null +++ b/benchmark/http/headers.js @@ -0,0 +1,36 @@ +'use strict'; + +const common = require('../common.js'); +const http = require('http'); + +const bench = common.createBenchmark(main, { + duplicates: [1, 100], + n: [10, 1000], +}); + +function main({ duplicates, n }) { + const headers = { + 'Connection': 'keep-alive', + 'Transfer-Encoding': 'chunked', + }; + + for (var i = 0; i < n / duplicates; i++) { + headers[`foo${i}`] = []; + for (var j = 0; j < duplicates; j++) { + headers[`foo${i}`].push(`some header value ${i}`); + } + } + + const server = http.createServer(function(req, res) { + res.writeHead(200, headers); + res.end(); + }); + server.listen(common.PORT, function() { + bench.http({ + path: '/', + connections: 10 + }, function() { + server.close(); + }); + }); +} diff --git a/benchmark/process/next-tick-depth-args.js b/benchmark/process/next-tick-depth-args.js index 52d349c776b326..a7670d99efc354 100644 --- a/benchmark/process/next-tick-depth-args.js +++ b/benchmark/process/next-tick-depth-args.js @@ -8,13 +8,14 @@ const bench = common.createBenchmark(main, { process.maxTickDepth = Infinity; function main({ n }) { + let counter = n; function cb4(arg1, arg2, arg3, arg4) { - if (--n) { - if (n % 4 === 0) + if (--counter) { + if (counter % 4 === 0) process.nextTick(cb4, 3.14, 1024, true, false); - else if (n % 3 === 0) + else if (counter % 3 === 0) process.nextTick(cb3, 512, true, null); - else if (n % 2 === 0) + else if (counter % 2 === 0) process.nextTick(cb2, false, 5.1); else process.nextTick(cb1, 0); @@ -22,12 +23,12 @@ function main({ n }) { bench.end(n); } function cb3(arg1, arg2, arg3) { - if (--n) { - if (n % 4 === 0) + if (--counter) { + if (counter % 4 === 0) process.nextTick(cb4, 3.14, 1024, true, false); - else if (n % 3 === 0) + else if (counter % 3 === 0) process.nextTick(cb3, 512, true, null); - else if (n % 2 === 0) + else if (counter % 2 === 0) process.nextTick(cb2, false, 5.1); else process.nextTick(cb1, 0); @@ -35,12 +36,12 @@ function main({ n }) { bench.end(n); } function cb2(arg1, arg2) { - if (--n) { - if (n % 4 === 0) + if (--counter) { + if (counter % 4 === 0) process.nextTick(cb4, 3.14, 1024, true, false); - else if (n % 3 === 0) + else if (counter % 3 === 0) process.nextTick(cb3, 512, true, null); - else if (n % 2 === 0) + else if (counter % 2 === 0) process.nextTick(cb2, false, 5.1); else process.nextTick(cb1, 0); @@ -48,12 +49,12 @@ function main({ n }) { bench.end(n); } function cb1(arg1) { - if (--n) { - if (n % 4 === 0) + if (--counter) { + if (counter % 4 === 0) process.nextTick(cb4, 3.14, 1024, true, false); - else if (n % 3 === 0) + else if (counter % 3 === 0) process.nextTick(cb3, 512, true, null); - else if (n % 2 === 0) + else if (counter % 2 === 0) process.nextTick(cb2, false, 5.1); else process.nextTick(cb1, 0); diff --git a/benchmark/process/next-tick-depth.js b/benchmark/process/next-tick-depth.js index 6669936e398272..1ad32c806181b0 100644 --- a/benchmark/process/next-tick-depth.js +++ b/benchmark/process/next-tick-depth.js @@ -7,11 +7,11 @@ const bench = common.createBenchmark(main, { process.maxTickDepth = Infinity; function main({ n }) { - + let counter = n; bench.start(); process.nextTick(onNextTick); function onNextTick() { - if (--n) + if (--counter) process.nextTick(onNextTick); else bench.end(n); diff --git a/benchmark/process/next-tick-exec-args.js b/benchmark/process/next-tick-exec-args.js index 3be86cc08e177a..f5d0fb94224148 100644 --- a/benchmark/process/next-tick-exec-args.js +++ b/benchmark/process/next-tick-exec-args.js @@ -5,8 +5,11 @@ const bench = common.createBenchmark(main, { }); function main({ n }) { + function onNextTick(i) { + if (i + 1 === n) + bench.end(n); + } - bench.start(); for (var i = 0; i < n; i++) { if (i % 4 === 0) process.nextTick(onNextTick, i, true, 10, 'test'); @@ -17,8 +20,6 @@ function main({ n }) { else process.nextTick(onNextTick, i); } - function onNextTick(i) { - if (i + 1 === n) - bench.end(n); - } + + bench.start(); } diff --git a/benchmark/process/next-tick-exec.js b/benchmark/process/next-tick-exec.js index d00ee017de4bff..936b253bfaf324 100644 --- a/benchmark/process/next-tick-exec.js +++ b/benchmark/process/next-tick-exec.js @@ -5,13 +5,14 @@ const bench = common.createBenchmark(main, { }); function main({ n }) { - - bench.start(); - for (var i = 0; i < n; i++) { - process.nextTick(onNextTick, i); - } function onNextTick(i) { if (i + 1 === n) bench.end(n); } + + for (var i = 0; i < n; i++) { + process.nextTick(onNextTick, i); + } + + bench.start(); } diff --git a/benchmark/util/splice-one.js b/benchmark/util/splice-one.js new file mode 100644 index 00000000000000..5c2a39f6d72a11 --- /dev/null +++ b/benchmark/util/splice-one.js @@ -0,0 +1,33 @@ +'use strict'; + +const common = require('../common'); + +const bench = common.createBenchmark(main, { + n: [1e7], + pos: ['start', 'middle', 'end'], + size: [10, 100, 500], +}, { flags: ['--expose-internals'] }); + +function main({ n, pos, size }) { + const { spliceOne } = require('internal/util'); + const arr = new Array(size); + arr.fill(''); + let index; + switch (pos) { + case 'end': + index = size - 1; + break; + case 'middle': + index = Math.floor(size / 2); + break; + default: // start + index = 0; + } + + bench.start(); + for (var i = 0; i < n; i++) { + spliceOne(arr, index); + arr.push(''); + } + bench.end(n); +} diff --git a/benchmark/zlib/pipe.js b/benchmark/zlib/pipe.js new file mode 100644 index 00000000000000..9b05749bbb824d --- /dev/null +++ b/benchmark/zlib/pipe.js @@ -0,0 +1,39 @@ +'use strict'; +const common = require('../common.js'); +const fs = require('fs'); +const zlib = require('zlib'); + +const bench = common.createBenchmark(main, { + inputLen: [1024], + duration: [5], + type: ['string', 'buffer'] +}); + +function main({ inputLen, duration, type }) { + const buffer = Buffer.alloc(inputLen, fs.readFileSync(__filename)); + const chunk = type === 'buffer' ? buffer : buffer.toString('utf8'); + + const input = zlib.createGzip(); + const output = zlib.createGunzip(); + + let readFromOutput = 0; + input.pipe(output); + if (type === 'string') + output.setEncoding('utf8'); + output.on('data', (chunk) => readFromOutput += chunk.length); + + function write() { + input.write(chunk, write); + } + + bench.start(); + write(); + + setTimeout(() => { + // Give result in GBit/s, like the net benchmarks do + bench.end(readFromOutput * 8 / (1024 ** 3)); + + // Cut off writing the easy way. + input.write = () => {}; + }, duration * 1000); +} diff --git a/common.gypi b/common.gypi index d1304a14478d2c..3bb10d611fb1d5 100644 --- a/common.gypi +++ b/common.gypi @@ -27,7 +27,7 @@ # Reset this number to 0 on major V8 upgrades. # Increment by one for each non-official patch applied to deps/v8. - 'v8_embedder_string': '-node.5', + 'v8_embedder_string': '-node.6', # Enable disassembler for `--print-code` v8 options 'v8_enable_disassembler': 1, diff --git a/configure b/configure index c1170f9a132a16..17e13a48d47e5a 100755 --- a/configure +++ b/configure @@ -501,11 +501,6 @@ parser.add_option('--without-node-options', dest='without_node_options', help='build without NODE_OPTIONS support') -parser.add_option('--xcode', - action='store_true', - dest='use_xcode', - help='generate build files for use with xcode') - parser.add_option('--ninja', action='store_true', dest='use_ninja', @@ -1005,9 +1000,6 @@ def configure_node(o): o['variables']['asan'] = int(options.enable_asan or 0) - if options.use_xcode and options.use_ninja: - raise Exception('--xcode and --ninja cannot be used together.') - if options.coverage: o['variables']['coverage'] = 'true' else: @@ -1530,7 +1522,6 @@ write('config.gypi', do_not_edit + config = { 'BUILDTYPE': 'Debug' if options.debug else 'Release', - 'USE_XCODE': str(int(options.use_xcode or 0)), 'PYTHON': sys.executable, 'NODE_TARGET_TYPE': variables['node_target_type'], } @@ -1549,9 +1540,7 @@ write('config.mk', do_not_edit + config) gyp_args = ['--no-parallel'] -if options.use_xcode: - gyp_args += ['-f', 'xcode'] -elif options.use_ninja: +if options.use_ninja: gyp_args += ['-f', 'ninja'] elif flavor == 'win' and sys.platform != 'msys': gyp_args += ['-f', 'msvs', '-G', 'msvs_version=auto'] diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h index 68d0a359292bd7..81f014cbd4b68d 100644 --- a/deps/v8/include/v8-version.h +++ b/deps/v8/include/v8-version.h @@ -11,7 +11,7 @@ #define V8_MAJOR_VERSION 6 #define V8_MINOR_VERSION 6 #define V8_BUILD_NUMBER 346 -#define V8_PATCH_LEVEL 24 +#define V8_PATCH_LEVEL 27 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) diff --git a/deps/v8/src/builtins/builtins-object-gen.cc b/deps/v8/src/builtins/builtins-object-gen.cc index 1ebfbacf38ecb6..3fb8d7792d6df0 100644 --- a/deps/v8/src/builtins/builtins-object-gen.cc +++ b/deps/v8/src/builtins/builtins-object-gen.cc @@ -268,7 +268,7 @@ TNode ObjectEntriesValuesBuiltinsAssembler::FastGetOwnValuesOrEntries( object_enum_length, IntPtrConstant(kInvalidEnumCacheSentinel)); // In case, we found enum_cache in object, - // we use it as array_length becuase it has same size for + // we use it as array_length because it has same size for // Object.(entries/values) result array object length. // So object_enum_length use less memory space than // NumberOfOwnDescriptorsBits value. @@ -285,7 +285,7 @@ TNode ObjectEntriesValuesBuiltinsAssembler::FastGetOwnValuesOrEntries( INTPTR_PARAMETERS, kAllowLargeObjectAllocation)); // If in case we have enum_cache, - // we can't detect accessor of object until loop through descritpros. + // we can't detect accessor of object until loop through descriptors. // So if object might have accessor, // we will remain invalid addresses of FixedArray. // Because in that case, we need to jump to runtime call. @@ -299,7 +299,7 @@ TNode ObjectEntriesValuesBuiltinsAssembler::FastGetOwnValuesOrEntries( Variable* vars[] = {&var_descriptor_number, &var_result_index}; // Let desc be ? O.[[GetOwnProperty]](key). TNode descriptors = LoadMapDescriptors(map); - Label loop(this, 2, vars), after_loop(this), loop_condition(this); + Label loop(this, 2, vars), after_loop(this), next_descriptor(this); Branch(IntPtrEqual(var_descriptor_number.value(), object_enum_length), &after_loop, &loop); @@ -316,7 +316,7 @@ TNode ObjectEntriesValuesBuiltinsAssembler::FastGetOwnValuesOrEntries( Node* next_key = DescriptorArrayGetKey(descriptors, descriptor_index); // Skip Symbols. - GotoIf(IsSymbol(next_key), &loop_condition); + GotoIf(IsSymbol(next_key), &next_descriptor); TNode details = TNode::UncheckedCast( DescriptorArrayGetDetails(descriptors, descriptor_index)); @@ -326,8 +326,9 @@ TNode ObjectEntriesValuesBuiltinsAssembler::FastGetOwnValuesOrEntries( GotoIf(IsPropertyKindAccessor(kind), if_call_runtime_with_fast_path); CSA_ASSERT(this, IsPropertyKindData(kind)); - // If desc is not undefined and desc.[[Enumerable]] is true, then - GotoIfNot(IsPropertyEnumerable(details), &loop_condition); + // If desc is not undefined and desc.[[Enumerable]] is true, then skip to + // the next descriptor. + GotoIfNot(IsPropertyEnumerable(details), &next_descriptor); VARIABLE(var_property_value, MachineRepresentation::kTagged, UndefinedConstant()); @@ -357,12 +358,12 @@ TNode ObjectEntriesValuesBuiltinsAssembler::FastGetOwnValuesOrEntries( StoreFixedArrayElement(values_or_entries, var_result_index.value(), value); Increment(&var_result_index, 1); - Goto(&loop_condition); + Goto(&next_descriptor); - BIND(&loop_condition); + BIND(&next_descriptor); { Increment(&var_descriptor_number, 1); - Branch(IntPtrEqual(var_descriptor_number.value(), object_enum_length), + Branch(IntPtrEqual(var_result_index.value(), object_enum_length), &after_loop, &loop); } } diff --git a/deps/v8/src/keys.cc b/deps/v8/src/keys.cc index 4f59c2553caf0c..638c83f4270b95 100644 --- a/deps/v8/src/keys.cc +++ b/deps/v8/src/keys.cc @@ -77,7 +77,14 @@ void KeyAccumulator::AddKey(Handle key, AddKeyConversion convert) { Handle::cast(key)->AsArrayIndex(&index)) { key = isolate_->factory()->NewNumberFromUint(index); } - keys_ = OrderedHashSet::Add(keys(), key); + Handle new_set = OrderedHashSet::Add(keys(), key); + if (*new_set != *keys_) { + // The keys_ Set is converted directly to a FixedArray in GetKeys which can + // be left-trimmer. Hence the previous Set should not keep a pointer to the + // new one. + keys_->set(OrderedHashTableBase::kNextTableIndex, Smi::kZero); + keys_ = new_set; + } } void KeyAccumulator::AddKeys(Handle array, diff --git a/deps/v8/src/wasm/wasm-js.cc b/deps/v8/src/wasm/wasm-js.cc index dc1f690a63ac8b..915d4d9ead6b1f 100644 --- a/deps/v8/src/wasm/wasm-js.cc +++ b/deps/v8/src/wasm/wasm-js.cc @@ -330,16 +330,22 @@ MaybeLocal WebAssemblyInstantiateImpl(Isolate* isolate, i::MaybeHandle instance_object; { ScheduledErrorThrower thrower(i_isolate, "WebAssembly Instantiation"); + + // TODO(ahaas): These checks on the module should not be necessary here They + // are just a workaround for https://crbug.com/837417. + i::Handle module_obj = Utils::OpenHandle(*module); + if (!module_obj->IsWasmModuleObject()) { + thrower.TypeError("Argument 0 must be a WebAssembly.Module object"); + return {}; + } + i::MaybeHandle maybe_imports = GetValueAsImports(ffi, &thrower); if (thrower.error()) return {}; - i::Handle module_obj = - i::Handle::cast( - Utils::OpenHandle(Object::Cast(*module))); instance_object = i_isolate->wasm_engine()->SyncInstantiate( - i_isolate, &thrower, module_obj, maybe_imports, - i::MaybeHandle()); + i_isolate, &thrower, i::Handle::cast(module_obj), + maybe_imports, i::MaybeHandle()); } DCHECK_EQ(instance_object.is_null(), i_isolate->has_scheduled_exception()); @@ -347,25 +353,7 @@ MaybeLocal WebAssemblyInstantiateImpl(Isolate* isolate, return Utils::ToLocal(instance_object.ToHandleChecked()); } -// Entered as internal implementation detail of sync and async instantiate. -// args[0] *must* be a WebAssembly.Module. -void WebAssemblyInstantiateImplCallback( - const v8::FunctionCallbackInfo& args) { - DCHECK_GE(args.Length(), 1); - v8::Isolate* isolate = args.GetIsolate(); - MicrotasksScope does_not_run_microtasks(isolate, - MicrotasksScope::kDoNotRunMicrotasks); - - HandleScope scope(args.GetIsolate()); - Local module = args[0]; - Local ffi = args.Data(); - Local instance; - if (WebAssemblyInstantiateImpl(isolate, module, ffi).ToLocal(&instance)) { - args.GetReturnValue().Set(instance); - } -} - -void WebAssemblyInstantiateToPairCallback( +void WebAssemblyInstantiateCallback( const v8::FunctionCallbackInfo& args) { DCHECK_GE(args.Length(), 1); Isolate* isolate = args.GetIsolate(); @@ -454,7 +442,7 @@ void WebAssemblyInstantiateStreaming( DCHECK(!module_promise.IsEmpty()); Local data = args[1]; ASSIGN(Function, instantiate_impl, - Function::New(context, WebAssemblyInstantiateToPairCallback, data)); + Function::New(context, WebAssemblyInstantiateCallback, data)); ASSIGN(Promise, result, module_promise->Then(context, instantiate_impl)); args.GetReturnValue().Set(result); } @@ -476,10 +464,12 @@ void WebAssemblyInstantiate(const v8::FunctionCallbackInfo& args) { Local context = isolate->GetCurrentContext(); ASSIGN(Promise::Resolver, resolver, Promise::Resolver::New(context)); - Local module_promise = resolver->GetPromise(); - args.GetReturnValue().Set(module_promise); + Local promise = resolver->GetPromise(); + args.GetReturnValue().Set(promise); Local first_arg_value = args[0]; + // If args.Length < 2, this will be undefined - see FunctionCallbackInfo. + Local ffi = args[1]; i::Handle first_arg = Utils::OpenHandle(*first_arg_value); if (!first_arg->IsJSObject()) { thrower.TypeError( @@ -490,26 +480,35 @@ void WebAssemblyInstantiate(const v8::FunctionCallbackInfo& args) { return; } - FunctionCallback instantiator = nullptr; if (first_arg->IsWasmModuleObject()) { - module_promise = resolver->GetPromise(); - if (!resolver->Resolve(context, first_arg_value).IsJust()) return; - instantiator = WebAssemblyInstantiateImplCallback; - } else { - ASSIGN(Function, async_compile, Function::New(context, WebAssemblyCompile)); - ASSIGN(Value, async_compile_retval, - async_compile->Call(context, args.Holder(), 1, &first_arg_value)); - module_promise = Local::Cast(async_compile_retval); - instantiator = WebAssemblyInstantiateToPairCallback; + i::Handle module_obj = + i::Handle::cast(first_arg); + // If args.Length < 2, this will be undefined - see FunctionCallbackInfo. + i::MaybeHandle maybe_imports = + GetValueAsImports(ffi, &thrower); + + if (thrower.error()) { + auto maybe = resolver->Reject(context, Utils::ToLocal(thrower.Reify())); + CHECK_IMPLIES(!maybe.FromMaybe(false), + i_isolate->has_scheduled_exception()); + return; + } + + i_isolate->wasm_engine()->AsyncInstantiate( + i_isolate, Utils::OpenHandle(*promise), module_obj, maybe_imports); + return; } - DCHECK(!module_promise.IsEmpty()); - DCHECK_NOT_NULL(instantiator); - // If args.Length < 2, this will be undefined - see FunctionCallbackInfo. - // We'll check for that in WebAssemblyInstantiateImpl. - Local data = args[1]; + + // We did not get a WasmModuleObject as input, we first have to compile the + // input. + ASSIGN(Function, async_compile, Function::New(context, WebAssemblyCompile)); + ASSIGN(Value, async_compile_retval, + async_compile->Call(context, args.Holder(), 1, &first_arg_value)); + promise = Local::Cast(async_compile_retval); + DCHECK(!promise.IsEmpty()); ASSIGN(Function, instantiate_impl, - Function::New(context, instantiator, data)); - ASSIGN(Promise, result, module_promise->Then(context, instantiate_impl)); + Function::New(context, WebAssemblyInstantiateCallback, ffi)); + ASSIGN(Promise, result, promise->Then(context, instantiate_impl)); args.GetReturnValue().Set(result); } diff --git a/deps/v8/test/mjsunit/es8/object-entries.js b/deps/v8/test/mjsunit/es8/object-entries.js index 1c6358648b9ede..51ce4692e40e19 100644 --- a/deps/v8/test/mjsunit/es8/object-entries.js +++ b/deps/v8/test/mjsunit/es8/object-entries.js @@ -210,6 +210,24 @@ function TestPropertyFilter(withWarmup) { TestPropertyFilter(); TestPropertyFilter(true); +function TestPropertyFilter2(withWarmup) { + var object = { }; + Object.defineProperty(object, "prop1", { value: 10 }); + Object.defineProperty(object, "prop2", { value: 20 }); + object.prop3 = 30; + + if (withWarmup) { + for (const key in object) {} + } + + values = Object.entries(object); + assertEquals(1, values.length); + assertEquals([ + [ "prop3", 30 ], + ], values); +} +TestPropertyFilter2(); +TestPropertyFilter2(true); function TestWithProxy(withWarmup) { var obj1 = {prop1:10}; diff --git a/deps/v8/test/mjsunit/regress/regress-crbug-831984.js b/deps/v8/test/mjsunit/regress/regress-crbug-831984.js new file mode 100644 index 00000000000000..c4833232c4edfd --- /dev/null +++ b/deps/v8/test/mjsunit/regress/regress-crbug-831984.js @@ -0,0 +1,10 @@ +// Copyright 2018 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + + +let arr = [...Array(9000)]; +for (let j = 0; j < 40; j++) { + Reflect.ownKeys(arr).shift(); + Array(64386); +} diff --git a/deps/v8/test/mjsunit/regress/wasm/regress-836141.js b/deps/v8/test/mjsunit/regress/wasm/regress-836141.js new file mode 100644 index 00000000000000..b37dbea628de37 --- /dev/null +++ b/deps/v8/test/mjsunit/regress/wasm/regress-836141.js @@ -0,0 +1,20 @@ +// Copyright 2018 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +load('test/mjsunit/wasm/wasm-constants.js'); +load('test/mjsunit/wasm/wasm-module-builder.js'); + +const builder = new WasmModuleBuilder(); +builder.addMemory(16, 32); +builder.addFunction("test", kSig_i_v).addBody([ + kExprI32Const, 12, // i32.const 0 +]); + +let module = new WebAssembly.Module(builder.toBuffer()); +module.then = () => { + // Use setTimeout to get out of the promise chain. + setTimeout(assertUnreachable); +}; + +WebAssembly.instantiate(module); diff --git a/deps/v8/test/mjsunit/regress/wasm/regress-837417.js b/deps/v8/test/mjsunit/regress/wasm/regress-837417.js new file mode 100644 index 00000000000000..572139fac55825 --- /dev/null +++ b/deps/v8/test/mjsunit/regress/wasm/regress-837417.js @@ -0,0 +1,23 @@ +// Copyright 2018 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +load('test/mjsunit/wasm/wasm-constants.js'); +load('test/mjsunit/wasm/wasm-module-builder.js'); + +const builder = new WasmModuleBuilder(); +builder.addMemory(16, 32); +builder.addFunction("test", kSig_i_v).addBody([ + kExprI32Const, 12, // i32.const 0 +]); + +WebAssembly.Module.prototype.then = resolve => resolve( + String.fromCharCode(null, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41)); + +// WebAssembly.instantiate should not actually throw a TypeError in this case. +// However, this is a workaround for +assertPromiseResult( + WebAssembly.instantiate(builder.toBuffer()), assertUnreachable, + exception => { + assertInstanceof(exception, TypeError); + }); diff --git a/deps/v8/third_party/eu-strip/README.v8 b/deps/v8/third_party/eu-strip/README.v8 deleted file mode 100644 index e84974d92b9cec..00000000000000 --- a/deps/v8/third_party/eu-strip/README.v8 +++ /dev/null @@ -1,24 +0,0 @@ -Name: eu-strip -URL: https://sourceware.org/elfutils/ -Version: 0.158 -Security Critical: no -License: LGPL 3 -License File: NOT_SHIPPED - -Description: - -Patched eu-strip from elfutils. - -Build instructions (on Trusty; note that this will build the -Ubuntu-patched version of elfutils): -$ mkdir elfutils -$ cd elfutils -$ apt-get source elfutils -$ cd elfutils-0.158 -[ Edit libelf/elf_end.c and remove the free() on line 164. ] -$ ./configure -$ make -$ gcc -std=gnu99 -Wall -Wshadow -Wunused -Wextra -fgnu89-inline - -Wformat=2 -Werror -g -O2 -Wl,-rpath-link,libelf:libdw -o eu-strip - src/strip.o libebl/libebl.a libelf/libelf.a lib/libeu.a -ldl -$ eu-strip ./eu-strip # Keep the binary small, please. diff --git a/deps/v8/third_party/eu-strip/bin/eu-strip b/deps/v8/third_party/eu-strip/bin/eu-strip deleted file mode 100755 index 994e2263b9185f..00000000000000 Binary files a/deps/v8/third_party/eu-strip/bin/eu-strip and /dev/null differ diff --git a/doc/api/addons.md b/doc/api/addons.md index 3c4c7b39bedfeb..a207a71b717604 100644 --- a/doc/api/addons.md +++ b/doc/api/addons.md @@ -9,7 +9,7 @@ just as if they were an ordinary Node.js module. They are used primarily to provide an interface between JavaScript running in Node.js and C/C++ libraries. At the moment, the method for implementing Addons is rather complicated, -involving knowledge of several components and APIs : +involving knowledge of several components and APIs: - V8: the C++ library Node.js currently uses to provide the JavaScript implementation. V8 provides the mechanisms for creating objects, @@ -93,7 +93,7 @@ There is no semi-colon after `NODE_MODULE` as it's not a function (see `node.h`). The `module_name` must match the filename of the final binary (excluding -the .node suffix). +the `.node` suffix). In the `hello.cc` example, then, the initialization function is `init` and the Addon module name is `addon`. @@ -217,7 +217,6 @@ Addon developers are recommended to use to keep compatibility between past and future releases of V8 and Node.js. See the `nan` [examples][] for an illustration of how it can be used. - ## N-API > Stability: 1 - Experimental @@ -307,7 +306,6 @@ built using `node-gyp`: $ node-gyp configure build ``` - ### Function arguments Addons will typically expose objects and functions that can be accessed from @@ -381,7 +379,6 @@ const addon = require('./build/Release/addon'); console.log('This should be eight:', addon.add(3, 5)); ``` - ### Callbacks It is common practice within Addons to pass JavaScript functions to a C++ @@ -488,7 +485,6 @@ console.log(obj1.msg, obj2.msg); // Prints: 'hello world' ``` - ### Function factory Another common scenario is creating JavaScript functions that wrap C++ @@ -546,7 +542,6 @@ console.log(fn()); // Prints: 'hello world' ``` - ### Wrapping C++ objects It is also possible to wrap C++ objects/classes in a way that allows new @@ -916,7 +911,6 @@ console.log(obj2.plusOne()); // Prints: 23 ``` - ### Passing wrapped objects around In addition to wrapping and returning C++ objects, it is possible to pass @@ -1091,9 +1085,9 @@ console.log(result); ### AtExit hooks -An "AtExit" hook is a function that is invoked after the Node.js event loop +An `AtExit` hook is a function that is invoked after the Node.js event loop has ended but before the JavaScript VM is terminated and Node.js shuts down. -"AtExit" hooks are registered using the `node::AtExit` API. +`AtExit` hooks are registered using the `node::AtExit` API. #### void AtExit(callback, args) @@ -1105,12 +1099,12 @@ has ended but before the JavaScript VM is terminated and Node.js shuts down. Registers exit hooks that run after the event loop has ended but before the VM is killed. -AtExit takes two parameters: a pointer to a callback function to run at exit, +`AtExit` takes two parameters: a pointer to a callback function to run at exit, and a pointer to untyped context data to be passed to that callback. Callbacks are run in last-in first-out order. -The following `addon.cc` implements AtExit: +The following `addon.cc` implements `AtExit`: ```cpp // addon.cc diff --git a/doc/api/assert.md b/doc/api/assert.md index ab4aa9c7cd2499..43e5800ff031b8 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -102,31 +102,25 @@ It can be accessed using: const assert = require('assert').strict; ``` -Example error diff (the `expected`, `actual`, and `Lines skipped` will be on a -single row): +Example error diff: ```js const assert = require('assert').strict; assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); -``` - -```diff -AssertionError [ERR_ASSERTION]: Input A expected to deepStrictEqual input B: -+ expected -- actual -... Lines skipped - - [ - [ -... - 2, -- 3 -+ '3' - ], -... - 5 - ] +// AssertionError: Input A expected to strictly deep-equal input B: +// + expected - actual ... Lines skipped +// +// [ +// [ +// ... +// 2, +// - 3 +// + '3' +// ], +// ... +// 5 +// ] ``` To deactivate the colors, use the `NODE_DISABLE_COLORS` environment variable. @@ -171,10 +165,10 @@ added: v0.1.21 changes: - version: v9.0.0 pr-url: https://github.com/nodejs/node/pull/15001 - description: Error names and messages are now properly compared + description: The `Error` names and messages are now properly compared - version: v8.0.0 pr-url: https://github.com/nodejs/node/pull/12142 - description: Set and Map content is also compared + description: The `Set` and `Map` content is also compared - version: v6.4.0, v4.7.1 pr-url: https://github.com/nodejs/node/pull/8002 description: Typed array slices are handled correctly now. @@ -214,7 +208,7 @@ the [`RegExp`][] object are not enumerable: assert.deepEqual(/a/gi, new Date()); ``` -An exception is made for [`Map`][] and [`Set`][]. Maps and Sets have their +An exception is made for [`Map`][] and [`Set`][]. `Map`s and `Set`s have their contained items compared too, as expected. "Deep" equality means that the enumerable "own" properties of child objects @@ -270,15 +264,15 @@ changes: description: Enumerable symbol properties are now compared. - version: v9.0.0 pr-url: https://github.com/nodejs/node/pull/15036 - description: NaN is now compared using the + description: The `NaN` is now compared using the [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero) comparison. - version: v8.5.0 pr-url: https://github.com/nodejs/node/pull/15001 - description: Error names and messages are now properly compared + description: The `Error` names and messages are now properly compared - version: v8.0.0 pr-url: https://github.com/nodejs/node/pull/12142 - description: Set and Map content is also compared + description: The `Set` and `Map` content is also compared - version: v6.4.0, v4.7.1 pr-url: https://github.com/nodejs/node/pull/8002 description: Typed array slices are handled correctly now. @@ -309,8 +303,8 @@ are recursively evaluated also by the following rules. enumerable properties. * Enumerable own [`Symbol`][] properties are compared as well. * [Object wrappers][] are compared both as objects and unwrapped values. -* Object properties are compared unordered. -* Map keys and Set items are compared unordered. +* `Object` properties are compared unordered. +* `Map` keys and `Set` items are compared unordered. * Recursion stops when both sides differ or both sides encounter a circular reference. * [`WeakMap`][] and [`WeakSet`][] comparison does not rely on their values. See @@ -319,9 +313,14 @@ are recursively evaluated also by the following rules. ```js const assert = require('assert').strict; +// This fails because 1 !== '1'. assert.deepStrictEqual({ a: 1 }, { a: '1' }); -// AssertionError: { a: 1 } deepStrictEqual { a: '1' } -// because 1 !== '1' using SameValue comparison +// AssertionError: Input A expected to strictly deep-equal input B: +// + expected - actual +// { +// - a: 1 +// + a: '1' +// } // The following objects don't have own properties const date = new Date(); @@ -329,33 +328,52 @@ const object = {}; const fakeDate = {}; Object.setPrototypeOf(fakeDate, Date.prototype); +// Different [[Prototype]]: assert.deepStrictEqual(object, fakeDate); -// AssertionError: {} deepStrictEqual Date {} -// Different [[Prototype]] +// AssertionError: Input A expected to strictly deep-equal input B: +// + expected - actual +// - {} +// + Date {} +// Different type tags: assert.deepStrictEqual(date, fakeDate); -// AssertionError: 2017-03-11T14:25:31.849Z deepStrictEqual Date {} -// Different type tags +// AssertionError: Input A expected to strictly deep-equal input B: +// + expected - actual +// - 2018-04-26T00:49:08.604Z +// + Date {} assert.deepStrictEqual(NaN, NaN); // OK, because of the SameValue comparison +// Different unwrapped numbers: assert.deepStrictEqual(new Number(1), new Number(2)); -// Fails because the wrapped number is unwrapped and compared as well. +// AssertionError: Input A expected to strictly deep-equal input B: +// + expected - actual +// - [Number: 1] +// + [Number: 2] + assert.deepStrictEqual(new String('foo'), Object('foo')); // OK because the object and the string are identical when unwrapped. assert.deepStrictEqual(-0, -0); // OK + +// Different zeros using the SameValue Comparison: assert.deepStrictEqual(0, -0); -// AssertionError: 0 deepStrictEqual -0 +// AssertionError: Input A expected to strictly deep-equal input B: +// + expected - actual +// - 0 +// + -0 const symbol1 = Symbol(); const symbol2 = Symbol(); assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 }); // OK, because it is the same symbol on both objects. assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 }); -// Fails because symbol1 !== symbol2! +// AssertionError [ERR_ASSERTION]: Input objects not identical: +// { +// [Symbol()]: 1 +// } const weakMap1 = new WeakMap(); const weakMap2 = new WeakMap([[{}, {}]]); @@ -364,8 +382,16 @@ weakMap3.unequal = true; assert.deepStrictEqual(weakMap1, weakMap2); // OK, because it is impossible to compare the entries + +// Fails because weakMap3 has a property that weakMap1 does not contain: assert.deepStrictEqual(weakMap1, weakMap3); -// Fails because weakMap3 has a property that weakMap1 does not contain! +// AssertionError: Input A expected to strictly deep-equal input B: +// + expected - actual +// WeakMap { +// - [items unknown] +// + [items unknown], +// + unequal: true +// } ``` If the values are not equal, an `AssertionError` is thrown with a `message` @@ -387,10 +413,10 @@ function and awaits the returned promise to complete. It will then check that the promise is not rejected. If `block` is a function and it throws an error synchronously, -`assert.doesNotReject()` will return a rejected Promise with that error. If the -function does not return a promise, `assert.doesNotReject()` will return a -rejected Promise with an [`ERR_INVALID_RETURN_VALUE`][] error. In both cases the -error handler is skipped. +`assert.doesNotReject()` will return a rejected `Promise` with that error. If +the function does not return a promise, `assert.doesNotReject()` will return a +rejected `Promise` with an [`ERR_INVALID_RETURN_VALUE`][] error. In both cases +the error handler is skipped. Please note: Using `assert.doesNotReject()` is actually not useful because there is little benefit by catching a rejection and then rejecting it again. Instead, @@ -468,7 +494,7 @@ assert.doesNotThrow( ``` However, the following will result in an `AssertionError` with the message -'Got unwanted exception (TypeError)..': +'Got unwanted exception...': ```js @@ -493,7 +519,7 @@ assert.doesNotThrow( /Wrong value/, 'Whoops' ); -// Throws: AssertionError: Got unwanted exception (TypeError). Whoops +// Throws: AssertionError: Got unwanted exception: Whoops ``` ## assert.equal(actual, expected[, message]) @@ -630,7 +656,7 @@ changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18247 description: Instead of throwing the original error it is now wrapped into - a AssertionError that contains the full stack trace. + an `AssertionError` that contains the full stack trace. - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18247 description: Value may now only be `undefined` or `null`. Before any truthy @@ -639,7 +665,9 @@ changes: * `value` {any} Throws `value` if `value` is not `undefined` or `null`. This is useful when -testing the `error` argument in callbacks. +testing the `error` argument in callbacks. The stack trace contains all frames +from the error passed to `ifError()` including the potential new frames for +`ifError()` itself. See below for an example. ```js const assert = require('assert').strict; @@ -652,6 +680,19 @@ assert.ifError('error'); // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' assert.ifError(new Error()); // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + +// Create some random error frames. +let err; +(function errorFrame() { + err = new Error('test error'); +})(); + +(function ifErrorFrame() { + assert.ifError(err); +})(); +// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error +// at ifErrorFrame +// at errorFrame ``` ## assert.notDeepEqual(actual, expected[, message]) @@ -660,10 +701,10 @@ added: v0.1.21 changes: - version: v9.0.0 pr-url: https://github.com/nodejs/node/pull/15001 - description: Error names and messages are now properly compared + description: The `Error` names and messages are now properly compared - version: v8.0.0 pr-url: https://github.com/nodejs/node/pull/12142 - description: Set and Map content is also compared + description: The `Set` and `Map` content is also compared - version: v6.4.0, v4.7.1 pr-url: https://github.com/nodejs/node/pull/8002 description: Typed array slices are handled correctly now. @@ -733,18 +774,18 @@ added: v1.2.0 changes: - version: v9.0.0 pr-url: https://github.com/nodejs/node/pull/15398 - description: -0 and +0 are not considered equal anymore. + description: The `-0` and `+0` are not considered equal anymore. - version: v9.0.0 pr-url: https://github.com/nodejs/node/pull/15036 - description: NaN is now compared using the + description: The `NaN` is now compared using the [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero) comparison. - version: v9.0.0 pr-url: https://github.com/nodejs/node/pull/15001 - description: Error names and messages are now properly compared + description: The `Error` names and messages are now properly compared - version: v8.0.0 pr-url: https://github.com/nodejs/node/pull/12142 - description: Set and Map content is also compared + description: The `Set` and `Map` content is also compared - version: v6.4.0, v4.7.1 pr-url: https://github.com/nodejs/node/pull/8002 description: Typed array slices are handled correctly now. @@ -834,7 +875,7 @@ assert.notStrictEqual(1, 2); // OK assert.notStrictEqual(1, 1); -// AssertionError: 1 notStrictEqual 1 +// AssertionError [ERR_ASSERTION]: Identical input passed to notStrictEqual: 1 assert.notStrictEqual(1, '1'); // OK @@ -852,7 +893,8 @@ added: v0.1.21 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18319 - description: assert.ok() (no arguments) will now use a predefined error msg. + description: The `assert.ok()` (no arguments) will now use a predefined + error message. --> * `value` {any} * `message` {any} @@ -866,7 +908,7 @@ parameter is `undefined`, a default error message is assigned. If the `message` parameter is an instance of an [`Error`][] then it will be thrown instead of the `AssertionError`. If no arguments are passed in at all `message` will be set to the string: -"No value argument passed to assert.ok". +``'No value argument passed to `assert.ok()`'``. Be aware that in the `repl` the error message will be different to the one thrown in a file! See below for further details. @@ -880,40 +922,34 @@ assert.ok(1); // OK assert.ok(); -// throws: -// "AssertionError: No value argument passed to `assert.ok`. +// AssertionError: No value argument passed to `assert.ok()` assert.ok(false, 'it\'s false'); -// throws "AssertionError: it's false" +// AssertionError: it's false // In the repl: assert.ok(typeof 123 === 'string'); -// throws: -// "AssertionError: false == true +// AssertionError: false == true // In a file (e.g. test.js): assert.ok(typeof 123 === 'string'); -// throws: -// "AssertionError: The expression evaluated to a falsy value: +// AssertionError: The expression evaluated to a falsy value: // // assert.ok(typeof 123 === 'string') assert.ok(false); -// throws: -// "AssertionError: The expression evaluated to a falsy value: +// AssertionError: The expression evaluated to a falsy value: // // assert.ok(false) assert.ok(0); -// throws: -// "AssertionError: The expression evaluated to a falsy value: +// AssertionError: The expression evaluated to a falsy value: // // assert.ok(0) // Using `assert()` works the same: assert(0); -// throws: -// "AssertionError: The expression evaluated to a falsy value: +// AssertionError: The expression evaluated to a falsy value: // // assert(0) ``` @@ -931,9 +967,9 @@ function and awaits the returned promise to complete. It will then check that the promise is rejected. If `block` is a function and it throws an error synchronously, -`assert.rejects()` will return a rejected Promise with that error. If the +`assert.rejects()` will return a rejected `Promise` with that error. If the function does not return a promise, `assert.rejects()` will return a rejected -Promise with an [`ERR_INVALID_RETURN_VALUE`][] error. In both cases the error +`Promise` with an [`ERR_INVALID_RETURN_VALUE`][] error. In both cases the error handler is skipped. Besides the async nature to await the completion behaves identically to @@ -995,13 +1031,19 @@ determined by the [SameValue Comparison][]. const assert = require('assert').strict; assert.strictEqual(1, 2); -// AssertionError: 1 strictEqual 2 +// AssertionError [ERR_ASSERTION]: Input A expected to strictly equal input B: +// + expected - actual +// - 1 +// + 2 assert.strictEqual(1, 1); // OK assert.strictEqual(1, '1'); -// AssertionError: 1 strictEqual '1' +// AssertionError [ERR_ASSERTION]: Input A expected to strictly equal input B: +// + expected - actual +// - 1 +// + '1' ``` If the values are not strictly equal, an `AssertionError` is thrown with a @@ -1035,6 +1077,34 @@ each property will be tested for including the non-enumerable `message` and If specified, `message` will be the message provided by the `AssertionError` if the block fails to throw. +Custom error object / error instance: + +```js +const err = new TypeError('Wrong value'); +err.code = 404; + +assert.throws( + () => { + throw err; + }, + { + name: 'TypeError', + message: 'Wrong value' + // Note that only properties on the error object will be tested! + } +); + +// Fails due to the different `message` and `name` properties: +assert.throws( + () => { + const otherErr = new Error('Not found'); + otherErr.code = 404; + throw otherErr; + }, + err // This tests for `message`, `name` and `code`. +); +``` + Validate instanceof using constructor: ```js @@ -1076,39 +1146,12 @@ assert.throws( ); ``` -Custom error object / error instance: - -```js -const err = new TypeError('Wrong value'); -err.code = 404; - -assert.throws( - () => { - throw err; - }, - { - name: 'TypeError', - message: 'Wrong value' - // Note that only properties on the error object will be tested! - } -); - -// Fails due to the different `message` and `name` properties: -assert.throws( - () => { - const otherErr = new Error('Not found'); - otherErr.code = 404; - throw otherErr; - }, - err // This tests for `message`, `name` and `code`. -); -``` - Note that `error` cannot be a string. If a string is provided as the second argument, then `error` is assumed to be omitted and the string will be used for -`message` instead. This can lead to easy-to-miss mistakes. Please read the -example below carefully if using a string as the second argument gets -considered: +`message` instead. This can lead to easy-to-miss mistakes. Using the same +message as the thrown error message is going to result in an +`ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using +a string as the second argument gets considered: ```js @@ -1121,10 +1164,15 @@ function throwingSecond() { function notThrowing() {} // The second argument is a string and the input function threw an Error. -// In that case both cases do not throw as neither is going to try to -// match for the error message thrown by the input function! +// The first case will not throw as it does not match for the error message +// thrown by the input function! assert.throws(throwingFirst, 'Second'); +// In the next example the message has no benefit over the message from the +// error and since it is not clear if the user intended to actually match +// against the error message, Node.js thrown an `ERR_AMBIGUOUS_ARGUMENT` error. assert.throws(throwingSecond, 'Second'); +// Throws an error: +// TypeError [ERR_AMBIGUOUS_ARGUMENT] // The string is only used (as message) in case the function does not throw: assert.throws(notThrowing, 'Second'); @@ -1134,7 +1182,7 @@ assert.throws(notThrowing, 'Second'); assert.throws(throwingSecond, /Second$/); // Does not throw because the error messages match. assert.throws(throwingFirst, /Second$/); -// Throws a error: +// Throws an error: // Error: First // at throwingFirst (repl:2:9) ``` diff --git a/doc/api/async_hooks.md b/doc/api/async_hooks.md index 2628cc290a5660..b97bc73304a4d7 100644 --- a/doc/api/async_hooks.md +++ b/doc/api/async_hooks.md @@ -17,8 +17,8 @@ const async_hooks = require('async_hooks'); An asynchronous resource represents an object with an associated callback. This callback may be called multiple times, for example, the `'connection'` event in `net.createServer()`, or just a single time like in `fs.open()`. -A resource can also be closed before the callback is called. AsyncHook does not -explicitly distinguish between these different cases but will represent them +A resource can also be closed before the callback is called. `AsyncHook` does +not explicitly distinguish between these different cases but will represent them as the abstract concept that is a resource. ## Public API @@ -141,7 +141,6 @@ future. This is subject to change in the future if a comprehensive analysis is performed to ensure an exception can follow the normal control flow without unintentional side effects. - ##### Printing in AsyncHooks callbacks Because printing to the console is an asynchronous operation, `console.log()` @@ -189,7 +188,7 @@ const hook = async_hooks.createHook(callbacks).enable(); * Returns: {AsyncHook} A reference to `asyncHook`. Disable the callbacks for a given `AsyncHook` instance from the global pool of -AsyncHook callbacks to be executed. Once a hook has been disabled it will not +`AsyncHook` callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. For API consistency `disable()` also returns the `AsyncHook` instance. @@ -257,7 +256,6 @@ the new resource to initialize and that caused `init` to call. This is different from `async_hooks.executionAsyncId()` that only shows *when* a resource was created, while `triggerAsyncId` shows *why* a resource was created. - The following is a simple demonstration of `triggerAsyncId`: ```js @@ -301,10 +299,10 @@ and document their own resource objects. For example, such a resource object could contain the SQL query being executed. In the case of Promises, the `resource` object will have `promise` property -that refers to the Promise that is being initialized, and a `isChainedPromise` -property, set to `true` if the promise has a parent promise, and `false` -otherwise. For example, in the case of `b = a.then(handler)`, `a` is considered -a parent Promise of `b`. Here, `b` is considered a chained promise. +that refers to the `Promise` that is being initialized, and an +`isChainedPromise` property, set to `true` if the promise has a parent promise, +and `false` otherwise. For example, in the case of `b = a.then(handler)`, `a` is +considered a parent `Promise` of `b`. Here, `b` is considered a chained promise. In some cases the resource object is reused for performance reasons, it is thus not safe to use it as a key in a `WeakMap` or add properties to it. @@ -395,7 +393,6 @@ API the user's callback is placed in a `process.nextTick()`. The graph only shows *when* a resource was created, not *why*, so to track the *why* use `triggerAsyncId`. - ##### before(asyncId) * `asyncId` {number} @@ -413,7 +410,6 @@ asynchronous resources like a TCP server will typically call the `before` callback multiple times, while other operations like `fs.open()` will call it only once. - ##### after(asyncId) * `asyncId` {number} @@ -424,7 +420,6 @@ If an uncaught exception occurs during execution of the callback, then `after` will run *after* the `'uncaughtException'` event is emitted or a `domain`'s handler runs. - ##### destroy(asyncId) * `asyncId` {number} @@ -471,7 +466,7 @@ added: v8.1.0 changes: - version: v8.2.0 pr-url: https://github.com/nodejs/node/pull/13490 - description: Renamed from currentId + description: Renamed from `currentId` --> * Returns: {number} The `asyncId` of the current execution context. Useful to @@ -503,7 +498,7 @@ const server = net.createServer(function onConnection(conn) { }); ``` -Note that promise contexts may not get precise executionAsyncIds by default. +Note that promise contexts may not get precise `executionAsyncIds` by default. See the section on [promise execution tracking][]. #### async_hooks.triggerAsyncId() @@ -526,12 +521,12 @@ const server = net.createServer((conn) => { }); ``` -Note that promise contexts may not get valid triggerAsyncIds by default. See +Note that promise contexts may not get valid `triggerAsyncId`s by default. See the section on [promise execution tracking][]. ## Promise execution tracking -By default, promise executions are not assigned asyncIds due to the relatively +By default, promise executions are not assigned `asyncId`s due to the relatively expensive nature of the [promise introspection API][PromiseHooks] provided by V8. This means that programs using promises or `async`/`await` will not get correct execution and trigger ids for promise callback contexts by default. @@ -547,10 +542,10 @@ Promise.resolve(1729).then(() => { // eid 1 tid 0 ``` -Observe that the `then` callback claims to have executed in the context of the +Observe that the `then()` callback claims to have executed in the context of the outer scope even though there was an asynchronous hop involved. Also note that -the triggerAsyncId value is 0, which means that we are missing context about the -resource that caused (triggered) the `then` callback to be executed. +the `triggerAsyncId` value is `0`, which means that we are missing context about +the resource that caused (triggered) the `then()` callback to be executed. Installing async hooks via `async_hooks.createHook` enables promise execution tracking. Example: @@ -567,15 +562,16 @@ Promise.resolve(1729).then(() => { In this example, adding any actual hook function enabled the tracking of promises. There are two promises in the example above; the promise created by -`Promise.resolve()` and the promise returned by the call to `then`. In the -example above, the first promise got the asyncId 6 and the latter got asyncId 7. -During the execution of the `then` callback, we are executing in the context of -promise with asyncId 7. This promise was triggered by async resource 6. +`Promise.resolve()` and the promise returned by the call to `then()`. In the +example above, the first promise got the `asyncId` `6` and the latter got +`asyncId` `7`. During the execution of the `then()` callback, we are executing +in the context of promise with `asyncId` `7`. This promise was triggered by +async resource `6`. Another subtlety with promises is that `before` and `after` callbacks are run -only on chained promises. That means promises not created by `then`/`catch` will -not have the `before` and `after` callbacks fired on them. For more details see -the details of the V8 [PromiseHooks][] API. +only on chained promises. That means promises not created by `then()`/`catch()` +will not have the `before` and `after` callbacks fired on them. For more details +see the details of the V8 [PromiseHooks][] API. ## JavaScript Embedder API @@ -637,8 +633,9 @@ asyncResource.emitAfter(); async event. **Default:** `executionAsyncId()`. * `requireManualDestroy` {boolean} Disables automatic `emitDestroy` when the object is garbage collected. This usually does not need to be set (even if - `emitDestroy` is called manually), unless the resource's asyncId is retrieved - and the sensitive API's `emitDestroy` is called with it. **Default:** `false`. + `emitDestroy` is called manually), unless the resource's `asyncId` is + retrieved and the sensitive API's `emitDestroy` is called with it. + **Default:** `false`. Example usage: diff --git a/doc/api/buffer.md b/doc/api/buffer.md index 0195c1cd2651d8..c219f00e4a1f48 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -221,7 +221,7 @@ elements, and not as a byte array of the target type. That is, `[0x1020304]` or `[0x4030201]`. It is possible to create a new `Buffer` that shares the same allocated memory as -a [`TypedArray`] instance by using the TypeArray object's `.buffer` property. +a [`TypedArray`] instance by using the `TypeArray` object's `.buffer` property. ```js const arr = new Uint16Array(2); @@ -427,7 +427,8 @@ changes: run from code outside the `node_modules` directory. - version: v8.0.0 pr-url: https://github.com/nodejs/node/pull/12141 - description: new Buffer(size) will return zero-filled memory by default. + description: The `new Buffer(size)` will return zero-filled memory by + default. - version: v7.2.1 pr-url: https://github.com/nodejs/node/pull/9529 description: Calling this constructor no longer emits a deprecation warning. @@ -980,8 +981,8 @@ console.log(buf.toString('ascii')); ### buf.buffer -The `buffer` property references the underlying `ArrayBuffer` object based on -which this Buffer object is created. +* {ArrayBuffer} The underlying `ArrayBuffer` object based on + which this `Buffer` object is created. ```js const arrayBuffer = new ArrayBuffer(16); @@ -1507,8 +1508,8 @@ added: v0.11.15 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `offset` {integer} Number of bytes to skip before starting to read. Must @@ -1537,8 +1538,8 @@ added: v0.11.15 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `offset` {integer} Number of bytes to skip before starting to read. Must @@ -1566,8 +1567,8 @@ added: v0.5.0 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `offset` {integer} Number of bytes to skip before starting to read. Must @@ -1596,8 +1597,8 @@ added: v0.5.5 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `offset` {integer} Number of bytes to skip before starting to read. Must @@ -1628,8 +1629,8 @@ added: v0.5.5 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `offset` {integer} Number of bytes to skip before starting to read. Must @@ -1660,8 +1661,8 @@ added: v0.11.15 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset and - byteLength to uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + and `byteLength` to `uint32` anymore. --> * `offset` {integer} Number of bytes to skip before starting to read. Must @@ -1693,8 +1694,8 @@ added: v0.5.0 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `offset` {integer} Number of bytes to skip before starting to read. Must @@ -1721,8 +1722,8 @@ added: v0.5.5 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `offset` {integer} Number of bytes to skip before starting to read. Must @@ -1755,8 +1756,8 @@ added: v0.5.5 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `offset` {integer} Number of bytes to skip before starting to read. Must @@ -1785,8 +1786,8 @@ added: v0.11.15 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset and - byteLength to uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + and `byteLength` to `uint32` anymore. --> * `offset` {integer} Number of bytes to skip before starting to read. Must @@ -2102,8 +2103,8 @@ added: v0.11.15 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `value` {number} Number to be written to `buf`. @@ -2137,8 +2138,8 @@ added: v0.11.15 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `value` {number} Number to be written to `buf`. @@ -2171,8 +2172,8 @@ added: v0.5.0 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `value` {integer} Number to be written to `buf`. @@ -2203,8 +2204,8 @@ added: v0.5.5 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `value` {integer} Number to be written to `buf`. @@ -2236,8 +2237,8 @@ added: v0.5.5 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `value` {integer} Number to be written to `buf`. @@ -2269,8 +2270,8 @@ added: v0.11.15 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset and - byteLength to uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + and `byteLength` to `uint32` anymore. --> * `value` {integer} Number to be written to `buf`. @@ -2304,8 +2305,8 @@ added: v0.5.0 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `value` {integer} Number to be written to `buf`. @@ -2336,8 +2337,8 @@ added: v0.5.5 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `value` {integer} Number to be written to `buf`. @@ -2373,8 +2374,8 @@ added: v0.5.5 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset to - uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + to `uint32` anymore. --> * `value` {integer} Number to be written to `buf`. @@ -2408,8 +2409,8 @@ added: v0.5.5 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/18395 - description: Removed noAssert and no implicit coercion of the offset and - byteLength to uint32 anymore. + description: Removed `noAssert` and no implicit coercion of the offset + and `byteLength` to `uint32` anymore. --> * `value` {integer} Number to be written to `buf`. @@ -2458,7 +2459,7 @@ added: v3.0.0 * {integer} The largest size allowed for a single `Buffer` instance. -An alias for [`buffer.constants.MAX_LENGTH`][] +An alias for [`buffer.constants.MAX_LENGTH`][]. Note that this is a property on the `buffer` module returned by `require('buffer')`, not on the `Buffer` global or a `Buffer` instance. diff --git a/doc/api/child_process.md b/doc/api/child_process.md index 6e26cd8be8d064..1fc2855e4f65f5 100644 --- a/doc/api/child_process.md +++ b/doc/api/child_process.md @@ -211,7 +211,7 @@ Unlike the exec(3) POSIX system call, `child_process.exec()` does not replace the existing process and uses a shell to execute the command. If this method is invoked as its [`util.promisify()`][]ed version, it returns -a Promise for an object with `stdout` and `stderr` properties. In case of an +a `Promise` for an `Object` with `stdout` and `stderr` properties. In case of an error (including any error resulting in an exit code other than 0), a rejected promise is returned, with the same `error` object given in the callback, but with an additional two properties `stdout` and `stderr`. @@ -290,7 +290,7 @@ stderr output. If `encoding` is `'buffer'`, or an unrecognized character encoding, `Buffer` objects will be passed to the callback instead. If this method is invoked as its [`util.promisify()`][]ed version, it returns -a Promise for an object with `stdout` and `stderr` properties. In case of an +a `Promise` for an `Object` with `stdout` and `stderr` properties. In case of an error (including any error resulting in an exit code other than 0), a rejected promise is returned, with the same `error` object given in the callback, but with an additional two properties `stdout` and `stderr`. @@ -456,7 +456,6 @@ ls.on('close', (code) => { }); ``` - Example: A very elaborate way to run `ps ax | grep ssh` ```js @@ -494,7 +493,6 @@ grep.on('close', (code) => { }); ``` - Example of checking for failed `spawn`: ```js @@ -654,7 +652,7 @@ child registers an event handler for the [`'disconnect'`][] event or the [`'message'`][] event. This allows the child to exit normally without the process being held open by the open IPC channel.* -See also: [`child_process.exec()`][] and [`child_process.fork()`][] +See also: [`child_process.exec()`][] and [`child_process.fork()`][]. ## Synchronous Process Creation @@ -778,7 +776,7 @@ process has exited.* If the process times out or has a non-zero exit code, this method ***will*** throw. The [`Error`][] object will contain the entire result from -[`child_process.spawnSync()`][] +[`child_process.spawnSync()`][]. **Never pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.** @@ -1058,7 +1056,7 @@ does not indicate that the child process has been terminated. added: v0.1.90 --> -* {number} Integer +* {integer} Returns the process identifier (PID) of the child process. diff --git a/doc/api/cli.md b/doc/api/cli.md index 164e370fff5e15..6d055d9d03a6dd 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -8,7 +8,6 @@ debugging, multiple ways to execute scripts, and other helpful runtime options. To view this documentation as a manual page in a terminal, run `man node`. - ## Synopsis `node [options] [V8 options] [script.js | -e "script" | -] [--] [arguments]` @@ -21,7 +20,6 @@ Execute without arguments to start the [REPL][]. _For more info about `node debug`, please see the [debugger][] documentation._ - ## Options ### `-` @@ -33,7 +31,6 @@ Alias for stdin, analogous to the use of - in other command line utilities, meaning that the script will be read from stdin, and the rest of the options are passed to that script. - ### `--` Enable FIPS-compliant crypto at startup. (Requires Node.js to be built with -`./configure --openssl-fips`) - +`./configure --openssl-fips`.) ### `--experimental-modules` Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.) -(Same requirements as `--enable-fips`) - +(Same requirements as `--enable-fips`.) ### `--icu-data-dir=file` -Specify ICU data load path. (overrides `NODE_ICU_DATA`) - +Specify ICU data load path. (Overrides `NODE_ICU_DATA`.) ### `--inspect-brk[=[host:]port]` -Activate inspector on host:port and break at start of user script. -Default host:port is 127.0.0.1:9229. - +Activate inspector on `host:port` and break at start of user script. +Default `host:port` is `127.0.0.1:9229`. ### `--inspect-port=[host:]port` -Set the host:port to be used when the inspector is activated. +Set the `host:port` to be used when the inspector is activated. Useful when activating the inspector by sending the `SIGUSR1` signal. -Default host is 127.0.0.1. - +Default host is `127.0.0.1`. ### `--inspect[=[host:]port]` -Activate inspector on host:port. Default is 127.0.0.1:9229. +Activate inspector on `host:port`. Default is `127.0.0.1:9229`. V8 inspector integration allows tools such as Chrome DevTools and IDEs to debug and profile Node.js instances. The tools attach to Node.js instances via a tcp port and communicate using the [Chrome DevTools Protocol][]. - ### `--napi-modules` -Enable loading native modules compiled with the ABI-stable Node.js API (N-API) -(experimental). - +This option is a no-op. It is kept for compatibility. ### `--no-deprecation` -Specify an alternative default TLS cipher list. (Requires Node.js to be built -with crypto support. (Default)) - +Specify an alternative default TLS cipher list. Requires Node.js to be built +with crypto support (default). ### `--trace-deprecation` -Data path for ICU (Intl object) data. Will extend linked-in data when compiled +Data path for ICU (`Intl` object) data. Will extend linked-in data when compiled with small-icu support. - ### `NODE_NO_WARNINGS=1` -A Worker object contains all public information and method about a worker. +A `Worker` object contains all public information and method about a worker. In the master it can be obtained using `cluster.workers`. In a worker it can be obtained using `cluster.worker`. @@ -363,7 +363,7 @@ Each new worker is given its own unique id, this id is stored in the `id`. While a worker is alive, this is the key that indexes it in -cluster.workers +`cluster.workers`. ### worker.isConnected() -* `settings` {Object} see [`cluster.settings`][] +* `settings` {Object} See [`cluster.settings`][]. `setupMaster` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`. @@ -813,10 +813,10 @@ A hash that stores the active worker objects, keyed by `id` field. Makes it easy to loop through all the workers. It is only available in the master process. -A worker is removed from cluster.workers after the worker has disconnected _and_ -exited. The order between these two events cannot be determined in advance. -However, it is guaranteed that the removal from the cluster.workers list happens -before last `'disconnect'` or `'exit'` event is emitted. +A worker is removed from `cluster.workers` after the worker has disconnected +_and_ exited. The order between these two events cannot be determined in +advance. However, it is guaranteed that the removal from the `cluster.workers` +list happens before last `'disconnect'` or `'exit'` event is emitted. ```js // Go through all workers @@ -840,12 +840,12 @@ socket.on('data', (id) => { [`ChildProcess.send()`]: child_process.html#child_process_subprocess_send_message_sendhandle_options_callback [`child_process.fork()`]: child_process.html#child_process_child_process_fork_modulepath_args_options +[`child_process` event: `'exit'`]: child_process.html#child_process_event_exit +[`child_process` event: `'message'`]: child_process.html#child_process_event_message +[`cluster.settings`]: #cluster_cluster_settings [`disconnect`]: child_process.html#child_process_subprocess_disconnect [`kill`]: process.html#process_process_kill_pid_signal [`process` event: `'message'`]: process.html#process_event_message [`server.close()`]: net.html#net_event_close [`worker.exitedAfterDisconnect`]: #cluster_worker_exitedafterdisconnect [Child Process module]: child_process.html#child_process_child_process_fork_modulepath_args_options -[child_process event: `'exit'`]: child_process.html#child_process_event_exit -[child_process event: `'message'`]: child_process.html#child_process_event_message -[`cluster.settings`]: #cluster_cluster_settings diff --git a/doc/api/console.md b/doc/api/console.md index 825ca28e28a537..5ef55e63da27c6 100644 --- a/doc/api/console.md +++ b/doc/api/console.md @@ -63,7 +63,6 @@ changes: will now be ignored by default. --> - The `Console` class can be used to create a simple logger with configurable @@ -100,7 +99,7 @@ changes: Setting to `true` enables coloring while inspecting values, setting to `'auto'` will make color support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the respective stream. - **Default:** `'auto'` + **Default:** `'auto'`. Creates a new `Console` with one or two writable stream instances. `stdout` is a writable stream to print log or info output. `stderr` is used for warning or @@ -165,7 +164,7 @@ operates similarly to the `clear` shell command. On Windows, `console.clear()` will clear only the output in the current terminal viewport for the Node.js binary. -### console.count([label]) +### console.count([label='default']) @@ -354,7 +353,7 @@ added: v10.0.0 * `properties` {string[]} Alternate properties for constructing the table. Try to construct a table with the columns of the properties of `tabularData` -(or use `properties`) and rows of `tabularData` and logit. Falls back to just +(or use `properties`) and rows of `tabularData` and log it. Falls back to just logging the argument if it can’t be parsed as tabular. ```js @@ -364,9 +363,7 @@ console.table(Symbol()); console.table(undefined); // undefined -``` -```js console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); // ┌─────────┬─────┬─────┐ // │ (index) │ a │ b │ @@ -374,9 +371,7 @@ console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); // │ 0 │ 1 │ 'Y' │ // │ 1 │ 'Z' │ 2 │ // └─────────┴─────┴─────┘ -``` -```js console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); // ┌─────────┬─────┐ // │ (index) │ a │ @@ -495,17 +490,6 @@ current JavaScript CPU profiling session if one has been started and prints the report to the **Profiles** panel of the inspector. See [`console.profile()`][] for an example. -### console.table(array[, columns]) - -* `array` {Array|Object} -* `columns` {string[]} Display only selected properties of objects in the - `array`. - -This method does not display anything unless used in the inspector. Prints to -`stdout` the array `array` formatted as a table. - ### console.timeStamp([label]) -* `port` {number} Integer. +* `port` {integer} * `address` {string} * `callback` {Function} with no parameters. Called when binding is complete. @@ -264,7 +264,7 @@ added: v0.1.99 changes: - version: v8.0.0 pr-url: https://github.com/nodejs/node/pull/11985 - description: The `msg` parameter can be an Uint8Array now. + description: The `msg` parameter can be an `Uint8Array` now. - version: v8.0.0 pr-url: https://github.com/nodejs/node/pull/10473 description: The `address` parameter is always optional now. @@ -279,9 +279,9 @@ changes: --> * `msg` {Buffer|Uint8Array|string|Array} Message to be sent. -* `offset` {number} Integer. Offset in the buffer where the message starts. -* `length` {number} Integer. Number of bytes in the message. -* `port` {number} Integer. Destination port. +* `offset` {integer} Offset in the buffer where the message starts. +* `length` {integer} Number of bytes in the message. +* `port` {integer} Destination port. * `address` {string} Destination hostname or IP address. * `callback` {Function} Called when the message has been sent. @@ -464,7 +464,6 @@ A socket's address family's ANY address (IPv4 `'0.0.0.0'` or IPv6 `'::'`) can be used to return control of the sockets default outgoing interface to the system for future multicast packets. - ### socket.setMulticastLoopback(flag) -* `ttl` {number} Integer. +* `ttl` {integer} Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for "Time to Live", in this context it specifies the number of IP hops that a @@ -496,7 +495,7 @@ between 0 and 255. The default on most systems is `1` but can vary. added: v8.7.0 --> -* `size` {number} Integer +* `size` {integer} Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer in bytes. @@ -506,7 +505,7 @@ in bytes. added: v8.7.0 --> -* `size` {number} Integer +* `size` {integer} Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer in bytes. @@ -516,7 +515,7 @@ in bytes. added: v0.1.101 --> -* `ttl` {number} Integer. +* `ttl` {integer} Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", in this context it specifies the number of IP hops that a packet is allowed to diff --git a/doc/api/dns.md b/doc/api/dns.md index a878ad27177b7d..e8932be9e387cd 100644 --- a/doc/api/dns.md +++ b/doc/api/dns.md @@ -194,7 +194,7 @@ dns.lookup('example.com', options, (err, addresses) => ``` If this method is invoked as its [`util.promisify()`][]ed version, and `all` -is not set to `true`, it returns a Promise for an object with `address` and +is not set to `true`, it returns a `Promise` for an `Object` with `address` and `family` properties. ### Supported getaddrinfo flags @@ -238,7 +238,7 @@ dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { ``` If this method is invoked as its [`util.promisify()`][]ed version, it returns a -Promise for an object with `hostname` and `service` properties. +`Promise` for an `Object` with `hostname` and `service` properties. ## dns.resolve(hostname[, rrtype], callback) -If domains are in use, then all **new** EventEmitter objects (including +If domains are in use, then all **new** `EventEmitter` objects (including Stream objects, requests, responses, etc.) will be implicitly bound to the active domain at the time of their creation. Additionally, callbacks passed to lowlevel event loop requests (such as -to fs.open, or other callback-taking methods) will automatically be +to `fs.open()`, or other callback-taking methods) will automatically be bound to the active domain. If they throw, then the domain will catch the error. -In order to prevent excessive memory usage, Domain objects themselves +In order to prevent excessive memory usage, `Domain` objects themselves are not implicitly added as children of the active domain. If they were, then it would be too easy to prevent request and response objects from being properly garbage collected. -To nest Domain objects as children of a parent Domain they must be explicitly -added. +To nest `Domain` objects as children of a parent `Domain` they must be +explicitly added. Implicit binding routes thrown errors and `'error'` events to the -Domain's `'error'` event, but does not register the EventEmitter on the -Domain. +`Domain`'s `'error'` event, but does not register the `EventEmitter` on the +`Domain`. Implicit binding only takes care of thrown errors and `'error'` events. ## Explicit Binding @@ -271,14 +271,12 @@ serverDomain.run(() => { * Returns: {Domain} -Returns a new Domain object. - ## Class: Domain -The Domain class encapsulates the functionality of routing errors and -uncaught exceptions to the active Domain object. +The `Domain` class encapsulates the functionality of routing errors and +uncaught exceptions to the active `Domain` object. -Domain is a child class of [`EventEmitter`][]. To handle the errors that it +`Domain` is a child class of [`EventEmitter`][]. To handle the errors that it catches, listen to its `'error'` event. ### domain.members @@ -301,7 +299,7 @@ This also works with timers that are returned from [`setInterval()`][] and [`setTimeout()`][]. If their callback function throws, it will be caught by the domain `'error'` handler. -If the Timer or EventEmitter was already bound to a domain, it is removed +If the Timer or `EventEmitter` was already bound to a domain, it is removed from that one, and bound to this one instead. ### domain.bind(callback) @@ -444,7 +442,7 @@ than crashing the program. ## Domains and Promises As of Node.js 8.0.0, the handlers of Promises are run inside the domain in -which the call to `.then` or `.catch` itself was made: +which the call to `.then()` or `.catch()` itself was made: ```js const d1 = domain.create(); @@ -481,7 +479,7 @@ d2.run(() => { ``` Note that domains will not interfere with the error handling mechanisms for -Promises, i.e. no `'error'` event will be emitted for unhandled Promise +Promises, i.e. no `'error'` event will be emitted for unhandled `Promise` rejections. [`Error`]: errors.html#errors_class_error diff --git a/doc/api/errors.md b/doc/api/errors.md index df81718e7d7fb0..a2489c6ac2e7e7 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -18,7 +18,7 @@ errors: as attempting to open a file that does not exist, attempting to send data over a closed socket, etc; - And User-specified errors triggered by application code. -- Assertion Errors are a special class of error that can be triggered whenever +- `AssertionError`s are a special class of error that can be triggered whenever Node.js detects an exceptional logic violation that should never occur. These are raised typically by the `assert` module. @@ -32,7 +32,7 @@ to provide *at least* the properties available on that class. Node.js supports several mechanisms for propagating and handling errors that occur while an application is running. How these errors are reported and -handled depends entirely on the type of Error and the style of the API that is +handled depends entirely on the type of `Error` and the style of the API that is called. All JavaScript errors are handled as exceptions that *immediately* generate @@ -107,7 +107,7 @@ pass or fail). For *all* [`EventEmitter`][] objects, if an `'error'` event handler is not provided, the error will be thrown, causing the Node.js process to report an -unhandled exception and crash unless either: The [`domain`][domains] module is +uncaught exception and crash unless either: The [`domain`][domains] module is used appropriately or a handler has been registered for the [`'uncaughtException'`][] event. @@ -137,7 +137,7 @@ pattern referred to as an _error-first callback_ (sometimes referred to as a _Node.js style callback_). With this pattern, a callback function is passed to the method as an argument. When the operation either completes or an error is raised, the callback function is called with -the Error object (if any) passed as the first argument. If no error was +the `Error` object (if any) passed as the first argument. If no error was raised, the first argument will be passed as `null`. ```js @@ -422,7 +422,7 @@ they may only be caught by other contexts. A subclass of `Error` that indicates that a provided argument is not an allowable type. For example, passing a function to a parameter which expects a -string would be considered a TypeError. +string would be considered a `TypeError`. ```js require('url').parse(() => { }); @@ -440,7 +440,7 @@ A JavaScript exception is a value that is thrown as a result of an invalid operation or as the target of a `throw` statement. While it is not required that these values are instances of `Error` or classes which inherit from `Error`, all exceptions thrown by Node.js or the JavaScript runtime *will* be -instances of Error. +instances of `Error`. Some exceptions are *unrecoverable* at the JavaScript layer. Such exceptions will *always* cause the Node.js process to crash. Examples include `assert()` @@ -479,7 +479,6 @@ The following properties are provided: * `dest` {Buffer} When reporting a file system error, the `dest` will identify the file path destination (if any). - #### error.code * {string} @@ -493,7 +492,7 @@ typically `E` followed by a sequence of capital letters. The `error.errno` property is a number or a string. The number is a **negative** value which corresponds to the error code defined -in [`libuv Error handling`]. See uv-errno.h header file +in [`libuv Error handling`]. See `uv-errno.h` header file (`deps/uv/include/uv-errno.h` in the Node.js source tree) for details. In case of a string, it is the same as `error.code`. @@ -1082,7 +1081,7 @@ An invalid or unsupported value was passed for a given argument. ### ERR_INVALID_ARRAY_LENGTH -An Array was not of the expected length or in a valid range. +An array was not of the expected length or in a valid range. ### ERR_INVALID_ASYNC_ID @@ -1517,7 +1516,7 @@ length. ### ERR_TLS_CERT_ALTNAME_INVALID While using TLS, the hostname/IP of the peer did not match any of the -subjectAltNames in its certificate. +`subjectAltNames` in its certificate. ### ERR_TLS_DH_PARAM_SIZE @@ -1571,12 +1570,12 @@ the `--without-v8-platform` flag. ### ERR_TRANSFORM_ALREADY_TRANSFORMING -A Transform stream finished while it was still transforming. +A `Transform` stream finished while it was still transforming. ### ERR_TRANSFORM_WITH_LENGTH_0 -A Transform stream finished with data still in the write buffer. +A `Transform` stream finished with data still in the write buffer. ### ERR_TTY_INIT_FAILED @@ -1646,7 +1645,7 @@ itself, although it is possible for user code to trigger it. ### ERR_V8BREAKITERATOR -The V8 BreakIterator API was used but the full ICU data set is not installed. +The V8 `BreakIterator` API was used but the full ICU data set is not installed. ### ERR_VALID_PERFORMANCE_ENTRY_TYPE @@ -1657,7 +1656,7 @@ entry types were found. ### ERR_VALUE_OUT_OF_RANGE -Superseded by `ERR_OUT_OF_RANGE` +Superseded by `ERR_OUT_OF_RANGE`. ### ERR_VM_MODULE_ALREADY_LINKED diff --git a/doc/api/esm.md b/doc/api/esm.md index 4090e545fdb54b..a1e3cb149ab7d8 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -134,8 +134,8 @@ export async function resolve(specifier, } ``` -The parentURL is provided as `undefined` when performing main Node.js load -itself. +The `parentModuleURL` is provided as `undefined` when performing main Node.js +load itself. The default Node.js ES module resolution function is provided as a third argument to the resolver for easy compatibility workflows. diff --git a/doc/api/events.md b/doc/api/events.md index a5a45ca3de4834..0dd9e4be5dbc6d 100644 --- a/doc/api/events.md +++ b/doc/api/events.md @@ -8,8 +8,7 @@ Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") -periodically emit named events that cause Function objects ("listeners") to be -called. +emit named events that cause `Function` objects ("listeners") to be called. For instance: a [`net.Server`][] object emits an event each time a peer connects to it; a [`fs.ReadStream`][] emits an event when the file is opened; @@ -44,21 +43,21 @@ myEmitter.emit('event'); ## Passing arguments and `this` to listeners The `eventEmitter.emit()` method allows an arbitrary set of arguments to be -passed to the listener functions. It is important to keep in mind that when an -ordinary listener function is called by the `EventEmitter`, the standard `this` -keyword is intentionally set to reference the `EventEmitter` to which the +passed to the listener functions. It is important to keep in mind that when +an ordinary listener function is called, the standard `this` keyword +is intentionally set to reference the `EventEmitter` instance to which the listener is attached. ```js const myEmitter = new MyEmitter(); myEmitter.on('event', function(a, b) { - console.log(a, b, this); + console.log(a, b, this, this === myEmitter); // Prints: // a b MyEmitter { // domain: null, // _events: { event: [Function] }, // _eventsCount: 1, - // _maxListeners: undefined } + // _maxListeners: undefined } true }); myEmitter.emit('event', 'a', 'b'); ``` @@ -167,7 +166,7 @@ The `EventEmitter` class is defined and exposed by the `events` module: const EventEmitter = require('events'); ``` -All EventEmitters emit the event `'newListener'` when new listeners are +All `EventEmitter`s emit the event `'newListener'` when new listeners are added and `'removeListener'` when existing listeners are removed. ### Event: 'newListener' @@ -314,7 +313,7 @@ added: v6.0.0 - Returns: {Array} Returns an array listing the events for which the emitter has registered -listeners. The values in the array will be strings or Symbols. +listeners. The values in the array will be strings or `Symbol`s. ```js const EventEmitter = require('events'); @@ -372,6 +371,17 @@ console.log(util.inspect(server.listeners('connection'))); // Prints: [ [Function] ] ``` +### emitter.off(eventName, listener) + + +* `eventName` {string|symbol} +* `listener` {Function} +* Returns: {EventEmitter} + +Alias for [`emitter.removeListener()`][]. + ### emitter.on(eventName, listener) -* `file` {string|Buffer|URL|number} filename or file descriptor +* `path` {string|Buffer|URL|number} filename or file descriptor * `data` {string|Buffer} * `options` {Object|string} * `encoding` {string|null} **Default:** `'utf8'` @@ -939,7 +962,7 @@ If `options` is a string, then it specifies the encoding. Example: fs.appendFile('message.txt', 'data to append', 'utf8', callback); ``` -The `file` may be specified as a numeric file descriptor that has been opened +The `path` may be specified as a numeric file descriptor that has been opened for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will not be closed automatically. @@ -955,7 +978,7 @@ fs.open('message.txt', 'a', (err, fd) => { }); ``` -## fs.appendFileSync(file, data[, options]) +## fs.appendFileSync(path, data[, options]) -* `file` {string|Buffer|URL|number} filename or file descriptor +* `path` {string|Buffer|URL|number} filename or file descriptor * `data` {string|Buffer} * `options` {Object|string} * `encoding` {string|null} **Default:** `'utf8'` @@ -994,7 +1017,7 @@ If `options` is a string, then it specifies the encoding. Example: fs.appendFileSync('message.txt', 'data to append', 'utf8'); ``` -The `file` may be specified as a numeric file descriptor that has been opened +The `path` may be specified as a numeric file descriptor that has been opened for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will not be closed automatically. @@ -1038,7 +1061,7 @@ changes: Asynchronously changes the permissions of a file. No arguments other than a possible exception are given to the completion callback. -See also: chmod(2) +See also: chmod(2). ### File modes @@ -1097,7 +1120,7 @@ changes: Synchronously changes the permissions of a file. Returns `undefined`. This is the synchronous version of [`fs.chmod()`][]. -See also: chmod(2) +See also: chmod(2). ## fs.chown(path, uid, gid, callback) * `atime` {number|string|Date} -* `mtime` {number|string|Date}` +* `mtime` {number|string|Date} * Returns: {Promise} Change the file system timestamps of the object referenced by the `FileHandle` @@ -3691,12 +3708,12 @@ condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible. -### fsPromises.appendFile(file, data[, options]) +### fsPromises.appendFile(path, data[, options]) -* `file` {string|Buffer|URL|FileHandle} filename or `FileHandle` +* `path` {string|Buffer|URL|FileHandle} filename or `FileHandle` * `data` {string|Buffer} * `options` {Object|string} * `encoding` {string|null} **Default:** `'utf8'` @@ -3710,7 +3727,7 @@ resolved with no arguments upon success. If `options` is a string, then it specifies the encoding. -The `file` may be specified as a `FileHandle` that has been opened +The `path` may be specified as a `FileHandle` that has been opened for appending (using `fsPromises.open()`). ### fsPromises.chmod(path, mode) @@ -3882,7 +3899,7 @@ doTruncate().catch(console.error); ``` If the file previously was shorter than `len` bytes, it is extended, and the -extended part is filled with null bytes ('\0'). For example, +extended part is filled with null bytes (`'\0'`). For example, ```js console.log(fs.readFileSync('temp.txt', 'utf8')); @@ -3897,7 +3914,7 @@ async function doTruncate() { doTruncate().catch(console.error); ``` -The last three bytes are null bytes ('\0'), to compensate the over-truncation. +The last three bytes are null bytes (`'\0'`), to compensate the over-truncation. ### fsPromises.futimes(filehandle, atime, mtime) @@ -925,10 +930,7 @@ This method is identical to [`server.listen()`][] from [`net.Server`][]. added: v5.7.0 --> -* {boolean} - -A Boolean indicating whether or not the server is listening for -connections. +* {boolean} Indicates whether or not the server is listening for connections. ### server.maxHeadersCount -Emitted when the request has been aborted and the network socket has closed. +Emitted when the request has been aborted. ### Event: 'close' + +* {boolean} + +The `message.aborted` property will be `true` if the request has +been aborted. + ### message.destroy([error]) - `options` {Object} - * `IncomingMessage` {http.IncomingMessage} Specifies the IncomingMessage class - to be used. Useful for extending the original `IncomingMessage`. + * `IncomingMessage` {http.IncomingMessage} Specifies the `IncomingMessage` + class to be used. Useful for extending the original `IncomingMessage`. **Default:** `IncomingMessage`. - * `ServerResponse` {http.ServerResponse} Specifies the ServerResponse class to - be used. Useful for extending the original `ServerResponse`. **Default:** + * `ServerResponse` {http.ServerResponse} Specifies the `ServerResponse` class + to be used. Useful for extending the original `ServerResponse`. **Default:** `ServerResponse`. - `requestListener` {Function} @@ -1790,7 +1801,7 @@ automatically. Note that the callback must take care to consume the response data for reasons stated in [`http.ClientRequest`][] section. The `callback` is invoked with a single argument that is an instance of -[`http.IncomingMessage`][] +[`http.IncomingMessage`][]. JSON Fetching Example: @@ -1860,8 +1871,8 @@ changes: v6 will be used. * `port` {number} Port of remote server. **Default:** `80`. * `localAddress` {string} Local interface to bind for network connections. - * `socketPath` {string} Unix Domain Socket (use one of host:port or - socketPath). + * `socketPath` {string} Unix Domain Socket (use one of `host:port` or + `socketPath`). * `method` {string} A string specifying the HTTP request method. **Default:** `'GET'`. * `path` {string} Request path. Should include query string if any. @@ -2064,7 +2075,7 @@ not abort the request or do anything besides add a `'timeout'` event. [`socket.setKeepAlive()`]: net.html#net_socket_setkeepalive_enable_initialdelay [`socket.setNoDelay()`]: net.html#net_socket_setnodelay_nodelay [`socket.setTimeout()`]: net.html#net_socket_settimeout_timeout_callback +[`socket.unref()`]: net.html#net_socket_unref [`url.parse()`]: url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost [Readable Stream]: stream.html#stream_class_stream_readable [Writable Stream]: stream.html#stream_class_stream_writable -[socket.unref()]: net.html#net_socket_unref diff --git a/doc/api/http2.md b/doc/api/http2.md index dd53e9f27fafcc..d737471e8670ee 100644 --- a/doc/api/http2.md +++ b/doc/api/http2.md @@ -108,7 +108,7 @@ have occasion to work with the `Http2Session` object directly, with most actions typically taken through interactions with either the `Http2Server` or `Http2Stream` objects. -#### Http2Session and Sockets +#### `Http2Session` and Sockets Every `Http2Session` instance is associated with exactly one [`net.Socket`][] or [`tls.TLSSocket`][] when it is created. When either the `Socket` or the @@ -159,18 +159,16 @@ an `Http2Session`. added: v8.4.0 --> +* `type` {integer} The frame type. +* `code` {integer} The error code. +* `id` {integer} The stream id (or `0` if the frame isn't associated with a + stream). + The `'frameError'` event is emitted when an error occurs while attempting to send a frame on the session. If the frame that could not be sent is associated with a specific `Http2Stream`, an attempt to emit `'frameError'` event on the `Http2Stream` is made. -When invoked, the handler function will receive three arguments: - -* An integer identifying the frame type. -* An integer identifying the error code. -* An integer identifying the stream (or 0 if the frame is not associated with - a stream). - If the `'frameError'` event is associated with a stream, the stream will be closed and destroyed immediately following the `'frameError'` event. If the event is not associated with a stream, the `Http2Session` will be shut down @@ -181,15 +179,14 @@ immediately following the `'frameError'` event. added: v8.4.0 --> -The `'goaway'` event is emitted when a `GOAWAY` frame is received. When invoked, -the handler function will receive three arguments: - * `errorCode` {number} The HTTP/2 error code specified in the `GOAWAY` frame. * `lastStreamID` {number} The ID of the last stream the remote peer successfully processed (or `0` if no ID is specified). * `opaqueData` {Buffer} If additional opaque data was included in the `GOAWAY` frame, a `Buffer` instance will be passed containing that data. +The `'goaway'` event is emitted when a `GOAWAY` frame is received. + The `Http2Session` instance will be shut down automatically when the `'goaway'` event is emitted. @@ -198,9 +195,10 @@ event is emitted. added: v8.4.0 --> +* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received. + The `'localSettings'` event is emitted when an acknowledgment `SETTINGS` frame -has been received. When invoked, the handler function will receive a copy of -the local settings. +has been received. When using `http2session.settings()` to submit new settings, the modified settings do not take effect until the `'localSettings'` event is emitted. @@ -218,9 +216,10 @@ session.on('localSettings', (settings) => { added: v8.4.0 --> +* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received. + The `'remoteSettings'` event is emitted when a new `SETTINGS` frame is received -from the connected peer. When invoked, the handler function will receive a copy -of the remote settings. +from the connected peer. ```js session.on('remoteSettings', (settings) => { @@ -233,10 +232,13 @@ session.on('remoteSettings', (settings) => { added: v8.4.0 --> -The `'stream'` event is emitted when a new `Http2Stream` is created. When -invoked, the handler function will receive a reference to the `Http2Stream` -object, a [HTTP/2 Headers Object][], and numeric flags associated with the -creation of the stream. +* `stream` {Http2Stream} A reference to the stream +* `headers` {HTTP/2 Headers Object} An object describing the headers +* `flags` {number} The associated numeric flags +* `rawHeaders` {Array} An array containing the raw header names followed by + their respective values. + +The `'stream'` event is emitted when a new `Http2Stream` is created. ```js const http2 = require('http2'); @@ -411,7 +413,7 @@ added: v9.4.0 * {string[]|undefined} If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property -will return an Array of origins for which the `Http2Session` may be +will return an `Array` of origins for which the `Http2Session` may be considered authoritative. #### http2session.pendingSettingsAck @@ -501,12 +503,12 @@ added: v8.4.0 * {net.Socket|tls.TLSSocket} -Returns a Proxy object that acts as a `net.Socket` (or `tls.TLSSocket`) but +Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but limits available methods to ones safe to use with HTTP/2. `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See -[Http2Session and Sockets][] for more information. +[`Http2Session` and Sockets][] for more information. `setTimeout` method will be called on this `Http2Session`. @@ -593,8 +595,9 @@ added: v9.4.0 * `alt` {string} A description of the alternative service configuration as defined by [RFC 7838][]. * `originOrStream` {number|string|URL|Object} Either a URL string specifying - the origin (or an Object with an `origin` property) or the numeric identifier - of an active `Http2Stream` as given by the `http2stream.id` property. + the origin (or an `Object` with an `origin` property) or the numeric + identifier of an active `Http2Stream` as given by the `http2stream.id` + property. Submits an `ALTSVC` frame (as defined by [RFC 7838][]) to the connected client. @@ -643,7 +646,7 @@ protocol is available on the host `'example.org'` on TCP/IP port 81. The host and port *must* be contained within the quote (`"`) characters. Multiple alternatives may be specified, for instance: `'h2="example.org:81", -h2=":82"'` +h2=":82"'`. The protocol identifier (`'h2'` in the examples) may be any valid [ALPN Protocol ID][]. @@ -1042,7 +1045,7 @@ Provides miscellaneous information about the current state of the * `localWindowSize` {number} The number of bytes the connected peer may send for this `Http2Stream` without receiving a `WINDOW_UPDATE`. * `state` {number} A flag indicating the low-level current state of the - `Http2Stream` as determined by nghttp2. + `Http2Stream` as determined by `nghttp2`. * `localClose` {number} `true` if this `Http2Stream` has been closed locally. * `remoteClose` {number} `true` if this `Http2Stream` has been closed remotely. @@ -1141,7 +1144,7 @@ added: v8.4.0 The `'response'` event is emitted when a response `HEADERS` frame has been received for this stream from the connected HTTP/2 server. The listener is -invoked with two arguments: an Object containing the received +invoked with two arguments: an `Object` containing the received [HTTP/2 Headers Object][], and flags associated with the headers. ```js @@ -1181,7 +1184,7 @@ added: v8.4.0 * {boolean} -Boolean (read-only). True if headers were sent, false otherwise. +True if headers were sent, false otherwise (read-only). #### http2stream.pushAllowed + +* {boolean} + +The `request.aborted` property will be `true` if the request has +been aborted. + #### request.destroy([error]) -* {Object} Module object +* {module} The module that first required this one. diff --git a/doc/api/n-api.md b/doc/api/n-api.md index 826b83e2251f32..17958c8daf255e 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -33,22 +33,6 @@ properties: using `napi_get_last_error_info`. More information can be found in the error handling section [Error Handling][]. -The documentation for N-API is structured as follows: - -* [Basic N-API Data Types][] -* [Error Handling][] -* [Object Lifetime Management][] -* [Module Registration][] -* [Working with JavaScript Values][] -* [Working with JavaScript Values - Abstract Operations][] -* [Working with JavaScript Properties][] -* [Working with JavaScript Functions][] -* [Object Wrap][] -* [Simple Asynchronous Operations][] -* [Custom Asynchronous Operations][] -* [Promises][] -* [Script Execution][] - The N-API is a C API that ensures ABI stability across Node.js versions and different compiler levels. However, we also understand that a C++ API can be easier to use in many cases. To support these cases we expect @@ -56,10 +40,10 @@ there to be one or more C++ wrapper modules that provide an inlineable C++ API. Binaries built with these wrapper modules will depend on the symbols for the N-API C based functions exported by Node.js. These wrappers are not part of N-API, nor will they be maintained as part of Node.js. One such -example is: [node-api](https://github.com/nodejs/node-api). +example is: [node-addon-api](https://github.com/nodejs/node-addon-api). In order to use the N-API functions, include the file -[node_api.h](https://github.com/nodejs/node/blob/master/src/node_api.h) +[`node_api.h`](https://github.com/nodejs/node/blob/master/src/node_api.h) which is located in the src directory in the node development tree: ```C @@ -89,7 +73,9 @@ typedef enum { napi_generic_failure, napi_pending_exception, napi_cancelled, - napi_status_last + napi_escape_called_twice, + napi_handle_scope_mismatch, + napi_callback_scope_mismatch } napi_status; ``` If additional information is required upon an API returning a failed status, @@ -185,7 +171,6 @@ typedef void (*napi_finalize)(napi_env env, void* finalize_hint); ``` - #### napi_async_execute_callback Function pointer used with functions that support asynchronous operations. Callback functions must statisfy the following signature: @@ -223,7 +208,7 @@ In cases where a return value other than `napi_ok` or must be called to check if an exception is pending. See the section on exceptions for more details. -The full set of possible napi_status values is defined +The full set of possible `napi_status` values is defined in `napi_api_types.h`. The `napi_status` return value provides a VM-independent representation of @@ -282,7 +267,6 @@ logging purposes. This API can be called even if there is a pending JavaScript exception. - ### Exceptions Any N-API function call may result in a pending JavaScript exception. This is obviously the case for any function that may cause the execution of @@ -312,10 +296,10 @@ and then continue. This is only recommended in specific cases where it is known that the exception can be safely handled. In these cases [`napi_get_and_clear_last_exception`][] can be used to get and clear the exception. On success, result will contain the handle to -the last JavaScript Object thrown. If it is determined, after +the last JavaScript `Object` thrown. If it is determined, after retrieving the exception, the exception cannot be handled after all it can be re-thrown it with [`napi_throw`][] where error is the -JavaScript Error object to be thrown. +JavaScript `Error` object to be thrown. The following utility functions are also available in case native code needs to throw an exception or determine if a `napi_value` is an instance @@ -324,10 +308,10 @@ of a JavaScript `Error` object: [`napi_throw_error`][], [`napi_is_error`][]. The following utility functions are also available in case native -code needs to create an Error object: [`napi_create_error`][], -[`napi_create_type_error`][], and [`napi_create_range_error`][]. -where result is the napi_value that refers to the newly created -JavaScript Error object. +code needs to create an `Error` object: [`napi_create_error`][], +[`napi_create_type_error`][], and [`napi_create_range_error`][], +where result is the `napi_value` that refers to the newly created +JavaScript `Error` object. The Node.js project is adding error codes to all of the errors generated internally. The goal is for applications to use these @@ -346,9 +330,9 @@ the name associated with the error is also updated to be: originalName [code] ``` -where originalName is the original name associated with the error -and code is the code that was provided. For example if the code -is 'ERR_ERROR_1' and a TypeError is being created the name will be: +where `originalName` is the original name associated with the error +and `code` is the code that was provided. For example if the code +is `'ERR_ERROR_1'` and a `TypeError` is being created the name will be: ```text TypeError [ERR_ERROR_1] @@ -362,12 +346,11 @@ added: v8.0.0 NODE_EXTERN napi_status napi_throw(napi_env env, napi_value error); ``` - `[in] env`: The environment that the API is invoked under. -- `[in] error`: The `napi_value` for the Error to be thrown. +- `[in] error`: The JavaScript value to be thrown. Returns `napi_ok` if the API succeeded. -This API throws the JavaScript Error provided. - +This API throws the JavaScript value provided. #### napi_throw_error -A Boolean indicating whether or not the server is listening for -connections. +* {boolean} Indicates whether or not the server is listening for connections. ### server.maxConnections ```js @@ -381,15 +381,17 @@ systems. ## os.uptime() * Returns: {integer} The `os.uptime()` method returns the system uptime in number of seconds. -On Windows the returned value includes fractions of a second. Use `Math.floor()` -to get whole seconds. - ## os.userInfo([options]) +* `code` {integer} + The `'exit'` event is emitted when the Node.js process is about to exit as a result of either: @@ -56,7 +58,7 @@ all `'exit'` listeners have finished running the Node.js process will terminate. The listener callback function is invoked with the exit code specified either by the [`process.exitCode`][] property, or the `exitCode` argument passed to the -[`process.exit()`] method, as the only argument. +[`process.exit()`] method. ```js process.on('exit', (code) => { @@ -82,16 +84,16 @@ process.on('exit', (code) => { added: v0.5.10 --> +* `message` { Object | boolean | number | string | null } a parsed JSON object + or a serializable primitive value. +* `sendHandle` {net.Server|net.Socket} a [`net.Server`][] or [`net.Socket`][] + object, or undefined. + If the Node.js process is spawned with an IPC channel (see the [Child Process][] and [Cluster][] documentation), the `'message'` event is emitted whenever a message sent by a parent process using [`childprocess.send()`][] is received by the child process. -The listener callback is invoked with the following arguments: -* `message` {Object} a parsed JSON object or primitive value. -* `sendHandle` {net.Server|net.Socket} a [`net.Server`][] or [`net.Socket`][] - object, or undefined. - The message goes through serialization and parsing. The resulting message might not be the same as what is originally sent. @@ -100,13 +102,12 @@ not be the same as what is originally sent. added: v1.4.1 --> +* `promise` {Promise} The late handled promise. + The `'rejectionHandled'` event is emitted whenever a `Promise` has been rejected and an error handler was attached to it (using [`promise.catch()`][], for example) later than one turn of the Node.js event loop. -The listener callback is invoked with a reference to the rejected `Promise` as -the only argument. - The `Promise` object would have previously been emitted in an `'unhandledRejection'` event, but during the course of processing gained a rejection handler. @@ -129,11 +130,11 @@ when the list of unhandled rejections shrinks. ```js const unhandledRejections = new Map(); -process.on('unhandledRejection', (reason, p) => { - unhandledRejections.set(p, reason); +process.on('unhandledRejection', (reason, promise) => { + unhandledRejections.set(promise, reason); }); -process.on('rejectionHandled', (p) => { - unhandledRejections.delete(p); +process.on('rejectionHandled', (promise) => { + unhandledRejections.delete(promise); }); ``` @@ -204,10 +205,10 @@ added: v1.4.1 changes: - version: v7.0.0 pr-url: https://github.com/nodejs/node/pull/8217 - description: Not handling Promise rejections has been deprecated. + description: Not handling `Promise` rejections has been deprecated. - version: v6.6.0 pr-url: https://github.com/nodejs/node/pull/8223 - description: Unhandled Promise rejections will now emit + description: Unhandled `Promise` rejections will now emit a process warning. --> @@ -233,7 +234,7 @@ process.on('unhandledRejection', (reason, p) => { somePromise.then((res) => { return reportToUser(JSON.pasre(res)); // note the typo (`pasre`) -}); // no `.catch` or `.then` +}); // no `.catch()` or `.then()` ``` The following will also trigger the `'unhandledRejection'` event to be @@ -261,6 +262,12 @@ being emitted. Alternatively, the [`'rejectionHandled'`][] event may be used. added: v6.0.0 --> +* `warning` {Error} Key properties of the warning are: + * `name` {string} The name of the warning. **Default:** `'Warning'`. + * `message` {string} A system-provided description of the warning. + * `stack` {string} A stack trace to the location in the code where the warning + was issued. + The `'warning'` event is emitted whenever Node.js emits a process warning. A process warning is similar to an error in that it describes exceptional @@ -269,14 +276,6 @@ are not part of the normal Node.js and JavaScript error handling flow. Node.js can emit warnings whenever it detects bad coding practices that could lead to sub-optimal application performance, bugs, or security vulnerabilities. -The listener function is called with a single `warning` argument whose value is -an `Error` object. There are three key properties that describe the warning: - -* `name` {string} The name of the warning (currently `'Warning'` by default). -* `message` {string} A system-provided description of the warning. -* `stack` {string} A stack trace to the location in the code where the warning - was issued. - ```js process.on('warning', (warning) => { console.warn(warning.name); // Print the warning name @@ -290,7 +289,7 @@ command-line option can be used to suppress the default console output but the `'warning'` event will still be emitted by the `process` object. The following example illustrates the warning that is printed to `stderr` when -too many listeners have been added to an event +too many listeners have been added to an event: ```txt $ node @@ -525,7 +524,7 @@ added: v0.7.7 * {Object} -The `process.config` property returns an Object containing the JavaScript +The `process.config` property returns an `Object` containing the JavaScript representation of the configure options used to compile the current Node.js executable. This is the same as the `config.gypi` file that was produced when running the `./configure` script. @@ -700,10 +699,10 @@ added: v8.0.0 * `warning` {string|Error} The warning to emit. * `options` {Object} - * `type` {string} When `warning` is a String, `type` is the name to use + * `type` {string} When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted. **Default:** `'Warning'`. * `code` {string} A unique identifier for the warning instance being emitted. - * `ctor` {Function} When `warning` is a String, `ctor` is an optional + * `ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. **Default:** `process.emitWarning`. * `detail` {string} Additional text to include with the error. @@ -745,10 +744,10 @@ added: v6.0.0 --> * `warning` {string|Error} The warning to emit. -* `type` {string} When `warning` is a String, `type` is the name to use +* `type` {string} When `warning` is a `String`, `type` is the name to use for the *type* of warning being emitted. **Default:** `'Warning'`. * `code` {string} A unique identifier for the warning instance being emitted. -* `ctor` {Function} When `warning` is a String, `ctor` is an optional +* `ctor` {Function} When `warning` is a `String`, `ctor` is an optional function used to limit the generated stack trace. **Default:** `process.emitWarning`. @@ -966,7 +965,6 @@ that started the Node.js process. '/usr/local/bin/node' ``` - ## process.exit([code]) * `str` {string} - The `querystring.unescape()` method performs decoding of URL percent-encoded characters on the given `str`. diff --git a/doc/api/readline.md b/doc/api/readline.md index c1e50ef7eee350..a2a4adf3093a9a 100644 --- a/doc/api/readline.md +++ b/doc/api/readline.md @@ -90,7 +90,7 @@ The `'pause'` event is emitted when one of the following occur: * The `input` stream is paused. * The `input` stream is not paused and receives the `'SIGCONT'` event. (See - events [`'SIGTSTP'`][] and [`'SIGCONT'`][]) + events [`'SIGTSTP'`][] and [`'SIGCONT'`][].) The listener function is called without passing any arguments. @@ -303,7 +303,7 @@ rl.write('Delete this!'); rl.write(null, { ctrl: true, name: 'u' }); ``` -The `rl.write()` method will write the data to the `readline` Interface's +The `rl.write()` method will write the data to the `readline` `Interface`'s `input` *as if it were provided by the user*. ## readline.clearLine(stream, dir) @@ -320,7 +320,6 @@ added: v0.7.7 The `readline.clearLine()` method clears current line of given [TTY][] stream in a specified direction identified by `dir`. - ## readline.clearScreenDown(stream) ```js @@ -63,7 +63,7 @@ The following key combinations in the REPL have these special effects: When pressed twice on a blank line, has the same effect as the `.exit` command. * `-D` - Has the same effect as the `.exit` command. -* `` - When pressed on a blank line, displays global and local(scope) +* `` - When pressed on a blank line, displays global and local (scope) variables. When pressed while entering other input, displays relevant autocompletion options. @@ -141,6 +141,17 @@ global or scoped variable, the input `fs` will be evaluated on-demand as > fs.createReadStream('./some/file'); ``` +#### Global Uncaught Exceptions + +The REPL uses the [`domain`][] module to catch all uncaught exceptions for that +REPL session. + +This use of the [`domain`][] module in the REPL has these side effects: + +* Uncaught exceptions do not emit the [`'uncaughtException'`][] event. +* Trying to use [`process.setUncaughtExceptionCaptureCallback()`][] throws + an [`ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE`][] error. + #### Assignment of the `_` (underscore) variable -Both [Writable][] and [Readable][] streams will store data in an internal +Both [`Writable`][] and [`Readable`][] streams will store data in an internal buffer that can be retrieved using `writable.writableBuffer` or `readable.readableBuffer`, respectively. @@ -74,7 +74,7 @@ passed into the streams constructor. For normal streams, the `highWaterMark` option specifies a [total number of bytes][hwm-gotcha]. For streams operating in object mode, the `highWaterMark` specifies a total number of objects. -Data is buffered in Readable streams when the implementation calls +Data is buffered in `Readable` streams when the implementation calls [`stream.push(chunk)`][stream-push]. If the consumer of the Stream does not call [`stream.read()`][stream-read], the data will sit in the internal queue until it is consumed. @@ -85,7 +85,7 @@ underlying resource until the data currently buffered can be consumed (that is, the stream will stop calling the internal `readable._read()` method that is used to fill the read buffer). -Data is buffered in Writable streams when the +Data is buffered in `Writable` streams when the [`writable.write(chunk)`][stream-write] method is called repeatedly. While the total size of the internal write buffer is below the threshold set by `highWaterMark`, calls to `writable.write()` will return `true`. Once @@ -96,15 +96,15 @@ A key goal of the `stream` API, particularly the [`stream.pipe()`] method, is to limit the buffering of data to acceptable levels such that sources and destinations of differing speeds will not overwhelm the available memory. -Because [Duplex][] and [Transform][] streams are both Readable and Writable, -each maintain *two* separate internal buffers used for reading and writing, -allowing each side to operate independently of the other while maintaining an -appropriate and efficient flow of data. For example, [`net.Socket`][] instances -are [Duplex][] streams whose Readable side allows consumption of data received -*from* the socket and whose Writable side allows writing data *to* the socket. -Because data may be written to the socket at a faster or slower rate than data -is received, it is important for each side to operate (and buffer) independently -of the other. +Because [`Duplex`][] and [`Transform`][] streams are both `Readable` and +`Writable`, each maintain *two* separate internal buffers used for reading and +writing, allowing each side to operate independently of the other while +maintaining an appropriate and efficient flow of data. For example, +[`net.Socket`][] instances are [`Duplex`][] streams whose `Readable` side allows +consumption of data received *from* the socket and whose `Writable` side allows +writing data *to* the socket. Because data may be written to the socket at a +faster or slower rate than data is received, it is important for each side to +operate (and buffer) independently of the other. ## API for Stream Consumers @@ -156,17 +156,18 @@ server.listen(1337); // error: Unexpected token o in JSON at position 1 ``` -[Writable][] streams (such as `res` in the example) expose methods such as +[`Writable`][] streams (such as `res` in the example) expose methods such as `write()` and `end()` that are used to write data onto the stream. -[Readable][] streams use the [`EventEmitter`][] API for notifying application +[`Readable`][] streams use the [`EventEmitter`][] API for notifying application code when data is available to be read off the stream. That available data can be read from the stream in multiple ways. -Both [Writable][] and [Readable][] streams use the [`EventEmitter`][] API in +Both [`Writable`][] and [`Readable`][] streams use the [`EventEmitter`][] API in various ways to communicate the current state of the stream. -[Duplex][] and [Transform][] streams are both [Writable][] and [Readable][]. +[`Duplex`][] and [`Transform`][] streams are both [`Writable`][] and +[`Readable`][]. Applications that are either writing data to or consuming data from a stream are not required to implement the stream interfaces directly and will generally @@ -180,7 +181,7 @@ section [API for Stream Implementers][]. Writable streams are an abstraction for a *destination* to which data is written. -Examples of [Writable][] streams include: +Examples of [`Writable`][] streams include: * [HTTP requests, on the client][] * [HTTP responses, on the server][] @@ -191,14 +192,14 @@ Examples of [Writable][] streams include: * [child process stdin][] * [`process.stdout`][], [`process.stderr`][] -Some of these examples are actually [Duplex][] streams that implement the -[Writable][] interface. +Some of these examples are actually [`Duplex`][] streams that implement the +[`Writable`][] interface. -All [Writable][] streams implement the interface defined by the +All [`Writable`][] streams implement the interface defined by the `stream.Writable` class. -While specific instances of [Writable][] streams may differ in various ways, -all Writable streams follow the same fundamental usage pattern as illustrated +While specific instances of [`Writable`][] streams may differ in various ways, +all `Writable` streams follow the same fundamental usage pattern as illustrated in the example below: ```js @@ -224,7 +225,7 @@ The `'close'` event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates that no more events will be emitted, and no further computation will occur. -Not all Writable streams will emit the `'close'` event. +Not all `Writable` streams will emit the `'close'` event. ##### Event: 'drain' -Duplex streams are streams that implement both the [Readable][] and -[Writable][] interfaces. +Duplex streams are streams that implement both the [`Readable`][] and +[`Writable`][] interfaces. -Examples of Duplex streams include: +Examples of `Duplex` streams include: * [TCP sockets][] * [zlib streams][zlib] @@ -1270,11 +1272,11 @@ added: v0.9.4 -Transform streams are [Duplex][] streams where the output is in some way -related to the input. Like all [Duplex][] streams, Transform streams -implement both the [Readable][] and [Writable][] interfaces. +Transform streams are [`Duplex`][] streams where the output is in some way +related to the input. Like all [`Duplex`][] streams, `Transform` streams +implement both the [`Readable`][] and [`Writable`][] interfaces. -Examples of Transform streams include: +Examples of `Transform` streams include: * [zlib streams][zlib] * [crypto streams][crypto] @@ -1436,7 +1438,7 @@ on the type of stream being created, as detailed in the chart below:

Reading only

-

[Readable](#stream_class_stream_readable)

+

[`Readable`](#stream_class_stream_readable)

[_read][stream-_read]

@@ -1447,7 +1449,7 @@ on the type of stream being created, as detailed in the chart below:

Writing only

-

[Writable](#stream_class_stream_writable)

+

[`Writable`](#stream_class_stream_writable)

@@ -1462,7 +1464,7 @@ on the type of stream being created, as detailed in the chart below:

Reading and writing

-

[Duplex](#stream_class_stream_duplex)

+

[`Duplex`](#stream_class_stream_duplex)

@@ -1477,7 +1479,7 @@ on the type of stream being created, as detailed in the chart below:

Operate on written data, then read the result

-

[Transform](#stream_class_stream_transform)

+

[`Transform`](#stream_class_stream_transform)

@@ -1516,9 +1518,9 @@ const myWritable = new Writable({ ### Implementing a Writable Stream -The `stream.Writable` class is extended to implement a [Writable][] stream. +The `stream.Writable` class is extended to implement a [`Writable`][] stream. -Custom Writable streams *must* call the `new stream.Writable([options])` +Custom `Writable` streams *must* call the `new stream.Writable([options])` constructor and implement the `writable._write()` method. The `writable._writev()` method *may* also be implemented. @@ -1536,7 +1538,7 @@ changes: [`stream.write()`][stream-write] starts returning `false`. **Default:** `16384` (16kb), or `16` for `objectMode` streams. * `decodeStrings` {boolean} Whether or not to decode strings into - Buffers before passing them to [`stream._write()`][stream-_write]. + `Buffer`s before passing them to [`stream._write()`][stream-_write]. **Default:** `true`. * `objectMode` {boolean} Whether or not the [`stream.write(anyObj)`][stream-write] is a valid operation. When set, @@ -1606,16 +1608,16 @@ const myWritable = new Writable({ * `callback` {Function} Call this function (optionally with an error argument) when processing is complete for the supplied chunk. -All Writable stream implementations must provide a +All `Writable` stream implementations must provide a [`writable._write()`][stream-_write] method to send data to the underlying resource. -[Transform][] streams provide their own implementation of the +[`Transform`][] streams provide their own implementation of the [`writable._write()`][stream-_write]. This function MUST NOT be called by application code directly. It should be -implemented by child classes, and called by the internal Writable class methods -only. +implemented by child classes, and called by the internal `Writable` class +methods only. The `callback` method must be called to signal either that the write completed successfully or failed with an error. The first argument passed to the @@ -1647,8 +1649,8 @@ user programs. argument) to be invoked when processing is complete for the supplied chunks. This function MUST NOT be called by application code directly. It should be -implemented by child classes, and called by the internal Writable class methods -only. +implemented by child classes, and called by the internal `Writable` class +methods only. The `writable._writev()` method may be implemented in addition to `writable._write()` in stream implementations that are capable of processing @@ -1680,7 +1682,7 @@ added: v8.0.0 argument) when finished writing any remaining data. The `_final()` method **must not** be called directly. It may be implemented -by child classes, and if so, will be called by the internal Writable +by child classes, and if so, will be called by the internal `Writable` class methods only. This optional function will be called before the stream closes, delaying the @@ -1692,13 +1694,13 @@ or write buffered data before a stream ends. It is recommended that errors occurring during the processing of the `writable._write()` and `writable._writev()` methods are reported by invoking the callback and passing the error as the first argument. This will cause an -`'error'` event to be emitted by the Writable. Throwing an Error from within +`'error'` event to be emitted by the `Writable`. Throwing an `Error` from within `writable._write()` can result in unexpected and inconsistent behavior depending on how the stream is being used. Using the callback ensures consistent and predictable handling of errors. -If a Readable stream pipes into a Writable stream when Writable emits an -error, the Readable stream will be unpiped. +If a `Readable` stream pipes into a `Writable` stream when `Writable` emits an +error, the `Readable` stream will be unpiped. ```js const { Writable } = require('stream'); @@ -1717,9 +1719,9 @@ const myWritable = new Writable({ #### An Example Writable Stream The following illustrates a rather simplistic (and somewhat pointless) custom -Writable stream implementation. While this specific Writable stream instance +`Writable` stream implementation. While this specific `Writable` stream instance is not of any real particular usefulness, the example illustrates each of the -required elements of a custom [Writable][] stream instance: +required elements of a custom [`Writable`][] stream instance: ```js const { Writable } = require('stream'); @@ -1745,7 +1747,7 @@ class MyWritable extends Writable { Decoding buffers is a common task, for instance, when using transformers whose input is a string. This is not a trivial process when using multi-byte characters encoding, such as UTF-8. The following example shows how to decode -multi-byte strings using `StringDecoder` and [Writable][]. +multi-byte strings using `StringDecoder` and [`Writable`][]. ```js const { Writable } = require('stream'); @@ -1782,9 +1784,9 @@ console.log(w.data); // currency: € ### Implementing a Readable Stream -The `stream.Readable` class is extended to implement a [Readable][] stream. +The `stream.Readable` class is extended to implement a [`Readable`][] stream. -Custom Readable streams *must* call the `new stream.Readable([options])` +Custom `Readable` streams *must* call the `new stream.Readable([options])` constructor and implement the `readable._read()` method. #### new stream.Readable([options]) @@ -1797,7 +1799,7 @@ constructor and implement the `readable._read()` method. strings using the specified encoding. **Default:** `null`. * `objectMode` {boolean} Whether this stream should behave as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns - a single value instead of a Buffer of size n. **Default:** `false`. + a single value instead of a `Buffer` of size `n`. **Default:** `false`. * `read` {Function} Implementation for the [`stream._read()`][stream-_read] method. * `destroy` {Function} Implementation for the @@ -1847,16 +1849,16 @@ added: v0.9.4 changes: - version: v10.0.0 pr-url: https://github.com/nodejs/node/pull/17979 - description: call _read() only once per microtick + description: call `_read()` only once per microtick --> * `size` {number} Number of bytes to read asynchronously This function MUST NOT be called by application code directly. It should be -implemented by child classes, and called by the internal Readable class methods -only. +implemented by child classes, and called by the internal `Readable` class +methods only. -All Readable stream implementations must provide an implementation of the +All `Readable` stream implementations must provide an implementation of the `readable._read()` method to fetch data from the underlying resource. When `readable._read()` is called, if data is available from the resource, the @@ -1906,7 +1908,7 @@ changes: string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be any JavaScript value. * `encoding` {string} Encoding of string chunks. Must be a valid - Buffer encoding, such as `'utf8'` or `'ascii'` + `Buffer` encoding, such as `'utf8'` or `'ascii'`. * Returns: {boolean} `true` if additional chunks of data may continued to be pushed; `false` otherwise. @@ -1915,18 +1917,18 @@ be added to the internal queue for users of the stream to consume. Passing `chunk` as `null` signals the end of the stream (EOF), after which no more data can be written. -When the Readable is operating in paused mode, the data added with +When the `Readable` is operating in paused mode, the data added with `readable.push()` can be read out by calling the [`readable.read()`][stream-read] method when the [`'readable'`][] event is emitted. -When the Readable is operating in flowing mode, the data added with +When the `Readable` is operating in flowing mode, the data added with `readable.push()` will be delivered by emitting a `'data'` event. The `readable.push()` method is designed to be as flexible as possible. For example, when wrapping a lower-level source that provides some form of pause/resume mechanism, and a data callback, the low-level source can be wrapped -by the custom Readable instance as illustrated in the following example: +by the custom `Readable` instance as illustrated in the following example: ```js // source is an object with readStop() and readStart() methods, @@ -1959,8 +1961,8 @@ class SourceWrapper extends Readable { } ``` -The `readable.push()` method is intended be called only by Readable -Implementers, and only from within the `readable._read()` method. +The `readable.push()` method is intended be called only by `Readable` +implementers, and only from within the `readable._read()` method. For streams not operating in object mode, if the `chunk` parameter of `readable.push()` is `undefined`, it will be treated as empty string or @@ -1970,7 +1972,7 @@ buffer. See [`readable.push('')`][] for more information. It is recommended that errors occurring during the processing of the `readable._read()` method are emitted using the `'error'` event rather than -being thrown. Throwing an Error from within `readable._read()` can result in +being thrown. Throwing an `Error` from within `readable._read()` can result in unexpected and inconsistent behavior depending on whether the stream is operating in flowing or paused mode. Using the `'error'` event ensures consistent and predictable handling of errors. @@ -1994,7 +1996,7 @@ const myReadable = new Readable({ -The following is a basic example of a Readable stream that emits the numerals +The following is a basic example of a `Readable` stream that emits the numerals from 1 to 1,000,000 in ascending order, and then ends. ```js @@ -2022,11 +2024,11 @@ class Counter extends Readable { ### Implementing a Duplex Stream -A [Duplex][] stream is one that implements both [Readable][] and [Writable][], -such as a TCP socket connection. +A [`Duplex`][] stream is one that implements both [`Readable`][] and +[`Writable`][], such as a TCP socket connection. Because JavaScript does not have support for multiple inheritance, the -`stream.Duplex` class is extended to implement a [Duplex][] stream (as opposed +`stream.Duplex` class is extended to implement a [`Duplex`][] stream (as opposed to extending the `stream.Readable` *and* `stream.Writable` classes). The `stream.Duplex` class prototypically inherits from `stream.Readable` and @@ -2034,7 +2036,7 @@ parasitically from `stream.Writable`, but `instanceof` will work properly for both base classes due to overriding [`Symbol.hasInstance`][] on `stream.Writable`. -Custom Duplex streams *must* call the `new stream.Duplex([options])` +Custom `Duplex` streams *must* call the `new stream.Duplex([options])` constructor and implement *both* the `readable._read()` and `writable._write()` methods. @@ -2047,7 +2049,7 @@ changes: are supported now. --> -* `options` {Object} Passed to both Writable and Readable +* `options` {Object} Passed to both `Writable` and `Readable` constructors. Also has the following fields: * `allowHalfOpen` {boolean} If set to `false`, then the stream will automatically end the writable side when the readable side ends. @@ -2103,13 +2105,13 @@ const myDuplex = new Duplex({ #### An Example Duplex Stream -The following illustrates a simple example of a Duplex stream that wraps a +The following illustrates a simple example of a `Duplex` stream that wraps a hypothetical lower-level source object to which data can be written, and from which data can be read, albeit using an API that is not compatible with Node.js streams. -The following illustrates a simple example of a Duplex stream that buffers -incoming written data via the [Writable][] interface that is read back out -via the [Readable][] interface. +The following illustrates a simple example of a `Duplex` stream that buffers +incoming written data via the [`Writable`][] interface that is read back out +via the [`Readable`][] interface. ```js const { Duplex } = require('stream'); @@ -2137,20 +2139,20 @@ class MyDuplex extends Duplex { } ``` -The most important aspect of a Duplex stream is that the Readable and Writable -sides operate independently of one another despite co-existing within a single -object instance. +The most important aspect of a `Duplex` stream is that the `Readable` and +`Writable` sides operate independently of one another despite co-existing within +a single object instance. #### Object Mode Duplex Streams -For Duplex streams, `objectMode` can be set exclusively for either the Readable -or Writable side using the `readableObjectMode` and `writableObjectMode` options -respectively. +For `Duplex` streams, `objectMode` can be set exclusively for either the +`Readable` or `Writable` side using the `readableObjectMode` and +`writableObjectMode` options respectively. -In the following example, for instance, a new Transform stream (which is a -type of [Duplex][] stream) is created that has an object mode Writable side +In the following example, for instance, a new `Transform` stream (which is a +type of [`Duplex`][] stream) is created that has an object mode `Writable` side that accepts JavaScript numbers that are converted to hexadecimal strings on -the Readable side. +the `Readable` side. ```js const { Transform } = require('stream'); @@ -2184,31 +2186,31 @@ myTransform.write(100); ### Implementing a Transform Stream -A [Transform][] stream is a [Duplex][] stream where the output is computed +A [`Transform`][] stream is a [`Duplex`][] stream where the output is computed in some way from the input. Examples include [zlib][] streams or [crypto][] streams that compress, encrypt, or decrypt data. There is no requirement that the output be the same size as the input, the same -number of chunks, or arrive at the same time. For example, a Hash stream will +number of chunks, or arrive at the same time. For example, a `Hash` stream will only ever have a single chunk of output which is provided when the input is ended. A `zlib` stream will produce output that is either much smaller or much larger than its input. -The `stream.Transform` class is extended to implement a [Transform][] stream. +The `stream.Transform` class is extended to implement a [`Transform`][] stream. The `stream.Transform` class prototypically inherits from `stream.Duplex` and implements its own versions of the `writable._write()` and `readable._read()` -methods. Custom Transform implementations *must* implement the +methods. Custom `Transform` implementations *must* implement the [`transform._transform()`][stream-_transform] method and *may* also implement the [`transform._flush()`][stream-_flush] method. -Care must be taken when using Transform streams in that data written to the -stream can cause the Writable side of the stream to become paused if the output -on the Readable side is not consumed. +Care must be taken when using `Transform` streams in that data written to the +stream can cause the `Writable` side of the stream to become paused if the +output on the `Readable` side is not consumed. #### new stream.Transform([options]) -* `options` {Object} Passed to both Writable and Readable +* `options` {Object} Passed to both `Writable` and `Readable` constructors. Also has the following fields: * `transform` {Function} Implementation for the [`stream._transform()`][stream-_transform] method. @@ -2267,8 +2269,8 @@ after all data has been output, which occurs after the callback in argument and data) to be called when remaining data has been flushed. This function MUST NOT be called by application code directly. It should be -implemented by child classes, and called by the internal Readable class methods -only. +implemented by child classes, and called by the internal `Readable` class +methods only. In some cases, a transform operation may need to emit an additional bit of data at the end of the stream. For example, a `zlib` compression stream will @@ -2276,10 +2278,10 @@ store an amount of internal state used to optimally compress the output. When the stream ends, however, that additional data needs to be flushed so that the compressed data will be complete. -Custom [Transform][] implementations *may* implement the `transform._flush()` +Custom [`Transform`][] implementations *may* implement the `transform._flush()` method. This will be called when there is no more written data to be consumed, but before the [`'end'`][] event is emitted signaling the end of the -[Readable][] stream. +[`Readable`][] stream. Within the `transform._flush()` implementation, the `readable.push()` method may be called zero or more times, as appropriate. The `callback` function must @@ -2302,10 +2304,10 @@ user programs. processed. This function MUST NOT be called by application code directly. It should be -implemented by child classes, and called by the internal Readable class methods -only. +implemented by child classes, and called by the internal `Readable` class +methods only. -All Transform stream implementations must provide a `_transform()` +All `Transform` stream implementations must provide a `_transform()` method to accept input and produce output. The `transform._transform()` implementation handles the bytes being written, computes an output, then passes that output off to the readable portion using the `readable.push()` method. @@ -2343,7 +2345,7 @@ called, either synchronously or asynchronously. #### Class: stream.PassThrough -The `stream.PassThrough` class is a trivial implementation of a [Transform][] +The `stream.PassThrough` class is a trivial implementation of a [`Transform`][] stream that simply passes the input bytes across to the output. Its purpose is primarily for examples and testing, but there are some use cases where `stream.PassThrough` is useful as a building block for novel sorts of streams. @@ -2356,7 +2358,7 @@ primarily for examples and testing, but there are some use cases where -In versions of Node.js prior to v0.10, the Readable stream interface was +In versions of Node.js prior to v0.10, the `Readable` stream interface was simpler, but also less powerful and less useful. * Rather than waiting for calls the [`stream.read()`][stream-read] method, @@ -2367,9 +2369,9 @@ simpler, but also less powerful and less useful. guaranteed. This meant that it was still necessary to be prepared to receive [`'data'`][] events *even when the stream was in a paused state*. -In Node.js v0.10, the [Readable][] class was added. For backwards compatibility -with older Node.js programs, Readable streams switch into "flowing mode" when a -[`'data'`][] event handler is added, or when the +In Node.js v0.10, the [`Readable`][] class was added. For backwards +compatibility with older Node.js programs, `Readable` streams switch into +"flowing mode" when a [`'data'`][] event handler is added, or when the [`stream.resume()`][stream-resume] method is called. The effect is that, even when not using the new [`stream.read()`][stream-read] method and [`'readable'`][] event, it is no longer necessary to worry about losing @@ -2407,22 +2409,19 @@ The workaround in this situation is to call the ```js // Workaround net.createServer((socket) => { - socket.on('end', () => { socket.end('The message was received but was not processed.\n'); }); // start the flow of data, discarding it. socket.resume(); - }).listen(1337); ``` -In addition to new Readable streams switching into flowing mode, -pre-v0.10 style streams can be wrapped in a Readable class using the +In addition to new `Readable` streams switching into flowing mode, +pre-v0.10 style streams can be wrapped in a `Readable` class using the [`readable.wrap()`][`stream.wrap()`] method. - ### `readable.read(0)` There are some cases where it is necessary to trigger a refresh of the @@ -2436,7 +2435,7 @@ a low-level [`stream._read()`][stream-_read] call. While most applications will almost never need to do this, there are situations within Node.js where this is done, particularly in the -Readable stream class internals. +`Readable` stream class internals. ### `readable.push('')` @@ -2486,13 +2485,13 @@ contain multi-byte characters. [API for Stream Consumers]: #stream_api_for_stream_consumers [API for Stream Implementers]: #stream_api_for_stream_implementers [Compatibility]: #stream_compatibility_with_older_node_js_versions -[Duplex]: #stream_class_stream_duplex +[`Duplex`]: #stream_class_stream_duplex [HTTP requests, on the client]: http.html#http_class_http_clientrequest [HTTP responses, on the server]: http.html#http_class_http_serverresponse -[Readable]: #stream_class_stream_readable +[`Readable`]: #stream_class_stream_readable [TCP sockets]: net.html#net_class_net_socket -[Transform]: #stream_class_stream_transform -[Writable]: #stream_class_stream_writable +[`Transform`]: #stream_class_stream_transform +[`Writable`]: #stream_class_stream_writable [child process stdin]: child_process.html#child_process_subprocess_stdin [child process stdout and stderr]: child_process.html#child_process_subprocess_stdout [crypto]: crypto.html diff --git a/doc/api/synopsis.md b/doc/api/synopsis.md index 508dde1ff483f8..ad14fae7b8d791 100644 --- a/doc/api/synopsis.md +++ b/doc/api/synopsis.md @@ -88,9 +88,9 @@ $ node hello-world.js An output like this should appear in the terminal to indicate Node.js server is running: - ```console - Server running at http://127.0.0.1:3000/ - ```` +```console +Server running at http://127.0.0.1:3000/ +``` Now, open any preferred web browser and visit `http://127.0.0.1:3000`. diff --git a/doc/api/timers.md b/doc/api/timers.md index 0cc535352a0697..376b5312e5a41a 100644 --- a/doc/api/timers.md +++ b/doc/api/timers.md @@ -28,7 +28,7 @@ functions that can be used to control this default behavior. added: v9.7.0 --> -* Returns: {Immediate} +* Returns: {Immediate} a reference to `immediate` When called, requests that the Node.js event loop *not* exit so long as the `Immediate` is active. Calling `immediate.ref()` multiple times will have no @@ -37,22 +37,18 @@ effect. By default, all `Immediate` objects are "ref'ed", making it normally unnecessary to call `immediate.ref()` unless `immediate.unref()` had been called previously. -Returns a reference to the `Immediate`. - ### immediate.unref() -* Returns: {Immediate} +* Returns: {Immediate} a reference to `immediate` When called, the active `Immediate` object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the `Immediate` object's callback is invoked. Calling `immediate.unref()` multiple times will have no effect. -Returns a reference to the `Immediate`. - ## Class: Timeout This object is created internally and is returned from [`setTimeout()`][] and @@ -70,7 +66,7 @@ control this default behavior. added: v0.9.1 --> -* Returns: {Timeout} +* Returns: {Timeout} a reference to `timeout` When called, requests that the Node.js event loop *not* exit so long as the `Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. @@ -78,14 +74,12 @@ When called, requests that the Node.js event loop *not* exit so long as the By default, all `Timeout` objects are "ref'ed", making it normally unnecessary to call `timeout.ref()` unless `timeout.unref()` had been called previously. -Returns a reference to the `Timeout`. - ### timeout.unref() -* Returns: {Timeout} +* Returns: {Timeout} a reference to `timeout` When called, the active `Timeout` object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, @@ -96,8 +90,6 @@ Calling `timeout.unref()` creates an internal timer that will wake the Node.js event loop. Creating too many of these can adversely impact performance of the Node.js application. -Returns a reference to the `Timeout`. - ## Scheduling Timers A timer in Node.js is an internal construct that calls a given function after @@ -113,9 +105,10 @@ added: v0.9.1 * `callback` {Function} The function to call at the end of this turn of [the Node.js Event Loop] * `...args` {any} Optional arguments to pass when the `callback` is called. +* Returns: {Immediate} for use with [`clearImmediate()`][] Schedules the "immediate" execution of the `callback` after I/O events' -callbacks. Returns an `Immediate` for use with [`clearImmediate()`][]. +callbacks. When multiple calls to `setImmediate()` are made, the `callback` functions are queued for execution in the order in which they are created. The entire callback @@ -155,10 +148,9 @@ added: v0.0.1 * `delay` {number} The number of milliseconds to wait before calling the `callback`. * `...args` {any} Optional arguments to pass when the `callback` is called. -* Returns: {Timeout} +* Returns: {Timeout} for use with [`clearInterval()`][] Schedules repeated execution of `callback` every `delay` milliseconds. -Returns a `Timeout` for use with [`clearInterval()`][]. When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. @@ -174,10 +166,9 @@ added: v0.0.1 * `delay` {number} The number of milliseconds to wait before calling the `callback`. * `...args` {any} Optional arguments to pass when the `callback` is called. -* Returns: {Timeout} +* Returns: {Timeout} for use with [`clearTimeout()`][] Schedules execution of a one-time `callback` after `delay` milliseconds. -Returns a `Timeout` for use with [`clearTimeout()`][]. The `callback` will likely not be invoked in precisely `delay` milliseconds. Node.js makes no guarantees about the exact timing of when callbacks will fire, @@ -239,7 +230,6 @@ added: v0.0.1 Cancels a `Timeout` object created by [`setTimeout()`][]. - [`TypeError`]: errors.html#errors_class_typeerror [`clearImmediate()`]: timers.html#timers_clearimmediate_immediate [`clearInterval()`]: timers.html#timers_clearinterval_timeout diff --git a/doc/api/tls.md b/doc/api/tls.md index 0f9e46f2474d57..e22286adb45ad3 100644 --- a/doc/api/tls.md +++ b/doc/api/tls.md @@ -404,7 +404,7 @@ added: v3.0.0 * Returns: {Buffer} Returns a `Buffer` instance holding the keys currently used for -encryption/decryption of the [TLS Session Tickets][] +encryption/decryption of the [TLS Session Tickets][]. ### server.listen() @@ -422,13 +422,11 @@ added: v3.0.0 Updates the keys for encryption/decryption of the [TLS Session Tickets][]. The key's `Buffer` should be 48 bytes long. See `ticketKeys` option in -[tls.createServer](#tls_tls_createserver_options_secureconnectionlistener) for -more information on how it is used. +[`tls.createServer()`] for more information on how it is used. Changes to the ticket keys are effective only for future server connections. Existing or currently pending server connections will use the previous keys. - ## Class: tls.TLSSocket -The `tty.WriteStream` class is a subclass of `net.Socket` that represents the -writable side of a TTY. In normal circumstances, [`process.stdout`][] and +The `tty.WriteStream` class is a subclass of [`net.Socket`][] that represents +the writable side of a TTY. In normal circumstances, [`process.stdout`][] and [`process.stderr`][] will be the only `tty.WriteStream` instances created for a Node.js process and there should be no reason to create additional instances. @@ -126,15 +126,15 @@ is updated whenever the `'resize'` event is emitted. added: v9.9.0 --> -* `env` {Object} A object containing the environment variables to check. +* `env` {Object} An object containing the environment variables to check. **Default:** `process.env`. * Returns: {number} Returns: -* 1 for 2, -* 4 for 16, -* 8 for 256, -* 24 for 16,777,216 +* `1` for 2, +* `4` for 16, +* `8` for 256, +* `24` for 16,777,216 colors supported. Use this to determine what colors the terminal supports. Due to the nature of diff --git a/doc/api/url.md b/doc/api/url.md index 35a72da8ee681f..64b7b444c54ffd 100644 --- a/doc/api/url.md +++ b/doc/api/url.md @@ -86,8 +86,8 @@ The `URL` class is also available on the global object. In accordance with browser conventions, all properties of `URL` objects are implemented as getters and setters on the class prototype, rather than as -data properties on the object itself. Thus, unlike [legacy urlObject][]s, using -the `delete` keyword on any properties of `URL` objects (e.g. `delete +data properties on the object itself. Thus, unlike [legacy `urlObject`][]s, +using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still return `true`. @@ -132,8 +132,6 @@ and a `base` is provided, it is advised to validate that the `origin` of the `URL` object is what is expected. ```js -const { URL } = require('url'); - let myURL = new URL('http://anotherExample.org/', 'https://example.org/'); // http://anotherexample.org/ @@ -348,7 +346,7 @@ console.log(myURL.port); // Prints 1234 ``` -The port value may be set as either a number or as a String containing a number +The port value may be set as either a number or as a string containing a number in the range `0` to `65535` (inclusive). Setting the value to the default port of the `URL` objects given `protocol` will result in the `port` value becoming the empty string (`''`). @@ -583,7 +581,7 @@ added: v7.10.0 * `iterable` {Iterable} An iterable object whose elements are key-value pairs Instantiate a new `URLSearchParams` object with an iterable map in a way that -is similar to [`Map`][]'s constructor. `iterable` can be an Array or any +is similar to [`Map`][]'s constructor. `iterable` can be an `Array` or any iterable object. That means `iterable` can be another `URLSearchParams`, in which case the constructor will simply create a clone of the provided `URLSearchParams`. Elements of `iterable` are key-value pairs, and can @@ -646,16 +644,16 @@ Remove all name-value pairs whose name is `name`. * Returns: {Iterator} -Returns an ES6 Iterator over each of the name-value pairs in the query. -Each item of the iterator is a JavaScript Array. The first item of the Array -is the `name`, the second item of the Array is the `value`. +Returns an ES6 `Iterator` over each of the name-value pairs in the query. +Each item of the iterator is a JavaScript `Array`. The first item of the `Array` +is the `name`, the second item of the `Array` is the `value`. Alias for [`urlSearchParams[@@iterator]()`][`urlSearchParams@@iterator()`]. #### urlSearchParams.forEach(fn[, thisArg]) -* `fn` {Function} Function invoked for each name-value pair in the query. -* `thisArg` {Object} Object to be used as `this` value for when `fn` is called +* `fn` {Function} Invoked for each name-value pair in the query +* `thisArg` {Object} To be used as `this` value for when `fn` is called Iterates over each name-value pair in the query and invokes the given function. @@ -697,7 +695,7 @@ Returns `true` if there is at least one name-value pair whose name is `name`. * Returns: {Iterator} -Returns an ES6 Iterator over the names of each name-value pair. +Returns an ES6 `Iterator` over the names of each name-value pair. ```js const params = new URLSearchParams('foo=bar&foo=baz'); @@ -762,15 +760,15 @@ percent-encoded where necessary. * Returns: {Iterator} -Returns an ES6 Iterator over the values of each name-value pair. +Returns an ES6 `Iterator` over the values of each name-value pair. #### urlSearchParams\[Symbol.iterator\]() * Returns: {Iterator} -Returns an ES6 Iterator over each of the name-value pairs in the query string. -Each item of the iterator is a JavaScript Array. The first item of the Array -is the `name`, the second item of the Array is the `value`. +Returns an ES6 `Iterator` over each of the name-value pairs in the query string. +Each item of the iterator is a JavaScript `Array`. The first item of the `Array` +is the `name`, the second item of the `Array` is the `value`. Alias for [`urlSearchParams.entries()`][]. @@ -848,7 +846,7 @@ added: v7.6.0 Punycode encoded. **Default:** `false`. * Returns: {string} -Returns a customizable serialization of a URL String representation of a +Returns a customizable serialization of a URL `String` representation of a [WHATWG URL][] object. The URL object has both a `toString()` method and `href` property that return @@ -873,9 +871,9 @@ console.log(url.format(myURL, { fragment: false, unicode: true, auth: false })); ## Legacy URL API -### Legacy urlObject +### Legacy `urlObject` -The legacy urlObject (`require('url').Url`) is created and returned by the +The legacy `urlObject` (`require('url').Url`) is created and returned by the `url.parse()` function. #### urlObject.auth @@ -886,42 +884,42 @@ double slashes (if present) and precedes the `host` component, delimited by an ASCII "at sign" (`@`). The format of the string is `{username}[:{password}]`, with the `[:{password}]` portion being optional. -For example: `'user:pass'` +For example: `'user:pass'`. #### urlObject.hash The `hash` property consists of the "fragment" portion of the URL including the leading ASCII hash (`#`) character. -For example: `'#hash'` +For example: `'#hash'`. #### urlObject.host The `host` property is the full lower-cased host portion of the URL, including the `port` if specified. -For example: `'sub.host.com:8080'` +For example: `'sub.host.com:8080'`. #### urlObject.hostname The `hostname` property is the lower-cased host name portion of the `host` component *without* the `port` included. -For example: `'sub.host.com'` +For example: `'sub.host.com'`. #### urlObject.href The `href` property is the full URL string that was parsed with both the `protocol` and `host` components converted to lower-case. -For example: `'http://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash'` +For example: `'http://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash'`. #### urlObject.path The `path` property is a concatenation of the `pathname` and `search` components. -For example: `'/p/a/t/h?query=string'` +For example: `'/p/a/t/h?query=string'`. No decoding of the `path` is performed. @@ -932,7 +930,7 @@ is everything following the `host` (including the `port`) and before the start of the `query` or `hash` components, delimited by either the ASCII question mark (`?`) or hash (`#`) characters. -For example `'/p/a/t/h'` +For example `'/p/a/t/h'`. No decoding of the path string is performed. @@ -940,13 +938,13 @@ No decoding of the path string is performed. The `port` property is the numeric port portion of the `host` component. -For example: `'8080'` +For example: `'8080'`. #### urlObject.protocol The `protocol` property identifies the URL's lower-cased protocol scheme. -For example: `'http:'` +For example: `'http:'`. #### urlObject.query @@ -955,7 +953,7 @@ question mark (`?`), or an object returned by the [`querystring`][] module's `parse()` method. Whether the `query` property is a string or object is determined by the `parseQueryString` argument passed to `url.parse()`. -For example: `'query=string'` or `{'query': 'string'}` +For example: `'query=string'` or `{'query': 'string'}`. If returned as a string, no decoding of the query string is performed. If returned as an object, both keys and values are decoded. @@ -965,7 +963,7 @@ returned as an object, both keys and values are decoded. The `search` property consists of the entire "query string" portion of the URL, including the leading ASCII question mark (`?`) character. -For example: `'?query=string'` +For example: `'?query=string'`. No decoding of the query string is performed. @@ -1041,7 +1039,7 @@ The formatting process operates as follows: `urlObject.host` is coerced to a string and appended to `result`. * If the `urlObject.pathname` property is a string that is not an empty string: * If the `urlObject.pathname` *does not start* with an ASCII forward slash - (`/`), then the literal string '/' is appended to `result`. + (`/`), then the literal string `'/'` is appended to `result`. * The value of `urlObject.pathname` is appended to `result`. * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an [`Error`][] is thrown. @@ -1063,7 +1061,6 @@ The formatting process operates as follows: string, an [`Error`][] is thrown. * `result` is returned. - ### url.parse(urlString[, parseQueryString[, slashesDenoteHost]]) -* `object` {any} Any JavaScript primitive or Object. +* `object` {any} Any JavaScript primitive or `Object`. * `options` {Object} * `showHidden` {boolean} If `true`, the `object`'s non-enumerable symbols and properties will be included in the formatted result as well as [`WeakMap`][] @@ -623,7 +623,7 @@ util.inspect(obj); added: v6.6.0 --> -A Symbol that can be used to declare custom inspect functions, see +A {symbol} that can be used to declare custom inspect functions, see [Custom inspection functions on Objects][]. ### util.inspect.defaultOptions @@ -670,7 +670,7 @@ added: v8.0.0 * Returns: {Function} Takes a function following the common error-first callback style, i.e. taking -a `(err, value) => ...` callback as the last argument, and returns a version +an `(err, value) => ...` callback as the last argument, and returns a version that returns promises. ```js @@ -752,7 +752,7 @@ added: v8.0.0 * {symbol} -A Symbol that can be used to declare custom promisified variants of functions, +A {symbol} that can be used to declare custom promisified variants of functions, see [Custom promisified functions][]. ## Class: util.TextDecoder @@ -859,7 +859,7 @@ supported encodings or an alias. ### textDecoder.decode([input[, options]]) * `input` {ArrayBuffer|DataView|TypedArray} An `ArrayBuffer`, `DataView` or - Typed Array instance containing the encoded data. + `Typed Array` instance containing the encoded data. * `options` {Object} * `stream` {boolean} `true` if additional chunks of data are expected. **Default:** `false`. @@ -1537,7 +1537,6 @@ const module = new WebAssembly.Module(wasmBuffer); util.types.isWebAssemblyCompiledModule(module); // Returns true ``` - ## Deprecated APIs The following APIs have been deprecated and should no longer be used. Existing diff --git a/doc/api/vm.md b/doc/api/vm.md index 75fb03642cc6b7..9e1249dc4ed8bb 100644 --- a/doc/api/vm.md +++ b/doc/api/vm.md @@ -162,20 +162,20 @@ const contextifiedSandbox = vm.createContext({ secret: 42 }); * `url` {string} URL used in module resolution and stack traces. **Default:** `'vm:module(i)'` where `i` is a context-specific ascending index. * `context` {Object} The [contextified][] object as returned by the - `vm.createContext()` method, to compile and evaluate this Module in. + `vm.createContext()` method, to compile and evaluate this `Module` in. * `lineOffset` {integer} Specifies the line number offset that is displayed - in stack traces produced by this Module. - * `columnOffset` {integer} Spcifies the column number offset that is displayed - in stack traces produced by this Module. - * `initalizeImportMeta` {Function} Called during evaluation of this Module to - initialize the `import.meta`. This function has the signature `(meta, - module)`, where `meta` is the `import.meta` object in the Module, and + in stack traces produced by this `Module`. + * `columnOffset` {integer} Specifies the column number offset that is + displayed in stack traces produced by this `Module`. + * `initalizeImportMeta` {Function} Called during evaluation of this `Module` + to initialize the `import.meta`. This function has the signature `(meta, + module)`, where `meta` is the `import.meta` object in the `Module`, and `module` is this `vm.Module` object. Creates a new ES `Module` object. *Note*: Properties assigned to the `import.meta` object that are objects may -allow the Module to access information outside the specified `context`, if the +allow the `Module` to access information outside the specified `context`, if the object is created in the top level context. Use `vm.runInContext()` to create objects in a specific context. @@ -217,8 +217,8 @@ const contextifiedSandbox = vm.createContext({ secret: 42 }); The specifiers of all dependencies of this module. The returned array is frozen to disallow any changes to it. -Corresponds to the [[RequestedModules]] field of [Source Text Module Record][]s -in the ECMAScript specification. +Corresponds to the `[[RequestedModules]]` field of +[Source Text Module Record][]s in the ECMAScript specification. ### module.error @@ -231,7 +231,7 @@ accessing this property will result in a thrown exception. The value `undefined` cannot be used for cases where there is not a thrown exception due to possible ambiguity with `throw undefined;`. -Corresponds to the [[EvaluationError]] field of [Source Text Module Record][]s +Corresponds to the `[[EvaluationError]]` field of [Source Text Module Record][]s in the ECMAScript specification. ### module.linkingStatus @@ -246,8 +246,8 @@ The current linking status of `module`. It will be one of the following values: - `'linked'`: `module.link()` has been called, and all its dependencies have been successfully linked. - `'errored'`: `module.link()` has been called, but at least one of its - dependencies failed to link, either because the callback returned a Promise - that is rejected, or because the Module the callback returned is invalid. + dependencies failed to link, either because the callback returned a `Promise` + that is rejected, or because the `Module` the callback returned is invalid. ### module.namespace @@ -289,9 +289,9 @@ The current status of the module. Will be one of: - `'errored'`: The module has been evaluated, but an exception was thrown. Other than `'errored'`, this status string corresponds to the specification's -[Source Text Module Record][]'s [[Status]] field. `'errored'` corresponds to -`'evaluated'` in the specification, but with [[EvaluationError]] set to a value -that is not `undefined`. +[Source Text Module Record][]'s `[[Status]]` field. `'errored'` corresponds to +`'evaluated'` in the specification, but with `[[EvaluationError]]` set to a +value that is not `undefined`. ### module.url @@ -472,7 +472,6 @@ changes: during script execution, but will continue to work after that. If execution is terminated, an [`Error`][] will be thrown. - Runs the compiled code contained by the `vm.Script` object within the given `contextifiedSandbox` and returns the result. Running code does not have access to local scope. @@ -868,7 +867,7 @@ const code = ` })`; vm.runInThisContext(code)(require); - ``` +``` The `require()` in the above case shares the state with the context it is passed from. This may introduce risks when untrusted code is executed, e.g. diff --git a/doc/api/zlib.md b/doc/api/zlib.md index 1fe05f26ca3b5d..0e66abdcfb0766 100644 --- a/doc/api/zlib.md +++ b/doc/api/zlib.md @@ -165,7 +165,7 @@ The memory requirements for deflate are (in bytes): (1 << (windowBits + 2)) + (1 << (memLevel + 9)) ``` -That is: 128K for windowBits = 15 + 128K for memLevel = 8 +That is: 128K for `windowBits` = 15 + 128K for `memLevel` = 8 (default values) plus a few kilobytes for small objects. For example, to reduce the default memory requirements from 256K to 128K, the @@ -178,7 +178,7 @@ const options = { windowBits: 14, memLevel: 7 }; This will, however, generally degrade compression. The memory requirements for inflate are (in bytes) `1 << windowBits`. -That is, 32K for windowBits = 15 (default value) plus a few kilobytes +That is, 32K for `windowBits` = 15 (default value) plus a few kilobytes for small objects. This is in addition to a single internal output slab buffer of size @@ -287,10 +287,10 @@ added: v0.11.1 changes: - version: v9.4.0 pr-url: https://github.com/nodejs/node/pull/16042 - description: The `dictionary` option can be an ArrayBuffer. + description: The `dictionary` option can be an `ArrayBuffer`. - version: v8.0.0 pr-url: https://github.com/nodejs/node/pull/12001 - description: The `dictionary` option can be an Uint8Array now. + description: The `dictionary` option can be an `Uint8Array` now. - version: v5.11.0 pr-url: https://github.com/nodejs/node/pull/6069 description: The `finishFlush` option is supported now. @@ -312,7 +312,7 @@ ignored by the decompression classes. * `strategy` {integer} (compression only) * `dictionary` {Buffer|TypedArray|DataView|ArrayBuffer} (deflate/inflate only, empty dictionary by default) -* `info` {boolean} (If `true`, returns an object with `buffer` and `engine`) +* `info` {boolean} (If `true`, returns an object with `buffer` and `engine`.) See the description of `deflateInit2` and `inflateInit2` at for more information on these. @@ -473,17 +473,17 @@ Provides an object enumerating Zlib-related constants. added: v0.5.8 --> -Creates and returns a new [Deflate][] object with the given [`options`][]. +Creates and returns a new [`Deflate`][] object with the given [`options`][]. ## zlib.createDeflateRaw([options]) -Creates and returns a new [DeflateRaw][] object with the given [`options`][]. +Creates and returns a new [`DeflateRaw`][] object with the given [`options`][]. -An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when windowBits -is set to 8 for raw deflate streams. zlib would automatically set windowBits +An upgrade of zlib from 1.2.8 to 1.2.11 changed behavior when `windowBits` +is set to 8 for raw deflate streams. zlib would automatically set `windowBits` to 9 if was initially set to 8. Newer versions of zlib will throw an exception, so Node.js restored the original behavior of upgrading a value of 8 to 9, since passing `windowBits = 9` to zlib actually results in a compressed stream @@ -494,35 +494,35 @@ that effectively uses an 8-bit window only. added: v0.5.8 --> -Creates and returns a new [Gunzip][] object with the given [`options`][]. +Creates and returns a new [`Gunzip`][] object with the given [`options`][]. ## zlib.createGzip([options]) -Creates and returns a new [Gzip][] object with the given [`options`][]. +Creates and returns a new [`Gzip`][] object with the given [`options`][]. ## zlib.createInflate([options]) -Creates and returns a new [Inflate][] object with the given [`options`][]. +Creates and returns a new [`Inflate`][] object with the given [`options`][]. ## zlib.createInflateRaw([options]) -Creates and returns a new [InflateRaw][] object with the given [`options`][]. +Creates and returns a new [`InflateRaw`][] object with the given [`options`][]. ## zlib.createUnzip([options]) -Creates and returns a new [Unzip][] object with the given [`options`][]. +Creates and returns a new [`Unzip`][] object with the given [`options`][]. ## Convenience Methods @@ -542,13 +542,13 @@ added: v0.6.0 changes: - version: v9.4.0 pr-url: https://github.com/nodejs/node/pull/16042 - description: The `buffer` parameter can be an ArrayBuffer. + description: The `buffer` parameter can be an `ArrayBuffer`. - version: v8.0.0 pr-url: https://github.com/nodejs/node/pull/12223 - description: The `buffer` parameter can be any TypedArray or DataView now. + description: The `buffer` parameter can be any `TypedArray` or `DataView`. - version: v8.0.0 pr-url: https://github.com/nodejs/node/pull/12001 - description: The `buffer` parameter can be an Uint8Array now. + description: The `buffer` parameter can be an `Uint8Array` now. --> ### zlib.deflateSync(buffer[, options]) - `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string} -Compress a chunk of data with [Deflate][]. +Compress a chunk of data with [`Deflate`][]. ### zlib.deflateRaw(buffer[, options], callback) ### zlib.deflateRawSync(buffer[, options]) - `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string} -Compress a chunk of data with [DeflateRaw][]. +Compress a chunk of data with [`DeflateRaw`][]. ### zlib.gunzip(buffer[, options], callback) ### zlib.gunzipSync(buffer[, options]) - `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string} -Decompress a chunk of data with [Gunzip][]. +Decompress a chunk of data with [`Gunzip`][]. ### zlib.gzip(buffer[, options], callback) ### zlib.gzipSync(buffer[, options]) - `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string} -Compress a chunk of data with [Gzip][]. +Compress a chunk of data with [`Gzip`][]. ### zlib.inflate(buffer[, options], callback) ### zlib.inflateSync(buffer[, options]) - `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string} -Decompress a chunk of data with [Inflate][]. +Decompress a chunk of data with [`Inflate`][]. ### zlib.inflateRaw(buffer[, options], callback) ### zlib.inflateRawSync(buffer[, options]) - `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string} -Decompress a chunk of data with [InflateRaw][]. +Decompress a chunk of data with [`InflateRaw`][]. ### zlib.unzip(buffer[, options], callback) ### zlib.unzipSync(buffer[, options]) - `buffer` {Buffer|TypedArray|DataView|ArrayBuffer|string} -Decompress a chunk of data with [Unzip][]. +Decompress a chunk of data with [`Unzip`][]. [`.flush()`]: #zlib_zlib_flush_kind_callback [`Accept-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3 @@ -770,16 +770,16 @@ Decompress a chunk of data with [Unzip][]. [`Buffer`]: buffer.html#buffer_class_buffer [`Content-Encoding`]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11 [`DataView`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView +[`Deflate`]: #zlib_class_zlib_deflate +[`DeflateRaw`]: #zlib_class_zlib_deflateraw +[`Gunzip`]: #zlib_class_zlib_gunzip +[`Gzip`]: #zlib_class_zlib_gzip +[`Inflate`]: #zlib_class_zlib_inflate +[`InflateRaw`]: #zlib_class_zlib_inflateraw [`TypedArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray -[`options`]: #zlib_class_options -[DeflateRaw]: #zlib_class_zlib_deflateraw -[Deflate]: #zlib_class_zlib_deflate -[Gunzip]: #zlib_class_zlib_gunzip -[Gzip]: #zlib_class_zlib_gzip -[InflateRaw]: #zlib_class_zlib_inflateraw -[Inflate]: #zlib_class_zlib_inflate -[Memory Usage Tuning]: #zlib_memory_usage_tuning -[Unzip]: #zlib_class_zlib_unzip [`UV_THREADPOOL_SIZE`]: cli.html#cli_uv_threadpool_size_size +[`Unzip`]: #zlib_class_zlib_unzip +[`options`]: #zlib_class_options [`zlib.bytesWritten`]: #zlib_zlib_byteswritten +[Memory Usage Tuning]: #zlib_memory_usage_tuning [zlib documentation]: https://zlib.net/manual.html#Constants diff --git a/doc/changelogs/CHANGELOG_V10.md b/doc/changelogs/CHANGELOG_V10.md index 1f027679b3bf83..48e757a5c452bc 100644 --- a/doc/changelogs/CHANGELOG_V10.md +++ b/doc/changelogs/CHANGELOG_V10.md @@ -9,6 +9,7 @@ +10.1.0
10.0.0
@@ -26,6 +27,197 @@ * [io.js](CHANGELOG_IOJS.md) * [Archive](CHANGELOG_ARCHIVE.md) + +## 2018-05-08, Version 10.1.0 (Current), @MylesBorins + +### Notable Changes + +* **console**: + - make console.table() use colored inspect (TSUYUSATO Kitsune) [#20510](https://github.com/nodejs/node/pull/20510) +* **fs**: + - move fs/promises to fs.promises (cjihrig) [#20504](https://github.com/nodejs/node/pull/20504) +* **http**: + - added aborted property to request (Robert Nagy) [#20094](https://github.com/nodejs/node/pull/20094) +* **n-api**: + - initialize a module via a special symbol (Gabriel Schulhof) [#20161](https://github.com/nodejs/node/pull/20161) +* **src**: + - add public API to expose the main V8 Platform (Allen Yonghuang Wang) [#20447](https://github.com/nodejs/node/pull/20447) + +### Commits + +* [[`7293c58d51`](https://github.com/nodejs/node/commit/7293c58d51)] - **assert**: make skipping indicator blue (Ruben Bridgewater) [#20315](https://github.com/nodejs/node/pull/20315) +* [[`f5054d3412`](https://github.com/nodejs/node/commit/f5054d3412)] - **assert**: minor error message improvements (Ruben Bridgewater) [#20315](https://github.com/nodejs/node/pull/20315) +* [[`16970ffda4`](https://github.com/nodejs/node/commit/16970ffda4)] - **benchmark**: track exec time in next-tick-exec (Anatoli Papirovski) [#20462](https://github.com/nodejs/node/pull/20462) +* [[`289e4cef3f`](https://github.com/nodejs/node/commit/289e4cef3f)] - **benchmark**: fix next-tick-depth (Anatoli Papirovski) [#20461](https://github.com/nodejs/node/pull/20461) +* [[`b0e6f10530`](https://github.com/nodejs/node/commit/b0e6f10530)] - **benchmark**: add bench for zlib gzip + gunzip cycle (Anna Henningsen) [#20034](https://github.com/nodejs/node/pull/20034) +* [[`167de1f038`](https://github.com/nodejs/node/commit/167de1f038)] - **build**: check for different deprecation signatures (Ruben Bridgewater) [#20384](https://github.com/nodejs/node/pull/20384) +* [[`348d391a71`](https://github.com/nodejs/node/commit/348d391a71)] - **build**: remove --xcode configure switch (Ben Noordhuis) [#20328](https://github.com/nodejs/node/pull/20328) +* [[`2ce4b7cb8c`](https://github.com/nodejs/node/commit/2ce4b7cb8c)] - **build**: do not depend on `cp` in `PATH` (Anna Henningsen) [#20296](https://github.com/nodejs/node/pull/20296) +* [[`c5b3459003`](https://github.com/nodejs/node/commit/c5b3459003)] - **build**: use -9 with `kill` in Makefile (Rich Trott) [#20195](https://github.com/nodejs/node/pull/20195) +* [[`b5931e1d45`](https://github.com/nodejs/node/commit/b5931e1d45)] - **child_process**: name anonymous functions (Denis Fäcke) [#20399](https://github.com/nodejs/node/pull/20399) +* [[`ec2037da12`](https://github.com/nodejs/node/commit/ec2037da12)] - **child_process**: fix leak when passing http sockets (Santiago Gimeno) [#20305](https://github.com/nodejs/node/pull/20305) +* [[`a7758c76c0`](https://github.com/nodejs/node/commit/a7758c76c0)] - **(SEMVER-MINOR)** **console**: make console.table() use colored inspect (TSUYUSATO Kitsune) [#20510](https://github.com/nodejs/node/pull/20510) +* [[`29bc735d42`](https://github.com/nodejs/node/commit/29bc735d42)] - **console**: fix console.table() display edge case (Rich Trott) [#20323](https://github.com/nodejs/node/pull/20323) +* [[`dfcf20f5fd`](https://github.com/nodejs/node/commit/dfcf20f5fd)] - **crypto**: use new OpenSSL constants in CipherBase (Tobias Nießen) [#20339](https://github.com/nodejs/node/pull/20339) +* [[`e17280e8c9`](https://github.com/nodejs/node/commit/e17280e8c9)] - **crypto**: make pbkdf2 use checkIsArrayBufferView (Daniel Bevenius) [#20251](https://github.com/nodejs/node/pull/20251) +* [[`61e93963ce`](https://github.com/nodejs/node/commit/61e93963ce)] - **crypto**: add checkIsArrayBufferView (Daniel Bevenius) [#20251](https://github.com/nodejs/node/pull/20251) +* [[`e81bb9f8a3`](https://github.com/nodejs/node/commit/e81bb9f8a3)] - **crypto**: add getIntOption function to reduce dupl (Daniel Bevenius) [#20247](https://github.com/nodejs/node/pull/20247) +* [[`391d2f830a`](https://github.com/nodejs/node/commit/391d2f830a)] - **crypto**: simplify diffiehellman getFormat function (Daniel Bevenius) [#20246](https://github.com/nodejs/node/pull/20246) +* [[`3cf53b66c2`](https://github.com/nodejs/node/commit/3cf53b66c2)] - **deps**: patch V8 to 6.6.346.27 (Myles Borins) [#20480](https://github.com/nodejs/node/pull/20480) +* [[`da8bc6ab50`](https://github.com/nodejs/node/commit/da8bc6ab50)] - **deps**: cherry-pick 76cab5f from upstream V8 (Michaël Zasso) [#20350](https://github.com/nodejs/node/pull/20350) +* [[`05ce635e9a`](https://github.com/nodejs/node/commit/05ce635e9a)] - **doc**: match console.count()/countReset() signatures (Lambdac0re) [#20599](https://github.com/nodejs/node/pull/20599) +* [[`e995ae5992`](https://github.com/nodejs/node/commit/e995ae5992)] - **doc**: clarify `this` in event listeners (daGo) [#20537](https://github.com/nodejs/node/pull/20537) +* [[`bd27a59865`](https://github.com/nodejs/node/commit/bd27a59865)] - **doc**: move tunniclm to Emeritus (Rich Trott) [#20533](https://github.com/nodejs/node/pull/20533) +* [[`ec65fe48d8`](https://github.com/nodejs/node/commit/ec65fe48d8)] - **doc**: add trace category for fs sync methods (Chin Huang) [#20526](https://github.com/nodejs/node/pull/20526) +* [[`8148fca730`](https://github.com/nodejs/node/commit/8148fca730)] - **doc**: update "Who to cc..." in COLLABORATOR\_GUIDE (Vse Mozhet Byt) [#20564](https://github.com/nodejs/node/pull/20564) +* [[`70586c0334`](https://github.com/nodejs/node/commit/70586c0334)] - **doc**: excise "periodically" before "emit events" (Jesse W. Collins) [#20581](https://github.com/nodejs/node/pull/20581) +* [[`01560b69a7`](https://github.com/nodejs/node/commit/01560b69a7)] - **doc**: edit text about revoking deprecations (Rich Trott) [#20519](https://github.com/nodejs/node/pull/20519) +* [[`eed3f10615`](https://github.com/nodejs/node/commit/eed3f10615)] - **doc**: edit text for DEP0013 (Rich Trott) [#20519](https://github.com/nodejs/node/pull/20519) +* [[`b2b4871c15`](https://github.com/nodejs/node/commit/b2b4871c15)] - **doc**: minor edit to DEP0065 (Rich Trott) [#20519](https://github.com/nodejs/node/pull/20519) +* [[`73f5ea9bd9`](https://github.com/nodejs/node/commit/73f5ea9bd9)] - **doc**: fix minor typographical error in DEP0079 text (Rich Trott) [#20519](https://github.com/nodejs/node/pull/20519) +* [[`faa81937a5`](https://github.com/nodejs/node/commit/faa81937a5)] - **doc**: edit text for DEP0082 (Rich Trott) [#20519](https://github.com/nodejs/node/pull/20519) +* [[`f796b0856c`](https://github.com/nodejs/node/commit/f796b0856c)] - **doc**: fix text for DEP0085 (Rich Trott) [#20519](https://github.com/nodejs/node/pull/20519) +* [[`74c74db35e`](https://github.com/nodejs/node/commit/74c74db35e)] - **doc**: edit text for DEP0094 (Rich Trott) [#20519](https://github.com/nodejs/node/pull/20519) +* [[`c6e4ffa429`](https://github.com/nodejs/node/commit/c6e4ffa429)] - **doc**: edit text for DEP0012 (Rich Trott) [#20519](https://github.com/nodejs/node/pull/20519) +* [[`adf5b80b20`](https://github.com/nodejs/node/commit/adf5b80b20)] - **doc**: edit text for DEP0101 (Rich Trott) [#20519](https://github.com/nodejs/node/pull/20519) +* [[`67e44bf588`](https://github.com/nodejs/node/commit/67e44bf588)] - **doc**: edit text for DEP0104 (Rich Trott) [#20519](https://github.com/nodejs/node/pull/20519) +* [[`0e8805186f`](https://github.com/nodejs/node/commit/0e8805186f)] - **doc**: add parameters for Http2Session:stream event (Ujjwal Sharma) [#20547](https://github.com/nodejs/node/pull/20547) +* [[`98ccaead0d`](https://github.com/nodejs/node/commit/98ccaead0d)] - **doc**: clearer doc-only deprecations (Ruben Bridgewater) [#20381](https://github.com/nodejs/node/pull/20381) +* [[`bea4ffcc97`](https://github.com/nodejs/node/commit/bea4ffcc97)] - **doc**: update one more command in crypto.md (Shobhit Chittora) [#20500](https://github.com/nodejs/node/pull/20500) +* [[`018b5ad800`](https://github.com/nodejs/node/commit/018b5ad800)] - **doc**: add snake\_case section for C-like structs (Daniel Bevenius) [#20423](https://github.com/nodejs/node/pull/20423) +* [[`8bd45d8212`](https://github.com/nodejs/node/commit/8bd45d8212)] - **doc**: updates crypto doc with openssl list -cipher-algorithms (Shobhit Chittora) [#20502](https://github.com/nodejs/node/pull/20502) +* [[`880772a7ff`](https://github.com/nodejs/node/commit/880772a7ff)] - **doc**: fix N-API property descriptor documentation (Gabriel Schulhof) [#20433](https://github.com/nodejs/node/pull/20433) +* [[`79e1260cd8`](https://github.com/nodejs/node/commit/79e1260cd8)] - **doc**: fix manpage warning (Jérémy Lal) [#20383](https://github.com/nodejs/node/pull/20383) +* [[`745e0a5583`](https://github.com/nodejs/node/commit/745e0a5583)] - **doc**: document using `domain` in REPL (Ayush Gupta) [#20382](https://github.com/nodejs/node/pull/20382) +* [[`b2e8b9c473`](https://github.com/nodejs/node/commit/b2e8b9c473)] - **doc**: fix mkdtemp() documentation (Rich Trott) [#20512](https://github.com/nodejs/node/pull/20512) +* [[`d7db306d3b`](https://github.com/nodejs/node/commit/d7db306d3b)] - **doc**: update examples for fs.access() (BeniCheni) [#20460](https://github.com/nodejs/node/pull/20460) +* [[`b2d6eb74d4`](https://github.com/nodejs/node/commit/b2d6eb74d4)] - **doc**: cleanup n-api.md doc (Michael Dawson) [#20430](https://github.com/nodejs/node/pull/20430) +* [[`e5537477d4`](https://github.com/nodejs/node/commit/e5537477d4)] - **doc**: update Collaborator Guide reference (Rich Trott) [#20473](https://github.com/nodejs/node/pull/20473) +* [[`391c420c3e`](https://github.com/nodejs/node/commit/391c420c3e)] - **doc**: synchronize argument names for appendFile() (Rich Trott) [#20489](https://github.com/nodejs/node/pull/20489) +* [[`8b17e7ae04`](https://github.com/nodejs/node/commit/8b17e7ae04)] - **doc**: update cli flag in crypto.md (Shobhit Chittora) [#20400](https://github.com/nodejs/node/pull/20400) +* [[`74685f1b8f`](https://github.com/nodejs/node/commit/74685f1b8f)] - **doc**: add missing periods in documentation.md (Vse Mozhet Byt) [#20469](https://github.com/nodejs/node/pull/20469) +* [[`b0ed31cf9c`](https://github.com/nodejs/node/commit/b0ed31cf9c)] - **doc**: update writing-and-running-benchmarks.md (xsbchen) [#20379](https://github.com/nodejs/node/pull/20379) +* [[`658fbdc105`](https://github.com/nodejs/node/commit/658fbdc105)] - **doc**: add http.ClientRequest maxHeadersCount (Daiki Arai) [#20361](https://github.com/nodejs/node/pull/20361) +* [[`7a769ebba8`](https://github.com/nodejs/node/commit/7a769ebba8)] - **doc**: add squash guideline to pull-requests doc (Rich Trott) [#20413](https://github.com/nodejs/node/pull/20413) +* [[`166df9e15c`](https://github.com/nodejs/node/commit/166df9e15c)] - **doc**: remove squash guideline from onboarding doc (Rich Trott) [#20413](https://github.com/nodejs/node/pull/20413) +* [[`56c27c6a2b`](https://github.com/nodejs/node/commit/56c27c6a2b)] - **doc**: add more missing backticks (Vse Mozhet Byt) [#20438](https://github.com/nodejs/node/pull/20438) +* [[`abf11550b2`](https://github.com/nodejs/node/commit/abf11550b2)] - **doc**: add missing periods or colons (Vse Mozhet Byt) [#20401](https://github.com/nodejs/node/pull/20401) +* [[`261776d6b4`](https://github.com/nodejs/node/commit/261776d6b4)] - **doc**: mitigate `marked` bug (Vse Mozhet Byt) [#20411](https://github.com/nodejs/node/pull/20411) +* [[`54e93315ed`](https://github.com/nodejs/node/commit/54e93315ed)] - **doc**: specify types of listener parameter (Vse Mozhet Byt) [#20405](https://github.com/nodejs/node/pull/20405) +* [[`fcc5492df2`](https://github.com/nodejs/node/commit/fcc5492df2)] - **doc**: clarify FileHandle text (Rich Trott) [#20450](https://github.com/nodejs/node/pull/20450) +* [[`5a839b9911`](https://github.com/nodejs/node/commit/5a839b9911)] - **doc**: remove unclear text from fs.write() (Rich Trott) [#20450](https://github.com/nodejs/node/pull/20450) +* [[`459c20c0b8`](https://github.com/nodejs/node/commit/459c20c0b8)] - **doc**: edit fs.createReadStream() highWaterMark (Rich Trott) [#20450](https://github.com/nodejs/node/pull/20450) +* [[`f36a5e3ba5`](https://github.com/nodejs/node/commit/f36a5e3ba5)] - **doc**: remove redundant table of contents for N-API (Ayush Gupta) [#20395](https://github.com/nodejs/node/pull/20395) +* [[`4bc87c185b`](https://github.com/nodejs/node/commit/4bc87c185b)] - **doc**: add parameters for settings events (Ujjwal Sharma) [#20371](https://github.com/nodejs/node/pull/20371) +* [[`d7557e111e`](https://github.com/nodejs/node/commit/d7557e111e)] - **doc**: refine napi\_get\_property\_names() doc (Gabriel Schulhof) [#20427](https://github.com/nodejs/node/pull/20427) +* [[`b61ae7fe09`](https://github.com/nodejs/node/commit/b61ae7fe09)] - **doc**: remove "has been known" tentativeness (Rich Trott) [#20412](https://github.com/nodejs/node/pull/20412) +* [[`de9d1f15de`](https://github.com/nodejs/node/commit/de9d1f15de)] - **doc**: remove parenthetical in onboarding-extras (Rich Trott) [#20393](https://github.com/nodejs/node/pull/20393) +* [[`5542a98aa4`](https://github.com/nodejs/node/commit/5542a98aa4)] - **doc**: improve process event headers (Ruben Bridgewater) [#20312](https://github.com/nodejs/node/pull/20312) +* [[`90026c3f3e`](https://github.com/nodejs/node/commit/90026c3f3e)] - **doc**: improve assert docs (Ruben Bridgewater) [#20313](https://github.com/nodejs/node/pull/20313) +* [[`57e5a3e15f`](https://github.com/nodejs/node/commit/57e5a3e15f)] - **doc**: remove redundant empty lines (Vse Mozhet Byt) [#20398](https://github.com/nodejs/node/pull/20398) +* [[`9cf3ae5bc3`](https://github.com/nodejs/node/commit/9cf3ae5bc3)] - **doc**: add missing backticks in n-api.md (Vse Mozhet Byt) [#20390](https://github.com/nodejs/node/pull/20390) +* [[`be34388a07`](https://github.com/nodejs/node/commit/be34388a07)] - **doc**: unify and dedupe returned values in timers.md (Vse Mozhet Byt) [#20310](https://github.com/nodejs/node/pull/20310) +* [[`9c11a18f70`](https://github.com/nodejs/node/commit/9c11a18f70)] - **doc**: remove eu-strip from tarball (jvelezpo) [#20304](https://github.com/nodejs/node/pull/20304) +* [[`b47044ac0f`](https://github.com/nodejs/node/commit/b47044ac0f)] - **doc**: improve parameters for Http2Session:goaway event (Ujjwal Sharma) +* [[`701f536ef4`](https://github.com/nodejs/node/commit/701f536ef4)] - **doc**: remove superfluous URL require statement (Mark Tiedemann) [#20364](https://github.com/nodejs/node/pull/20364) +* [[`d9bc9217a7`](https://github.com/nodejs/node/commit/d9bc9217a7)] - **doc**: fix typo in console.md (Daniel Hritzkiv) [#20349](https://github.com/nodejs/node/pull/20349) +* [[`cc09d7ec5b`](https://github.com/nodejs/node/commit/cc09d7ec5b)] - **doc**: remove console.table() as inspector-dependent (Rich Trott) [#20346](https://github.com/nodejs/node/pull/20346) +* [[`14188b1266`](https://github.com/nodejs/node/commit/14188b1266)] - **doc**: add Slack community to support options (Tracy) [#18191](https://github.com/nodejs/node/pull/18191) +* [[`3a3144cf04`](https://github.com/nodejs/node/commit/3a3144cf04)] - **doc**: remove os.uptime() Windows note (cjihrig) [#20308](https://github.com/nodejs/node/pull/20308) +* [[`c139d2ab8d`](https://github.com/nodejs/node/commit/c139d2ab8d)] - **doc**: fix unhandled to uncaught (Ruben Bridgewater) [#20293](https://github.com/nodejs/node/pull/20293) +* [[`7f6172b64b`](https://github.com/nodejs/node/commit/7f6172b64b)] - **doc**: improve docs for Http2Session:frameError (Ujjwal Sharma) [#20236](https://github.com/nodejs/node/pull/20236) +* [[`c9b202f817`](https://github.com/nodejs/node/commit/c9b202f817)] - **doc**: add emitter.off() to events.md (Ajido) [#20291](https://github.com/nodejs/node/pull/20291) +* [[`3bf736e569`](https://github.com/nodejs/node/commit/3bf736e569)] - **doc**: update pull request template in guide (Zachary Vacura) [#20277](https://github.com/nodejs/node/pull/20277) +* [[`171cbb1c64`](https://github.com/nodejs/node/commit/171cbb1c64)] - **doc**: fix net.Socket link inconsistencies (Hackzzila) [#20271](https://github.com/nodejs/node/pull/20271) +* [[`26525ef5ab`](https://github.com/nodejs/node/commit/26525ef5ab)] - **doc**: fix typos in doc/changelogs/CHANGELOG\_V10.md (Vse Mozhet Byt) [#20265](https://github.com/nodejs/node/pull/20265) +* [[`3bc5353110`](https://github.com/nodejs/node/commit/3bc5353110)] - **doc**: fix spelling of API name in 10.0.0 changelog (Tobias Nießen) [#20257](https://github.com/nodejs/node/pull/20257) +* [[`e25f2c9e91`](https://github.com/nodejs/node/commit/e25f2c9e91)] - **errors**: remove dead code (Ruben Bridgewater) [#20483](https://github.com/nodejs/node/pull/20483) +* [[`b89d8178b4`](https://github.com/nodejs/node/commit/b89d8178b4)] - **errors**: minor (SystemError) refactoring (Ruben Bridgewater) [#20337](https://github.com/nodejs/node/pull/20337) +* [[`58a65d6689`](https://github.com/nodejs/node/commit/58a65d6689)] - **events**: optimize condition for optimal scenario (Anatoli Papirovski) [#20452](https://github.com/nodejs/node/pull/20452) +* [[`eb483dbac5`](https://github.com/nodejs/node/commit/eb483dbac5)] - **fs**: fchmod-\>fchown in promises/lchown (Сковорода Никита Андреевич) [#20407](https://github.com/nodejs/node/pull/20407) +* [[`eb724f00a3`](https://github.com/nodejs/node/commit/eb724f00a3)] - **fs**: remove broken code in promises/write (Сковорода Никита Андреевич) [#20407](https://github.com/nodejs/node/pull/20407) +* [[`0b5dd102e0`](https://github.com/nodejs/node/commit/0b5dd102e0)] - **fs**: move fs/promises to fs.promises (cjihrig) [#20504](https://github.com/nodejs/node/pull/20504) +* [[`e45e5b809d`](https://github.com/nodejs/node/commit/e45e5b809d)] - **fs**: point isFd to isUint32 (Daniel Bevenius) [#20330](https://github.com/nodejs/node/pull/20330) +* [[`f0b2b2605a`](https://github.com/nodejs/node/commit/f0b2b2605a)] - **http**: refactor outgoing headers processing (Anatoli Papirovski) [#20250](https://github.com/nodejs/node/pull/20250) +* [[`1385ffcccf`](https://github.com/nodejs/node/commit/1385ffcccf)] - **(SEMVER-MINOR)** **http**: added aborted property to request (Robert Nagy) [#20094](https://github.com/nodejs/node/pull/20094) +* [[`6acefc36ee`](https://github.com/nodejs/node/commit/6acefc36ee)] - **http2**: rename http2\_state class to Http2State (Daniel Bevenius) [#20423](https://github.com/nodejs/node/pull/20423) +* [[`42bbaa338d`](https://github.com/nodejs/node/commit/42bbaa338d)] - **http2**: reduce require calls in http2/core (Daniel Bevenius) [#20422](https://github.com/nodejs/node/pull/20422) +* [[`e397d19e58`](https://github.com/nodejs/node/commit/e397d19e58)] - **http2**: remove unnecessary v8 qualified names (Daniel Bevenius) [#20420](https://github.com/nodejs/node/pull/20420) +* [[`b2bbc3619e`](https://github.com/nodejs/node/commit/b2bbc3619e)] - **http2**: remove unused using declarations node\_http2 (Daniel Bevenius) [#20420](https://github.com/nodejs/node/pull/20420) +* [[`7d9f1f3971`](https://github.com/nodejs/node/commit/7d9f1f3971)] - **http2**: fix ping callback (Ruben Bridgewater) [#20311](https://github.com/nodejs/node/pull/20311) +* [[`46bd86235d`](https://github.com/nodejs/node/commit/46bd86235d)] - **http2**: fix responses to long payload reqs (Anatoli Papirovski) [#20084](https://github.com/nodejs/node/pull/20084) +* [[`0b16c2482d`](https://github.com/nodejs/node/commit/0b16c2482d)] - **https**: defines maxHeadersCount in the constructor (Daiki Arai) [#20359](https://github.com/nodejs/node/pull/20359) +* [[`1490164230`](https://github.com/nodejs/node/commit/1490164230)] - **inspector**: allow concurrent inspector sessions (Eugene Ostroukhov) [#20137](https://github.com/nodejs/node/pull/20137) +* [[`375994f940`](https://github.com/nodejs/node/commit/375994f940)] - **inspector**: Use default uv\_listen backlog size (Eugene Ostroukhov) [#20254](https://github.com/nodejs/node/pull/20254) +* [[`7b8e9ca7b8`](https://github.com/nodejs/node/commit/7b8e9ca7b8)] - **lib**: expose FixedQueue internally and fix nextTick bug (Anatoli Papirovski) [#20468](https://github.com/nodejs/node/pull/20468) +* [[`b6de6a7e35`](https://github.com/nodejs/node/commit/b6de6a7e35)] - **lib**: named anonymous functions (Carrie Coxwell) [#20408](https://github.com/nodejs/node/pull/20408) +* [[`9eacd66bcb`](https://github.com/nodejs/node/commit/9eacd66bcb)] - **lib**: make sure `console` is writable (Kyle Farnung) [#20185](https://github.com/nodejs/node/pull/20185) +* [[`17dbf6c77f`](https://github.com/nodejs/node/commit/17dbf6c77f)] - **n-api**: make test\_error functions static (Gabriel Schulhof) +* [[`ad793ab93c`](https://github.com/nodejs/node/commit/ad793ab93c)] - **n-api**: test and doc napi\_throw() of a primitive (Gabriel Schulhof) [#20428](https://github.com/nodejs/node/pull/20428) +* [[`1908668826`](https://github.com/nodejs/node/commit/1908668826)] - **n-api**: document the look of napi\_external values (Gabriel Schulhof) [#20426](https://github.com/nodejs/node/pull/20426) +* [[`7ac491b8ac`](https://github.com/nodejs/node/commit/7ac491b8ac)] - **n-api**: document that native strings are copied (Gabriel Schulhof) [#20425](https://github.com/nodejs/node/pull/20425) +* [[`705d9ecd13`](https://github.com/nodejs/node/commit/705d9ecd13)] - **n-api**: remove unused Test function (Daniel Bevenius) [#20320](https://github.com/nodejs/node/pull/20320) +* [[`8d24b6ed34`](https://github.com/nodejs/node/commit/8d24b6ed34)] - **n-api**: update cli documentation (Gabriel Schulhof) [#20301](https://github.com/nodejs/node/pull/20301) +* [[`cd83df386b`](https://github.com/nodejs/node/commit/cd83df386b)] - **(SEMVER-MINOR)** **n-api**: initialize a module via a special symbol (Gabriel Schulhof) [#20161](https://github.com/nodejs/node/pull/20161) +* [[`b5c1c146f5`](https://github.com/nodejs/node/commit/b5c1c146f5)] - **n-api,test**: remove superfluous persistent (Gabriel Schulhof) [#20299](https://github.com/nodejs/node/pull/20299) +* [[`2de3343474`](https://github.com/nodejs/node/commit/2de3343474)] - **n-api,test**: make method static (Gabriel Schulhof) [#20292](https://github.com/nodejs/node/pull/20292) +* [[`b239591ed8`](https://github.com/nodejs/node/commit/b239591ed8)] - **n-api,test**: make methods static (Gabriel Schulhof) [#20243](https://github.com/nodejs/node/pull/20243) +* [[`d3a219c6ec`](https://github.com/nodejs/node/commit/d3a219c6ec)] - **repl**: add spaces to load/save messages (cjihrig) [#20536](https://github.com/nodejs/node/pull/20536) +* [[`d357875ea1`](https://github.com/nodejs/node/commit/d357875ea1)] - **(SEMVER-MINOR)** **src**: add public API to expose the main V8 Platform (Allen Yonghuang Wang) [#20447](https://github.com/nodejs/node/pull/20447) +* [[`df2cddc9c7`](https://github.com/nodejs/node/commit/df2cddc9c7)] - **src**: removed unnecessary prototypes from Environment::SetProtoMethod (Brandon Ruggles) [#20321](https://github.com/nodejs/node/pull/20321) +* [[`54f30658a3`](https://github.com/nodejs/node/commit/54f30658a3)] - **src**: fix inconsistency in extern declaration (Yang Guo) [#20436](https://github.com/nodejs/node/pull/20436) +* [[`f5d42532a3`](https://github.com/nodejs/node/commit/f5d42532a3)] - **src**: refactor `BaseObject` internal field management (Anna Henningsen) [#20455](https://github.com/nodejs/node/pull/20455) +* [[`c21a52f415`](https://github.com/nodejs/node/commit/c21a52f415)] - **src**: access `ContextifyContext\*` more directly in property cbs (Anna Henningsen) [#20455](https://github.com/nodejs/node/pull/20455) +* [[`c0f153528e`](https://github.com/nodejs/node/commit/c0f153528e)] - **src**: remove `kFlagNoShutdown` flag (Anna Henningsen) [#20388](https://github.com/nodejs/node/pull/20388) +* [[`58be6efd29`](https://github.com/nodejs/node/commit/58be6efd29)] - **src**: avoid `std::make\_unique` (Anna Henningsen) [#20386](https://github.com/nodejs/node/pull/20386) +* [[`31812edb2d`](https://github.com/nodejs/node/commit/31812edb2d)] - **src**: remove unnecessary copy operations in tracing (Anna Henningsen) [#20356](https://github.com/nodejs/node/pull/20356) +* [[`e0d2bc5cce`](https://github.com/nodejs/node/commit/e0d2bc5cce)] - **src**: improve fatal exception (Ruben Bridgewater) [#20294](https://github.com/nodejs/node/pull/20294) +* [[`44fdd36b96`](https://github.com/nodejs/node/commit/44fdd36b96)] - **src**: remove SecureContext `\_external` getter (Anna Henningsen) [#20237](https://github.com/nodejs/node/pull/20237) +* [[`81de533836`](https://github.com/nodejs/node/commit/81de533836)] - **src**: create per-isolate strings after platform setup (Ulan Degenbaev) [#20175](https://github.com/nodejs/node/pull/20175) +* [[`b5bc6bd94b`](https://github.com/nodejs/node/commit/b5bc6bd94b)] - **src**: fix Systemtap node\_gc\_stop probe (William Cohen) [#20152](https://github.com/nodejs/node/pull/20152) +* [[`6bf816fde2`](https://github.com/nodejs/node/commit/6bf816fde2)] - **src**: limit foreground tasks draining loop (Ulan Degenbaev) [#19987](https://github.com/nodejs/node/pull/19987) +* [[`bd2e521096`](https://github.com/nodejs/node/commit/bd2e521096)] - **src**: rename return var in VerifySpkac functions (Daniel Bevenius) [#20218](https://github.com/nodejs/node/pull/20218) +* [[`a4dae6c226`](https://github.com/nodejs/node/commit/a4dae6c226)] - **src**: prefer false instead of bool zero (Daniel Bevenius) [#20218](https://github.com/nodejs/node/pull/20218) +* [[`4c4be85655`](https://github.com/nodejs/node/commit/4c4be85655)] - ***Revert*** "**stream**: prevent 'end' to be emitted after 'error'" (Brian White) [#20449](https://github.com/nodejs/node/pull/20449) +* [[`05b7b8d506`](https://github.com/nodejs/node/commit/05b7b8d506)] - **stream**: fix error handling with async iteration (Julien Fontanet) [#20329](https://github.com/nodejs/node/pull/20329) +* [[`fd912a37a0`](https://github.com/nodejs/node/commit/fd912a37a0)] - **stream**: only check options once in Duplex ctor (Daniel Bevenius) [#20353](https://github.com/nodejs/node/pull/20353) +* [[`e19200a666`](https://github.com/nodejs/node/commit/e19200a666)] - **test**: fix flaky http2-flow-control test (Anatoli Papirovski) [#20556](https://github.com/nodejs/node/pull/20556) +* [[`b2d3db433d`](https://github.com/nodejs/node/commit/b2d3db433d)] - **test**: use common.canCreateSymLink() consistently (cjihrig) [#20540](https://github.com/nodejs/node/pull/20540) +* [[`578e0546e0`](https://github.com/nodejs/node/commit/578e0546e0)] - **test**: fix test-cli-node-options.js on mips (Ruben Bridgewater) [#20377](https://github.com/nodejs/node/pull/20377) +* [[`601f138063`](https://github.com/nodejs/node/commit/601f138063)] - **test**: fix buffer writes on mips (Ruben Bridgewater) [#20377](https://github.com/nodejs/node/pull/20377) +* [[`1de67c71fb`](https://github.com/nodejs/node/commit/1de67c71fb)] - **test**: fix common.canCreateSymLink() on non-Windows (Masashi Hirano) [#20511](https://github.com/nodejs/node/pull/20511) +* [[`70b2e169b4`](https://github.com/nodejs/node/commit/70b2e169b4)] - **test**: fix up N-API error test (Gabriel Schulhof) [#20487](https://github.com/nodejs/node/pull/20487) +* [[`6052ccc009`](https://github.com/nodejs/node/commit/6052ccc009)] - **test**: rename misnamed test (Rich Trott) [#20532](https://github.com/nodejs/node/pull/20532) +* [[`80bdff0086`](https://github.com/nodejs/node/commit/80bdff0086)] - **test**: add fs/promises filehandle stat test (Masashi Hirano) [#20492](https://github.com/nodejs/node/pull/20492) +* [[`4dce39a919`](https://github.com/nodejs/node/commit/4dce39a919)] - **test**: use fs.copyFileSync() (Richard Lau) [#20340](https://github.com/nodejs/node/pull/20340) +* [[`b24ee078f6`](https://github.com/nodejs/node/commit/b24ee078f6)] - **test**: remove unnecessary strictEqual() argument from remoteClose() (Daylor Yanes) [#20343](https://github.com/nodejs/node/pull/20343) +* [[`2b8b40f800`](https://github.com/nodejs/node/commit/2b8b40f800)] - **test**: fix a TODO and remove obsolete TODOs (Ruben Bridgewater) [#20319](https://github.com/nodejs/node/pull/20319) +* [[`645a97a44e`](https://github.com/nodejs/node/commit/645a97a44e)] - **test**: verify arguments length in common.expectsError (Ruben Bridgewater) [#20311](https://github.com/nodejs/node/pull/20311) +* [[`b646566ab4`](https://github.com/nodejs/node/commit/b646566ab4)] - **test**: removed assert.strictEqual message (kailash k yogeshwar) [#20223](https://github.com/nodejs/node/pull/20223) +* [[`61a56fe437`](https://github.com/nodejs/node/commit/61a56fe437)] - **test**: added coverage for fs/promises API (Mithun Sasidharan) [#20219](https://github.com/nodejs/node/pull/20219) +* [[`769b6c8fd2`](https://github.com/nodejs/node/commit/769b6c8fd2)] - **test**: fix flaky child-process-exec-kill-throws (Santiago Gimeno) [#20213](https://github.com/nodejs/node/pull/20213) +* [[`99e0b913c6`](https://github.com/nodejs/node/commit/99e0b913c6)] - **test**: add checkMethods function for Certificate (Daniel Bevenius) [#20224](https://github.com/nodejs/node/pull/20224) +* [[`d4b19cf43f`](https://github.com/nodejs/node/commit/d4b19cf43f)] - **test,n-api**: re-write test\_error in C (Gabriel Schulhof) [#20244](https://github.com/nodejs/node/pull/20244) +* [[`e552158dd2`](https://github.com/nodejs/node/commit/e552158dd2)] - **timers**: named anonymous functions (Kyle Martin) [#20397](https://github.com/nodejs/node/pull/20397) +* [[`1109104206`](https://github.com/nodejs/node/commit/1109104206)] - **tls**: remove sharedCreds in Server constructor (Daniel Bevenius) [#20491](https://github.com/nodejs/node/pull/20491) +* [[`1ebec18624`](https://github.com/nodejs/node/commit/1ebec18624)] - **tls**: cleanup onhandshakestart callback (Anatoli Papirovski) [#20466](https://github.com/nodejs/node/pull/20466) +* [[`9b30bc4f81`](https://github.com/nodejs/node/commit/9b30bc4f81)] - **tls**: fix getEphemeralKeyInfo to support X25519 (Shigeki Ohtsu) [#20273](https://github.com/nodejs/node/pull/20273) +* [[`73cd2798df`](https://github.com/nodejs/node/commit/73cd2798df)] - **tls**: specify options.name in validateKeyCert (Daniel Bevenius) [#20284](https://github.com/nodejs/node/pull/20284) +* [[`f7267b4af0`](https://github.com/nodejs/node/commit/f7267b4af0)] - **tools**: add eslint check for skipIfEslintMissing (Richard Lau) [#20372](https://github.com/nodejs/node/pull/20372) +* [[`2a1efa26a7`](https://github.com/nodejs/node/commit/2a1efa26a7)] - **tools**: add v10 to alternative version docs menu (Vse Mozhet Byt) [#20586](https://github.com/nodejs/node/pull/20586) +* [[`a4d2089c76`](https://github.com/nodejs/node/commit/a4d2089c76)] - **tools**: remove redundant code in doc/html.js (Vse Mozhet Byt) [#20514](https://github.com/nodejs/node/pull/20514) +* [[`3912551252`](https://github.com/nodejs/node/commit/3912551252)] - **tools**: fix TypeError from `test.py --time` (Richard Lau) [#20368](https://github.com/nodejs/node/pull/20368) +* [[`b0c0352742`](https://github.com/nodejs/node/commit/b0c0352742)] - **tools**: dedupe property access in doc/type-parser (Vse Mozhet Byt) [#20387](https://github.com/nodejs/node/pull/20387) +* [[`ccf1b24af2`](https://github.com/nodejs/node/commit/ccf1b24af2)] - **tools**: remove redundant RegExp flag (Vse Mozhet Byt) [#20309](https://github.com/nodejs/node/pull/20309) +* [[`a12d13ad06`](https://github.com/nodejs/node/commit/a12d13ad06)] - **tools**: simplify HTML generation (Vse Mozhet Byt) [#20307](https://github.com/nodejs/node/pull/20307) +* [[`8ddbac2fd6`](https://github.com/nodejs/node/commit/8ddbac2fd6)] - **tools**: add log output to crashes (Ruben Bridgewater) [#20295](https://github.com/nodejs/node/pull/20295) +* [[`ab13f13a6c`](https://github.com/nodejs/node/commit/ab13f13a6c)] - **tools**: show stdout/stderr for timed out tests (Rich Trott) [#20260](https://github.com/nodejs/node/pull/20260) +* [[`b5584c448a`](https://github.com/nodejs/node/commit/b5584c448a)] - **tools**: modernize and optimize doc/addon-verify.js (Vse Mozhet Byt) [#20188](https://github.com/nodejs/node/pull/20188) +* [[`ff619d39e6`](https://github.com/nodejs/node/commit/ff619d39e6)] - **url**: fix WHATWG host formatting error (Yichao 'Peak' Ji) [#20493](https://github.com/nodejs/node/pull/20493) +* [[`1b9c40cc71`](https://github.com/nodejs/node/commit/1b9c40cc71)] - **util**: named anonymous functions (Carrie Coxwell) [#20408](https://github.com/nodejs/node/pull/20408) +* [[`e854c953fd`](https://github.com/nodejs/node/commit/e854c953fd)] - **util**: improve spliceOne perf (Anatoli Papirovski) [#20453](https://github.com/nodejs/node/pull/20453) +* [[`3962c734ae`](https://github.com/nodejs/node/commit/3962c734ae)] - **util**: fix isInsideNodeModules inside error (Anatoli Papirovski) [#20266](https://github.com/nodejs/node/pull/20266) + ## 2018-04-24, Version 10.0.0 (Current), @jasnell @@ -58,7 +250,7 @@ * EventEmitter * The `EventEmitter.prototype.off()` method has been added as an alias for `EventEmitter.prototype.removeListener()`. [[`3bb6f07d52`](https://github.com/nodejs/node/commit/3bb6f07d52)] * File System - * The `fs.promises` API provides experimental promisified versions of the `fs` functions. [[`329fc78e49`](https://github.com/nodejs/node/commit/329fc78e49)] + * The `fs/promises` API provides experimental promisified versions of the `fs` functions. [[`329fc78e49`](https://github.com/nodejs/node/commit/329fc78e49)] * Invalid path errors are now thrown synchronously. [[`d8f73385e2`](https://github.com/nodejs/node/commit/d8f73385e2)] * The `fs.readFile()` method now partitions reads to avoid thread pool exhaustion. [[`67a4ce1c6e`](https://github.com/nodejs/node/commit/67a4ce1c6e)] * HTTP @@ -88,11 +280,11 @@ * Timers * The `enroll()` and `unenroll()` methods have been deprecated. [[`68783ae0b8`](https://github.com/nodejs/node/commit/68783ae0b8)] * TLS - * The `tls.convertNONProtocols()` method has been deprecated. [[`9204a0db6e`](https://github.com/nodejs/node/commit/9204a0db6e)] + * The `tls.convertNPNProtocols()` method has been deprecated. [[`9204a0db6e`](https://github.com/nodejs/node/commit/9204a0db6e)] * Support for NPN (next protocol negotiation) has been dropped. [[`5bfbe5ceae`](https://github.com/nodejs/node/commit/5bfbe5ceae)] * The `ecdhCurve` default is now `'auto'`. [[`af78840b19`](https://github.com/nodejs/node/commit/af78840b19)] * Trace Events - * A new `trace_events` top-level module allows trace event categories to be enabled/disabld at runtime. [[`da5d818a54`](https://github.com/nodejs/node/commit/da5d818a54)] + * A new `trace_events` top-level module allows trace event categories to be enabled/disabled at runtime. [[`da5d818a54`](https://github.com/nodejs/node/commit/da5d818a54)] * URL * The WHATWG URL API is now a global. [[`312414662b`](https://github.com/nodejs/node/commit/312414662b)] * Util @@ -113,7 +305,7 @@ The following APIs have been deprecated in Node.js 10.0.0 * Previously deprecated internal getters/setters on `net.Server` has reached end-of-life and have been removed. [[`3701b02309`](https://github.com/nodejs/node/commit/3701b02309)] * Use of non-string values for `process.env` has been deprecated in documentation. [[`5826fe4e79`](https://github.com/nodejs/node/commit/5826fe4e79)] * Use of `process.assert()` will emit a runtime deprecation warning. [[`703e37cf3f`](https://github.com/nodejs/node/commit/703e37cf3f)] -* Previously deprecated `NODE\_REPL\_HISTORY\_FILE` environment variable has reached end-of-life and has been removed. [[`60c9ad7979`](https://github.com/nodejs/node/commit/60c9ad7979)] +* Previously deprecated `NODE_REPL_HISTORY_FILE` environment variable has reached end-of-life and has been removed. [[`60c9ad7979`](https://github.com/nodejs/node/commit/60c9ad7979)] * Use of the `timers.enroll()` and `timers.unenroll()` methods will emit a runtime deprecation warning. [[`68783ae0b8`](https://github.com/nodejs/node/commit/68783ae0b8)] * Use of the `tls.convertNPNProtocols()` method will emit a runtime deprecation warning. Support for NPN has been removed from Node.js. [[`9204a0db6e`](https://github.com/nodejs/node/commit/9204a0db6e)] * The `crypto.fips` property has been deprecated in documentation. [[`6e7992e8b8`](https://github.com/nodejs/node/commit/6e7992e8b8)] @@ -138,7 +330,7 @@ The following APIs have been deprecated in Node.js 10.0.0 * [[`876836b135`](https://github.com/nodejs/node/commit/876836b135)] - **(SEMVER-MAJOR)** **benchmark**: rename file (Ruben Bridgewater) [#18790](https://github.com/nodejs/node/pull/18790) * [[`e9ec9ff269`](https://github.com/nodejs/node/commit/e9ec9ff269)] - **(SEMVER-MAJOR)** **benchmark**: add buffer fill benchmark (Ruben Bridgewater) [#18790](https://github.com/nodejs/node/pull/18790) * [[`94d64877ff`](https://github.com/nodejs/node/commit/94d64877ff)] - **(SEMVER-MAJOR)** **benchmark**: improve buffer.readInt(B|L)E benchmarks (Rich Trott) [#11146](https://github.com/nodejs/node/pull/11146) -* [[`9d4ab90117`](https://github.com/nodejs/node/commit/9d4ab90117)] - **(SEMVER-MAJOR)** **buffer**: do deprecation warning outside `node\_modules` (Anna Henningsen) [#19524](https://github.com/nodejs/node/pull/19524) +* [[`9d4ab90117`](https://github.com/nodejs/node/commit/9d4ab90117)] - **(SEMVER-MAJOR)** **buffer**: do deprecation warning outside `node_modules` (Anna Henningsen) [#19524](https://github.com/nodejs/node/pull/19524) * [[`e8bb1f35df`](https://github.com/nodejs/node/commit/e8bb1f35df)] - **(SEMVER-MAJOR)** **buffer**: refactor all read/write functions (Ruben Bridgewater) [#18395](https://github.com/nodejs/node/pull/18395) * [[`a6c490cc8e`](https://github.com/nodejs/node/commit/a6c490cc8e)] - **(SEMVER-MAJOR)** **buffer**: remove double ln (Ruben Bridgewater) [#18395](https://github.com/nodejs/node/pull/18395) * [[`1411b30f46`](https://github.com/nodejs/node/commit/1411b30f46)] - **(SEMVER-MAJOR)** **buffer**: move c++ float functions to js (Ruben Bridgewater) [#18395](https://github.com/nodejs/node/pull/18395) @@ -710,12 +902,12 @@ The following APIs have been deprecated in Node.js 10.0.0 * [[`070a82e82c`](https://github.com/nodejs/node/commit/070a82e82c)] - **module**: replace "magic" numbers by constants (Sergey Golovin) [#18869](https://github.com/nodejs/node/pull/18869) * [[`c86fe511f4`](https://github.com/nodejs/node/commit/c86fe511f4)] - **module**: replace magic numbers by constants (Sergey Golovin) [#18785](https://github.com/nodejs/node/pull/18785) * [[`3b9cc424a4`](https://github.com/nodejs/node/commit/3b9cc424a4)] - **module**: remove unused code in module.js (Rich Trott) [#18768](https://github.com/nodejs/node/pull/18768) -* [[`c529168249`](https://github.com/nodejs/node/commit/c529168249)] - **n-api**: add more `int64\_t` tests (Kyle Farnung) [#19402](https://github.com/nodejs/node/pull/19402) +* [[`c529168249`](https://github.com/nodejs/node/commit/c529168249)] - **n-api**: add more `int64_t` tests (Kyle Farnung) [#19402](https://github.com/nodejs/node/pull/19402) * [[`a342cd693c`](https://github.com/nodejs/node/commit/a342cd693c)] - **net**: honor default values in Socket constructor (Santiago Gimeno) [#19971](https://github.com/nodejs/node/pull/19971) * [[`923fb5cc18`](https://github.com/nodejs/node/commit/923fb5cc18)] - **net**: track bytesWritten in C++ land (Anna Henningsen) [#19551](https://github.com/nodejs/node/pull/19551) * [[`7c73cd4c70`](https://github.com/nodejs/node/commit/7c73cd4c70)] - **net**: emit error on invalid address family (cjihrig) [#19415](https://github.com/nodejs/node/pull/19415) * [[`67b5985c08`](https://github.com/nodejs/node/commit/67b5985c08)] - **net**: fix usage of writeBuffer in makeSyncWrite (Joyee Cheung) [#19103](https://github.com/nodejs/node/pull/19103) -* [[`03ddd13d8a`](https://github.com/nodejs/node/commit/03ddd13d8a)] - **net**: use `\_final` instead of `on('finish')` (Anna Henningsen) [#18608](https://github.com/nodejs/node/pull/18608) +* [[`03ddd13d8a`](https://github.com/nodejs/node/commit/03ddd13d8a)] - **net**: use `_final` instead of `on('finish')` (Anna Henningsen) [#18608](https://github.com/nodejs/node/pull/18608) * [[`e85c20b511`](https://github.com/nodejs/node/commit/e85c20b511)] - **net,http2**: merge write error handling & property names (Anna Henningsen) [#19734](https://github.com/nodejs/node/pull/19734) * [[`496d6023e0`](https://github.com/nodejs/node/commit/496d6023e0)] - **net,stream**: remove DuplexBase (Luigi Pinca) [#19779](https://github.com/nodejs/node/pull/19779) * [[`2ec6995555`](https://github.com/nodejs/node/commit/2ec6995555)] - **perf_hooks**: simplify perf\_hooks (James M Snell) [#19563](https://github.com/nodejs/node/pull/19563) diff --git a/doc/guides/contributing/pull-requests.md b/doc/guides/contributing/pull-requests.md index f481a2cacb9f01..0da7022d101ed5 100644 --- a/doc/guides/contributing/pull-requests.md +++ b/doc/guides/contributing/pull-requests.md @@ -35,7 +35,7 @@ so that you can make the actual changes. This is where we will start. * [Getting Approvals for your Pull Request](#getting-approvals-for-your-pull-request) * [CI Testing](#ci-testing) * [Waiting Until the Pull Request Gets Landed](#waiting-until-the-pull-request-gets-landed) - * [Check Out the Collaborator's Guide](#check-out-the-collaborators-guide) + * [Check Out the Collaborator Guide](#check-out-the-collaborator-guide) ## Dependencies @@ -334,9 +334,6 @@ Contributors guide: https://github.com/nodejs/node/blob/master/CONTRIBUTING.md - [ ] tests and/or benchmarks are included - [ ] documentation is changed or added - [ ] commit message follows [commit guidelines](https://github.com/nodejs/node/blob/master/doc/guides/contributing/pull-requests.md#commit-message-guidelines) - -#### Affected core subsystem(s) - ``` Please try to do your best at filling out the details, but feel free to skip @@ -602,9 +599,10 @@ whether the failure was caused by the changes in the Pull Request. ### Commit Squashing -When the commits in your Pull Request land, they may be squashed -into one commit per logical change. Metadata will be added to the commit -message (including links to the Pull Request, links to relevant issues, +In most cases, do not squash commits that you add to your Pull Request during +the review process. When the commits in your Pull Request land, they may be +squashed into one commit per logical change. Metadata will be added to the +commit message (including links to the Pull Request, links to relevant issues, and the names of the reviewers). The commit history of your Pull Request, however, will stay intact on the Pull Request page. @@ -647,17 +645,17 @@ doesn't need to wait. A Pull Request may well take longer to be merged in. All these precautions are important because Node.js is widely used, so don't be discouraged! -### Check Out the Collaborator's Guide +### Check Out the Collaborator Guide -If you want to know more about the code review and the landing process, -you can take a look at the -[collaborator's guide](https://github.com/nodejs/node/blob/master/COLLABORATOR_GUIDE.md). +If you want to know more about the code review and the landing process, see the +[Collaborator Guide][]. [approved]: #getting-approvals-for-your-pull-request [benchmark results]: ../writing-and-running-benchmarks.md [Building guide]: ../../../BUILDING.md [CI (Continuous Integration) test run]: #ci-testing [Code of Conduct]: https://github.com/nodejs/admin/blob/master/CODE_OF_CONDUCT.md +[Collaborator Guide]: ../../../COLLABORATOR_GUIDE.md [guide for writing tests in Node.js]: ../writing-tests.md [https://ci.nodejs.org/]: https://ci.nodejs.org/ [IRC in the #node-dev channel]: https://webchat.freenode.net?channels=node-dev&uio=d4 diff --git a/doc/guides/writing-and-running-benchmarks.md b/doc/guides/writing-and-running-benchmarks.md index a6482c607893ca..7fa5400b4ae31b 100644 --- a/doc/guides/writing-and-running-benchmarks.md +++ b/doc/guides/writing-and-running-benchmarks.md @@ -202,12 +202,11 @@ For analysing the benchmark results use the `compare.R` tool. ```console $ cat compare-pr-5134.csv | Rscript benchmark/compare.R - improvement confidence p.value -string_decoder/string-decoder.js n=250000 chunk=1024 inlen=1024 encoding=ascii 12.46 % *** 1.165345e-04 -string_decoder/string-decoder.js n=250000 chunk=1024 inlen=1024 encoding=base64-ascii 24.70 % *** 1.820615e-15 -string_decoder/string-decoder.js n=250000 chunk=1024 inlen=1024 encoding=base64-utf8 23.60 % *** 2.105625e-12 -string_decoder/string-decoder.js n=250000 chunk=1024 inlen=1024 encoding=utf8 14.04 % *** 1.291105e-07 -string_decoder/string-decoder.js n=250000 chunk=1024 inlen=128 encoding=ascii 6.70 % * 2.928003e-02 + confidence improvement accuracy (*) (**) (***) + string_decoder/string-decoder.js n=2500000 chunkLen=16 inLen=128 encoding='ascii' *** -3.76 % ±1.36% ±1.82% ±2.40% + string_decoder/string-decoder.js n=2500000 chunkLen=16 inLen=128 encoding='utf8' ** -0.81 % ±0.53% ±0.71% ±0.93% + string_decoder/string-decoder.js n=2500000 chunkLen=16 inLen=32 encoding='ascii' *** -2.70 % ±0.83% ±1.11% ±1.45% + string_decoder/string-decoder.js n=2500000 chunkLen=16 inLen=32 encoding='base64-ascii' *** -1.57 % ±0.83% ±1.11% ±1.46% ... ``` @@ -241,14 +240,13 @@ results afterwards using tools such as `sed` or `grep`. In the `sed` case be sure to keep the first line since that contains the header information. ```console -$ cat compare-pr-5134.csv | sed '1p;/encoding=ascii/!d' | Rscript benchmark/compare.R --plot compare-plot.png - - improvement confidence p.value -string_decoder/string-decoder.js n=250000 chunk=1024 inlen=1024 encoding=ascii 12.46 % *** 1.165345e-04 -string_decoder/string-decoder.js n=250000 chunk=1024 inlen=128 encoding=ascii 6.70 % * 2.928003e-02 -string_decoder/string-decoder.js n=250000 chunk=1024 inlen=32 encoding=ascii 7.47 % *** 5.780583e-04 -string_decoder/string-decoder.js n=250000 chunk=16 inlen=1024 encoding=ascii 8.94 % *** 1.788579e-04 -string_decoder/string-decoder.js n=250000 chunk=16 inlen=128 encoding=ascii 10.54 % *** 4.016172e-05 +$ cat compare-pr-5134.csv | sed '1p;/encoding='"'"ascii"'"'/!d' | Rscript benchmark/compare.R --plot compare-plot.png + + confidence improvement accuracy (*) (**) (***) + string_decoder/string-decoder.js n=2500000 chunkLen=16 inLen=128 encoding='ascii' *** -3.76 % ±1.36% ±1.82% ±2.40% + string_decoder/string-decoder.js n=2500000 chunkLen=16 inLen=32 encoding='ascii' *** -2.70 % ±0.83% ±1.11% ±1.45% + string_decoder/string-decoder.js n=2500000 chunkLen=16 inLen=4096 encoding='ascii' *** -4.06 % ±0.31% ±0.41% ±0.54% + string_decoder/string-decoder.js n=2500000 chunkLen=256 inLen=1024 encoding='ascii' *** -1.42 % ±0.58% ±0.77% ±1.01% ... ``` diff --git a/doc/node.1 b/doc/node.1 index 24d8260b8765ac..238572c74c4796 100644 --- a/doc/node.1 +++ b/doc/node.1 @@ -122,8 +122,7 @@ V8 Inspector integration allows attaching Chrome DevTools and IDEs to Node.js in It uses the Chrome DevTools Protocol. . .It Fl -napi-modules -Enable loading native modules compiled with the ABI-stable Node.js API (N-API) -(experimental). +This option is a no-op. It is kept for compatibility. . .It Fl -no-deprecation Silence deprecation warnings. @@ -385,4 +384,3 @@ IRC (Node.js core development): .Sh AUTHORS Written and maintained by 1000+ contributors: .Sy https://github.com/nodejs/node/blob/master/AUTHORS -. diff --git a/doc/onboarding-extras.md b/doc/onboarding-extras.md index 080918049f66c0..62a7f7bb6b2837 100644 --- a/doc/onboarding-extras.md +++ b/doc/onboarding-extras.md @@ -91,10 +91,9 @@ need to be attached anymore, as only important bugfixes will be included. to update from nodejs/node: * `git checkout master` -* `git remote update -p` OR `git fetch --all` (I prefer the former) +* `git remote update -p` OR `git fetch --all` * `git merge --ff-only upstream/master` (or `REMOTENAME/BRANCH`) ## Best practices * When making PRs, spend time writing a thorough description. -* Usually only squash at the end of your work. diff --git a/lib/_http_client.js b/lib/_http_client.js index 22ae85c92782ec..04880182dace91 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -279,6 +279,7 @@ ClientRequest.prototype.abort = function abort() { if (!this.aborted) { process.nextTick(emitAbortNT.bind(this)); } + // Mark as aborting so we can avoid sending queued request data // This is used as a truthy flag elsewhere. The use of Date.now is for // debugging purposes only. @@ -330,7 +331,10 @@ function socketCloseListener() { var parser = socket.parser; if (req.res && req.res.readable) { // Socket closed before we emitted 'end' below. - if (!req.res.complete) req.res.emit('aborted'); + if (!req.res.complete) { + req.res.aborted = true; + req.res.emit('aborted'); + } var res = req.res; res.on('end', function() { res.emit('close'); diff --git a/lib/_http_incoming.js b/lib/_http_incoming.js index 55c196399c5e6b..23ac4d54be1ec5 100644 --- a/lib/_http_incoming.js +++ b/lib/_http_incoming.js @@ -54,6 +54,8 @@ function IncomingMessage(socket) { this.readable = true; + this.aborted = false; + this.upgrade = null; // request (server) only diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index 770e555d1ead8a..f075e0ecad7a2b 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -52,6 +52,8 @@ const { utcDate } = internalHttp; const kIsCorked = Symbol('isCorked'); +const hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty); + var RE_CONN_CLOSE = /(?:^|\W)close(?:$|\W)/i; var RE_TE_CHUNKED = common.chunkExpression; @@ -116,7 +118,7 @@ Object.defineProperty(OutgoingMessage.prototype, '_headers', { if (val == null) { this[outHeadersKey] = null; } else if (typeof val === 'object') { - const headers = this[outHeadersKey] = {}; + const headers = this[outHeadersKey] = Object.create(null); const keys = Object.keys(val); for (var i = 0; i < keys.length; ++i) { const name = keys[i]; @@ -129,7 +131,7 @@ Object.defineProperty(OutgoingMessage.prototype, '_headers', { Object.defineProperty(OutgoingMessage.prototype, '_headerNames', { get: function() { const headers = this[outHeadersKey]; - if (headers) { + if (headers !== null) { const out = Object.create(null); const keys = Object.keys(headers); for (var i = 0; i < keys.length; ++i) { @@ -138,9 +140,8 @@ Object.defineProperty(OutgoingMessage.prototype, '_headerNames', { out[key] = val; } return out; - } else { - return headers; } + return null; }, set: function(val) { if (typeof val === 'object' && val !== null) { @@ -164,14 +165,14 @@ OutgoingMessage.prototype._renderHeaders = function _renderHeaders() { } var headersMap = this[outHeadersKey]; - if (!headersMap) return {}; - - var headers = {}; - var keys = Object.keys(headersMap); + const headers = {}; - for (var i = 0, l = keys.length; i < l; i++) { - var key = keys[i]; - headers[headersMap[key][0]] = headersMap[key][1]; + if (headersMap !== null) { + const keys = Object.keys(headersMap); + for (var i = 0, l = keys.length; i < l; i++) { + const key = keys[i]; + headers[headersMap[key][0]] = headersMap[key][1]; + } } return headers; }; @@ -285,72 +286,40 @@ OutgoingMessage.prototype._storeHeader = _storeHeader; function _storeHeader(firstLine, headers) { // firstLine in the case of request is: 'GET /index.html HTTP/1.1\r\n' // in the case of response it is: 'HTTP/1.1 200 OK\r\n' - var state = { + const state = { connection: false, contLen: false, te: false, date: false, expect: false, trailer: false, - upgrade: false, header: firstLine }; - var field; var key; - var value; - var i; - var j; if (headers === this[outHeadersKey]) { for (key in headers) { - var entry = headers[key]; - field = entry[0]; - value = entry[1]; - - if (value instanceof Array) { - if (value.length < 2 || !isCookieField(field)) { - for (j = 0; j < value.length; j++) - storeHeader(this, state, field, value[j], false); - continue; - } - value = value.join('; '); - } - storeHeader(this, state, field, value, false); + const entry = headers[key]; + processHeader(this, state, entry[0], entry[1], false); } - } else if (headers instanceof Array) { - for (i = 0; i < headers.length; i++) { - field = headers[i][0]; - value = headers[i][1]; - - if (value instanceof Array) { - for (j = 0; j < value.length; j++) { - storeHeader(this, state, field, value[j], true); - } - } else { - storeHeader(this, state, field, value, true); - } + } else if (Array.isArray(headers)) { + for (var i = 0; i < headers.length; i++) { + const entry = headers[i]; + processHeader(this, state, entry[0], entry[1], true); } } else if (headers) { - var keys = Object.keys(headers); - for (i = 0; i < keys.length; i++) { - field = keys[i]; - value = headers[field]; - - if (value instanceof Array) { - if (value.length < 2 || !isCookieField(field)) { - for (j = 0; j < value.length; j++) - storeHeader(this, state, field, value[j], true); - continue; - } - value = value.join('; '); + for (key in headers) { + if (hasOwnProperty(headers, key)) { + processHeader(this, state, key, headers[key], true); } - storeHeader(this, state, field, value, true); } } + let { header } = state; + // Date header if (this.sendDate && !state.date) { - state.header += 'Date: ' + utcDate() + CRLF; + header += 'Date: ' + utcDate() + CRLF; } // Force the connection to close when the response is a 204 No Content or @@ -364,9 +333,9 @@ function _storeHeader(firstLine, headers) { // It was pointed out that this might confuse reverse proxies to the point // of creating security liabilities, so suppress the zero chunk and force // the connection to close. - var statusCode = this.statusCode; - if ((statusCode === 204 || statusCode === 304) && this.chunkedEncoding) { - debug(statusCode + ' response should not use chunked encoding,' + + if (this.chunkedEncoding && (this.statusCode === 204 || + this.statusCode === 304)) { + debug(this.statusCode + ' response should not use chunked encoding,' + ' closing connection.'); this.chunkedEncoding = false; this.shouldKeepAlive = false; @@ -377,13 +346,13 @@ function _storeHeader(firstLine, headers) { this._last = true; this.shouldKeepAlive = false; } else if (!state.connection) { - var shouldSendKeepAlive = this.shouldKeepAlive && + const shouldSendKeepAlive = this.shouldKeepAlive && (state.contLen || this.useChunkedEncodingByDefault || this.agent); if (shouldSendKeepAlive) { - state.header += 'Connection: keep-alive\r\n'; + header += 'Connection: keep-alive\r\n'; } else { this._last = true; - state.header += 'Connection: close\r\n'; + header += 'Connection: close\r\n'; } } @@ -396,9 +365,9 @@ function _storeHeader(firstLine, headers) { } else if (!state.trailer && !this._removedContLen && typeof this._contentLength === 'number') { - state.header += 'Content-Length: ' + this._contentLength + CRLF; + header += 'Content-Length: ' + this._contentLength + CRLF; } else if (!this._removedTE) { - state.header += 'Transfer-Encoding: chunked\r\n'; + header += 'Transfer-Encoding: chunked\r\n'; this.chunkedEncoding = true; } else { // We should only be able to get here if both Content-Length and @@ -416,7 +385,7 @@ function _storeHeader(firstLine, headers) { throw new ERR_HTTP_TRAILER_INVALID(); } - this._header = state.header + CRLF; + this._header = header + CRLF; this._headerSent = false; // wait until the first body chunk, or close(), is sent to flush, @@ -424,10 +393,23 @@ function _storeHeader(firstLine, headers) { if (state.expect) this._send(''); } -function storeHeader(self, state, key, value, validate) { - if (validate) { - validateHeader(key, value); +function processHeader(self, state, key, value, validate) { + if (validate) + validateHeaderName(key); + if (Array.isArray(value)) { + if (value.length < 2 || !isCookieField(key)) { + for (var i = 0; i < value.length; i++) + storeHeader(self, state, key, value[i], validate); + return; + } + value = value.join('; '); } + storeHeader(self, state, key, value, validate); +} + +function storeHeader(self, state, key, value, validate) { + if (validate) + validateHeaderValue(key, value); state.header += key + ': ' + escapeHeaderValue(value) + CRLF; matchHeader(self, state, key, value); } @@ -439,6 +421,7 @@ function matchHeader(self, state, field, value) { switch (field) { case 'connection': state.connection = true; + self._removedConnection = false; if (RE_CONN_CLOSE.test(value)) self._last = true; else @@ -446,32 +429,39 @@ function matchHeader(self, state, field, value) { break; case 'transfer-encoding': state.te = true; + self._removedTE = false; if (RE_TE_CHUNKED.test(value)) self.chunkedEncoding = true; break; case 'content-length': state.contLen = true; + self._removedContLen = false; break; case 'date': case 'expect': case 'trailer': - case 'upgrade': state[field] = true; break; } } -function validateHeader(name, value) { - let err; +function validateHeaderName(name) { if (typeof name !== 'string' || !name || !checkIsHttpToken(name)) { - err = new ERR_INVALID_HTTP_TOKEN('Header name', name); - } else if (value === undefined) { + const err = new ERR_INVALID_HTTP_TOKEN('Header name', name); + Error.captureStackTrace(err, validateHeaderName); + throw err; + } +} + +function validateHeaderValue(name, value) { + let err; + if (value === undefined) { err = new ERR_HTTP_INVALID_HEADER_VALUE(value, name); } else if (checkInvalidHeaderChar(value)) { debug('Header "%s" contains invalid characters', name); err = new ERR_INVALID_CHAR('header content', name); } if (err !== undefined) { - Error.captureStackTrace(err, validateHeader); + Error.captureStackTrace(err, validateHeaderValue); throw err; } } @@ -480,25 +470,14 @@ OutgoingMessage.prototype.setHeader = function setHeader(name, value) { if (this._header) { throw new ERR_HTTP_HEADERS_SENT('set'); } - validateHeader(name, value); + validateHeaderName(name); + validateHeaderValue(name, value); - if (!this[outHeadersKey]) - this[outHeadersKey] = {}; + let headers = this[outHeadersKey]; + if (headers === null) + this[outHeadersKey] = headers = Object.create(null); - const key = name.toLowerCase(); - this[outHeadersKey][key] = [name, value]; - - switch (key) { - case 'connection': - this._removedConnection = false; - break; - case 'content-length': - this._removedContLen = false; - break; - case 'transfer-encoding': - this._removedTE = false; - break; - } + headers[name.toLowerCase()] = [name, value]; }; @@ -507,18 +486,18 @@ OutgoingMessage.prototype.getHeader = function getHeader(name) { throw new ERR_INVALID_ARG_TYPE('name', 'string', name); } - if (!this[outHeadersKey]) return; - - var entry = this[outHeadersKey][name.toLowerCase()]; - if (!entry) + const headers = this[outHeadersKey]; + if (headers === null) return; - return entry[1]; + + const entry = headers[name.toLowerCase()]; + return entry && entry[1]; }; // Returns an array of the names of the current outgoing headers. OutgoingMessage.prototype.getHeaderNames = function getHeaderNames() { - return (this[outHeadersKey] ? Object.keys(this[outHeadersKey]) : []); + return this[outHeadersKey] !== null ? Object.keys(this[outHeadersKey]) : []; }; @@ -543,7 +522,8 @@ OutgoingMessage.prototype.hasHeader = function hasHeader(name) { throw new ERR_INVALID_ARG_TYPE('name', 'string', name); } - return !!(this[outHeadersKey] && this[outHeadersKey][name.toLowerCase()]); + return this[outHeadersKey] !== null && + !!this[outHeadersKey][name.toLowerCase()]; }; @@ -573,7 +553,7 @@ OutgoingMessage.prototype.removeHeader = function removeHeader(name) { break; } - if (this[outHeadersKey]) { + if (this[outHeadersKey] !== null) { delete this[outHeadersKey][key]; } }; diff --git a/lib/_http_server.js b/lib/_http_server.js index bf228de643422e..9c8b5cb8fbfe8e 100644 --- a/lib/_http_server.js +++ b/lib/_http_server.js @@ -440,6 +440,7 @@ function socketOnClose(socket, state) { function abortIncoming(incoming) { while (incoming.length) { var req = incoming.shift(); + req.aborted = true; req.emit('aborted'); req.emit('close'); } diff --git a/lib/_stream_duplex.js b/lib/_stream_duplex.js index b123cdcb4d776f..7059757dbd44b1 100644 --- a/lib/_stream_duplex.js +++ b/lib/_stream_duplex.js @@ -50,17 +50,19 @@ function Duplex(options) { Readable.call(this, options); Writable.call(this, options); + this.allowHalfOpen = true; - if (options && options.readable === false) - this.readable = false; + if (options) { + if (options.readable === false) + this.readable = false; - if (options && options.writable === false) - this.writable = false; + if (options.writable === false) + this.writable = false; - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } } } diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index 31a8a11e4a0673..8073e174cc586f 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -99,9 +99,6 @@ function ReadableState(options, stream, isDuplex) { this.endEmitted = false; this.reading = false; - // Flipped if an 'error' is emitted. - this.errorEmitted = false; - // a flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also @@ -1072,23 +1069,20 @@ function fromList(n, state) { function endReadable(stream) { var state = stream._readableState; - debug('endReadable', state.endEmitted, state.errorEmitted); - if (!state.endEmitted && !state.errorEmitted) { + debug('endReadable', state.endEmitted); + if (!state.endEmitted) { state.ended = true; process.nextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length, state.errorEmitted); + debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; stream.readable = false; - - if (!state.errorEmitted) { - state.endEmitted = true; - stream.emit('end'); - } + stream.emit('end'); } } diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index 0891f85526f132..d21daf0541d339 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -424,22 +424,12 @@ function onwriteError(stream, state, sync, er, cb) { // this can emit finish, and it will always happen // after error process.nextTick(finishMaybe, stream, state); - - // needed for duplex, fixes https://github.com/nodejs/node/issues/6083 - if (stream._readableState) { - stream._readableState.errorEmitted = true; - } stream._writableState.errorEmitted = true; stream.emit('error', er); } else { // the caller expect this to happen before if // it is async cb(er); - - // needed for duplex, fixes https://github.com/nodejs/node/issues/6083 - if (stream._readableState) { - stream._readableState.errorEmitted = true; - } stream._writableState.errorEmitted = true; stream.emit('error', er); // this can emit finish, but finish must diff --git a/lib/_tls_common.js b/lib/_tls_common.js index a9fe0d8f06aa0d..d8f6afed0bd8fb 100644 --- a/lib/_tls_common.js +++ b/lib/_tls_common.js @@ -56,11 +56,10 @@ function SecureContext(secureProtocol, secureOptions, context) { if (secureOptions) this.context.setOptions(secureOptions); } -function validateKeyCert(value, type) { +function validateKeyCert(name, value) { if (typeof value !== 'string' && !isArrayBufferView(value)) { throw new ERR_INVALID_ARG_TYPE( - // TODO(BridgeAR): Change this to `options.${type}` - type, + `options.${name}`, ['string', 'Buffer', 'TypedArray', 'DataView'], value ); @@ -100,11 +99,11 @@ exports.createSecureContext = function createSecureContext(options, context) { if (Array.isArray(ca)) { for (i = 0; i < ca.length; ++i) { val = ca[i]; - validateKeyCert(val, 'ca'); + validateKeyCert('ca', val); c.context.addCACert(val); } } else { - validateKeyCert(ca, 'ca'); + validateKeyCert('ca', ca); c.context.addCACert(ca); } } else { @@ -116,11 +115,11 @@ exports.createSecureContext = function createSecureContext(options, context) { if (Array.isArray(cert)) { for (i = 0; i < cert.length; ++i) { val = cert[i]; - validateKeyCert(val, 'cert'); + validateKeyCert('cert', val); c.context.setCert(val); } } else { - validateKeyCert(cert, 'cert'); + validateKeyCert('cert', cert); c.context.setCert(cert); } } @@ -137,11 +136,11 @@ exports.createSecureContext = function createSecureContext(options, context) { val = key[i]; // eslint-disable-next-line eqeqeq const pem = (val != undefined && val.pem !== undefined ? val.pem : val); - validateKeyCert(pem, 'key'); + validateKeyCert('key', pem); c.context.setKey(pem, val.passphrase || passphrase); } } else { - validateKeyCert(key, 'key'); + validateKeyCert('key', key); c.context.setKey(key, passphrase); } } diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 2e6b2e8da559db..d85d85752b631b 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -62,32 +62,28 @@ const noop = () => {}; function onhandshakestart(now) { debug('onhandshakestart'); - assert(now >= this.lastHandshakeTime); + const { lastHandshakeTime } = this; + assert(now >= lastHandshakeTime); - const owner = this.owner; + this.lastHandshakeTime = now; - if ((now - this.lastHandshakeTime) >= tls.CLIENT_RENEG_WINDOW * 1000) { - this.handshakes = 0; - } + // If this is the first handshake we can skip the rest of the checks. + if (lastHandshakeTime === 0) + return; - const first = (this.lastHandshakeTime === 0); - this.lastHandshakeTime = now; - if (first) return; + if ((now - lastHandshakeTime) >= tls.CLIENT_RENEG_WINDOW * 1000) + this.handshakes = 1; + else + this.handshakes++; - if (++this.handshakes > tls.CLIENT_RENEG_LIMIT) { - // Defer the error event to the next tick. We're being called from OpenSSL's - // state machine and OpenSSL is not re-entrant. We cannot allow the user's - // callback to destroy the connection right now, it would crash and burn. - setImmediate(emitSessionAttackError, owner); + const { owner } = this; + if (this.handshakes > tls.CLIENT_RENEG_LIMIT) { + owner._emitTLSError(new ERR_TLS_SESSION_ATTACK()); + return; } - if (owner[kDisableRenegotiation] && this.handshakes > 0) { + if (owner[kDisableRenegotiation]) owner._emitTLSError(new ERR_TLS_RENEGOTIATION_DISABLED()); - } -} - -function emitSessionAttackError(socket) { - socket._emitTLSError(new ERR_TLS_SESSION_ATTACK()); } function onhandshakedone() { @@ -875,7 +871,7 @@ function Server(options, listener) { // Handle option defaults: this.setOptions(options); - var sharedCreds = tls.createSecureContext({ + this._sharedCreds = tls.createSecureContext({ pfx: this.pfx, key: this.key, passphrase: this.passphrase, @@ -891,7 +887,6 @@ function Server(options, listener) { crl: this.crl, sessionIdContext: this.sessionIdContext }); - this._sharedCreds = sharedCreds; this[kHandshakeTimeout] = options.handshakeTimeout || (120 * 1000); this[kSNICallback] = options.SNICallback; @@ -902,11 +897,11 @@ function Server(options, listener) { } if (this.sessionTimeout) { - sharedCreds.context.setSessionTimeout(this.sessionTimeout); + this._sharedCreds.context.setSessionTimeout(this.sessionTimeout); } if (this.ticketKeys) { - sharedCreds.context.setTicketKeys(this.ticketKeys); + this._sharedCreds.context.setTicketKeys(this.ticketKeys); } // constructor call diff --git a/lib/child_process.js b/lib/child_process.js index ee3752a817e781..734f67d7a51f99 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -59,7 +59,7 @@ function stdioStringToArray(option) { } } -exports.fork = function(modulePath /* , args, options */) { +exports.fork = function fork(modulePath /* , args, options */) { // Get options and args arguments. var execArgv; @@ -110,7 +110,7 @@ exports.fork = function(modulePath /* , args, options */) { }; -exports._forkChild = function(fd) { +exports._forkChild = function _forkChild(fd) { // set process.send() var p = new Pipe(PipeConstants.IPC); p.open(fd); @@ -143,7 +143,7 @@ function normalizeExecArgs(command, options, callback) { } -exports.exec = function(command /* , options, callback */) { +exports.exec = function exec(command /* , options, callback */) { var opts = normalizeExecArgs.apply(null, arguments); return exports.execFile(opts.file, opts.options, @@ -172,7 +172,7 @@ Object.defineProperty(exports.exec, util.promisify.custom, { value: customPromiseExecFunction(exports.exec) }); -exports.execFile = function(file /* , args, options, callback */) { +exports.execFile = function execFile(file /* , args, options, callback */) { var args = []; var callback; var options = { @@ -511,7 +511,7 @@ function normalizeSpawnArguments(file, args, options) { } -var spawn = exports.spawn = function(/* file, args, options */) { +var spawn = exports.spawn = function spawn(/* file, args, options */) { var opts = normalizeSpawnArguments.apply(null, arguments); var options = opts.options; var child = new ChildProcess(); diff --git a/lib/console.js b/lib/console.js index 39bcf701bf83eb..0f08e37fa7e22c 100644 --- a/lib/console.js +++ b/lib/console.js @@ -315,15 +315,6 @@ const iterKey = '(iteration index)'; const isArray = (v) => ArrayIsArray(v) || isTypedArray(v) || isBuffer(v); -const inspect = (v) => { - const opt = { depth: 0, maxArrayLength: 3 }; - if (v !== null && typeof v === 'object' && - !isArray(v) && ObjectKeys(v).length > 2) - opt.depth = -1; - return util.inspect(v, opt); -}; - -const getIndexArray = (length) => ArrayFrom({ length }, (_, i) => inspect(i)); // https://console.spec.whatwg.org/#table Console.prototype.table = function(tabularData, properties) { @@ -336,6 +327,16 @@ Console.prototype.table = function(tabularData, properties) { const final = (k, v) => this.log(cliTable(k, v)); + const inspect = (v) => { + const opt = { depth: 0, maxArrayLength: 3 }; + if (v !== null && typeof v === 'object' && + !isArray(v) && ObjectKeys(v).length > 2) + opt.depth = -1; + Object.assign(opt, this[kGetInspectOptions](this._stdout)); + return util.inspect(v, opt); + }; + const getIndexArray = (length) => ArrayFrom({ length }, (_, i) => inspect(i)); + const mapIter = isMapIterator(tabularData); if (mapIter) tabularData = previewMapIterator(tabularData); @@ -363,9 +364,7 @@ Console.prototype.table = function(tabularData, properties) { tabularData = previewSetIterator(tabularData); const setlike = setIter || isSet(tabularData); - if (setlike || - (properties === undefined && - (isArray(tabularData) || isTypedArray(tabularData)))) { + if (setlike) { const values = []; let length = 0; for (const v of tabularData) { diff --git a/lib/events.js b/lib/events.js index 46d1223e69a4bf..ff1648d6aa13e7 100644 --- a/lib/events.js +++ b/lib/events.js @@ -235,22 +235,20 @@ function _addListener(target, type, listener, prepend) { } // Check for listener leak - if (!existing.warned) { - m = $getMaxListeners(target); - if (m && m > 0 && existing.length > m) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - const w = new Error('Possible EventEmitter memory leak detected. ' + - `${existing.length} ${String(type)} listeners ` + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - process.emitWarning(w); - } + m = $getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + const w = new Error('Possible EventEmitter memory leak detected. ' + + `${existing.length} ${String(type)} listeners ` + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + process.emitWarning(w); } } diff --git a/lib/fs.js b/lib/fs.js index d71e31565fbad6..e9d878803ddffd 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -45,7 +45,8 @@ const { Readable, Writable } = require('stream'); const EventEmitter = require('events'); const { FSReqWrap, statValues, kFsStatsFieldsLength } = binding; const { FSEvent } = process.binding('fs_event_wrap'); -const internalFS = require('internal/fs'); +const promises = require('internal/fs/promises'); +const internalFS = require('internal/fs/utils'); const { getPathFromURL } = require('internal/url'); const internalUtil = require('internal/util'); const { @@ -72,6 +73,21 @@ const { CHAR_BACKWARD_SLASH, } = require('internal/constants'); +let warn = true; + +Object.defineProperty(fs, 'promises', { + configurable: true, + enumerable: true, + get() { + if (warn) { + warn = false; + process.emitWarning('The fs.promises API is experimental', + 'ExperimentalWarning'); + } + return promises; + } +}); + Object.defineProperty(exports, 'constants', { configurable: false, enumerable: true, @@ -151,9 +167,7 @@ function makeStatsCallback(cb) { }; } -function isFd(path) { - return (path >>> 0) === path; -} +const isFd = isUint32; fs.Stats = Stats; @@ -247,7 +261,7 @@ fs.readFile = function(path, options, callback) { req.oncomplete = readFileAfterOpen; if (context.isUserFd) { - process.nextTick(function() { + process.nextTick(function tick() { req.oncomplete(null, path); }); return; @@ -304,7 +318,7 @@ ReadFileContext.prototype.close = function(err) { this.err = err; if (this.isUserFd) { - process.nextTick(function() { + process.nextTick(function tick() { req.oncomplete(null); }); return; @@ -554,7 +568,7 @@ fs.read = function(fd, buffer, offset, length, position, callback) { length |= 0; if (length === 0) { - return process.nextTick(function() { + return process.nextTick(function tick() { callback && callback(null, 0, buffer); }); } @@ -1219,7 +1233,7 @@ function writeAll(fd, isUserFd, buffer, offset, length, position, callback) { if (isUserFd) { callback(writeErr); } else { - fs.close(fd, function() { + fs.close(fd, function close() { callback(writeErr); }); } diff --git a/lib/https.js b/lib/https.js index 4cca2fb9eeea88..2237a909e999c3 100644 --- a/lib/https.js +++ b/lib/https.js @@ -74,6 +74,7 @@ function Server(opts, requestListener) { this.timeout = 2 * 60 * 1000; this.keepAliveTimeout = 5000; + this.maxHeadersCount = null; } inherits(Server, tls.Server); diff --git a/lib/internal/bootstrap/node.js b/lib/internal/bootstrap/node.js index 7762aac84691d6..f9bed03d269fb2 100644 --- a/lib/internal/bootstrap/node.js +++ b/lib/internal/bootstrap/node.js @@ -356,7 +356,8 @@ Object.defineProperty(global, 'console', { configurable: true, enumerable: false, - value: wrappedConsole + value: wrappedConsole, + writable: true }); setupInspector(originalConsole, wrappedConsole, CJSModule); } diff --git a/lib/internal/child_process.js b/lib/internal/child_process.js index 8cca1c2f6b0443..a630cff717bcad 100644 --- a/lib/internal/child_process.js +++ b/lib/internal/child_process.js @@ -31,6 +31,8 @@ const SocketList = require('internal/socket_list'); const { convertToValidSignal } = require('internal/util'); const { isUint8Array } = require('internal/util/types'); const spawn_sync = process.binding('spawn_sync'); +const { HTTPParser } = process.binding('http_parser'); +const { freeParser } = require('_http_common'); const { UV_EACCES, @@ -107,6 +109,14 @@ const handleConversion = { if (!options.keepOpen) { handle.onread = nop; socket._handle = null; + socket.setTimeout(0); + // In case of an HTTP connection socket, release the associated + // resources + if (socket.parser && socket.parser instanceof HTTPParser) { + freeParser(socket.parser, null, socket); + if (socket._httpMessage) + socket._httpMessage.detachSocket(socket); + } } return handle; diff --git a/lib/internal/crypto/diffiehellman.js b/lib/internal/crypto/diffiehellman.js index 329add6d4d7cd5..dad7a903b26a5e 100644 --- a/lib/internal/crypto/diffiehellman.js +++ b/lib/internal/crypto/diffiehellman.js @@ -219,21 +219,15 @@ function encode(buffer, encoding) { } function getFormat(format) { - let f; if (format) { if (format === 'compressed') - f = POINT_CONVERSION_COMPRESSED; - else if (format === 'hybrid') - f = POINT_CONVERSION_HYBRID; - // Default - else if (format === 'uncompressed') - f = POINT_CONVERSION_UNCOMPRESSED; - else + return POINT_CONVERSION_COMPRESSED; + if (format === 'hybrid') + return POINT_CONVERSION_HYBRID; + if (format !== 'uncompressed') throw new ERR_CRYPTO_ECDH_INVALID_FORMAT(format); - } else { - f = POINT_CONVERSION_UNCOMPRESSED; } - return f; + return POINT_CONVERSION_UNCOMPRESSED; } module.exports = { diff --git a/lib/internal/crypto/pbkdf2.js b/lib/internal/crypto/pbkdf2.js index 4a7f26b509b521..82ea9feb852649 100644 --- a/lib/internal/crypto/pbkdf2.js +++ b/lib/internal/crypto/pbkdf2.js @@ -7,10 +7,10 @@ const { ERR_OUT_OF_RANGE } = require('internal/errors').codes; const { + checkIsArrayBufferView, getDefaultEncoding, toBuf } = require('internal/crypto/util'); -const { isArrayBufferView } = require('internal/util/types'); const { PBKDF2 } = process.binding('crypto'); @@ -39,19 +39,8 @@ function _pbkdf2(password, salt, iterations, keylen, digest, callback) { if (digest !== null && typeof digest !== 'string') throw new ERR_INVALID_ARG_TYPE('digest', ['string', 'null'], digest); - password = toBuf(password); - salt = toBuf(salt); - - if (!isArrayBufferView(password)) { - throw new ERR_INVALID_ARG_TYPE('password', - ['string', 'Buffer', 'TypedArray'], - password); - } - - if (!isArrayBufferView(salt)) { - throw new ERR_INVALID_ARG_TYPE('salt', - ['string', 'Buffer', 'TypedArray'], salt); - } + password = checkIsArrayBufferView('password', toBuf(password)); + salt = checkIsArrayBufferView('salt', toBuf(salt)); if (typeof iterations !== 'number') throw new ERR_INVALID_ARG_TYPE('iterations', 'number', iterations); diff --git a/lib/internal/crypto/sig.js b/lib/internal/crypto/sig.js index aed679e99b9b8f..1073b83d720098 100644 --- a/lib/internal/crypto/sig.js +++ b/lib/internal/crypto/sig.js @@ -14,10 +14,10 @@ const { RSA_PKCS1_PADDING } = process.binding('constants').crypto; const { + checkIsArrayBufferView, getDefaultEncoding, toBuf } = require('internal/crypto/util'); -const { isArrayBufferView } = require('internal/util/types'); const { Writable } = require('stream'); const { inherits } = require('util'); @@ -41,18 +41,30 @@ Sign.prototype._write = function _write(chunk, encoding, callback) { Sign.prototype.update = function update(data, encoding) { encoding = encoding || getDefaultEncoding(); - data = toBuf(data, encoding); - if (!isArrayBufferView(data)) { - throw new ERR_INVALID_ARG_TYPE( - 'data', - ['string', 'Buffer', 'TypedArray', 'DataView'], - data - ); - } + data = checkIsArrayBufferView('data', toBuf(data, encoding)); this._handle.update(data); return this; }; +function getPadding(options) { + return getIntOption('padding', RSA_PKCS1_PADDING, options); +} + +function getSaltLength(options) { + return getIntOption('saltLength', RSA_PSS_SALTLEN_AUTO, options); +} + +function getIntOption(name, defaultValue, options) { + if (options.hasOwnProperty(name)) { + if (options[name] === options[name] >> 0) { + return options[name]; + } else { + throw new ERR_INVALID_OPT_VALUE(name, options[name]); + } + } + return defaultValue; +} + Sign.prototype.sign = function sign(options, encoding) { if (!options) throw new ERR_CRYPTO_SIGN_KEY_REQUIRED(); @@ -61,32 +73,11 @@ Sign.prototype.sign = function sign(options, encoding) { var passphrase = options.passphrase || null; // Options specific to RSA - var rsaPadding = RSA_PKCS1_PADDING; - if (options.hasOwnProperty('padding')) { - if (options.padding === options.padding >> 0) { - rsaPadding = options.padding; - } else { - throw new ERR_INVALID_OPT_VALUE('padding', options.padding); - } - } + var rsaPadding = getPadding(options); - var pssSaltLength = RSA_PSS_SALTLEN_AUTO; - if (options.hasOwnProperty('saltLength')) { - if (options.saltLength === options.saltLength >> 0) { - pssSaltLength = options.saltLength; - } else { - throw new ERR_INVALID_OPT_VALUE('saltLength', options.saltLength); - } - } + var pssSaltLength = getSaltLength(options); - key = toBuf(key); - if (!isArrayBufferView(key)) { - throw new ERR_INVALID_ARG_TYPE( - 'key', - ['string', 'Buffer', 'TypedArray', 'DataView'], - key - ); - } + key = checkIsArrayBufferView('key', toBuf(key)); var ret = this._handle.sign(key, passphrase, rsaPadding, pssSaltLength); @@ -119,41 +110,14 @@ Verify.prototype.verify = function verify(options, signature, sigEncoding) { sigEncoding = sigEncoding || getDefaultEncoding(); // Options specific to RSA - var rsaPadding = RSA_PKCS1_PADDING; - if (options.hasOwnProperty('padding')) { - if (options.padding === options.padding >> 0) { - rsaPadding = options.padding; - } else { - throw new ERR_INVALID_OPT_VALUE('padding', options.padding); - } - } + var rsaPadding = getPadding(options); - var pssSaltLength = RSA_PSS_SALTLEN_AUTO; - if (options.hasOwnProperty('saltLength')) { - if (options.saltLength === options.saltLength >> 0) { - pssSaltLength = options.saltLength; - } else { - throw new ERR_INVALID_OPT_VALUE('saltLength', options.saltLength); - } - } + var pssSaltLength = getSaltLength(options); - key = toBuf(key); - if (!isArrayBufferView(key)) { - throw new ERR_INVALID_ARG_TYPE( - 'key', - ['string', 'Buffer', 'TypedArray', 'DataView'], - key - ); - } + key = checkIsArrayBufferView('key', toBuf(key)); - signature = toBuf(signature, sigEncoding); - if (!isArrayBufferView(signature)) { - throw new ERR_INVALID_ARG_TYPE( - 'signature', - ['string', 'Buffer', 'TypedArray', 'DataView'], - signature - ); - } + signature = checkIsArrayBufferView('signature', + toBuf(signature, sigEncoding)); return this._handle.verify(key, signature, rsaPadding, pssSaltLength); }; diff --git a/lib/internal/crypto/util.js b/lib/internal/crypto/util.js index 095ca0478bd99f..59a5d57a1e4f39 100644 --- a/lib/internal/crypto/util.js +++ b/lib/internal/crypto/util.js @@ -83,7 +83,19 @@ function timingSafeEqual(buf1, buf2) { return _timingSafeEqual(buf1, buf2); } +function checkIsArrayBufferView(name, buffer) { + if (!isArrayBufferView(buffer)) { + throw new ERR_INVALID_ARG_TYPE( + name, + ['string', 'Buffer', 'TypedArray', 'DataView'], + buffer + ); + } + return buffer; +} + module.exports = { + checkIsArrayBufferView, getCiphers, getCurves, getDefaultEncoding, diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 09f58506c44ea0..fc306e256c1f1a 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -15,6 +15,7 @@ const kInfo = Symbol('info'); const messages = new Map(); const codes = {}; +let blue = ''; let green = ''; let red = ''; let white = ''; @@ -78,16 +79,6 @@ function inspectValue(val) { ).split('\n'); } -function sysErrorMessage(prefix, ctx) { - let message = `${prefix}: ${ctx.syscall} returned ` + - `${ctx.code} (${ctx.message})`; - if (ctx.path !== undefined) - message += ` ${ctx.path}`; - if (ctx.dest !== undefined) - message += ` => ${ctx.dest}`; - return message; -} - // A specialized Error that includes an additional info property with // additional information about the error condition. // It has the properties present in a UVException but with a custom error @@ -97,9 +88,17 @@ function sysErrorMessage(prefix, ctx) { // The context passed into this error must have .code, .syscall and .message, // and may have .path and .dest. class SystemError extends Error { - constructor(key, context = {}) { - context = context || {}; - super(sysErrorMessage(message(key), context)); + constructor(key, context) { + const prefix = getMessage(key, []); + let message = `${prefix}: ${context.syscall} returned ` + + `${context.code} (${context.message})`; + + if (context.path !== undefined) + message += ` ${context.path}`; + if (context.dest !== undefined) + message += ` => ${context.dest}`; + + super(message); Object.defineProperty(this, kInfo, { configurable: false, enumerable: false, @@ -182,8 +181,8 @@ class SystemError extends Error { function makeSystemErrorWithCode(key) { return class NodeError extends SystemError { - constructor(...args) { - super(key, ...args); + constructor(ctx) { + super(key, ctx); } }; } @@ -191,7 +190,7 @@ function makeSystemErrorWithCode(key) { function makeNodeErrorWithCode(Base, key) { return class NodeError extends Base { constructor(...args) { - super(message(key, args)); + super(getMessage(key, args)); } get name() { @@ -259,7 +258,7 @@ function createErrDiff(actual, expected, operator) { const expectedLines = inspectValue(expected); const msg = READABLE_OPERATOR[operator] + `:\n${green}+ expected${white} ${red}- actual${white}`; - const skippedMsg = ' ... Lines skipped'; + const skippedMsg = ` ${blue}...${white} Lines skipped`; // Remove all ending lines that match (this optimizes the output for // readability by reducing the number of total changed lines). @@ -280,7 +279,7 @@ function createErrDiff(actual, expected, operator) { b = expectedLines[expectedLines.length - 1]; } if (i > 3) { - end = `\n...${end}`; + end = `\n${blue}...${white}${end}`; skipped = true; } if (other !== '') { @@ -297,7 +296,7 @@ function createErrDiff(actual, expected, operator) { if (actualLines.length < i + 1) { if (cur > 1 && i > 2) { if (cur > 4) { - res += '\n...'; + res += `\n${blue}...${white}`; skipped = true; } else if (cur > 3) { res += `\n ${expectedLines[i - 2]}`; @@ -313,7 +312,7 @@ function createErrDiff(actual, expected, operator) { } else if (expectedLines.length < i + 1) { if (cur > 1 && i > 2) { if (cur > 4) { - res += '\n...'; + res += `\n${blue}...${white}`; skipped = true; } else if (cur > 3) { res += `\n ${actualLines[i - 2]}`; @@ -329,7 +328,7 @@ function createErrDiff(actual, expected, operator) { } else if (actualLines[i] !== expectedLines[i]) { if (cur > 1 && i > 2) { if (cur > 4) { - res += '\n...'; + res += `\n${blue}...${white}`; skipped = true; } else if (cur > 3) { res += `\n ${actualLines[i - 2]}`; @@ -354,19 +353,17 @@ function createErrDiff(actual, expected, operator) { } // Inspected object to big (Show ~20 rows max) if (printedLines > 20 && i < maxLines - 2) { - return `${msg}${skippedMsg}\n${res}\n...${other}\n...`; + return `${msg}${skippedMsg}\n${res}\n${blue}...${white}${other}\n` + + `${blue}...${white}`; } } // Strict equal with identical objects that are not identical by reference. if (identical === maxLines) { - let base = 'Input object identical but not reference equal:'; - - if (operator !== 'strictEqual') { - // This code path should not be possible to reach. - // The output is identical but it is not clear why. - base = 'Input objects not identical:'; - } + // E.g., assert.deepStrictEqual(Symbol(), Symbol()) + const base = operator === 'strictEqual' ? + 'Input objects identical but not reference equal:' : + 'Input objects not identical:'; // We have to get the result again. The lines were all removed before. const actualLines = inspectValue(actual); @@ -374,13 +371,13 @@ function createErrDiff(actual, expected, operator) { // Only remove lines in case it makes sense to collapse those. // TODO: Accept env to always show the full error. if (actualLines.length > 30) { - actualLines[26] = '...'; + actualLines[26] = `${blue}...${white}`; while (actualLines.length > 27) { actualLines.pop(); } } - return `${base}\n\n ${actualLines.join('\n ')}\n`; + return `${base}\n\n${actualLines.join('\n')}\n`; } return `${msg}${skipped ? skippedMsg : ''}\n${res}${other}${end}`; } @@ -405,10 +402,12 @@ class AssertionError extends Error { // Reset on each call to make sure we handle dynamically set environment // variables correct. if (process.stdout.getColorDepth() !== 1) { + blue = '\u001b[34m'; green = '\u001b[32m'; white = '\u001b[39m'; red = '\u001b[31m'; } else { + blue = ''; green = ''; white = ''; red = ''; @@ -438,7 +437,7 @@ class AssertionError extends Error { // Only remove lines in case it makes sense to collapse those. // TODO: Accept env to always show the full error. if (res.length > 30) { - res[26] = '...'; + res[26] = `${blue}...${white}`; while (res.length > 27) { res.pop(); } @@ -448,7 +447,7 @@ class AssertionError extends Error { if (res.length === 1) { super(`${base} ${res[0]}`); } else { - super(`${base}\n\n ${res.join('\n ')}\n`); + super(`${base}\n\n${res.join('\n')}\n`); } } else { let res = util.inspect(actual); @@ -484,7 +483,7 @@ function internalAssert(condition, message) { } } -function message(key, args = []) { +function getMessage(key, args) { const msg = messages.get(key); if (util === undefined) util = require('util'); @@ -693,7 +692,7 @@ module.exports = { exceptionWithHostPort, uvException, isStackOverflowError, - message, + getMessage, AssertionError, SystemError, codes, @@ -871,7 +870,6 @@ E('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => { }, TypeError, RangeError); E('ERR_INVALID_ARRAY_LENGTH', (name, len, actual) => { - internalAssert(typeof actual === 'number', 'actual must be of type number'); return `The array "${name}" (length ${actual}) must be of length ${len}.`; }, TypeError); E('ERR_INVALID_ASYNC_ID', 'Invalid %s value: %s', RangeError); diff --git a/lib/internal/fixed_queue.js b/lib/internal/fixed_queue.js new file mode 100644 index 00000000000000..7571a8f67e36d2 --- /dev/null +++ b/lib/internal/fixed_queue.js @@ -0,0 +1,113 @@ +'use strict'; + +// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. +const kSize = 2048; +const kMask = kSize - 1; + +// The FixedQueue is implemented as a singly-linked list of fixed-size +// circular buffers. It looks something like this: +// +// head tail +// | | +// v v +// +-----------+ <-----\ +-----------+ <------\ +-----------+ +// | [null] | \----- | next | \------- | next | +// +-----------+ +-----------+ +-----------+ +// | item | <-- bottom | item | <-- bottom | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | bottom --> | item | +// | item | | item | | item | +// | ... | | ... | | ... | +// | item | | item | | item | +// | item | | item | | item | +// | [empty] | <-- top | item | | item | +// | [empty] | | item | | item | +// | [empty] | | [empty] | <-- top top --> | [empty] | +// +-----------+ +-----------+ +-----------+ +// +// Or, if there is only one circular buffer, it looks something +// like either of these: +// +// head tail head tail +// | | | | +// v v v v +// +-----------+ +-----------+ +// | [null] | | [null] | +// +-----------+ +-----------+ +// | [empty] | | item | +// | [empty] | | item | +// | item | <-- bottom top --> | [empty] | +// | item | | [empty] | +// | [empty] | <-- top bottom --> | item | +// | [empty] | | item | +// +-----------+ +-----------+ +// +// Adding a value means moving `top` forward by one, removing means +// moving `bottom` forward by one. After reaching the end, the queue +// wraps around. +// +// When `top === bottom` the current queue is empty and when +// `top + 1 === bottom` it's full. This wastes a single space of storage +// but allows much quicker checks. + +const FixedCircularBuffer = class FixedCircularBuffer { + constructor() { + this.bottom = 0; + this.top = 0; + this.list = new Array(kSize); + this.next = null; + } + + isEmpty() { + return this.top === this.bottom; + } + + isFull() { + return ((this.top + 1) & kMask) === this.bottom; + } + + push(data) { + this.list[this.top] = data; + this.top = (this.top + 1) & kMask; + } + + shift() { + const nextItem = this.list[this.bottom]; + if (nextItem === undefined) + return null; + this.list[this.bottom] = undefined; + this.bottom = (this.bottom + 1) & kMask; + return nextItem; + } +}; + +module.exports = class FixedQueue { + constructor() { + this.head = this.tail = new FixedCircularBuffer(); + } + + isEmpty() { + return this.head.isEmpty(); + } + + push(data) { + if (this.head.isFull()) { + // Head is full: Creates a new queue, sets the old queue's `.next` to it, + // and sets it as the new main queue. + this.head = this.head.next = new FixedCircularBuffer(); + } + this.head.push(data); + } + + shift() { + const { tail } = this; + const next = tail.shift(); + if (tail.isEmpty() && tail.next !== null) { + // If there is another queue, it forms the new tail. + this.tail = tail.next; + } + return next; + } +}; diff --git a/lib/fs/promises.js b/lib/internal/fs/promises.js similarity index 97% rename from lib/fs/promises.js rename to lib/internal/fs/promises.js index ba6c2b7aa64855..eb913adcbf975b 100644 --- a/lib/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -1,8 +1,5 @@ 'use strict'; -process.emitWarning('The fs/promises API is experimental', - 'ExperimentalWarning'); - const { F_OK, O_SYMLINK, @@ -37,7 +34,7 @@ const { validateOffsetLengthWrite, validatePath, validateUint32 -} = require('internal/fs'); +} = require('internal/fs/utils'); const pathModule = require('path'); const kHandle = Symbol('handle'); @@ -245,15 +242,6 @@ async function write(handle, buffer, offset, length, position) { if (typeof buffer !== 'string') buffer += ''; - if (typeof position !== 'function') { - if (typeof offset === 'function') { - position = offset; - offset = null; - } else { - position = length; - } - length = 'utf8'; - } const bytesWritten = (await binding.writeString(handle.fd, buffer, offset, length, kUsePromises)) || 0; return { bytesWritten, buffer }; @@ -400,7 +388,7 @@ async function lchown(path, uid, gid) { if (O_SYMLINK !== undefined) { const fd = await open(path, O_WRONLY | O_SYMLINK); - return fchmod(fd, uid, gid).finally(fd.close.bind(fd)); + return fchown(fd, uid, gid).finally(fd.close.bind(fd)); } throw new ERR_METHOD_NOT_IMPLEMENTED(); } diff --git a/lib/internal/fs.js b/lib/internal/fs/utils.js similarity index 100% rename from lib/internal/fs.js rename to lib/internal/fs/utils.js diff --git a/lib/internal/http2/compat.js b/lib/internal/http2/compat.js index 0bdbe7b69fdf10..d2aaa8838e2cbc 100644 --- a/lib/internal/http2/compat.js +++ b/lib/internal/http2/compat.js @@ -31,6 +31,7 @@ const kTrailers = Symbol('trailers'); const kRawTrailers = Symbol('rawTrailers'); const kProxySocket = Symbol('proxySocket'); const kSetHeader = Symbol('setHeader'); +const kAborted = Symbol('aborted'); const { HTTP2_HEADER_AUTHORITY, @@ -137,6 +138,7 @@ function onStreamDrain() { function onStreamAbortedRequest() { const request = this[kRequest]; if (request !== undefined && request[kState].closed === false) { + request[kAborted] = true; request.emit('aborted'); } } @@ -233,6 +235,7 @@ class Http2ServerRequest extends Readable { this[kTrailers] = {}; this[kRawTrailers] = []; this[kStream] = stream; + this[kAborted] = false; stream[kProxySocket] = null; stream[kRequest] = this; @@ -248,6 +251,10 @@ class Http2ServerRequest extends Readable { this.on('resume', onRequestResume); } + get aborted() { + return this[kAborted]; + } + get complete() { return this._readableState.ended || this[kState].closed || diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js index 495fa60ba39ce3..ede4f5d34371e8 100644 --- a/lib/internal/http2/core.js +++ b/lib/internal/http2/core.js @@ -68,10 +68,13 @@ const { onServerStream, Http2ServerResponse, } = require('internal/http2/compat'); const { utcDate } = require('internal/http'); -const { promisify } = require('internal/util'); +const { + promisify, + customInspectSymbol: kInspect +} = require('internal/util'); const { isArrayBufferView } = require('internal/util/types'); const { defaultTriggerAsyncIdScope } = require('internal/async_hooks'); -const { _connectionListener: httpConnectionListener } = require('http'); +const { _connectionListener: httpConnectionListener } = http; const { createPromise, promiseResolve } = process.binding('util'); const debug = util.debuglog('http2'); @@ -119,7 +122,6 @@ const { constants, nameForErrorCode } = binding; const NETServer = net.Server; const TLSServer = tls.Server; -const kInspect = require('internal/util').customInspectSymbol; const { kIncomingMessage } = require('_http_common'); const { kServerResponse } = require('_http_server'); @@ -206,6 +208,7 @@ const STREAM_FLAGS_CLOSED = 0x2; const STREAM_FLAGS_HEADERS_SENT = 0x4; const STREAM_FLAGS_HEAD_REQUEST = 0x8; const STREAM_FLAGS_ABORTED = 0x10; +const STREAM_FLAGS_HAS_TRAILERS = 0x20; const SESSION_FLAGS_PENDING = 0x0; const SESSION_FLAGS_READY = 0x1; @@ -330,26 +333,13 @@ function onStreamClose(code) { if (stream.destroyed) return; - const state = stream[kState]; - debug(`Http2Stream ${stream[kID]} [Http2Session ` + `${sessionName(stream[kSession][kType])}]: closed with code ${code}`); - if (!stream.closed) { - // Clear timeout and remove timeout listeners - stream.setTimeout(0); - stream.removeAllListeners('timeout'); - - // Set the state flags - state.flags |= STREAM_FLAGS_CLOSED; - state.rstCode = code; + if (!stream.closed) + closeStream(stream, code, false); - // Close the writable side of the stream - abort(stream); - stream.end(); - } - - state.fd = -1; + stream[kState].fd = -1; // Defer destroy we actually emit end. if (stream._readableState.endEmitted || code !== NGHTTP2_NO_ERROR) { // If errored or ended, we can destroy immediately. @@ -504,7 +494,7 @@ function requestOnConnect(headers, options) { // At this point, the stream should have already been destroyed during // the session.destroy() method. Do nothing else. - if (session.destroyed) + if (session === undefined || session.destroyed) return; // If the session was closed while waiting for the connect, destroy @@ -716,8 +706,11 @@ const proxySocketHandler = { // data received on the PING acknowlegement. function pingCallback(cb) { return function pingCallback(ack, duration, payload) { - const err = ack ? null : new ERR_HTTP2_PING_CANCEL(); - cb(err, duration, payload); + if (ack) { + cb(null, duration, payload); + } else { + cb(new ERR_HTTP2_PING_CANCEL()); + } }; } @@ -1412,6 +1405,9 @@ class ClientHttp2Session extends Http2Session { if (options.endStream) stream.end(); + if (options.waitForTrailers) + stream[kState].flags |= STREAM_FLAGS_HAS_TRAILERS; + const onConnect = requestOnConnect.bind(stream, headersList, options); if (this.connecting) { this.on('connect', onConnect); @@ -1445,8 +1441,11 @@ function afterDoStreamWrite(status, handle) { } function streamOnResume() { - if (!this.destroyed && !this.pending) + if (!this.destroyed && !this.pending) { + if (!this[kState].didRead) + this[kState].didRead = true; this[kHandle].readStart(); + } } function streamOnPause() { @@ -1454,16 +1453,6 @@ function streamOnPause() { this[kHandle].readStop(); } -// If the writable side of the Http2Stream is still open, emit the -// 'aborted' event and set the aborted flag. -function abort(stream) { - if (!stream.aborted && - !(stream._writableState.ended || stream._writableState.ending)) { - stream[kState].flags |= STREAM_FLAGS_ABORTED; - stream.emit('aborted'); - } -} - function afterShutdown() { this.callback(); const stream = this.handle[kOwner]; @@ -1471,6 +1460,51 @@ function afterShutdown() { stream[kMaybeDestroy](); } +function closeStream(stream, code, shouldSubmitRstStream = true) { + const state = stream[kState]; + state.flags |= STREAM_FLAGS_CLOSED; + state.rstCode = code; + + // Clear timeout and remove timeout listeners + stream.setTimeout(0); + stream.removeAllListeners('timeout'); + + const { ending, finished } = stream._writableState; + + if (!ending) { + // If the writable side of the Http2Stream is still open, emit the + // 'aborted' event and set the aborted flag. + if (!stream.aborted) { + state.flags |= STREAM_FLAGS_ABORTED; + stream.emit('aborted'); + } + + // Close the writable side. + stream.end(); + } + + if (shouldSubmitRstStream) { + const finishFn = finishCloseStream.bind(stream, code); + if (!ending || finished || code !== NGHTTP2_NO_ERROR) + finishFn(); + else + stream.once('finish', finishFn); + } +} + +function finishCloseStream(code) { + const rstStreamFn = submitRstStream.bind(this, code); + // If the handle has not yet been assigned, queue up the request to + // ensure that the RST_STREAM frame is sent after the stream ID has + // been determined. + if (this.pending) { + this.push(null); + this.once('ready', rstStreamFn); + return; + } + rstStreamFn(); +} + // An Http2Stream is a Duplex stream that is backed by a // node::http2::Http2Stream handle implementing StreamBase. class Http2Stream extends Duplex { @@ -1490,6 +1524,7 @@ class Http2Stream extends Duplex { this[kTimeout] = null; this[kState] = { + didRead: false, flags: STREAM_FLAGS_PENDING, rstCode: NGHTTP2_NO_ERROR, writeQueueSize: 0, @@ -1756,6 +1791,8 @@ class Http2Stream extends Duplex { throw headersList; this[kSentTrailers] = headers; + this[kState].flags &= ~STREAM_FLAGS_HAS_TRAILERS; + const ret = this[kHandle].trailers(headersList); if (ret < 0) this.destroy(new NghttpError(ret)); @@ -1786,38 +1823,13 @@ class Http2Stream extends Duplex { if (callback !== undefined && typeof callback !== 'function') throw new ERR_INVALID_CALLBACK(); - // Clear timeout and remove timeout listeners - this.setTimeout(0); - this.removeAllListeners('timeout'); - - // Close the writable - abort(this); - this.end(); - if (this.closed) return; - const state = this[kState]; - state.flags |= STREAM_FLAGS_CLOSED; - state.rstCode = code; - - if (callback !== undefined) { + if (callback !== undefined) this.once('close', callback); - } - - if (this[kHandle] === undefined) - return; - const rstStreamFn = submitRstStream.bind(this, code); - // If the handle has not yet been assigned, queue up the request to - // ensure that the RST_STREAM frame is sent after the stream ID has - // been determined. - if (this.pending) { - this.push(null); - this.once('ready', rstStreamFn); - return; - } - rstStreamFn(); + closeStream(this, code); } // Called by this.destroy(). @@ -1832,26 +1844,19 @@ class Http2Stream extends Duplex { debug(`Http2Stream ${this[kID] || ''} [Http2Session ` + `${sessionName(session[kType])}]: destroying stream`); const state = this[kState]; - const code = state.rstCode = - err != null ? - NGHTTP2_INTERNAL_ERROR : - state.rstCode || NGHTTP2_NO_ERROR; - if (handle !== undefined) { - // If the handle exists, we need to close, then destroy the handle - this.close(code); - if (!this._readableState.ended && !this._readableState.ending) - this.push(null); + const code = err != null ? + NGHTTP2_INTERNAL_ERROR : (state.rstCode || NGHTTP2_NO_ERROR); + + const hasHandle = handle !== undefined; + + if (!this.closed) + closeStream(this, code, hasHandle); + this.push(null); + + if (hasHandle) { handle.destroy(); session[kState].streams.delete(id); } else { - // Clear timeout and remove timeout listeners - this.setTimeout(0); - this.removeAllListeners('timeout'); - - state.flags |= STREAM_FLAGS_CLOSED; - abort(this); - this.end(); - this.push(null); session[kState].pendingStreams.delete(this); } @@ -1884,13 +1889,23 @@ class Http2Stream extends Duplex { } // TODO(mcollina): remove usage of _*State properties - if (this._readableState.ended && - this._writableState.ended && - this._writableState.pendingcb === 0 && - this.closed) { - this.destroy(); - // This should return, but eslint complains. - // return + if (this._writableState.ended && this._writableState.pendingcb === 0) { + if (this._readableState.ended && this.closed) { + this.destroy(); + return; + } + + // We've submitted a response from our server session, have not attempted + // to process any incoming data, and have no trailers. This means we can + // attempt to gracefully close the session. + const state = this[kState]; + if (this.headersSent && + this[kSession][kType] === NGHTTP2_SESSION_SERVER && + !(state.flags & STREAM_FLAGS_HAS_TRAILERS) && + !state.didRead && + !this._readableState.resumeScheduled) { + this.close(); + } } } } @@ -2095,7 +2110,6 @@ function afterOpen(session, options, headers, streamOptions, err, fd) { } if (this.destroyed || this.closed) { tryClose(fd); - abort(this); return; } state.fd = fd; @@ -2224,8 +2238,10 @@ class ServerHttp2Stream extends Http2Stream { if (options.endStream) streamOptions |= STREAM_OPTION_EMPTY_PAYLOAD; - if (options.waitForTrailers) + if (options.waitForTrailers) { streamOptions |= STREAM_OPTION_GET_TRAILERS; + state.flags |= STREAM_FLAGS_HAS_TRAILERS; + } headers = processHeaders(headers); const statusCode = headers[HTTP2_HEADER_STATUS] |= 0; @@ -2285,8 +2301,10 @@ class ServerHttp2Stream extends Http2Stream { } let streamOptions = 0; - if (options.waitForTrailers) + if (options.waitForTrailers) { streamOptions |= STREAM_OPTION_GET_TRAILERS; + this[kState].flags |= STREAM_FLAGS_HAS_TRAILERS; + } if (typeof fd !== 'number') throw new ERR_INVALID_ARG_TYPE('fd', 'number', fd); @@ -2346,8 +2364,10 @@ class ServerHttp2Stream extends Http2Stream { } let streamOptions = 0; - if (options.waitForTrailers) + if (options.waitForTrailers) { streamOptions |= STREAM_OPTION_GET_TRAILERS; + this[kState].flags |= STREAM_FLAGS_HAS_TRAILERS; + } const session = this[kSession]; debug(`Http2Stream ${this[kID]} [Http2Session ` + diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index 652378ad5782fb..85ab3ab1443ded 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -28,7 +28,7 @@ const { getURLFromFilePath } = require('internal/url'); const vm = require('vm'); const assert = require('assert').ok; const fs = require('fs'); -const internalFS = require('internal/fs'); +const internalFS = require('internal/fs/utils'); const path = require('path'); const { internalModuleReadJSON, diff --git a/lib/internal/modules/esm/default_resolve.js b/lib/internal/modules/esm/default_resolve.js index 60516535e9ad03..48d3ef73fd86cd 100644 --- a/lib/internal/modules/esm/default_resolve.js +++ b/lib/internal/modules/esm/default_resolve.js @@ -2,7 +2,7 @@ const { URL } = require('url'); const CJSmodule = require('internal/modules/cjs/loader'); -const internalFS = require('internal/fs'); +const internalFS = require('internal/fs/utils'); const { NativeModule, internalBinding } = require('internal/bootstrap/loaders'); const { extname } = require('path'); const { realpathSync } = require('fs'); diff --git a/lib/internal/process/next_tick.js b/lib/internal/process/next_tick.js index 7a5d2f88a6d17e..dbe0ce8cdbdacf 100644 --- a/lib/internal/process/next_tick.js +++ b/lib/internal/process/next_tick.js @@ -16,6 +16,7 @@ function setupNextTick() { } = require('internal/async_hooks'); const promises = require('internal/process/promises'); const { ERR_INVALID_CALLBACK } = require('internal/errors').codes; + const FixedQueue = require('internal/fixed_queue'); const { emitPromiseRejectionWarnings } = promises; // tickInfo is used so that the C++ code in src/node.cc can @@ -31,119 +32,7 @@ function setupNextTick() { const kHasScheduled = 0; const kHasPromiseRejections = 1; - // Queue size for each tick array. Must be a power of two. - const kQueueSize = 2048; - const kQueueMask = kQueueSize - 1; - - // The next tick queue is implemented as a singly-linked list of fixed-size - // circular buffers. It looks something like this: - // - // head tail - // | | - // v v - // +-----------+ <-----\ +-----------+ <------\ +-----------+ - // | [null] | \----- | next | \------- | next | - // +-----------+ +-----------+ +-----------+ - // | tick | <-- bottom | tick | <-- bottom | [empty] | - // | tick | | tick | | [empty] | - // | tick | | tick | | [empty] | - // | tick | | tick | | [empty] | - // | tick | | tick | bottom --> | tick | - // | tick | | tick | | tick | - // | ... | | ... | | ... | - // | tick | | tick | | tick | - // | tick | | tick | | tick | - // | [empty] | <-- top | tick | | tick | - // | [empty] | | tick | | tick | - // | [empty] | | tick | | tick | - // +-----------+ +-----------+ <-- top top --> +-----------+ - // - // Or, if there is only one fixed-size queue, it looks something - // like either of these: - // - // head tail head tail - // | | | | - // v v v v - // +-----------+ +-----------+ - // | [null] | | [null] | - // +-----------+ +-----------+ - // | [empty] | | tick | - // | [empty] | | tick | - // | tick | <-- bottom top --> | [empty] | - // | tick | | [empty] | - // | [empty] | <-- top bottom --> | tick | - // | [empty] | | tick | - // +-----------+ +-----------+ - // - // Adding a value means moving `top` forward by one, removing means - // moving `bottom` forward by one. - // - // We let `bottom` and `top` wrap around, so when `top` is conceptually - // pointing to the end of the list, that means that the actual value is `0`. - // - // In particular, when `top === bottom`, this can mean *either* that the - // current queue is empty or that it is full. We can differentiate by - // checking whether an entry in the queue is empty (a.k.a. `=== undefined`). - - class FixedQueue { - constructor() { - this.bottom = 0; - this.top = 0; - this.list = new Array(kQueueSize); - this.next = null; - } - - push(data) { - this.list[this.top] = data; - this.top = (this.top + 1) & kQueueMask; - } - - shift() { - const nextItem = this.list[this.bottom]; - if (nextItem === undefined) - return null; - this.list[this.bottom] = undefined; - this.bottom = (this.bottom + 1) & kQueueMask; - return nextItem; - } - } - - var head = new FixedQueue(); - var tail = head; - - function push(data) { - if (head.bottom === head.top) { - // Either empty or full: - if (head.list[head.top] !== undefined) { - // It's full: Creates a new queue, sets the old queue's `.next` to it, - // and sets it as the new main queue. - head = head.next = new FixedQueue(); - } else { - // If the head is empty, that means that it was the only fixed-sized - // queue in existence. - DCHECK_EQ(head.next, null); - // This is the first tick object in existence, so we need to inform - // the C++ side that we do want to run `_tickCallback()`. - tickInfo[kHasScheduled] = 1; - } - } - head.push(data); - } - - function shift() { - const next = tail.shift(); - if (tail.top === tail.bottom) { // -> .shift() emptied the current queue. - if (tail.next !== null) { - // If there is another queue, it forms the new tail. - tail = tail.next; - } else { - // We've just run out of items. Let the native side know that it - // doesn't need to bother calling into JS to run the queue. - tickInfo[kHasScheduled] = 0; - } - } - return next; - } + const queue = new FixedQueue(); process.nextTick = nextTick; // Needs to be accessible from beyond this scope. @@ -152,7 +41,7 @@ function setupNextTick() { function _tickCallback() { let tock; do { - while (tock = shift()) { + while (tock = queue.shift()) { const asyncId = tock[async_id_symbol]; emitBefore(asyncId, tock[trigger_async_id_symbol]); // emitDestroy() places the async_id_symbol into an asynchronous queue @@ -175,8 +64,9 @@ function setupNextTick() { emitAfter(asyncId); } + tickInfo[kHasScheduled] = 0; runMicrotasks(); - } while (head.top !== head.bottom || emitPromiseRejectionWarnings()); + } while (!queue.isEmpty() || emitPromiseRejectionWarnings()); tickInfo[kHasPromiseRejections] = 0; } @@ -222,6 +112,8 @@ function setupNextTick() { args[i - 1] = arguments[i]; } - push(new TickObject(callback, args, getDefaultTriggerAsyncId())); + if (queue.isEmpty()) + tickInfo[kHasScheduled] = 1; + queue.push(new TickObject(callback, args, getDefaultTriggerAsyncId())); } } diff --git a/lib/internal/process/stdio.js b/lib/internal/process/stdio.js index 29aee7d09bdab9..75ede6a8e7e157 100644 --- a/lib/internal/process/stdio.js +++ b/lib/internal/process/stdio.js @@ -158,7 +158,7 @@ function createWritableStdioStream(fd) { break; case 'FILE': - var fs = require('internal/fs'); + var fs = require('internal/fs/utils'); stream = new fs.SyncWriteStream(fd, { autoClose: false }); stream._type = 'fs'; break; diff --git a/lib/internal/streams/async_iterator.js b/lib/internal/streams/async_iterator.js index 9ca8e5ebe23b15..0e34573d877aee 100644 --- a/lib/internal/streams/async_iterator.js +++ b/lib/internal/streams/async_iterator.js @@ -58,7 +58,7 @@ function onError(iter, err) { iter[kLastReject] = null; reject(err); } - iter.error = err; + iter[kError] = err; } function wrapForNext(lastPromise, iter) { diff --git a/lib/internal/streams/destroy.js b/lib/internal/streams/destroy.js index 2ab614e1d597da..3a0383cc3cea70 100644 --- a/lib/internal/streams/destroy.js +++ b/lib/internal/streams/destroy.js @@ -8,14 +8,10 @@ function destroy(err, cb) { this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { - const readableErrored = this._readableState && - this._readableState.errorEmitted; - const writableErrored = this._writableState && - this._writableState.errorEmitted; - if (cb) { cb(err); - } else if (err && !readableErrored && !writableErrored) { + } else if (err && + (!this._writableState || !this._writableState.errorEmitted)) { process.nextTick(emitErrorNT, this, err); } return this; @@ -36,11 +32,6 @@ function destroy(err, cb) { this._destroy(err || null, (err) => { if (!cb && err) { process.nextTick(emitErrorAndCloseNT, this, err); - - if (this._readableState) { - this._readableState.errorEmitted = true; - } - if (this._writableState) { this._writableState.errorEmitted = true; } @@ -74,7 +65,6 @@ function undestroy() { this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; - this._readableState.errorEmitted = false; } if (this._writableState) { diff --git a/lib/internal/url.js b/lib/internal/url.js index cff94e6b7d2b5b..d9daef1524787d 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -400,7 +400,9 @@ Object.defineProperties(URL.prototype, { ret += '@'; } ret += options.unicode ? - domainToUnicode(this.host) : this.host; + domainToUnicode(this.hostname) : this.hostname; + if (ctx.port !== null) + ret += `:${ctx.port}`; } else if (ctx.scheme === 'file:') { ret += '//'; } diff --git a/lib/internal/util.js b/lib/internal/util.js index ce25317b778a3f..07515e2e090daa 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -322,10 +322,11 @@ function join(output, separator) { return str; } -// About 1.5x faster than the two-arg version of Array#splice(). +// As of V8 6.6, depending on the size of the array, this is anywhere +// between 1.5-10x faster than the two-arg version of Array#splice() function spliceOne(list, index) { - for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) - list[i] = list[k]; + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; list.pop(); } @@ -356,16 +357,17 @@ function isInsideNodeModules() { // Iterate over all stack frames and look for the first one not coming // from inside Node.js itself: - for (const frame of stack) { - const filename = frame.getFileName(); - // If a filename does not start with / or contain \, - // it's likely from Node.js core. - if (!/^\/|\\/.test(filename)) - continue; - return kNodeModulesRE.test(filename); + if (Array.isArray(stack)) { + for (const frame of stack) { + const filename = frame.getFileName(); + // If a filename does not start with / or contain \, + // it's likely from Node.js core. + if (!/^\/|\\/.test(filename)) + continue; + return kNodeModulesRE.test(filename); + } } - - return false; // This should be unreachable. + return false; } diff --git a/lib/repl.js b/lib/repl.js index 2bef57fa100170..600816a6058fbc 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -1429,9 +1429,9 @@ function defineDefaultCommands(repl) { action: function(file) { try { fs.writeFileSync(file, this.lines.join('\n') + '\n'); - this.outputStream.write('Session saved to:' + file + '\n'); + this.outputStream.write('Session saved to: ' + file + '\n'); } catch (e) { - this.outputStream.write('Failed to save:' + file + '\n'); + this.outputStream.write('Failed to save: ' + file + '\n'); } this.displayPrompt(); } @@ -1453,11 +1453,11 @@ function defineDefaultCommands(repl) { _turnOffEditorMode(this); this.write('\n'); } else { - this.outputStream.write('Failed to load:' + file + + this.outputStream.write('Failed to load: ' + file + ' is not a valid file\n'); } } catch (e) { - this.outputStream.write('Failed to load:' + file + '\n'); + this.outputStream.write('Failed to load: ' + file + '\n'); } this.displayPrompt(); } diff --git a/lib/timers.js b/lib/timers.js index 15700f5a1212ab..ff85a9f4b1d1e0 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -453,7 +453,7 @@ function rearm(timer, start = TimerWrap.now()) { } -const clearTimeout = exports.clearTimeout = function(timer) { +const clearTimeout = exports.clearTimeout = function clearTimeout(timer) { if (timer && timer._onTimeout) { timer._onTimeout = null; if (timer instanceof Timeout) { @@ -465,7 +465,7 @@ const clearTimeout = exports.clearTimeout = function(timer) { }; -exports.setInterval = function(callback, repeat, arg1, arg2, arg3) { +exports.setInterval = function setInterval(callback, repeat, arg1, arg2, arg3) { if (typeof callback !== 'function') { throw new ERR_INVALID_CALLBACK(); } @@ -774,7 +774,7 @@ setImmediate[internalUtil.promisify.custom] = function(value) { exports.setImmediate = setImmediate; -exports.clearImmediate = function(immediate) { +exports.clearImmediate = function clearImmediate(immediate) { if (!immediate || immediate._destroyed) return; diff --git a/lib/url.js b/lib/url.js index ac9879a650fce6..e4326e80b5d948 100644 --- a/lib/url.js +++ b/lib/url.js @@ -281,9 +281,6 @@ Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) { // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:b path:/?@c - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - var hostEnd = -1; var atSign = -1; var nonHost = -1; diff --git a/lib/util.js b/lib/util.js index 93bcb343a9eefc..45d98de194c836 100644 --- a/lib/util.js +++ b/lib/util.js @@ -277,12 +277,12 @@ function debuglog(set) { if (!debugs[set]) { if (debugEnvRegex.test(set)) { const pid = process.pid; - debugs[set] = function() { + debugs[set] = function debug() { const msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { - debugs[set] = function() {}; + debugs[set] = function debug() {}; } } return debugs[set]; diff --git a/node.gyp b/node.gyp index 8347beb18245ca..eb9c371c982c0f 100644 --- a/node.gyp +++ b/node.gyp @@ -39,7 +39,6 @@ 'lib/domain.js', 'lib/events.js', 'lib/fs.js', - 'lib/fs/promises.js', 'lib/http.js', 'lib/http2.js', 'lib/_http_agent.js', @@ -101,8 +100,10 @@ 'lib/internal/constants.js', 'lib/internal/encoding.js', 'lib/internal/errors.js', + 'lib/internal/fixed_queue.js', 'lib/internal/freelist.js', - 'lib/internal/fs.js', + 'lib/internal/fs/promises.js', + 'lib/internal/fs/utils.js', 'lib/internal/http.js', 'lib/internal/inspector_async_hook.js', 'lib/internal/linkedlist.js', @@ -680,13 +681,13 @@ 'toolsets': ['host'], 'conditions': [ [ 'v8_enable_inspector==1', { - 'actions': [ + 'copies': [ { - 'action_name': 'v8_inspector_copy_protocol_to_intermediate_folder', - 'inputs': [ 'deps/v8/src/inspector/js_protocol.pdl' ], - 'outputs': [ '<(SHARED_INTERMEDIATE_DIR)/js_protocol.pdl' ], - 'action': [ 'cp', '<@(_inputs)', '<(SHARED_INTERMEDIATE_DIR)' ], - }, + 'destination': '<(SHARED_INTERMEDIATE_DIR)', + 'files': ['deps/v8/src/inspector/js_protocol.pdl'] + } + ], + 'actions': [ { 'action_name': 'v8_inspector_convert_protocol_to_json', 'inputs': [ @@ -961,6 +962,7 @@ 'test/cctest/test_base64.cc', 'test/cctest/test_node_postmortem_metadata.cc', 'test/cctest/test_environment.cc', + 'test/cctest/test_platform.cc', 'test/cctest/test_util.cc', 'test/cctest/test_url.cc' ], diff --git a/src/async_wrap.cc b/src/async_wrap.cc index 06dcbb4fb1d29d..f7a6d4e68dd483 100644 --- a/src/async_wrap.cc +++ b/src/async_wrap.cc @@ -123,8 +123,8 @@ RetainedObjectInfo* WrapperInfo(uint16_t class_id, Local wrapper) { Local object = wrapper.As(); CHECK_GT(object->InternalFieldCount(), 0); - AsyncWrap* wrap = Unwrap(object); - if (wrap == nullptr) return nullptr; // ClearWrap() already called. + AsyncWrap* wrap; + ASSIGN_OR_RETURN_UNWRAP(&wrap, object, nullptr); return new RetainedAsyncInfo(class_id, wrap); } @@ -231,7 +231,7 @@ class PromiseWrap : public AsyncWrap { public: PromiseWrap(Environment* env, Local object, bool silent) : AsyncWrap(env, object, PROVIDER_PROMISE, -1, silent) { - MakeWeak(this); + MakeWeak(); } size_t self_size() const override { return sizeof(*this); } diff --git a/src/base_object-inl.h b/src/base_object-inl.h index 5ff211f473b86b..11ba1c88da0486 100644 --- a/src/base_object-inl.h +++ b/src/base_object-inl.h @@ -31,54 +31,90 @@ namespace node { -inline BaseObject::BaseObject(Environment* env, v8::Local handle) +BaseObject::BaseObject(Environment* env, v8::Local handle) : persistent_handle_(env->isolate(), handle), env_(env) { CHECK_EQ(false, handle.IsEmpty()); - // The zero field holds a pointer to the handle. Immediately set it to - // nullptr in case it's accessed by the user before construction is complete. - if (handle->InternalFieldCount() > 0) - handle->SetAlignedPointerInInternalField(0, nullptr); + CHECK_GT(handle->InternalFieldCount(), 0); + handle->SetAlignedPointerInInternalField(0, static_cast(this)); } -inline Persistent& BaseObject::persistent() { +BaseObject::~BaseObject() { + if (persistent_handle_.IsEmpty()) { + // This most likely happened because the weak callback below cleared it. + return; + } + + { + v8::HandleScope handle_scope(env_->isolate()); + object()->SetAlignedPointerInInternalField(0, nullptr); + } +} + + +Persistent& BaseObject::persistent() { return persistent_handle_; } -inline v8::Local BaseObject::object() { +v8::Local BaseObject::object() { return PersistentToLocal(env_->isolate(), persistent_handle_); } -inline Environment* BaseObject::env() const { +Environment* BaseObject::env() const { return env_; } -template -inline void BaseObject::WeakCallback( - const v8::WeakCallbackInfo& data) { - delete data.GetParameter(); +BaseObject* BaseObject::FromJSObject(v8::Local obj) { + CHECK_GT(obj->InternalFieldCount(), 0); + return static_cast(obj->GetAlignedPointerFromInternalField(0)); } -template -inline void BaseObject::MakeWeak(Type* ptr) { - v8::HandleScope scope(env_->isolate()); - v8::Local handle = object(); - CHECK_GT(handle->InternalFieldCount(), 0); - Wrap(handle, ptr); - persistent_handle_.SetWeak(ptr, WeakCallback, - v8::WeakCallbackType::kParameter); +template +T* BaseObject::FromJSObject(v8::Local object) { + return static_cast(FromJSObject(object)); } -inline void BaseObject::ClearWeak() { +void BaseObject::MakeWeak() { + persistent_handle_.SetWeak( + this, + [](const v8::WeakCallbackInfo& data) { + BaseObject* obj = data.GetParameter(); + // Clear the persistent handle so that ~BaseObject() doesn't attempt + // to mess with internal fields, since the JS object may have + // transitioned into an invalid state. + // Refs: https://github.com/nodejs/node/issues/18897 + obj->persistent_handle_.Reset(); + delete obj; + }, v8::WeakCallbackType::kParameter); +} + + +void BaseObject::ClearWeak() { persistent_handle_.ClearWeak(); } + +v8::Local +BaseObject::MakeLazilyInitializedJSTemplate(Environment* env) { + auto constructor = [](const v8::FunctionCallbackInfo& args) { +#ifdef DEBUG + CHECK(args.IsConstructCall()); + CHECK_GT(args.This()->InternalFieldCount(), 0); +#endif + args.This()->SetAlignedPointerInInternalField(0, nullptr); + }; + + v8::Local t = env->NewFunctionTemplate(constructor); + t->InstanceTemplate()->SetInternalFieldCount(1); + return t; +} + } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS diff --git a/src/base_object.h b/src/base_object.h index 478499bbfeb5b2..7d8281238b1c1d 100644 --- a/src/base_object.h +++ b/src/base_object.h @@ -26,6 +26,7 @@ #include "node_persistent.h" #include "v8.h" +#include // std::remove_reference namespace node { @@ -33,8 +34,10 @@ class Environment; class BaseObject { public: + // Associates this object with `handle`. It uses the 0th internal field for + // that, and in particular aborts if there is no such field. inline BaseObject(Environment* env, v8::Local handle); - virtual ~BaseObject() = default; + virtual inline ~BaseObject(); // Returns the wrapped object. Returns an empty handle when // persistent.IsEmpty() is true. @@ -44,23 +47,30 @@ class BaseObject { inline Environment* env() const; - // The handle_ must have an internal field count > 0, and the first - // index is reserved for a pointer to this class. This is an - // implicit requirement, but Node does not have a case where it's - // required that MakeWeak() be called and the internal field not - // be set. - template - inline void MakeWeak(Type* ptr); + // Get a BaseObject* pointer, or subclass pointer, for the JS object that + // was also passed to the `BaseObject()` constructor initially. + // This may return `nullptr` if the C++ object has not been constructed yet, + // e.g. when the JS object used `MakeLazilyInitializedJSTemplate`. + static inline BaseObject* FromJSObject(v8::Local object); + template + static inline T* FromJSObject(v8::Local object); + // Make the `Persistent` a weak reference and, `delete` this object once + // the JS object has been garbage collected. + inline void MakeWeak(); + + // Undo `MakeWeak()`, i.e. turn this into a strong reference. inline void ClearWeak(); + // Utility to create a FunctionTemplate with one internal field (used for + // the `BaseObject*` pointer) and a constructor that initializes that field + // to `nullptr`. + static inline v8::Local MakeLazilyInitializedJSTemplate( + Environment* env); + private: BaseObject(); - template - static inline void WeakCallback( - const v8::WeakCallbackInfo& data); - // persistent_handle_ needs to be at a fixed offset from the start of the // class because it is used by src/node_postmortem_metadata.cc to calculate // offsets and generate debug symbols for BaseObject, which assumes that the @@ -71,6 +81,22 @@ class BaseObject { Environment* env_; }; + +// Global alias for FromJSObject() to avoid churn. +template +inline T* Unwrap(v8::Local obj) { + return BaseObject::FromJSObject(obj); +} + + +#define ASSIGN_OR_RETURN_UNWRAP(ptr, obj, ...) \ + do { \ + *ptr = static_cast::type>( \ + BaseObject::FromJSObject(obj)); \ + if (*ptr == nullptr) \ + return __VA_ARGS__; \ + } while (0) + } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS diff --git a/src/cares_wrap.cc b/src/cares_wrap.cc index 0cc7ed1464fdb7..4df47d75d43ba8 100644 --- a/src/cares_wrap.cc +++ b/src/cares_wrap.cc @@ -187,7 +187,7 @@ ChannelWrap::ChannelWrap(Environment* env, is_servers_default_(true), library_inited_(false), active_query_count_(0) { - MakeWeak(this); + MakeWeak(); Setup(); } @@ -205,7 +205,6 @@ class GetAddrInfoReqWrap : public ReqWrap { GetAddrInfoReqWrap(Environment* env, Local req_wrap_obj, bool verbatim); - ~GetAddrInfoReqWrap(); size_t self_size() const override { return sizeof(*this); } bool verbatim() const { return verbatim_; } @@ -219,18 +218,12 @@ GetAddrInfoReqWrap::GetAddrInfoReqWrap(Environment* env, bool verbatim) : ReqWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_GETADDRINFOREQWRAP) , verbatim_(verbatim) { - Wrap(req_wrap_obj, this); -} - -GetAddrInfoReqWrap::~GetAddrInfoReqWrap() { - ClearWrap(object()); } class GetNameInfoReqWrap : public ReqWrap { public: GetNameInfoReqWrap(Environment* env, Local req_wrap_obj); - ~GetNameInfoReqWrap(); size_t self_size() const override { return sizeof(*this); } }; @@ -238,11 +231,6 @@ class GetNameInfoReqWrap : public ReqWrap { GetNameInfoReqWrap::GetNameInfoReqWrap(Environment* env, Local req_wrap_obj) : ReqWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_GETNAMEINFOREQWRAP) { - Wrap(req_wrap_obj, this); -} - -GetNameInfoReqWrap::~GetNameInfoReqWrap() { - ClearWrap(object()); } @@ -587,8 +575,6 @@ class QueryWrap : public AsyncWrap { QueryWrap(ChannelWrap* channel, Local req_wrap_obj) : AsyncWrap(channel->env(), req_wrap_obj, AsyncWrap::PROVIDER_QUERYWRAP), channel_(channel) { - Wrap(req_wrap_obj, this); - // Make sure the channel object stays alive during the query lifetime. req_wrap_obj->Set(env()->context(), env()->channel_string(), @@ -597,7 +583,6 @@ class QueryWrap : public AsyncWrap { ~QueryWrap() override { CHECK_EQ(false, persistent().IsEmpty()); - ClearWrap(object()); } // Subclasses should implement the appropriate Send method. @@ -2143,14 +2128,8 @@ void Initialize(Local target, target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "AI_V4MAPPED"), Integer::New(env->isolate(), AI_V4MAPPED)); - auto is_construct_call_callback = - [](const FunctionCallbackInfo& args) { - CHECK(args.IsConstructCall()); - ClearWrap(args.This()); - }; Local aiw = - FunctionTemplate::New(env->isolate(), is_construct_call_callback); - aiw->InstanceTemplate()->SetInternalFieldCount(1); + BaseObject::MakeLazilyInitializedJSTemplate(env); AsyncWrap::AddWrapMethods(env, aiw); Local addrInfoWrapString = FIXED_ONE_BYTE_STRING(env->isolate(), "GetAddrInfoReqWrap"); @@ -2158,8 +2137,7 @@ void Initialize(Local target, target->Set(addrInfoWrapString, aiw->GetFunction()); Local niw = - FunctionTemplate::New(env->isolate(), is_construct_call_callback); - niw->InstanceTemplate()->SetInternalFieldCount(1); + BaseObject::MakeLazilyInitializedJSTemplate(env); AsyncWrap::AddWrapMethods(env, niw); Local nameInfoWrapString = FIXED_ONE_BYTE_STRING(env->isolate(), "GetNameInfoReqWrap"); @@ -2167,8 +2145,7 @@ void Initialize(Local target, target->Set(nameInfoWrapString, niw->GetFunction()); Local qrw = - FunctionTemplate::New(env->isolate(), is_construct_call_callback); - qrw->InstanceTemplate()->SetInternalFieldCount(1); + BaseObject::MakeLazilyInitializedJSTemplate(env); AsyncWrap::AddWrapMethods(env, qrw); Local queryWrapString = FIXED_ONE_BYTE_STRING(env->isolate(), "QueryReqWrap"); diff --git a/src/connect_wrap.cc b/src/connect_wrap.cc index f9ea987e05f5a3..dacdf72da7c494 100644 --- a/src/connect_wrap.cc +++ b/src/connect_wrap.cc @@ -13,12 +13,6 @@ using v8::Object; ConnectWrap::ConnectWrap(Environment* env, Local req_wrap_obj, AsyncWrap::ProviderType provider) : ReqWrap(env, req_wrap_obj, provider) { - Wrap(req_wrap_obj, this); -} - - -ConnectWrap::~ConnectWrap() { - ClearWrap(object()); } } // namespace node diff --git a/src/connect_wrap.h b/src/connect_wrap.h index 6227542bcbee50..80eae7f9bb8290 100644 --- a/src/connect_wrap.h +++ b/src/connect_wrap.h @@ -15,7 +15,6 @@ class ConnectWrap : public ReqWrap { ConnectWrap(Environment* env, v8::Local req_wrap_obj, AsyncWrap::ProviderType provider); - ~ConnectWrap(); size_t self_size() const override { return sizeof(*this); } }; diff --git a/src/connection_wrap.h b/src/connection_wrap.h index 096672efddaae2..afb168c614aa97 100644 --- a/src/connection_wrap.h +++ b/src/connection_wrap.h @@ -29,7 +29,6 @@ class ConnectionWrap : public LibuvStreamWrap { UVType handle_; }; - } // namespace node #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS diff --git a/src/env-inl.h b/src/env-inl.h index fa241f9706ec65..6202e50548a3ce 100644 --- a/src/env-inl.h +++ b/src/env-inl.h @@ -482,12 +482,12 @@ inline void Environment::set_http_parser_buffer_in_use(bool in_use) { http_parser_buffer_in_use_ = in_use; } -inline http2::http2_state* Environment::http2_state() const { +inline http2::Http2State* Environment::http2_state() const { return http2_state_.get(); } inline void Environment::set_http2_state( - std::unique_ptr buffer) { + std::unique_ptr buffer) { CHECK(!http2_state_); // Should be set only once. http2_state_ = std::move(buffer); } @@ -583,9 +583,11 @@ inline void Environment::ThrowUVException(int errorno, inline v8::Local Environment::NewFunctionTemplate(v8::FunctionCallback callback, - v8::Local signature) { + v8::Local signature, + v8::ConstructorBehavior behavior) { v8::Local external = as_external(); - return v8::FunctionTemplate::New(isolate(), callback, external, signature); + return v8::FunctionTemplate::New(isolate(), callback, external, + signature, 0, behavior); } inline void Environment::SetMethod(v8::Local that, @@ -605,7 +607,8 @@ inline void Environment::SetProtoMethod(v8::Local that, const char* name, v8::FunctionCallback callback) { v8::Local signature = v8::Signature::New(isolate(), that); - v8::Local t = NewFunctionTemplate(callback, signature); + v8::Local t = + NewFunctionTemplate(callback, signature, v8::ConstructorBehavior::kThrow); // kInternalized strings are created in the old space. const v8::NewStringType type = v8::NewStringType::kInternalized; v8::Local name_string = diff --git a/src/env.cc b/src/env.cc index 1f47ea21af21b8..08d719a51011d1 100644 --- a/src/env.cc +++ b/src/env.cc @@ -28,44 +28,46 @@ IsolateData::IsolateData(Isolate* isolate, uv_loop_t* event_loop, MultiIsolatePlatform* platform, uint32_t* zero_fill_field) : - -// Create string and private symbol properties as internalized one byte strings. -// -// Internalized because it makes property lookups a little faster and because -// the string is created in the old space straight away. It's going to end up -// in the old space sooner or later anyway but now it doesn't go through -// v8::Eternal's new space handling first. -// -// One byte because our strings are ASCII and we can safely skip V8's UTF-8 -// decoding step. It's a one-time cost, but why pay it when you don't have to? -#define V(PropertyName, StringValue) \ - PropertyName ## _( \ - isolate, \ - Private::New( \ - isolate, \ - String::NewFromOneByte( \ - isolate, \ - reinterpret_cast(StringValue), \ - v8::NewStringType::kInternalized, \ - sizeof(StringValue) - 1).ToLocalChecked())), - PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V) -#undef V -#define V(PropertyName, StringValue) \ - PropertyName ## _( \ - isolate, \ - String::NewFromOneByte( \ - isolate, \ - reinterpret_cast(StringValue), \ - v8::NewStringType::kInternalized, \ - sizeof(StringValue) - 1).ToLocalChecked()), - PER_ISOLATE_STRING_PROPERTIES(V) -#undef V isolate_(isolate), event_loop_(event_loop), zero_fill_field_(zero_fill_field), platform_(platform) { if (platform_ != nullptr) platform_->RegisterIsolate(this, event_loop); + + // Create string and private symbol properties as internalized one byte + // strings after the platform is properly initialized. + // + // Internalized because it makes property lookups a little faster and + // because the string is created in the old space straight away. It's going + // to end up in the old space sooner or later anyway but now it doesn't go + // through v8::Eternal's new space handling first. + // + // One byte because our strings are ASCII and we can safely skip V8's UTF-8 + // decoding step. + +#define V(PropertyName, StringValue) \ + PropertyName ## _.Set( \ + isolate, \ + Private::New( \ + isolate, \ + String::NewFromOneByte( \ + isolate, \ + reinterpret_cast(StringValue), \ + v8::NewStringType::kInternalized, \ + sizeof(StringValue) - 1).ToLocalChecked())); + PER_ISOLATE_PRIVATE_SYMBOL_PROPERTIES(V) +#undef V +#define V(PropertyName, StringValue) \ + PropertyName ## _.Set( \ + isolate, \ + String::NewFromOneByte( \ + isolate, \ + reinterpret_cast(StringValue), \ + v8::NewStringType::kInternalized, \ + sizeof(StringValue) - 1).ToLocalChecked()); + PER_ISOLATE_STRING_PROPERTIES(V) +#undef V } IsolateData::~IsolateData() { diff --git a/src/env.h b/src/env.h index af4470ad8632fe..c0d79883d0ff1c 100644 --- a/src/env.h +++ b/src/env.h @@ -643,8 +643,8 @@ class Environment { inline bool http_parser_buffer_in_use() const; inline void set_http_parser_buffer_in_use(bool in_use); - inline http2::http2_state* http2_state() const; - inline void set_http2_state(std::unique_ptr state); + inline http2::Http2State* http2_state() const; + inline void set_http2_state(std::unique_ptr state); inline AliasedBuffer* fs_stats_field_array(); @@ -687,7 +687,9 @@ class Environment { inline v8::Local NewFunctionTemplate(v8::FunctionCallback callback, v8::Local signature = - v8::Local()); + v8::Local(), + v8::ConstructorBehavior behavior = + v8::ConstructorBehavior::kAllow); // Convenience methods for NewFunctionTemplate(). inline void SetMethod(v8::Local that, @@ -829,7 +831,7 @@ class Environment { char* http_parser_buffer_; bool http_parser_buffer_in_use_ = false; - std::unique_ptr http2_state_; + std::unique_ptr http2_state_; AliasedBuffer fs_stats_field_array_; diff --git a/src/fs_event_wrap.cc b/src/fs_event_wrap.cc index 1e7505d6d3219a..ed74f36719db79 100644 --- a/src/fs_event_wrap.cc +++ b/src/fs_event_wrap.cc @@ -131,7 +131,7 @@ void FSEventWrap::New(const FunctionCallbackInfo& args) { void FSEventWrap::Start(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); - FSEventWrap* wrap = Unwrap(args.Holder()); + FSEventWrap* wrap = Unwrap(args.This()); CHECK_NE(wrap, nullptr); CHECK(!wrap->initialized_); diff --git a/src/handle_wrap.cc b/src/handle_wrap.cc index a3b0209eb3121f..49bf0c55bea0a1 100644 --- a/src/handle_wrap.cc +++ b/src/handle_wrap.cc @@ -93,7 +93,6 @@ HandleWrap::HandleWrap(Environment* env, handle_(handle) { handle_->data = this; HandleScope scope(env->isolate()); - Wrap(object, this); env->handle_wrap_queue()->PushBack(this); } @@ -114,7 +113,6 @@ void HandleWrap::OnClose(uv_handle_t* handle) { if (have_close_callback) wrap->MakeCallback(env->onclose_string(), 0, nullptr); - ClearWrap(wrap->object()); delete wrap; } diff --git a/src/inspector_agent.cc b/src/inspector_agent.cc index e143d316d2e6fa..4e0c04a7b95527 100644 --- a/src/inspector_agent.cc +++ b/src/inspector_agent.cc @@ -189,9 +189,9 @@ const int CONTEXT_GROUP_ID = 1; class ChannelImpl final : public v8_inspector::V8Inspector::Channel { public: - explicit ChannelImpl(V8Inspector* inspector, - InspectorSessionDelegate* delegate) - : delegate_(delegate) { + explicit ChannelImpl(const std::unique_ptr& inspector, + std::unique_ptr delegate) + : delegate_(std::move(delegate)) { session_ = inspector->connect(1, this, StringView()); } @@ -201,19 +201,11 @@ class ChannelImpl final : public v8_inspector::V8Inspector::Channel { session_->dispatchProtocolMessage(message); } - bool waitForFrontendMessage() { - return delegate_->WaitForFrontendMessageWhilePaused(); - } - void schedulePauseOnNextStatement(const std::string& reason) { std::unique_ptr buffer = Utf8ToStringView(reason); session_->schedulePauseOnNextStatement(buffer->string(), buffer->string()); } - InspectorSessionDelegate* delegate() { - return delegate_; - } - private: void sendResponse( int callId, @@ -232,7 +224,7 @@ class ChannelImpl final : public v8_inspector::V8Inspector::Channel { delegate_->SendMessageToFrontend(message); } - InspectorSessionDelegate* const delegate_; + std::unique_ptr delegate_; std::unique_ptr session_; }; @@ -300,8 +292,7 @@ class InspectorTimerHandle { class NodeInspectorClient : public V8InspectorClient { public: NodeInspectorClient(node::Environment* env, node::NodePlatform* platform) - : env_(env), platform_(platform), terminated_(false), - running_nested_loop_(false) { + : env_(env), platform_(platform) { client_ = V8Inspector::create(env->isolate(), this); // TODO(bnoordhuis) Make name configurable from src/node.cc. ContextInfo info(GetHumanReadableProcessName()); @@ -310,18 +301,28 @@ class NodeInspectorClient : public V8InspectorClient { } void runMessageLoopOnPause(int context_group_id) override { - CHECK_NE(channel_, nullptr); + runMessageLoop(false); + } + + void runMessageLoop(bool ignore_terminated) { if (running_nested_loop_) return; terminated_ = false; running_nested_loop_ = true; - while (!terminated_ && channel_->waitForFrontendMessage()) { - platform_->FlushForegroundTasks(env_->isolate()); + while ((ignore_terminated || !terminated_) && waitForFrontendEvent()) { + while (platform_->FlushForegroundTasks(env_->isolate())) {} } terminated_ = false; running_nested_loop_ = false; } + bool waitForFrontendEvent() { + InspectorIo* io = env_->inspector_agent()->io(); + if (io == nullptr) + return false; + return io->WaitForFrontendEvent(); + } + double currentTimeMS() override { return uv_hrtime() * 1.0 / NANOS_PER_MSEC; } @@ -363,20 +364,23 @@ class NodeInspectorClient : public V8InspectorClient { terminated_ = true; } - void connectFrontend(InspectorSessionDelegate* delegate) { - CHECK_EQ(channel_, nullptr); - channel_ = std::unique_ptr( - new ChannelImpl(client_.get(), delegate)); + int connectFrontend(std::unique_ptr delegate) { + events_dispatched_ = true; + int session_id = next_session_id_++; + // TODO(addaleax): Revert back to using make_unique once we get issues + // with CI resolved (i.e. revert the patch that added this comment). + channels_[session_id].reset(new ChannelImpl(client_, std::move(delegate))); + return session_id; } - void disconnectFrontend() { - quitMessageLoopOnPause(); - channel_.reset(); + void disconnectFrontend(int session_id) { + events_dispatched_ = true; + channels_.erase(session_id); } - void dispatchMessageFromFrontend(const StringView& message) { - CHECK_NE(channel_, nullptr); - channel_->dispatchProtocolMessage(message); + void dispatchMessageFromFrontend(int session_id, const StringView& message) { + events_dispatched_ = true; + channels_[session_id]->dispatchProtocolMessage(message); } Local ensureDefaultContextInGroup(int contextGroupId) override { @@ -426,10 +430,6 @@ class NodeInspectorClient : public V8InspectorClient { script_id); } - ChannelImpl* channel() { - return channel_.get(); - } - void startRepeatingTimer(double interval_s, TimerCallback callback, void* data) override { @@ -464,20 +464,31 @@ class NodeInspectorClient : public V8InspectorClient { client_->allAsyncTasksCanceled(); } + void schedulePauseOnNextStatement(const std::string& reason) { + for (const auto& id_channel : channels_) { + id_channel.second->schedulePauseOnNextStatement(reason); + } + } + + bool hasConnectedSessions() { + return !channels_.empty(); + } + private: node::Environment* env_; node::NodePlatform* platform_; - bool terminated_; - bool running_nested_loop_; + bool terminated_ = false; + bool running_nested_loop_ = false; std::unique_ptr client_; - std::unique_ptr channel_; + std::unordered_map> channels_; std::unordered_map timers_; + int next_session_id_ = 1; + bool events_dispatched_ = false; }; Agent::Agent(Environment* env) : parent_env_(env), client_(nullptr), platform_(nullptr), - enabled_(false), pending_enable_async_hook_(false), pending_disable_async_hook_(false) {} @@ -491,7 +502,7 @@ bool Agent::Start(node::NodePlatform* platform, const char* path, path_ = path == nullptr ? "" : path; debug_options_ = options; client_ = - std::unique_ptr( + std::shared_ptr( new NodeInspectorClient(parent_env_, platform)); platform_ = platform; CHECK_EQ(0, uv_async_init(uv_default_loop(), @@ -515,7 +526,6 @@ bool Agent::StartIoThread(bool wait_for_connect) { CHECK_NE(client_, nullptr); - enabled_ = true; io_ = std::unique_ptr( new InspectorIo(parent_env_, platform_, path_, debug_options_, wait_for_connect)); @@ -554,13 +564,14 @@ void Agent::Stop() { if (io_ != nullptr) { io_->Stop(); io_.reset(); - enabled_ = false; } } -void Agent::Connect(InspectorSessionDelegate* delegate) { - enabled_ = true; - client_->connectFrontend(delegate); +std::unique_ptr Agent::Connect( + std::unique_ptr delegate) { + int session_id = client_->connectFrontend(std::move(delegate)); + return std::unique_ptr( + new InspectorSession(session_id, client_)); } void Agent::WaitForDisconnect() { @@ -568,6 +579,11 @@ void Agent::WaitForDisconnect() { client_->contextDestroyed(parent_env_->context()); if (io_ != nullptr) { io_->WaitForDisconnect(); + // There is a bug in V8 Inspector (https://crbug.com/834056) that + // calls V8InspectorClient::quitMessageLoopOnPause when a session + // disconnects. We are using this flag to ignore those calls so the message + // loop is spinning as long as there's a reason to expect inspector messages + client_->runMessageLoop(true); } } @@ -578,33 +594,8 @@ void Agent::FatalException(Local error, Local message) { WaitForDisconnect(); } -void Agent::Dispatch(const StringView& message) { - CHECK_NE(client_, nullptr); - client_->dispatchMessageFromFrontend(message); -} - -void Agent::Disconnect() { - CHECK_NE(client_, nullptr); - client_->disconnectFrontend(); -} - -void Agent::RunMessageLoop() { - CHECK_NE(client_, nullptr); - client_->runMessageLoopOnPause(CONTEXT_GROUP_ID); -} - -InspectorSessionDelegate* Agent::delegate() { - CHECK_NE(client_, nullptr); - ChannelImpl* channel = client_->channel(); - if (channel == nullptr) - return nullptr; - return channel->delegate(); -} - void Agent::PauseOnNextJavascriptStatement(const std::string& reason) { - ChannelImpl* channel = client_->channel(); - if (channel != nullptr) - channel->schedulePauseOnNextStatement(reason); + client_->schedulePauseOnNextStatement(reason); } void Agent::RegisterAsyncHook(Isolate* isolate, @@ -699,5 +690,20 @@ bool Agent::IsWaitingForConnect() { return debug_options_.wait_for_connect(); } +bool Agent::HasConnectedSessions() { + return client_->hasConnectedSessions(); +} + +InspectorSession::InspectorSession(int session_id, + std::shared_ptr client) + : session_id_(session_id), client_(client) {} + +InspectorSession::~InspectorSession() { + client_->disconnectFrontend(session_id_); +} + +void InspectorSession::Dispatch(const StringView& message) { + client_->dispatchMessageFromFrontend(session_id_, message); +} } // namespace inspector } // namespace node diff --git a/src/inspector_agent.h b/src/inspector_agent.h index 56fb407930fac5..64e4202ee88e13 100644 --- a/src/inspector_agent.h +++ b/src/inspector_agent.h @@ -23,18 +23,26 @@ class Environment; struct ContextInfo; namespace inspector { +class InspectorIo; +class NodeInspectorClient; + +class InspectorSession { + public: + InspectorSession(int session_id, std::shared_ptr client); + ~InspectorSession(); + void Dispatch(const v8_inspector::StringView& message); + private: + int session_id_; + std::shared_ptr client_; +}; class InspectorSessionDelegate { public: virtual ~InspectorSessionDelegate() = default; - virtual bool WaitForFrontendMessageWhilePaused() = 0; virtual void SendMessageToFrontend(const v8_inspector::StringView& message) = 0; }; -class InspectorIo; -class NodeInspectorClient; - class Agent { public: explicit Agent(node::Environment* env); @@ -66,19 +74,19 @@ class Agent { void RegisterAsyncHook(v8::Isolate* isolate, v8::Local enable_function, v8::Local disable_function); + void EnableAsyncHook(); + void DisableAsyncHook(); - // These methods are called by the WS protocol and JS binding to create - // inspector sessions. The inspector responds by using the delegate to send - // messages back. - void Connect(InspectorSessionDelegate* delegate); - void Disconnect(); - void Dispatch(const v8_inspector::StringView& message); - InspectorSessionDelegate* delegate(); + // Called by the WS protocol and JS binding to create inspector sessions. + // The inspector responds by using the delegate to send messages back. + std::unique_ptr Connect( + std::unique_ptr delegate); - void RunMessageLoop(); - bool enabled() { return enabled_; } void PauseOnNextJavascriptStatement(const std::string& reason); + // Returns true as long as there is at least one connected session. + bool HasConnectedSessions(); + InspectorIo* io() { return io_.get(); } @@ -92,18 +100,14 @@ class Agent { DebugOptions& options() { return debug_options_; } void ContextCreated(v8::Local context, const ContextInfo& info); - void EnableAsyncHook(); - void DisableAsyncHook(); - private: void ToggleAsyncHook(v8::Isolate* isolate, const Persistent& fn); node::Environment* parent_env_; - std::unique_ptr client_; + std::shared_ptr client_; std::unique_ptr io_; v8::Platform* platform_; - bool enabled_; std::string path_; DebugOptions debug_options_; diff --git a/src/inspector_io.cc b/src/inspector_io.cc index 01ddc296b08693..38d88d7ab890c9 100644 --- a/src/inspector_io.cc +++ b/src/inspector_io.cc @@ -122,11 +122,11 @@ std::unique_ptr Utf8ToStringView(const std::string& message) { class IoSessionDelegate : public InspectorSessionDelegate { public: - explicit IoSessionDelegate(InspectorIo* io) : io_(io) { } - bool WaitForFrontendMessageWhilePaused() override; + explicit IoSessionDelegate(InspectorIo* io, int id) : io_(io), id_(id) { } void SendMessageToFrontend(const v8_inspector::StringView& message) override; private: InspectorIo* io_; + int id_; }; // Passed to InspectorSocketServer to handle WS inspector protocol events, @@ -190,8 +190,7 @@ InspectorIo::InspectorIo(Environment* env, v8::Platform* platform, : options_(options), thread_(), delegate_(nullptr), state_(State::kNew), parent_env_(env), thread_req_(), platform_(platform), - dispatching_messages_(false), session_id_(0), - script_name_(path), + dispatching_messages_(false), script_name_(path), wait_for_connect_(wait_for_connect), port_(-1) { main_thread_req_ = new AsyncAndAgent({uv_async_t(), env->inspector_agent()}); CHECK_EQ(0, uv_async_init(env->event_loop(), &main_thread_req_->first, @@ -222,7 +221,7 @@ bool InspectorIo::Start() { } void InspectorIo::Stop() { - CHECK(state_ == State::kAccepting || state_ == State::kConnected); + CHECK(state_ == State::kAccepting || !sessions_.empty()); Write(TransportAction::kKill, 0, StringView()); int err = uv_thread_join(&thread_); CHECK_EQ(err, 0); @@ -237,12 +236,11 @@ bool InspectorIo::IsStarted() { void InspectorIo::WaitForDisconnect() { if (state_ == State::kAccepting) state_ = State::kDone; - if (state_ == State::kConnected) { + if (!sessions_.empty()) { state_ = State::kShutDown; Write(TransportAction::kStop, 0, StringView()); fprintf(stderr, "Waiting for the debugger to disconnect...\n"); fflush(stderr); - parent_env_->inspector_agent()->RunMessageLoop(); } } @@ -348,45 +346,23 @@ void InspectorIo::PostIncomingMessage(InspectorAction action, int session_id, isolate->RequestInterrupt(InterruptCallback, agent); CHECK_EQ(0, uv_async_send(&main_thread_req_->first)); } - NotifyMessageReceived(); + Mutex::ScopedLock scoped_lock(state_lock_); + incoming_message_cond_.Broadcast(scoped_lock); } std::vector InspectorIo::GetTargetIds() const { return delegate_ ? delegate_->GetTargetIds() : std::vector(); } -void InspectorIo::WaitForFrontendMessageWhilePaused() { - dispatching_messages_ = false; - Mutex::ScopedLock scoped_lock(state_lock_); - if (incoming_message_queue_.empty()) - incoming_message_cond_.Wait(scoped_lock); -} - -void InspectorIo::NotifyMessageReceived() { - Mutex::ScopedLock scoped_lock(state_lock_); - incoming_message_cond_.Broadcast(scoped_lock); -} - TransportAction InspectorIo::Attach(int session_id) { Agent* agent = parent_env_->inspector_agent(); - if (agent->delegate() != nullptr) - return TransportAction::kDeclineSession; - - CHECK_EQ(session_delegate_, nullptr); - session_id_ = session_id; - state_ = State::kConnected; fprintf(stderr, "Debugger attached.\n"); - session_delegate_ = std::unique_ptr( - new IoSessionDelegate(this)); - agent->Connect(session_delegate_.get()); + sessions_[session_id] = agent->Connect(std::unique_ptr( + new IoSessionDelegate(this, session_id))); return TransportAction::kAcceptSession; } void InspectorIo::DispatchMessages() { - // This function can be reentered if there was an incoming message while - // V8 was processing another inspector request (e.g. if the user is - // evaluating a long-running JS code snippet). This can happen only at - // specific points (e.g. the lines that call inspector_ methods) if (dispatching_messages_) return; dispatching_messages_ = true; @@ -409,17 +385,20 @@ void InspectorIo::DispatchMessages() { Attach(id); break; case InspectorAction::kEndSession: - CHECK_NE(session_delegate_, nullptr); + sessions_.erase(id); + if (!sessions_.empty()) + continue; if (state_ == State::kShutDown) { state_ = State::kDone; } else { state_ = State::kAccepting; } - parent_env_->inspector_agent()->Disconnect(); - session_delegate_.reset(); break; case InspectorAction::kSendMessage: - parent_env_->inspector_agent()->Dispatch(message); + auto session = sessions_.find(id); + if (session != sessions_.end() && session->second) { + session->second->Dispatch(message); + } break; } } @@ -445,6 +424,20 @@ void InspectorIo::Write(TransportAction action, int session_id, CHECK_EQ(0, err); } +bool InspectorIo::WaitForFrontendEvent() { + // We allow DispatchMessages reentry as we enter the pause. This is important + // to support debugging the code invoked by an inspector call, such + // as Runtime.evaluate + dispatching_messages_ = false; + Mutex::ScopedLock scoped_lock(state_lock_); + if (sessions_.empty()) + return false; + if (dispatching_message_queue_.empty() && incoming_message_queue_.empty()) { + incoming_message_cond_.Wait(scoped_lock); + } + return true; +} + InspectorIoDelegate::InspectorIoDelegate(InspectorIo* io, const std::string& script_path, const std::string& script_name, @@ -502,14 +495,9 @@ std::string InspectorIoDelegate::GetTargetUrl(const std::string& id) { return "file://" + script_path_; } -bool IoSessionDelegate::WaitForFrontendMessageWhilePaused() { - io_->WaitForFrontendMessageWhilePaused(); - return true; -} - void IoSessionDelegate::SendMessageToFrontend( const v8_inspector::StringView& message) { - io_->Write(TransportAction::kSendMessage, io_->session_id_, message); + io_->Write(TransportAction::kSendMessage, id_, message); } } // namespace inspector diff --git a/src/inspector_io.h b/src/inspector_io.h index 79ccc6095ffec3..276c78056cb0a1 100644 --- a/src/inspector_io.h +++ b/src/inspector_io.h @@ -7,6 +7,7 @@ #include "uv.h" #include +#include #include #include @@ -76,6 +77,7 @@ class InspectorIo { void ServerDone() { uv_close(reinterpret_cast(&thread_req_), nullptr); } + bool WaitForFrontendEvent(); int port() const { return port_; } std::string host() const { return options_.host_name(); } @@ -89,7 +91,6 @@ class InspectorIo { enum class State { kNew, kAccepting, - kConnected, kDone, kError, kShutDown @@ -107,7 +108,6 @@ class InspectorIo { // messages from outgoing_message_queue to the InspectorSockerServer template static void IoThreadAsyncCb(uv_async_t* async); - void SetConnected(bool connected); void DispatchMessages(); // Write action to outgoing_message_queue, and wake the thread void Write(TransportAction action, int session_id, @@ -122,10 +122,6 @@ class InspectorIo { template void SwapBehindLock(MessageQueue* vector1, MessageQueue* vector2); - // Wait on incoming_message_cond_ - void WaitForFrontendMessageWhilePaused(); - // Broadcast incoming_message_cond_ - void NotifyMessageReceived(); // Attach session to an inspector. Either kAcceptSession or kDeclineSession TransportAction Attach(int session_id); @@ -147,7 +143,6 @@ class InspectorIo { // Note that this will live while the async is being closed - likely, past // the parent object lifespan std::pair* main_thread_req_; - std::unique_ptr session_delegate_; v8::Platform* platform_; // Message queues @@ -155,15 +150,17 @@ class InspectorIo { Mutex state_lock_; // Locked before mutating either queue. MessageQueue incoming_message_queue_; MessageQueue outgoing_message_queue_; + // This queue is to maintain the order of the messages for the cases + // when we reenter the DispatchMessages function. MessageQueue dispatching_message_queue_; bool dispatching_messages_; - int session_id_; std::string script_name_; std::string script_path_; const bool wait_for_connect_; int port_; + std::unordered_map> sessions_; friend class DispatchMessagesTask; friend class IoSessionDelegate; diff --git a/src/inspector_js_api.cc b/src/inspector_js_api.cc index 9a380bb2df2169..ae353defe8079d 100644 --- a/src/inspector_js_api.cc +++ b/src/inspector_js_api.cc @@ -42,10 +42,6 @@ class JSBindingsConnection : public AsyncWrap { connection_(connection) { } - bool WaitForFrontendMessageWhilePaused() override { - return false; - } - void SendMessageToFrontend(const v8_inspector::StringView& message) override { Isolate* isolate = env_->isolate(); @@ -58,12 +54,6 @@ class JSBindingsConnection : public AsyncWrap { connection_->OnMessage(argument); } - void Disconnect() { - Agent* agent = env_->inspector_agent(); - if (agent->delegate() == this) - agent->Disconnect(); - } - private: Environment* env_; JSBindingsConnection* connection_; @@ -73,31 +63,16 @@ class JSBindingsConnection : public AsyncWrap { Local wrap, Local callback) : AsyncWrap(env, wrap, PROVIDER_INSPECTORJSBINDING), - delegate_(env, this), callback_(env->isolate(), callback) { - Wrap(wrap, this); - Agent* inspector = env->inspector_agent(); - if (inspector->delegate() != nullptr) { - // This signals JS code that it has to throw an error. - Local session_attached = - FIXED_ONE_BYTE_STRING(env->isolate(), "sessionAttached"); - wrap->Set(env->context(), session_attached, - Boolean::New(env->isolate(), true)).ToChecked(); - return; - } - inspector->Connect(&delegate_); + session_ = inspector->Connect(std::unique_ptr( + new JSBindingsSessionDelegate(env, this))); } void OnMessage(Local value) { MakeCallback(callback_.Get(env()->isolate()), 1, &value); } - void CheckIsCurrent() { - Agent* inspector = env()->inspector_agent(); - CHECK_EQ(&delegate_, inspector->delegate()); - } - static void New(const FunctionCallbackInfo& info) { Environment* env = Environment::GetCurrent(info); CHECK(info[0]->IsFunction()); @@ -106,10 +81,7 @@ class JSBindingsConnection : public AsyncWrap { } void Disconnect() { - delegate_.Disconnect(); - if (!persistent().IsEmpty()) { - ClearWrap(object()); - } + session_.reset(); delete this; } @@ -125,18 +97,23 @@ class JSBindingsConnection : public AsyncWrap { ASSIGN_OR_RETURN_UNWRAP(&session, info.Holder()); CHECK(info[0]->IsString()); - session->CheckIsCurrent(); - Agent* inspector = env->inspector_agent(); - inspector->Dispatch(ToProtocolString(env->isolate(), info[0])->string()); + if (session->session_) { + session->session_->Dispatch( + ToProtocolString(env->isolate(), info[0])->string()); + } } size_t self_size() const override { return sizeof(*this); } private: - JSBindingsSessionDelegate delegate_; + std::unique_ptr session_; Persistent callback_; }; +static bool InspectorEnabled(Environment* env) { + Agent* agent = env->inspector_agent(); + return agent->io() != nullptr || agent->HasConnectedSessions(); +} void AddCommandLineAPI(const FunctionCallbackInfo& info) { auto env = Environment::GetCurrent(info); @@ -178,7 +155,7 @@ void InspectorConsoleCall(const FunctionCallbackInfo& info) { call_args.push_back(info[i]); } Environment* env = Environment::GetCurrent(isolate); - if (env->inspector_agent()->enabled()) { + if (InspectorEnabled(env)) { Local inspector_method = info[0]; CHECK(inspector_method->IsFunction()); Local config_value = info[2]; @@ -256,7 +233,7 @@ static void RegisterAsyncHookWrapper(const FunctionCallbackInfo& args) { void IsEnabled(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); - args.GetReturnValue().Set(env->inspector_agent()->enabled()); + args.GetReturnValue().Set(InspectorEnabled(env)); } void Open(const FunctionCallbackInfo& args) { diff --git a/src/inspector_socket_server.cc b/src/inspector_socket_server.cc index 3725c19e93fb86..e890f66a38b53f 100644 --- a/src/inspector_socket_server.cc +++ b/src/inspector_socket_server.cc @@ -373,27 +373,17 @@ void InspectorSocketServer::SendListResponse(InspectorSocket* socket, target_map["url"] = delegate_->GetTargetUrl(id); Escape(&target_map["url"]); - bool connected = false; - for (const auto& session : connected_sessions_) { - if (session.second.first == id) { - connected = true; - break; - } - } - if (!connected) { - std::string detected_host = host; - if (detected_host.empty()) { - detected_host = FormatHostPort(socket->GetHost(), - session->server_port()); - } - std::ostringstream frontend_url; - frontend_url << "chrome-devtools://devtools/bundled"; - frontend_url << "/inspector.html?experiments=true&v8only=true&ws="; - frontend_url << FormatAddress(detected_host, id, false); - target_map["devtoolsFrontendUrl"] += frontend_url.str(); - target_map["webSocketDebuggerUrl"] = - FormatAddress(detected_host, id, true); + std::string detected_host = host; + if (detected_host.empty()) { + detected_host = FormatHostPort(socket->GetHost(), + session->server_port()); } + std::ostringstream frontend_url; + frontend_url << "chrome-devtools://devtools/bundled"; + frontend_url << "/inspector.html?experiments=true&v8only=true&ws="; + frontend_url << FormatAddress(detected_host, id, false); + target_map["devtoolsFrontendUrl"] += frontend_url.str(); + target_map["webSocketDebuggerUrl"] = FormatAddress(detected_host, id, true); } SendHttpResponse(socket, MapsToString(response)); } @@ -587,7 +577,8 @@ int ServerSocket::Listen(InspectorSocketServer* inspector_server, CHECK_EQ(0, uv_tcp_init(loop, server)); int err = uv_tcp_bind(server, addr, 0); if (err == 0) { - err = uv_listen(reinterpret_cast(server), 1, + // 511 is the value used by a 'net' module by default + err = uv_listen(reinterpret_cast(server), 511, ServerSocket::SocketConnectedCallback); } if (err == 0) { diff --git a/src/js_stream.cc b/src/js_stream.cc index ed6c6ee738e568..2293d8cf203d07 100644 --- a/src/js_stream.cc +++ b/src/js_stream.cc @@ -24,12 +24,7 @@ using v8::Value; JSStream::JSStream(Environment* env, Local obj) : AsyncWrap(env, obj, AsyncWrap::PROVIDER_JSSTREAM), StreamBase(env) { - node::Wrap(obj, this); - MakeWeak(this); -} - - -JSStream::~JSStream() { + MakeWeak(); } diff --git a/src/js_stream.h b/src/js_stream.h index 338cbe545630f1..b47a91a653ba7e 100644 --- a/src/js_stream.h +++ b/src/js_stream.h @@ -16,8 +16,6 @@ class JSStream : public AsyncWrap, public StreamBase { v8::Local unused, v8::Local context); - ~JSStream(); - bool IsAlive() override; bool IsClosing() override; int ReadStart() override; diff --git a/src/module_wrap.cc b/src/module_wrap.cc index 9bcdb4dce75ff2..fcccbfe93cea32 100644 --- a/src/module_wrap.cc +++ b/src/module_wrap.cc @@ -158,7 +158,6 @@ void ModuleWrap::New(const FunctionCallbackInfo& args) { obj->context_.Reset(isolate, context); env->module_map.emplace(module->GetIdentityHash(), obj); - Wrap(that, obj); that->SetIntegrityLevel(context, IntegrityLevel::kFrozen); args.GetReturnValue().Set(that); diff --git a/src/node.cc b/src/node.cc index 90defba40ba95e..693457d3ed0aae 100644 --- a/src/node.cc +++ b/src/node.cc @@ -1973,7 +1973,7 @@ static void InitGroups(const FunctionCallbackInfo& args) { static void WaitForInspectorDisconnect(Environment* env) { #if HAVE_INSPECTOR - if (env->inspector_agent()->delegate() != nullptr) { + if (env->inspector_agent()->HasConnectedSessions()) { // Restore signal dispositions, the app is done and is no longer // capable of handling signals. #if defined(__POSIX__) && !defined(NODE_SHARED_MODE) @@ -2227,6 +2227,13 @@ inline InitializerCallback GetInitializerCallback(DLib* dlib) { return reinterpret_cast(dlib->GetSymbolAddress(name)); } +inline napi_addon_register_func GetNapiInitializerCallback(DLib* dlib) { + const char* name = + STRINGIFY(NAPI_MODULE_INITIALIZER_BASE) STRINGIFY(NAPI_MODULE_VERSION); + return + reinterpret_cast(dlib->GetSymbolAddress(name)); +} + // DLOpen is process.dlopen(module, filename, flags). // Used to load 'module.node' dynamically shared objects. // @@ -2283,6 +2290,8 @@ static void DLOpen(const FunctionCallbackInfo& args) { if (mp == nullptr) { if (auto callback = GetInitializerCallback(&dlib)) { callback(exports, module, context); + } else if (auto napi_callback = GetNapiInitializerCallback(&dlib)) { + napi_module_register_by_symbol(exports, module, context, napi_callback); } else { dlib.Close(); env->ThrowError("Module did not self-register."); @@ -2379,39 +2388,30 @@ void FatalException(Isolate* isolate, Local fatal_exception_function = process_object->Get(fatal_exception_string).As(); - int exit_code = 0; if (!fatal_exception_function->IsFunction()) { - // failed before the process._fatalException function was added! + // Failed before the process._fatalException function was added! // this is probably pretty bad. Nothing to do but report and exit. ReportException(env, error, message); - exit_code = 6; - } - - if (exit_code == 0) { + exit(6); + } else { TryCatch fatal_try_catch(isolate); // Do not call FatalException when _fatalException handler throws fatal_try_catch.SetVerbose(false); - // this will return true if the JS layer handled it, false otherwise + // This will return true if the JS layer handled it, false otherwise Local caught = fatal_exception_function->Call(process_object, 1, &error); if (fatal_try_catch.HasCaught()) { - // the fatal exception function threw, so we must exit + // The fatal exception function threw, so we must exit ReportException(env, fatal_try_catch); - exit_code = 7; - } - - if (exit_code == 0 && false == caught->BooleanValue()) { + exit(7); + } else if (caught->IsFalse()) { ReportException(env, error, message); - exit_code = 1; + exit(1); } } - - if (exit_code) { - exit(exit_code); - } } @@ -4439,6 +4439,11 @@ void FreeEnvironment(Environment* env) { } +MultiIsolatePlatform* GetMainThreadMultiIsolatePlatform() { + return v8_platform.Platform(); +} + + MultiIsolatePlatform* CreatePlatform( int thread_pool_size, v8::TracingController* tracing_controller) { diff --git a/src/node.h b/src/node.h index ab5d1c120fa007..5a491c1abf5457 100644 --- a/src/node.h +++ b/src/node.h @@ -251,6 +251,11 @@ NODE_EXTERN Environment* CreateEnvironment(IsolateData* isolate_data, NODE_EXTERN void LoadEnvironment(Environment* env); NODE_EXTERN void FreeEnvironment(Environment* env); +// This returns the MultiIsolatePlatform used in the main thread of Node.js. +// If NODE_USE_V8_PLATFORM haven't been defined when Node.js was built, +// it returns nullptr. +NODE_EXTERN MultiIsolatePlatform* GetMainThreadMultiIsolatePlatform(); + NODE_EXTERN MultiIsolatePlatform* CreatePlatform( int thread_pool_size, v8::TracingController* tracing_controller); diff --git a/src/node.stp b/src/node.stp index 3369968c205146..ebc40d574fc2be 100644 --- a/src/node.stp +++ b/src/node.stp @@ -125,7 +125,7 @@ probe node_gc_start = process("node").mark("gc__start") flags); } -probe node_gc_stop = process("node").mark("gc__stop") +probe node_gc_stop = process("node").mark("gc__done") { scavenge = 1 << 0; compact = 1 << 1; diff --git a/src/node_api.cc b/src/node_api.cc index ea7ddba77dc2e2..4878cf241edc04 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -858,16 +858,23 @@ void napi_module_register_cb(v8::Local exports, v8::Local module, v8::Local context, void* priv) { - napi_module* mod = static_cast(priv); + napi_module_register_by_symbol(exports, module, context, + static_cast(priv)->nm_register_func); +} + +} // end of anonymous namespace +void napi_module_register_by_symbol(v8::Local exports, + v8::Local module, + v8::Local context, + napi_addon_register_func init) { // Create a new napi_env for this module or reference one if a pre-existing // one is found. napi_env env = v8impl::GetEnv(context); napi_value _exports; NAPI_CALL_INTO_MODULE_THROW(env, - _exports = mod->nm_register_func(env, - v8impl::JsValueFromV8LocalValue(exports))); + _exports = init(env, v8impl::JsValueFromV8LocalValue(exports))); // If register function returned a non-null exports object different from // the exports object we passed it, set that as the "exports" property of @@ -879,8 +886,6 @@ void napi_module_register_cb(v8::Local exports, } } -} // end of anonymous namespace - // Registers a NAPI module. void napi_module_register(napi_module* mod) { node::node_module* nm = new node::node_module { diff --git a/src/node_api.h b/src/node_api.h index aaf002b7584449..b010d32db7b086 100644 --- a/src/node_api.h +++ b/src/node_api.h @@ -90,9 +90,28 @@ typedef struct { } \ EXTERN_C_END -#define NAPI_MODULE(modname, regfunc) \ +#define NAPI_MODULE(modname, regfunc) \ NAPI_MODULE_X(modname, regfunc, NULL, 0) // NOLINT (readability/null_usage) +#define NAPI_MODULE_INITIALIZER_BASE napi_register_module_v + +#define NAPI_MODULE_INITIALIZER_X(base, version) \ + NAPI_MODULE_INITIALIZER_X_HELPER(base, version) +#define NAPI_MODULE_INITIALIZER_X_HELPER(base, version) base##version + +#define NAPI_MODULE_INITIALIZER \ + NAPI_MODULE_INITIALIZER_X(NAPI_MODULE_INITIALIZER_BASE, \ + NAPI_MODULE_VERSION) + +#define NAPI_MODULE_INIT() \ + EXTERN_C_START \ + NAPI_MODULE_EXPORT napi_value \ + NAPI_MODULE_INITIALIZER(napi_env env, napi_value exports); \ + EXTERN_C_END \ + NAPI_MODULE(NODE_GYP_MODULE_NAME, NAPI_MODULE_INITIALIZER) \ + napi_value NAPI_MODULE_INITIALIZER(napi_env env, \ + napi_value exports) + #define NAPI_AUTO_LENGTH SIZE_MAX EXTERN_C_START diff --git a/src/node_contextify.cc b/src/node_contextify.cc index e07d5ebcd29d0d..6e7027a29ba8a0 100644 --- a/src/node_contextify.cc +++ b/src/node_contextify.cc @@ -120,7 +120,7 @@ Local ContextifyContext::CreateDataWrapper(Environment* env) { if (wrapper.IsEmpty()) return scope.Escape(Local::New(env->isolate(), Local())); - Wrap(wrapper, this); + wrapper->SetAlignedPointerInInternalField(0, this); return scope.Escape(wrapper); } @@ -290,12 +290,19 @@ ContextifyContext* ContextifyContext::ContextFromContextifiedSandbox( return nullptr; } +// static +template +ContextifyContext* ContextifyContext::Get(const PropertyCallbackInfo& args) { + Local data = args.Data(); + return static_cast( + data.As()->GetAlignedPointerFromInternalField(0)); +} + // static void ContextifyContext::PropertyGetterCallback( Local property, const PropertyCallbackInfo& args) { - ContextifyContext* ctx; - ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Data().As()); + ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing if (ctx->context_.IsEmpty()) @@ -324,8 +331,7 @@ void ContextifyContext::PropertySetterCallback( Local property, Local value, const PropertyCallbackInfo& args) { - ContextifyContext* ctx; - ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Data().As()); + ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing if (ctx->context_.IsEmpty()) @@ -385,8 +391,7 @@ void ContextifyContext::PropertySetterCallback( void ContextifyContext::PropertyDescriptorCallback( Local property, const PropertyCallbackInfo& args) { - ContextifyContext* ctx; - ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Data().As()); + ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing if (ctx->context_.IsEmpty()) @@ -408,8 +413,7 @@ void ContextifyContext::PropertyDefinerCallback( Local property, const PropertyDescriptor& desc, const PropertyCallbackInfo& args) { - ContextifyContext* ctx; - ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Data().As()); + ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing if (ctx->context_.IsEmpty()) @@ -471,8 +475,7 @@ void ContextifyContext::PropertyDefinerCallback( void ContextifyContext::PropertyDeleterCallback( Local property, const PropertyCallbackInfo& args) { - ContextifyContext* ctx; - ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Data().As()); + ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing if (ctx->context_.IsEmpty()) @@ -491,8 +494,7 @@ void ContextifyContext::PropertyDeleterCallback( // static void ContextifyContext::PropertyEnumeratorCallback( const PropertyCallbackInfo& args) { - ContextifyContext* ctx; - ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Data().As()); + ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing if (ctx->context_.IsEmpty()) @@ -505,8 +507,7 @@ void ContextifyContext::PropertyEnumeratorCallback( void ContextifyContext::IndexedPropertyGetterCallback( uint32_t index, const PropertyCallbackInfo& args) { - ContextifyContext* ctx; - ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Data().As()); + ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing if (ctx->context_.IsEmpty()) @@ -521,8 +522,7 @@ void ContextifyContext::IndexedPropertySetterCallback( uint32_t index, Local value, const PropertyCallbackInfo& args) { - ContextifyContext* ctx; - ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Data().As()); + ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing if (ctx->context_.IsEmpty()) @@ -536,8 +536,7 @@ void ContextifyContext::IndexedPropertySetterCallback( void ContextifyContext::IndexedPropertyDescriptorCallback( uint32_t index, const PropertyCallbackInfo& args) { - ContextifyContext* ctx; - ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Data().As()); + ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing if (ctx->context_.IsEmpty()) @@ -552,8 +551,7 @@ void ContextifyContext::IndexedPropertyDefinerCallback( uint32_t index, const PropertyDescriptor& desc, const PropertyCallbackInfo& args) { - ContextifyContext* ctx; - ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Data().As()); + ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing if (ctx->context_.IsEmpty()) @@ -567,8 +565,7 @@ void ContextifyContext::IndexedPropertyDefinerCallback( void ContextifyContext::IndexedPropertyDeleterCallback( uint32_t index, const PropertyCallbackInfo& args) { - ContextifyContext* ctx; - ASSIGN_OR_RETURN_UNWRAP(&ctx, args.Data().As()); + ContextifyContext* ctx = ContextifyContext::Get(args); // Still initializing if (ctx->context_.IsEmpty()) @@ -887,7 +884,7 @@ class ContextifyScript : public BaseObject { ContextifyScript(Environment* env, Local object) : BaseObject(env, object) { - MakeWeak(this); + MakeWeak(); } }; diff --git a/src/node_contextify.h b/src/node_contextify.h index 565b8ef856ea49..70ce091af3b58e 100644 --- a/src/node_contextify.h +++ b/src/node_contextify.h @@ -55,6 +55,9 @@ class ContextifyContext { context()->GetEmbedderData(ContextEmbedderIndex::kSandboxObject)); } + template + static ContextifyContext* Get(const v8::PropertyCallbackInfo& args); + private: static void MakeContext(const v8::FunctionCallbackInfo& args); static void IsContext(const v8::FunctionCallbackInfo& args); diff --git a/src/node_crypto.cc b/src/node_crypto.cc index 111227e665c000..d5f27994307696 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -338,19 +338,6 @@ void SecureContext::Initialize(Environment* env, Local target) { t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kTicketKeyIVIndex"), Integer::NewFromUnsigned(env->isolate(), kTicketKeyIVIndex)); - Local ctx_getter_templ = - FunctionTemplate::New(env->isolate(), - CtxGetter, - env->as_external(), - Signature::New(env->isolate(), t)); - - - t->PrototypeTemplate()->SetAccessorProperty( - FIXED_ONE_BYTE_STRING(env->isolate(), "_external"), - ctx_getter_templ, - Local(), - static_cast(ReadOnly | DontDelete)); - target->Set(secureContextString, t->GetFunction()); env->set_secure_context_constructor_template(t); } @@ -1350,14 +1337,6 @@ int SecureContext::TicketCompatibilityCallback(SSL* ssl, } -void SecureContext::CtxGetter(const FunctionCallbackInfo& info) { - SecureContext* sc; - ASSIGN_OR_RETURN_UNWRAP(&sc, info.This()); - Local ext = External::New(info.GetIsolate(), sc->ctx_); - info.GetReturnValue().Set(ext); -} - - template void SecureContext::GetCertificate(const FunctionCallbackInfo& args) { SecureContext* wrap; @@ -2117,7 +2096,8 @@ void SSLWrap::GetEphemeralKeyInfo( EVP_PKEY* key; if (SSL_get_server_tmp_key(w->ssl_, &key)) { - switch (EVP_PKEY_id(key)) { + int kid = EVP_PKEY_id(key); + switch (kid) { case EVP_PKEY_DH: info->Set(context, env->type_string(), FIXED_ONE_BYTE_STRING(env->isolate(), "DH")).FromJust(); @@ -2125,19 +2105,29 @@ void SSLWrap::GetEphemeralKeyInfo( Integer::New(env->isolate(), EVP_PKEY_bits(key))).FromJust(); break; case EVP_PKEY_EC: + // TODO(shigeki) Change this to EVP_PKEY_X25519 and add EVP_PKEY_X448 + // after upgrading to 1.1.1. + case NID_X25519: { - EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key); - int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec)); - EC_KEY_free(ec); + const char* curve_name; + if (kid == EVP_PKEY_EC) { + EC_KEY* ec = EVP_PKEY_get1_EC_KEY(key); + int nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec)); + curve_name = OBJ_nid2sn(nid); + EC_KEY_free(ec); + } else { + curve_name = OBJ_nid2sn(kid); + } info->Set(context, env->type_string(), FIXED_ONE_BYTE_STRING(env->isolate(), "ECDH")).FromJust(); info->Set(context, env->name_string(), OneByteString(args.GetIsolate(), - OBJ_nid2sn(nid))).FromJust(); + curve_name)).FromJust(); info->Set(context, env->size_string(), Integer::New(env->isolate(), EVP_PKEY_bits(key))).FromJust(); } + break; } EVP_PKEY_free(key); } @@ -2801,10 +2791,7 @@ bool CipherBase::InitAuthenticated(const char *cipher_type, int iv_len, int auth_tag_len) { CHECK(IsAuthenticatedMode()); - // TODO(tniessen) Use EVP_CTRL_AEAD_SET_IVLEN when migrating to OpenSSL 1.1.0 - static_assert(EVP_CTRL_CCM_SET_IVLEN == EVP_CTRL_GCM_SET_IVLEN, - "OpenSSL constants differ between GCM and CCM"); - if (!EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_GCM_SET_IVLEN, iv_len, nullptr)) { + if (!EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_AEAD_SET_IVLEN, iv_len, nullptr)) { env()->ThrowError("Invalid IV length"); return false; } @@ -3095,10 +3082,8 @@ bool CipherBase::Final(unsigned char** out, int *out_len) { // must be specified in advance. if (mode == EVP_CIPH_GCM_MODE) auth_tag_len_ = sizeof(auth_tag_); - // TOOD(tniessen) Use EVP_CTRL_AEAP_GET_TAG in OpenSSL 1.1.0 - static_assert(EVP_CTRL_CCM_GET_TAG == EVP_CTRL_GCM_GET_TAG, - "OpenSSL constants differ between GCM and CCM"); - CHECK_EQ(1, EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_GCM_GET_TAG, auth_tag_len_, + CHECK_EQ(1, EVP_CIPHER_CTX_ctrl(ctx_, EVP_CTRL_AEAD_GET_TAG, + auth_tag_len_, reinterpret_cast(auth_tag_))); } } @@ -4668,7 +4653,6 @@ class PBKDF2Request : public AsyncWrap { keylen_(keylen), key_(node::Malloc(keylen)), iter_(iter) { - Wrap(object, this); } ~PBKDF2Request() override { @@ -4683,8 +4667,6 @@ class PBKDF2Request : public AsyncWrap { free(key_); key_ = nullptr; keylen_ = 0; - - ClearWrap(object()); } uv_work_t* work_req() { @@ -4846,11 +4828,6 @@ class RandomBytesRequest : public AsyncWrap { size_(size), data_(data), free_mode_(free_mode) { - Wrap(object, this); - } - - ~RandomBytesRequest() override { - ClearWrap(object()); } uv_work_t* work_req() { @@ -5148,7 +5125,7 @@ void GetCurves(const FunctionCallbackInfo& args) { bool VerifySpkac(const char* data, unsigned int len) { - bool i = 0; + bool verify_result = false; EVP_PKEY* pkey = nullptr; NETSCAPE_SPKI* spki = nullptr; @@ -5160,7 +5137,7 @@ bool VerifySpkac(const char* data, unsigned int len) { if (pkey == nullptr) goto exit; - i = NETSCAPE_SPKI_verify(spki, pkey) > 0; + verify_result = NETSCAPE_SPKI_verify(spki, pkey) > 0; exit: if (pkey != nullptr) @@ -5169,23 +5146,23 @@ bool VerifySpkac(const char* data, unsigned int len) { if (spki != nullptr) NETSCAPE_SPKI_free(spki); - return i; + return verify_result; } void VerifySpkac(const FunctionCallbackInfo& args) { - bool i = false; + bool verify_result = false; size_t length = Buffer::Length(args[0]); if (length == 0) - return args.GetReturnValue().Set(i); + return args.GetReturnValue().Set(verify_result); char* data = Buffer::Data(args[0]); CHECK_NE(data, nullptr); - i = VerifySpkac(data, length); + verify_result = VerifySpkac(data, length); - args.GetReturnValue().Set(i); + args.GetReturnValue().Set(verify_result); } diff --git a/src/node_crypto.h b/src/node_crypto.h index 2f7c904ee9212d..b3b91b30396c4a 100644 --- a/src/node_crypto.h +++ b/src/node_crypto.h @@ -44,6 +44,8 @@ #endif // !OPENSSL_NO_ENGINE #include #include +// TODO(shigeki) Remove this after upgrading to 1.1.1 +#include #include #include #include @@ -148,7 +150,6 @@ class SecureContext : public BaseObject { const v8::FunctionCallbackInfo& args); static void EnableTicketKeyCallback( const v8::FunctionCallbackInfo& args); - static void CtxGetter(const v8::FunctionCallbackInfo& info); template static void GetCertificate(const v8::FunctionCallbackInfo& args); @@ -174,7 +175,7 @@ class SecureContext : public BaseObject { ctx_(nullptr), cert_(nullptr), issuer_(nullptr) { - MakeWeak(this); + MakeWeak(); env->isolate()->AdjustAmountOfExternalAllocatedMemory(kExternalSize); } @@ -400,7 +401,7 @@ class CipherBase : public BaseObject { auth_tag_set_(false), auth_tag_len_(0), pending_auth_failed_(false) { - MakeWeak(this); + MakeWeak(); } private: @@ -431,7 +432,7 @@ class Hmac : public BaseObject { Hmac(Environment* env, v8::Local wrap) : BaseObject(env, wrap), ctx_(nullptr) { - MakeWeak(this); + MakeWeak(); } private: @@ -456,7 +457,7 @@ class Hash : public BaseObject { : BaseObject(env, wrap), mdctx_(nullptr), finalized_(false) { - MakeWeak(this); + MakeWeak(); } private: @@ -511,7 +512,7 @@ class Sign : public SignBase { static void SignFinal(const v8::FunctionCallbackInfo& args); Sign(Environment* env, v8::Local wrap) : SignBase(env, wrap) { - MakeWeak(this); + MakeWeak(); } }; @@ -534,7 +535,7 @@ class Verify : public SignBase { static void VerifyFinal(const v8::FunctionCallbackInfo& args); Verify(Environment* env, v8::Local wrap) : SignBase(env, wrap) { - MakeWeak(this); + MakeWeak(); } }; @@ -602,7 +603,7 @@ class DiffieHellman : public BaseObject { initialised_(false), verifyError_(0), dh(nullptr) { - MakeWeak(this); + MakeWeak(); } private: @@ -638,7 +639,7 @@ class ECDH : public BaseObject { : BaseObject(env, wrap), key_(key), group_(EC_KEY_get0_group(key_)) { - MakeWeak(this); + MakeWeak(); CHECK_NE(group_, nullptr); } diff --git a/src/node_file.cc b/src/node_file.cc index 89c53afc5b197e..97b957eed66b31 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -99,7 +99,7 @@ FileHandle::FileHandle(Environment* env, int fd, Local obj) AsyncWrap::PROVIDER_FILEHANDLE), StreamBase(env), fd_(fd) { - MakeWeak(this); + MakeWeak(); v8::PropertyAttribute attr = static_cast(v8::ReadOnly | v8::DontDelete); object()->DefineOwnProperty(env->context(), diff --git a/src/node_file.h b/src/node_file.h index d6c8aa443c39f4..03e41097d5f12e 100644 --- a/src/node_file.h +++ b/src/node_file.h @@ -28,11 +28,6 @@ class FSReqBase : public ReqWrap { FSReqBase(Environment* env, Local req, AsyncWrap::ProviderType type) : ReqWrap(env, req, type) { - Wrap(object(), this); - } - - virtual ~FSReqBase() { - ClearWrap(object()); } void Init(const char* syscall, @@ -249,10 +244,10 @@ class FileHandle : public AsyncWrap, public StreamBase { env->fdclose_constructor_template() ->NewInstance(env->context()).ToLocalChecked(), AsyncWrap::PROVIDER_FILEHANDLECLOSEREQ) { - Wrap(object(), this); promise_.Reset(env->isolate(), promise); ref_.Reset(env->isolate(), ref); } + ~CloseReq() { uv_fs_req_cleanup(req()); promise_.Reset(); diff --git a/src/node_http2.cc b/src/node_http2.cc index 1c5c68f09471f3..94f774e2d3506d 100644 --- a/src/node_http2.cc +++ b/src/node_http2.cc @@ -110,7 +110,7 @@ Http2Options::Http2Options(Environment* env) { // a bit differently. For now, let's let nghttp2 take care of it. nghttp2_option_set_builtin_recv_extension_type(options_, NGHTTP2_ALTSVC); - AliasedBuffer& buffer = + AliasedBuffer& buffer = env->http2_state()->options_buffer; uint32_t flags = buffer[IDX_OPTIONS_FLAGS]; @@ -191,7 +191,7 @@ Http2Options::Http2Options(Environment* env) { } void Http2Session::Http2Settings::Init() { - AliasedBuffer& buffer = + AliasedBuffer& buffer = env()->http2_state()->settings_buffer; uint32_t flags = buffer[IDX_SETTINGS_COUNT]; @@ -244,11 +244,6 @@ Http2Session::Http2Settings::Http2Settings( Init(); } -Http2Session::Http2Settings::~Http2Settings() { - if (!object().IsEmpty()) - ClearWrap(object()); -} - // Generates a Buffer that contains the serialized payload of a SETTINGS // frame. This can be used, for instance, to create the Base64-encoded // content of an Http2-Settings header field. @@ -270,7 +265,7 @@ Local Http2Session::Http2Settings::Pack() { void Http2Session::Http2Settings::Update(Environment* env, Http2Session* session, get_setting fn) { - AliasedBuffer& buffer = + AliasedBuffer& buffer = env->http2_state()->settings_buffer; buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] = fn(**session, NGHTTP2_SETTINGS_HEADER_TABLE_SIZE); @@ -288,7 +283,7 @@ void Http2Session::Http2Settings::Update(Environment* env, // Initializes the shared TypedArray with the default settings values. void Http2Session::Http2Settings::RefreshDefaults(Environment* env) { - AliasedBuffer& buffer = + AliasedBuffer& buffer = env->http2_state()->settings_buffer; buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] = @@ -458,7 +453,7 @@ Http2Session::Http2Session(Environment* env, nghttp2_session_type type) : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_HTTP2SESSION), session_type_(type) { - MakeWeak(this); + MakeWeak(); statistics_.start_time = uv_hrtime(); // Capture the configuration options for this session @@ -505,7 +500,7 @@ Http2Session::~Http2Session() { } inline bool HasHttp2Observer(Environment* env) { - AliasedBuffer& observers = + AliasedBuffer& observers = env->performance_state()->observers; return observers[performance::NODE_PERFORMANCE_ENTRY_TYPE_HTTP2] != 0; } @@ -522,7 +517,7 @@ void Http2Stream::EmitStatistics() { if (!HasHttp2Observer(env)) return; HandleScope handle_scope(env->isolate()); - AliasedBuffer& buffer = + AliasedBuffer& buffer = env->http2_state()->stream_stats_buffer; buffer[IDX_STREAM_STATS_ID] = entry->id(); if (entry->first_byte() != 0) { @@ -561,7 +556,7 @@ void Http2Session::EmitStatistics() { if (!HasHttp2Observer(env)) return; HandleScope handle_scope(env->isolate()); - AliasedBuffer& buffer = + AliasedBuffer& buffer = env->http2_state()->session_stats_buffer; buffer[IDX_SESSION_STATS_TYPE] = entry->type(); buffer[IDX_SESSION_STATS_PINGRTT] = entry->ping_rtt() / 1e6; @@ -690,7 +685,7 @@ ssize_t Http2Session::OnCallbackPadding(size_t frameLen, Local context = env()->context(); Context::Scope context_scope(context); - AliasedBuffer& buffer = + AliasedBuffer& buffer = env()->http2_state()->padding_buffer; buffer[PADDING_BUF_FRAME_LENGTH] = frameLen; buffer[PADDING_BUF_MAX_PAYLOAD_LENGTH] = maxPayloadLen; @@ -1364,16 +1359,35 @@ void Http2Session::MaybeScheduleWrite() { // storage for data and metadata that was associated with these writes. void Http2Session::ClearOutgoing(int status) { CHECK_NE(flags_ & SESSION_STATE_SENDING, 0); - flags_ &= ~SESSION_STATE_SENDING; - for (const nghttp2_stream_write& wr : outgoing_buffers_) { - WriteWrap* wrap = wr.req_wrap; - if (wrap != nullptr) - wrap->Done(status); + if (outgoing_buffers_.size() > 0) { + outgoing_storage_.clear(); + + for (const nghttp2_stream_write& wr : outgoing_buffers_) { + WriteWrap* wrap = wr.req_wrap; + if (wrap != nullptr) + wrap->Done(status); + } + + outgoing_buffers_.clear(); } - outgoing_buffers_.clear(); - outgoing_storage_.clear(); + flags_ &= ~SESSION_STATE_SENDING; + + // Now that we've finished sending queued data, if there are any pending + // RstStreams we should try sending again and then flush them one by one. + if (pending_rst_streams_.size() > 0) { + std::vector current_pending_rst_streams; + pending_rst_streams_.swap(current_pending_rst_streams); + + SendPendingData(); + + for (int32_t stream_id : current_pending_rst_streams) { + Http2Stream* stream = FindStream(stream_id); + if (stream != nullptr) + stream->FlushRstStream(); + } + } } // Queue a given block of data for sending. This always creates a copy, @@ -1397,18 +1411,19 @@ void Http2Session::CopyDataIntoOutgoing(const uint8_t* src, size_t src_length) { // chunk out to the i/o socket to be sent. This is a particularly hot method // that will generally be called at least twice be event loop iteration. // This is a potential performance optimization target later. -void Http2Session::SendPendingData() { +// Returns non-zero value if a write is already in progress. +uint8_t Http2Session::SendPendingData() { DEBUG_HTTP2SESSION(this, "sending pending data"); // Do not attempt to send data on the socket if the destroying flag has // been set. That means everything is shutting down and the socket // will not be usable. if (IsDestroyed()) - return; + return 0; flags_ &= ~SESSION_STATE_WRITE_SCHEDULED; // SendPendingData should not be called recursively. if (flags_ & SESSION_STATE_SENDING) - return; + return 1; // This is cleared by ClearOutgoing(). flags_ |= SESSION_STATE_SENDING; @@ -1432,15 +1447,15 @@ void Http2Session::SendPendingData() { // does take care of things like closing the individual streams after // a socket has been torn down, so we still need to call it. ClearOutgoing(UV_ECANCELED); - return; + return 0; } // Part Two: Pass Data to the underlying stream size_t count = outgoing_buffers_.size(); if (count == 0) { - flags_ &= ~SESSION_STATE_SENDING; - return; + ClearOutgoing(0); + return 0; } MaybeStackBuffer bufs; bufs.AllocateSufficientStorage(count); @@ -1471,6 +1486,8 @@ void Http2Session::SendPendingData() { DEBUG_HTTP2SESSION2(this, "wants data in return? %d", nghttp2_session_want_read(session_)); + + return 0; } @@ -1646,7 +1663,7 @@ Http2Stream::Http2Stream( session_(session), id_(id), current_headers_category_(category) { - MakeWeak(this); + MakeWeak(); statistics_.start_time = uv_hrtime(); // Limit the number of header pairs @@ -1830,12 +1847,25 @@ int Http2Stream::SubmitPriority(nghttp2_priority_spec* prispec, // peer. void Http2Stream::SubmitRstStream(const uint32_t code) { CHECK(!this->IsDestroyed()); + code_ = code; + // If possible, force a purge of any currently pending data here to make sure + // it is sent before closing the stream. If it returns non-zero then we need + // to wait until the current write finishes and try again to avoid nghttp2 + // behaviour where it prioritizes RstStream over everything else. + if (session_->SendPendingData() != 0) { + session_->AddPendingRstStream(id_); + return; + } + + FlushRstStream(); +} + +void Http2Stream::FlushRstStream() { + if (IsDestroyed()) + return; Http2Scope h2scope(this); - // Force a purge of any currently pending data here to make sure - // it is sent before closing the stream. - session_->SendPendingData(); CHECK_EQ(nghttp2_submit_rst_stream(**session_, NGHTTP2_FLAG_NONE, - id_, code), 0); + id_, code_), 0); } @@ -2123,7 +2153,7 @@ void Http2Session::RefreshState(const FunctionCallbackInfo& args) { ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder()); DEBUG_HTTP2SESSION(session, "refreshing state"); - AliasedBuffer& buffer = + AliasedBuffer& buffer = env->http2_state()->session_state_buffer; nghttp2_session* s = **session; @@ -2413,7 +2443,7 @@ void Http2Stream::RefreshState(const FunctionCallbackInfo& args) { DEBUG_HTTP2STREAM(stream, "refreshing state"); - AliasedBuffer& buffer = + AliasedBuffer& buffer = env->http2_state()->stream_state_buffer; nghttp2_stream* str = **stream; @@ -2580,11 +2610,6 @@ Http2Session::Http2Ping::Http2Ping( session_(session), startTime_(uv_hrtime()) { } -Http2Session::Http2Ping::~Http2Ping() { - if (!object().IsEmpty()) - ClearWrap(object()); -} - void Http2Session::Http2Ping::Send(uint8_t* payload) { uint8_t data[8]; if (payload == nullptr) { @@ -2625,7 +2650,7 @@ void Initialize(Local target, Isolate* isolate = env->isolate(); HandleScope scope(isolate); - std::unique_ptr state(new http2_state(isolate)); + std::unique_ptr state(new Http2State(isolate)); #define SET_STATE_TYPEDARRAY(name, field) \ target->Set(context, \ diff --git a/src/node_http2.h b/src/node_http2.h index 87c929cdea12f9..f4ac926bb54452 100644 --- a/src/node_http2.h +++ b/src/node_http2.h @@ -16,7 +16,6 @@ namespace http2 { using v8::Array; using v8::Context; -using v8::EscapableHandleScope; using v8::Isolate; using v8::MaybeLocal; @@ -591,6 +590,8 @@ class Http2Stream : public AsyncWrap, // Submits an RST_STREAM frame using the given code void SubmitRstStream(const uint32_t code); + void FlushRstStream(); + // Submits a PUSH_PROMISE frame with this stream as the parent. Http2Stream* SubmitPushPromise( nghttp2_nv* nva, @@ -797,7 +798,7 @@ class Http2Session : public AsyncWrap, public StreamListener { bool Ping(v8::Local function); - void SendPendingData(); + uint8_t SendPendingData(); // Submits a new request. If the request is a success, assigned // will be a pointer to the Http2Stream instance assigned. @@ -845,6 +846,11 @@ class Http2Session : public AsyncWrap, public StreamListener { size_t self_size() const override { return sizeof(*this); } + // Schedule an RstStream for after the current write finishes. + inline void AddPendingRstStream(int32_t stream_id) { + pending_rst_streams_.emplace_back(stream_id); + } + // Handle reads/writes from the underlying network transport. void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override; void OnStreamAfterWrite(WriteWrap* w, int status) override; @@ -1049,6 +1055,7 @@ class Http2Session : public AsyncWrap, public StreamListener { std::vector outgoing_buffers_; std::vector outgoing_storage_; + std::vector pending_rst_streams_; void CopyDataIntoOutgoing(const uint8_t* src, size_t src_length); void ClearOutgoing(int status); @@ -1141,7 +1148,6 @@ class Http2StreamPerformanceEntry : public PerformanceEntry { class Http2Session::Http2Ping : public AsyncWrap { public: explicit Http2Ping(Http2Session* session); - ~Http2Ping(); size_t self_size() const override { return sizeof(*this); } @@ -1162,7 +1168,6 @@ class Http2Session::Http2Settings : public AsyncWrap { public: explicit Http2Settings(Environment* env); explicit Http2Settings(Http2Session* session); - ~Http2Settings(); size_t self_size() const override { return sizeof(*this); } diff --git a/src/node_http2_state.h b/src/node_http2_state.h index ed88f068a04b16..64a0942f7ffa67 100644 --- a/src/node_http2_state.h +++ b/src/node_http2_state.h @@ -84,9 +84,9 @@ namespace http2 { IDX_SESSION_STATS_COUNT }; -class http2_state { +class Http2State { public: - explicit http2_state(v8::Isolate* isolate) : + explicit Http2State(v8::Isolate* isolate) : root_buffer( isolate, sizeof(http2_state_internal)), diff --git a/src/node_http_parser.cc b/src/node_http_parser.cc index 085f4494e3484e..d6f9b110c3af34 100644 --- a/src/node_http_parser.cc +++ b/src/node_http_parser.cc @@ -151,16 +151,10 @@ class Parser : public AsyncWrap, public StreamListener { : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_HTTPPARSER), current_buffer_len_(0), current_buffer_data_(nullptr) { - Wrap(object(), this); Init(type); } - ~Parser() override { - ClearWrap(object()); - } - - size_t self_size() const override { return sizeof(*this); } diff --git a/src/node_i18n.cc b/src/node_i18n.cc index f491d2191d7b55..5dd30a254ab969 100644 --- a/src/node_i18n.cc +++ b/src/node_i18n.cc @@ -259,7 +259,7 @@ class ConverterObject : public BaseObject, Converter { BaseObject(env, wrap), Converter(converter, sub), ignoreBOM_(ignoreBOM) { - MakeWeak(this); + MakeWeak(); switch (ucnv_getType(converter)) { case UCNV_UTF8: diff --git a/src/node_internals.h b/src/node_internals.h index 50047e330724fe..e5ea575ebc5981 100644 --- a/src/node_internals.h +++ b/src/node_internals.h @@ -33,6 +33,7 @@ #include "tracing/trace_event.h" #include "node_perf_common.h" #include "node_debug_options.h" +#include "node_api.h" #include #include @@ -243,9 +244,10 @@ v8::Local AddressToJS( template void GetSockOrPeerName(const v8::FunctionCallbackInfo& args) { - T* const wrap = Unwrap(args.Holder()); - if (wrap == nullptr) - return args.GetReturnValue().Set(UV_EBADF); + T* wrap; + ASSIGN_OR_RETURN_UNWRAP(&wrap, + args.Holder(), + args.GetReturnValue().Set(UV_EBADF)); CHECK(args[0]->IsObject()); sockaddr_storage storage; int addrlen = sizeof(storage); @@ -840,6 +842,10 @@ static inline const char *errno_string(int errorno) { } // namespace node +void napi_module_register_by_symbol(v8::Local exports, + v8::Local module, + v8::Local context, + napi_addon_register_func init); #endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS diff --git a/src/node_platform.cc b/src/node_platform.cc index d96db086925c01..b8f1344727cfd6 100644 --- a/src/node_platform.cc +++ b/src/node_platform.cc @@ -95,7 +95,7 @@ void PerIsolatePlatformData::PostDelayedTask( } PerIsolatePlatformData::~PerIsolatePlatformData() { - FlushForegroundTasksInternal(); + while (FlushForegroundTasksInternal()) {} CancelPendingDelayedTasks(); uv_close(reinterpret_cast(flush_tasks_), @@ -223,7 +223,13 @@ bool PerIsolatePlatformData::FlushForegroundTasksInternal() { }); }); } - while (std::unique_ptr task = foreground_tasks_.Pop()) { + // Move all foreground tasks into a separate queue and flush that queue. + // This way tasks that are posted while flushing the queue will be run on the + // next call of FlushForegroundTasksInternal. + std::queue> tasks = foreground_tasks_.PopAll(); + while (!tasks.empty()) { + std::unique_ptr task = std::move(tasks.front()); + tasks.pop(); did_work = true; RunForegroundTask(std::move(task)); } @@ -254,8 +260,8 @@ void NodePlatform::CallDelayedOnForegroundThread(Isolate* isolate, std::unique_ptr(task), delay_in_seconds); } -void NodePlatform::FlushForegroundTasks(v8::Isolate* isolate) { - ForIsolate(isolate)->FlushForegroundTasksInternal(); +bool NodePlatform::FlushForegroundTasks(v8::Isolate* isolate) { + return ForIsolate(isolate)->FlushForegroundTasksInternal(); } void NodePlatform::CancelPendingDelayedTasks(v8::Isolate* isolate) { @@ -348,4 +354,12 @@ void TaskQueue::Stop() { tasks_available_.Broadcast(scoped_lock); } +template +std::queue> TaskQueue::PopAll() { + Mutex::ScopedLock scoped_lock(lock_); + std::queue> result; + result.swap(task_queue_); + return result; +} + } // namespace node diff --git a/src/node_platform.h b/src/node_platform.h index b7546057871a1d..8f6ff89f491fe3 100644 --- a/src/node_platform.h +++ b/src/node_platform.h @@ -26,6 +26,7 @@ class TaskQueue { void Push(std::unique_ptr task); std::unique_ptr Pop(); std::unique_ptr BlockingPop(); + std::queue> PopAll(); void NotifyOfCompletion(); void BlockingDrain(); void Stop(); @@ -65,7 +66,9 @@ class PerIsolatePlatformData : void ref(); int unref(); - // Returns true iff work was dispatched or executed. + // Returns true if work was dispatched or executed. New tasks that are + // posted during flushing of the queue are postponed until the next + // flushing. bool FlushForegroundTasksInternal(); void CancelPendingDelayedTasks(); @@ -130,7 +133,10 @@ class NodePlatform : public MultiIsolatePlatform { double CurrentClockTimeMillis() override; v8::TracingController* GetTracingController() override; - void FlushForegroundTasks(v8::Isolate* isolate); + // Returns true if work was dispatched or executed. New tasks that are + // posted during flushing of the queue are postponed until the next + // flushing. + bool FlushForegroundTasks(v8::Isolate* isolate); void RegisterIsolate(IsolateData* isolate_data, uv_loop_t* loop) override; void UnregisterIsolate(IsolateData* isolate_data) override; diff --git a/src/node_serdes.cc b/src/node_serdes.cc index 6ace942c29fd56..520b350199245a 100644 --- a/src/node_serdes.cc +++ b/src/node_serdes.cc @@ -86,7 +86,7 @@ class DeserializerContext : public BaseObject, SerializerContext::SerializerContext(Environment* env, Local wrap) : BaseObject(env, wrap), serializer_(env->isolate(), this) { - MakeWeak(this); + MakeWeak(); } void SerializerContext::ThrowDataCloneError(Local message) { @@ -274,7 +274,7 @@ DeserializerContext::DeserializerContext(Environment* env, deserializer_(env->isolate(), data_, length_, this) { object()->Set(env->context(), env->buffer_string(), buffer).FromJust(); - MakeWeak(this); + MakeWeak(); } MaybeLocal DeserializerContext::ReadHostObject(Isolate* isolate) { diff --git a/src/node_stat_watcher.cc b/src/node_stat_watcher.cc index 41683a0dc1d36c..a2cfb1088c9d25 100644 --- a/src/node_stat_watcher.cc +++ b/src/node_stat_watcher.cc @@ -83,8 +83,7 @@ static void Delete(uv_handle_t* handle) { StatWatcher::StatWatcher(Environment* env, Local wrap) : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_STATWATCHER), watcher_(new uv_fs_poll_t) { - MakeWeak(this); - Wrap(wrap, this); + MakeWeak(); uv_fs_poll_init(env->event_loop(), watcher_); watcher_->data = static_cast(this); } @@ -191,7 +190,7 @@ void StatWatcher::Stop(const FunctionCallbackInfo& args) { void StatWatcher::Stop() { uv_fs_poll_stop(watcher_); - MakeWeak(this); + MakeWeak(); } diff --git a/src/node_trace_events.cc b/src/node_trace_events.cc index 1e02048d1f0843..0c0699f7be9e1f 100644 --- a/src/node_trace_events.cc +++ b/src/node_trace_events.cc @@ -37,7 +37,7 @@ class NodeCategorySet : public BaseObject { Local wrap, std::set categories) : BaseObject(env, wrap), categories_(categories) { - MakeWeak(this); + MakeWeak(); } bool enabled_ = false; @@ -63,7 +63,7 @@ void NodeCategorySet::Enable(const FunctionCallbackInfo& args) { NodeCategorySet* category_set; ASSIGN_OR_RETURN_UNWRAP(&category_set, args.Holder()); CHECK_NE(category_set, nullptr); - auto categories = category_set->GetCategories(); + const auto& categories = category_set->GetCategories(); if (!category_set->enabled_ && !categories.empty()) { env->tracing_agent()->Enable(categories); category_set->enabled_ = true; @@ -75,7 +75,7 @@ void NodeCategorySet::Disable(const FunctionCallbackInfo& args) { NodeCategorySet* category_set; ASSIGN_OR_RETURN_UNWRAP(&category_set, args.Holder()); CHECK_NE(category_set, nullptr); - auto categories = category_set->GetCategories(); + const auto& categories = category_set->GetCategories(); if (category_set->enabled_ && !categories.empty()) { env->tracing_agent()->Disable(categories); category_set->enabled_ = false; diff --git a/src/node_version.h b/src/node_version.h index 857f5e78791628..588e602d776c0b 100644 --- a/src/node_version.h +++ b/src/node_version.h @@ -23,13 +23,13 @@ #define SRC_NODE_VERSION_H_ #define NODE_MAJOR_VERSION 10 -#define NODE_MINOR_VERSION 0 -#define NODE_PATCH_VERSION 1 +#define NODE_MINOR_VERSION 1 +#define NODE_PATCH_VERSION 0 #define NODE_VERSION_IS_LTS 0 #define NODE_VERSION_LTS_CODENAME "" -#define NODE_VERSION_IS_RELEASE 0 +#define NODE_VERSION_IS_RELEASE 1 #ifndef NODE_STRINGIFY #define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n) diff --git a/src/node_win32_perfctr_provider.cc b/src/node_win32_perfctr_provider.cc index aac0203d719ebc..6ec3cbd5cfae69 100644 --- a/src/node_win32_perfctr_provider.cc +++ b/src/node_win32_perfctr_provider.cc @@ -119,7 +119,7 @@ PPERF_COUNTERSET_INSTANCE perfctr_instance; namespace node { -EXTERN_C DECLSPEC_SELECTANY HANDLE NodeCounterProvider = nullptr; +HANDLE NodeCounterProvider = nullptr; void InitPerfCountersWin32() { ULONG status; diff --git a/src/node_wrap.h b/src/node_wrap.h index 843fa7151743de..67cea2e715f869 100644 --- a/src/node_wrap.h +++ b/src/node_wrap.h @@ -33,6 +33,8 @@ namespace node { +// TODO(addaleax): Use real inheritance for the JS object templates to avoid +// this unnecessary case switching. #define WITH_GENERIC_UV_STREAM(env, obj, BODY, ELSE) \ do { \ if (env->tcp_constructor_template().IsEmpty() == false && \ diff --git a/src/node_zlib.cc b/src/node_zlib.cc index 67987baf8a375d..ec447638e2ae62 100644 --- a/src/node_zlib.cc +++ b/src/node_zlib.cc @@ -89,8 +89,6 @@ class ZCtx : public AsyncWrap { refs_(0), gzip_id_bytes_read_(0), write_result_(nullptr) { - MakeWeak(this); - Wrap(wrap, this); } @@ -662,7 +660,7 @@ class ZCtx : public AsyncWrap { void Unref() { CHECK_GT(refs_, 0); if (--refs_ == 0) { - MakeWeak(this); + MakeWeak(); } } diff --git a/src/pipe_wrap.cc b/src/pipe_wrap.cc index 0116051b3b6485..da7cb9e3ab55ba 100644 --- a/src/pipe_wrap.cc +++ b/src/pipe_wrap.cc @@ -102,12 +102,7 @@ void PipeWrap::Initialize(Local target, env->set_pipe_constructor_template(t); // Create FunctionTemplate for PipeConnectWrap. - auto constructor = [](const FunctionCallbackInfo& args) { - CHECK(args.IsConstructCall()); - ClearWrap(args.This()); - }; - auto cwt = FunctionTemplate::New(env->isolate(), constructor); - cwt->InstanceTemplate()->SetInternalFieldCount(1); + auto cwt = BaseObject::MakeLazilyInitializedJSTemplate(env); AsyncWrap::AddWrapMethods(env, cwt); Local wrapString = FIXED_ONE_BYTE_STRING(env->isolate(), "PipeConnectWrap"); diff --git a/src/stream_base-inl.h b/src/stream_base-inl.h index 392dc2c87c3ca3..cfe0de0872df4a 100644 --- a/src/stream_base-inl.h +++ b/src/stream_base-inl.h @@ -243,12 +243,6 @@ SimpleShutdownWrap::SimpleShutdownWrap( OtherBase(stream->stream_env(), req_wrap_obj, AsyncWrap::PROVIDER_SHUTDOWNWRAP) { - Wrap(req_wrap_obj, static_cast(this)); -} - -template -SimpleShutdownWrap::~SimpleShutdownWrap() { - ClearWrap(static_cast(this)->object()); } inline ShutdownWrap* StreamBase::CreateShutdownWrap( @@ -264,12 +258,6 @@ SimpleWriteWrap::SimpleWriteWrap( OtherBase(stream->stream_env(), req_wrap_obj, AsyncWrap::PROVIDER_WRITEWRAP) { - Wrap(req_wrap_obj, static_cast(this)); -} - -template -SimpleWriteWrap::~SimpleWriteWrap() { - ClearWrap(static_cast(this)->object()); } inline WriteWrap* StreamBase::CreateWriteWrap( @@ -335,8 +323,7 @@ void StreamBase::AddMethods(Environment* env, env->SetProtoMethod(t, "readStart", JSMethod); env->SetProtoMethod(t, "readStop", JSMethod); - if ((flags & kFlagNoShutdown) == 0) - env->SetProtoMethod(t, "shutdown", JSMethod); + env->SetProtoMethod(t, "shutdown", JSMethod); if ((flags & kFlagHasWritev) != 0) env->SetProtoMethod(t, "writev", JSMethod); env->SetProtoMethod(t, @@ -461,7 +448,7 @@ inline void StreamReq::ResetObject(v8::Local obj) { #ifdef DEBUG CHECK_GT(obj->InternalFieldCount(), StreamReq::kStreamReqField); #endif - ClearWrap(obj); + obj->SetAlignedPointerInInternalField(0, nullptr); // BaseObject field. obj->SetAlignedPointerInInternalField(StreamReq::kStreamReqField, nullptr); } diff --git a/src/stream_base.cc b/src/stream_base.cc index 801b7f4b2f4560..3708ffe7b65c0d 100644 --- a/src/stream_base.cc +++ b/src/stream_base.cc @@ -286,12 +286,6 @@ int StreamBase::WriteString(const FunctionCallbackInfo& args) { uv_stream_t* send_handle = nullptr; if (IsIPCPipe() && !send_handle_obj.IsEmpty()) { - // TODO(addaleax): This relies on the fact that HandleWrap comes first - // as a superclass of each individual subclass. - // There are similar assumptions in other places in the code base. - // A better idea would be having all BaseObject's internal pointers - // refer to the BaseObject* itself; this would require refactoring - // throughout the code base but makes Node rely much less on C++ quirks. HandleWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, send_handle_obj, UV_EINVAL); send_handle = reinterpret_cast(wrap->GetHandle()); diff --git a/src/stream_base.h b/src/stream_base.h index 96b8589b06831d..b91cf7df6cf8c4 100644 --- a/src/stream_base.h +++ b/src/stream_base.h @@ -257,8 +257,7 @@ class StreamBase : public StreamResource { public: enum Flags { kFlagNone = 0x0, - kFlagHasWritev = 0x1, - kFlagNoShutdown = 0x2 + kFlagHasWritev = 0x1 }; template @@ -351,7 +350,6 @@ class SimpleShutdownWrap : public ShutdownWrap, public OtherBase { public: SimpleShutdownWrap(StreamBase* stream, v8::Local req_wrap_obj); - ~SimpleShutdownWrap(); AsyncWrap* GetAsyncWrap() override { return this; } size_t self_size() const override { return sizeof(*this); } @@ -362,7 +360,6 @@ class SimpleWriteWrap : public WriteWrap, public OtherBase { public: SimpleWriteWrap(StreamBase* stream, v8::Local req_wrap_obj); - ~SimpleWriteWrap(); AsyncWrap* GetAsyncWrap() override { return this; } size_t self_size() const override { return sizeof(*this) + StorageSize(); } diff --git a/src/stream_pipe.cc b/src/stream_pipe.cc index 8f0263cd9ae99b..617a0129cfea07 100644 --- a/src/stream_pipe.cc +++ b/src/stream_pipe.cc @@ -17,7 +17,7 @@ StreamPipe::StreamPipe(StreamBase* source, StreamBase* sink, Local obj) : AsyncWrap(source->stream_env(), obj, AsyncWrap::PROVIDER_STREAMPIPE) { - MakeWeak(this); + MakeWeak(); CHECK_NE(sink, nullptr); CHECK_NE(source, nullptr); diff --git a/src/tcp_wrap.cc b/src/tcp_wrap.cc index 6158a1c4a424eb..3ccd157159c287 100644 --- a/src/tcp_wrap.cc +++ b/src/tcp_wrap.cc @@ -26,7 +26,6 @@ #include "handle_wrap.h" #include "node_buffer.h" #include "node_internals.h" -#include "node_wrap.h" #include "connect_wrap.h" #include "stream_base-inl.h" #include "stream_wrap.h" @@ -117,12 +116,8 @@ void TCPWrap::Initialize(Local target, env->set_tcp_constructor_template(t); // Create FunctionTemplate for TCPConnectWrap. - auto constructor = [](const FunctionCallbackInfo& args) { - CHECK(args.IsConstructCall()); - ClearWrap(args.This()); - }; - auto cwt = FunctionTemplate::New(env->isolate(), constructor); - cwt->InstanceTemplate()->SetInternalFieldCount(1); + Local cwt = + BaseObject::MakeLazilyInitializedJSTemplate(env); AsyncWrap::AddWrapMethods(env, cwt); Local wrapString = FIXED_ONE_BYTE_STRING(env->isolate(), "TCPConnectWrap"); diff --git a/src/timer_wrap.cc b/src/timer_wrap.cc index 02c0b8166981ab..88377a3e1b88cc 100644 --- a/src/timer_wrap.cc +++ b/src/timer_wrap.cc @@ -115,7 +115,8 @@ class TimerWrap : public HandleWrap { } static void Start(const FunctionCallbackInfo& args) { - TimerWrap* wrap = Unwrap(args.Holder()); + TimerWrap* wrap; + ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); CHECK(HandleWrap::IsAlive(wrap)); @@ -125,7 +126,8 @@ class TimerWrap : public HandleWrap { } static void Stop(const FunctionCallbackInfo& args) { - TimerWrap* wrap = Unwrap(args.Holder()); + TimerWrap* wrap; + ASSIGN_OR_RETURN_UNWRAP(&wrap, args.Holder()); CHECK(HandleWrap::IsAlive(wrap)); diff --git a/src/tls_wrap.cc b/src/tls_wrap.cc index 71adbdfc52ca36..3764e2f3c93d4c 100644 --- a/src/tls_wrap.cc +++ b/src/tls_wrap.cc @@ -68,8 +68,7 @@ TLSWrap::TLSWrap(Environment* env, shutdown_(false), cycle_depth_(0), eof_(false) { - node::Wrap(object(), this); - MakeWeak(this); + MakeWeak(); // sc comes from an Unwrap. Make sure it was assigned. CHECK_NE(sc, nullptr); @@ -873,16 +872,9 @@ void TLSWrap::Initialize(Local target, env->SetMethod(target, "wrap", TLSWrap::Wrap); - auto constructor = [](const FunctionCallbackInfo& args) { - CHECK(args.IsConstructCall()); - args.This()->SetAlignedPointerInInternalField(0, nullptr); - }; - + Local t = BaseObject::MakeLazilyInitializedJSTemplate(env); Local tlsWrapString = FIXED_ONE_BYTE_STRING(env->isolate(), "TLSWrap"); - - auto t = env->NewFunctionTemplate(constructor); - t->InstanceTemplate()->SetInternalFieldCount(1); t->SetClassName(tlsWrapString); Local get_write_queue_size = diff --git a/src/tty_wrap.cc b/src/tty_wrap.cc index 9977738afcbfd5..c5abc6bf9b9b91 100644 --- a/src/tty_wrap.cc +++ b/src/tty_wrap.cc @@ -61,7 +61,7 @@ void TTYWrap::Initialize(Local target, env->SetProtoMethod(t, "ref", HandleWrap::Ref); env->SetProtoMethod(t, "hasRef", HandleWrap::HasRef); - LibuvStreamWrap::AddMethods(env, t, StreamBase::kFlagNoShutdown); + LibuvStreamWrap::AddMethods(env, t); env->SetProtoMethod(t, "getWindowSize", TTYWrap::GetWindowSize); env->SetProtoMethod(t, "setRawMode", SetRawMode); diff --git a/src/udp_wrap.cc b/src/udp_wrap.cc index e02220a8784d74..414fe07eab6da8 100644 --- a/src/udp_wrap.cc +++ b/src/udp_wrap.cc @@ -53,7 +53,6 @@ using AsyncHooks = Environment::AsyncHooks; class SendWrap : public ReqWrap { public: SendWrap(Environment* env, Local req_wrap_obj, bool have_callback); - ~SendWrap(); inline bool have_callback() const; size_t msg_size; size_t self_size() const override { return sizeof(*this); } @@ -67,12 +66,6 @@ SendWrap::SendWrap(Environment* env, bool have_callback) : ReqWrap(env, req_wrap_obj, AsyncWrap::PROVIDER_UDPSENDWRAP), have_callback_(have_callback) { - Wrap(req_wrap_obj, this); -} - - -SendWrap::~SendWrap() { - ClearWrap(object()); } @@ -81,12 +74,6 @@ inline bool SendWrap::have_callback() const { } -static void NewSendWrap(const FunctionCallbackInfo& args) { - CHECK(args.IsConstructCall()); - ClearWrap(args.This()); -} - - UDPWrap::UDPWrap(Environment* env, Local object) : HandleWrap(env, object, @@ -153,8 +140,7 @@ void UDPWrap::Initialize(Local target, // Create FunctionTemplate for SendWrap Local swt = - FunctionTemplate::New(env->isolate(), NewSendWrap); - swt->InstanceTemplate()->SetInternalFieldCount(1); + BaseObject::MakeLazilyInitializedJSTemplate(env); AsyncWrap::AddWrapMethods(env, swt); Local sendWrapString = FIXED_ONE_BYTE_STRING(env->isolate(), "SendWrap"); diff --git a/src/util-inl.h b/src/util-inl.h index d07cfea9227fbe..41a22c97efd9c0 100644 --- a/src/util-inl.h +++ b/src/util-inl.h @@ -217,25 +217,6 @@ inline v8::Local OneByteString(v8::Isolate* isolate, length).ToLocalChecked(); } -template -void Wrap(v8::Local object, TypeName* pointer) { - CHECK_EQ(false, object.IsEmpty()); - CHECK_GT(object->InternalFieldCount(), 0); - object->SetAlignedPointerInInternalField(0, pointer); -} - -void ClearWrap(v8::Local object) { - Wrap(object, nullptr); -} - -template -TypeName* Unwrap(v8::Local object) { - CHECK_EQ(false, object.IsEmpty()); - CHECK_GT(object->InternalFieldCount(), 0); - void* pointer = object->GetAlignedPointerFromInternalField(0); - return static_cast(pointer); -} - void SwapBytes16(char* data, size_t nbytes) { CHECK_EQ(nbytes % 2, 0); diff --git a/src/util.h b/src/util.h index c8bad8171e3bc1..133899008fb7ce 100644 --- a/src/util.h +++ b/src/util.h @@ -35,7 +35,6 @@ #include #include // std::function -#include // std::remove_reference namespace node { @@ -84,8 +83,6 @@ NO_RETURN void Abort(); NO_RETURN void Assert(const char* const (*args)[4]); void DumpBacktrace(FILE* fp); -template using remove_reference = std::remove_reference; - #define FIXED_ONE_BYTE_STRING(isolate, string) \ (node::OneByteString((isolate), (string), sizeof(string) - 1)) @@ -135,14 +132,6 @@ template using remove_reference = std::remove_reference; #define UNREACHABLE() ABORT() -#define ASSIGN_OR_RETURN_UNWRAP(ptr, obj, ...) \ - do { \ - *ptr = \ - Unwrap::type>(obj); \ - if (*ptr == nullptr) \ - return __VA_ARGS__; \ - } while (0) - // TAILQ-style intrusive list node. template class ListNode; @@ -250,13 +239,6 @@ inline v8::Local OneByteString(v8::Isolate* isolate, const unsigned char* data, int length = -1); -inline void Wrap(v8::Local object, void* pointer); - -inline void ClearWrap(v8::Local object); - -template -inline TypeName* Unwrap(v8::Local object); - // Swaps bytes in place. nbytes is the number of bytes to swap and must be a // multiple of the word size (checked by function). inline void SwapBytes16(char* data, size_t nbytes); diff --git a/test/.eslintrc.yaml b/test/.eslintrc.yaml index 235b73baf06d49..7c90a5026b27d0 100644 --- a/test/.eslintrc.yaml +++ b/test/.eslintrc.yaml @@ -13,6 +13,7 @@ rules: node-core/prefer-common-expectserror: error node-core/prefer-common-mustnotcall: error node-core/crypto-check: error + node-core/eslint-check: error node-core/inspector-check: error node-core/number-isnan: error ## common module is mandatory in tests diff --git a/test/addons-napi/1_hello_world/binding.c b/test/addons-napi/1_hello_world/binding.c index 27d49079966d09..02cd5dd2f19418 100644 --- a/test/addons-napi/1_hello_world/binding.c +++ b/test/addons-napi/1_hello_world/binding.c @@ -2,7 +2,7 @@ #include "../common.h" #include -napi_value Method(napi_env env, napi_callback_info info) { +static napi_value Method(napi_env env, napi_callback_info info) { napi_value world; const char* str = "world"; size_t str_len = strlen(str); @@ -10,10 +10,8 @@ napi_value Method(napi_env env, napi_callback_info info) { return world; } -napi_value Init(napi_env env, napi_value exports) { +NAPI_MODULE_INIT() { napi_property_descriptor desc = DECLARE_NAPI_PROPERTY("hello", Method); NAPI_CALL(env, napi_define_properties(env, exports, 1, &desc)); return exports; } - -NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/test/addons-napi/1_hello_world/test.js b/test/addons-napi/1_hello_world/test.js index c975c48a733f5c..d1d67d34f688c9 100644 --- a/test/addons-napi/1_hello_world/test.js +++ b/test/addons-napi/1_hello_world/test.js @@ -1,6 +1,13 @@ 'use strict'; const common = require('../../common'); const assert = require('assert'); -const addon = require(`./build/${common.buildType}/binding`); +const bindingPath = require.resolve(`./build/${common.buildType}/binding`); +const binding = require(bindingPath); +assert.strictEqual(binding.hello(), 'world'); +console.log('binding.hello() =', binding.hello()); -assert.strictEqual(addon.hello(), 'world'); +// Test multiple loading of the same module. +delete require.cache[bindingPath]; +const rebinding = require(bindingPath); +assert.strictEqual(rebinding.hello(), 'world'); +assert.notStrictEqual(binding.hello, rebinding.hello); diff --git a/test/addons-napi/2_function_arguments/binding.c b/test/addons-napi/2_function_arguments/binding.c index c45ca0871db8ec..7d88c3d9e4ff19 100644 --- a/test/addons-napi/2_function_arguments/binding.c +++ b/test/addons-napi/2_function_arguments/binding.c @@ -1,7 +1,7 @@ #include #include "../common.h" -napi_value Add(napi_env env, napi_callback_info info) { +static napi_value Add(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -29,7 +29,7 @@ napi_value Add(napi_env env, napi_callback_info info) { return sum; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor desc = DECLARE_NAPI_PROPERTY("add", Add); NAPI_CALL(env, napi_define_properties(env, exports, 1, &desc)); return exports; diff --git a/test/addons-napi/3_callbacks/binding.c b/test/addons-napi/3_callbacks/binding.c index 7ebacf1d0653e9..1c0dd8126ce4ef 100644 --- a/test/addons-napi/3_callbacks/binding.c +++ b/test/addons-napi/3_callbacks/binding.c @@ -2,7 +2,7 @@ #include "../common.h" #include -napi_value RunCallback(napi_env env, napi_callback_info info) { +static napi_value RunCallback(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -34,7 +34,7 @@ napi_value RunCallback(napi_env env, napi_callback_info info) { return NULL; } -napi_value RunCallbackWithRecv(napi_env env, napi_callback_info info) { +static napi_value RunCallbackWithRecv(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -45,7 +45,7 @@ napi_value RunCallbackWithRecv(napi_env env, napi_callback_info info) { return NULL; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor desc[2] = { DECLARE_NAPI_PROPERTY("RunCallback", RunCallback), DECLARE_NAPI_PROPERTY("RunCallbackWithRecv", RunCallbackWithRecv), diff --git a/test/addons-napi/4_object_factory/binding.c b/test/addons-napi/4_object_factory/binding.c index 38b8ec8e1cab48..0ed95e93512a0b 100644 --- a/test/addons-napi/4_object_factory/binding.c +++ b/test/addons-napi/4_object_factory/binding.c @@ -1,7 +1,7 @@ #include #include "../common.h" -napi_value CreateObject(napi_env env, napi_callback_info info) { +static napi_value CreateObject(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -14,7 +14,7 @@ napi_value CreateObject(napi_env env, napi_callback_info info) { return obj; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { NAPI_CALL(env, napi_create_function(env, "exports", -1, CreateObject, NULL, &exports)); return exports; diff --git a/test/addons-napi/5_function_factory/binding.c b/test/addons-napi/5_function_factory/binding.c index 8cc41f6aac5c3d..19460b9ddc55f2 100644 --- a/test/addons-napi/5_function_factory/binding.c +++ b/test/addons-napi/5_function_factory/binding.c @@ -1,20 +1,20 @@ #include #include "../common.h" -napi_value MyFunction(napi_env env, napi_callback_info info) { +static napi_value MyFunction(napi_env env, napi_callback_info info) { napi_value str; NAPI_CALL(env, napi_create_string_utf8(env, "hello world", -1, &str)); return str; } -napi_value CreateFunction(napi_env env, napi_callback_info info) { +static napi_value CreateFunction(napi_env env, napi_callback_info info) { napi_value fn; NAPI_CALL(env, napi_create_function(env, "theFunction", -1, MyFunction, NULL, &fn)); return fn; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { NAPI_CALL(env, napi_create_function(env, "exports", -1, CreateFunction, NULL, &exports)); return exports; diff --git a/test/addons-napi/test_array/test_array.c b/test/addons-napi/test_array/test_array.c index f13867ca74f848..bd4f867c0c9117 100644 --- a/test/addons-napi/test_array/test_array.c +++ b/test/addons-napi/test_array/test_array.c @@ -2,7 +2,7 @@ #include #include "../common.h" -napi_value TestGetElement(napi_env env, napi_callback_info info) { +static napi_value TestGetElement(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -45,7 +45,7 @@ napi_value TestGetElement(napi_env env, napi_callback_info info) { return ret; } -napi_value TestHasElement(napi_env env, napi_callback_info info) { +static napi_value TestHasElement(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -84,7 +84,7 @@ napi_value TestHasElement(napi_env env, napi_callback_info info) { return ret; } -napi_value TestDeleteElement(napi_env env, napi_callback_info info) { +static napi_value TestDeleteElement(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; @@ -119,7 +119,7 @@ napi_value TestDeleteElement(napi_env env, napi_callback_info info) { return ret; } -napi_value New(napi_env env, napi_callback_info info) { +static napi_value New(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -147,7 +147,7 @@ napi_value New(napi_env env, napi_callback_info info) { return ret; } -napi_value NewWithLength(napi_env env, napi_callback_info info) { +static napi_value NewWithLength(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -169,7 +169,7 @@ napi_value NewWithLength(napi_env env, napi_callback_info info) { return ret; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("TestGetElement", TestGetElement), DECLARE_NAPI_PROPERTY("TestHasElement", TestHasElement), diff --git a/test/addons-napi/test_buffer/test_buffer.c b/test/addons-napi/test_buffer/test_buffer.c index 657eb7b3a051bf..552d280615739f 100644 --- a/test/addons-napi/test_buffer/test_buffer.c +++ b/test/addons-napi/test_buffer/test_buffer.c @@ -20,7 +20,7 @@ static void noopDeleter(napi_env env, void* data, void* finalize_hint) { deleterCallCount++; } -napi_value newBuffer(napi_env env, napi_callback_info info) { +static napi_value newBuffer(napi_env env, napi_callback_info info) { napi_value theBuffer; char* theCopy; const unsigned int kBufferSize = sizeof(theText); @@ -37,7 +37,7 @@ napi_value newBuffer(napi_env env, napi_callback_info info) { return theBuffer; } -napi_value newExternalBuffer(napi_env env, napi_callback_info info) { +static napi_value newExternalBuffer(napi_env env, napi_callback_info info) { napi_value theBuffer; char* theCopy = strdup(theText); NAPI_ASSERT(env, theCopy, "Failed to copy static text for newExternalBuffer"); @@ -53,20 +53,20 @@ napi_value newExternalBuffer(napi_env env, napi_callback_info info) { return theBuffer; } -napi_value getDeleterCallCount(napi_env env, napi_callback_info info) { +static napi_value getDeleterCallCount(napi_env env, napi_callback_info info) { napi_value callCount; NAPI_CALL(env, napi_create_int32(env, deleterCallCount, &callCount)); return callCount; } -napi_value copyBuffer(napi_env env, napi_callback_info info) { +static napi_value copyBuffer(napi_env env, napi_callback_info info) { napi_value theBuffer; NAPI_CALL(env, napi_create_buffer_copy( env, sizeof(theText), theText, NULL, &theBuffer)); return theBuffer; } -napi_value bufferHasInstance(napi_env env, napi_callback_info info) { +static napi_value bufferHasInstance(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -85,7 +85,7 @@ napi_value bufferHasInstance(napi_env env, napi_callback_info info) { return returnValue; } -napi_value bufferInfo(napi_env env, napi_callback_info info) { +static napi_value bufferInfo(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -106,7 +106,7 @@ napi_value bufferInfo(napi_env env, napi_callback_info info) { return returnValue; } -napi_value staticBuffer(napi_env env, napi_callback_info info) { +static napi_value staticBuffer(napi_env env, napi_callback_info info) { napi_value theBuffer; NAPI_CALL( env, @@ -119,7 +119,7 @@ napi_value staticBuffer(napi_env env, napi_callback_info info) { return theBuffer; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_value theValue; NAPI_CALL(env, diff --git a/test/addons-napi/test_constructor/test_constructor.c b/test/addons-napi/test_constructor/test_constructor.c index 4ee8323dd6ed40..8cc092049aef10 100644 --- a/test/addons-napi/test_constructor/test_constructor.c +++ b/test/addons-napi/test_constructor/test_constructor.c @@ -4,7 +4,7 @@ static double value_ = 1; static double static_value_ = 10; -napi_value GetValue(napi_env env, napi_callback_info info) { +static napi_value GetValue(napi_env env, napi_callback_info info) { size_t argc = 0; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, NULL, NULL, NULL)); @@ -16,7 +16,7 @@ napi_value GetValue(napi_env env, napi_callback_info info) { return number; } -napi_value SetValue(napi_env env, napi_callback_info info) { +static napi_value SetValue(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -28,7 +28,7 @@ napi_value SetValue(napi_env env, napi_callback_info info) { return NULL; } -napi_value Echo(napi_env env, napi_callback_info info) { +static napi_value Echo(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -38,14 +38,14 @@ napi_value Echo(napi_env env, napi_callback_info info) { return args[0]; } -napi_value New(napi_env env, napi_callback_info info) { +static napi_value New(napi_env env, napi_callback_info info) { napi_value _this; NAPI_CALL(env, napi_get_cb_info(env, info, NULL, NULL, &_this, NULL)); return _this; } -napi_value GetStaticValue(napi_env env, napi_callback_info info) { +static napi_value GetStaticValue(napi_env env, napi_callback_info info) { size_t argc = 0; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, NULL, NULL, NULL)); @@ -58,7 +58,7 @@ napi_value GetStaticValue(napi_env env, napi_callback_info info) { } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_value number; NAPI_CALL(env, napi_create_double(env, value_, &number)); diff --git a/test/addons-napi/test_constructor/test_constructor_name.c b/test/addons-napi/test_constructor/test_constructor_name.c index a5c89791f0f0cd..e12deb80d23af8 100644 --- a/test/addons-napi/test_constructor/test_constructor_name.c +++ b/test/addons-napi/test_constructor/test_constructor_name.c @@ -1,22 +1,17 @@ #include #include "../common.h" -napi_ref constructor_; - -napi_value New(napi_env env, napi_callback_info info) { +static napi_value New(napi_env env, napi_callback_info info) { napi_value _this; NAPI_CALL(env, napi_get_cb_info(env, info, NULL, NULL, &_this, NULL)); return _this; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_value cons; NAPI_CALL(env, napi_define_class( env, "MyObject_Extra", 8, New, NULL, 0, NULL, &cons)); - - NAPI_CALL(env, - napi_create_reference(env, cons, 1, &constructor_)); return cons; } diff --git a/test/addons-napi/test_conversions/test_conversions.c b/test/addons-napi/test_conversions/test_conversions.c index 4f92bafa35b79d..845b7e7c56d7df 100644 --- a/test/addons-napi/test_conversions/test_conversions.c +++ b/test/addons-napi/test_conversions/test_conversions.c @@ -1,7 +1,7 @@ #include #include "../common.h" -napi_value AsBool(napi_env env, napi_callback_info info) { +static napi_value AsBool(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -15,7 +15,7 @@ napi_value AsBool(napi_env env, napi_callback_info info) { return output; } -napi_value AsInt32(napi_env env, napi_callback_info info) { +static napi_value AsInt32(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -29,7 +29,7 @@ napi_value AsInt32(napi_env env, napi_callback_info info) { return output; } -napi_value AsUInt32(napi_env env, napi_callback_info info) { +static napi_value AsUInt32(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -43,7 +43,7 @@ napi_value AsUInt32(napi_env env, napi_callback_info info) { return output; } -napi_value AsInt64(napi_env env, napi_callback_info info) { +static napi_value AsInt64(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -57,7 +57,7 @@ napi_value AsInt64(napi_env env, napi_callback_info info) { return output; } -napi_value AsDouble(napi_env env, napi_callback_info info) { +static napi_value AsDouble(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -71,7 +71,7 @@ napi_value AsDouble(napi_env env, napi_callback_info info) { return output; } -napi_value AsString(napi_env env, napi_callback_info info) { +static napi_value AsString(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -87,7 +87,7 @@ napi_value AsString(napi_env env, napi_callback_info info) { return output; } -napi_value ToBool(napi_env env, napi_callback_info info) { +static napi_value ToBool(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -98,7 +98,7 @@ napi_value ToBool(napi_env env, napi_callback_info info) { return output; } -napi_value ToNumber(napi_env env, napi_callback_info info) { +static napi_value ToNumber(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -109,7 +109,7 @@ napi_value ToNumber(napi_env env, napi_callback_info info) { return output; } -napi_value ToObject(napi_env env, napi_callback_info info) { +static napi_value ToObject(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -120,7 +120,7 @@ napi_value ToObject(napi_env env, napi_callback_info info) { return output; } -napi_value ToString(napi_env env, napi_callback_info info) { +static napi_value ToString(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -131,7 +131,7 @@ napi_value ToString(napi_env env, napi_callback_info info) { return output; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("asBool", AsBool), DECLARE_NAPI_PROPERTY("asInt32", AsInt32), diff --git a/test/addons-napi/test_dataview/test_dataview.c b/test/addons-napi/test_dataview/test_dataview.c index 4d29ed07e9e6f7..8d29743522022f 100644 --- a/test/addons-napi/test_dataview/test_dataview.c +++ b/test/addons-napi/test_dataview/test_dataview.c @@ -2,7 +2,7 @@ #include #include "../common.h" -napi_value CreateDataView(napi_env env, napi_callback_info info) { +static napi_value CreateDataView(napi_env env, napi_callback_info info) { size_t argc = 3; napi_value args [3]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -49,7 +49,7 @@ napi_value CreateDataView(napi_env env, napi_callback_info info) { return output_dataview; } -napi_value CreateDataViewFromJSDataView(napi_env env, napi_callback_info info) { +static napi_value CreateDataViewFromJSDataView(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args [1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -85,7 +85,7 @@ napi_value CreateDataViewFromJSDataView(napi_env env, napi_callback_info info) { return output_dataview; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("CreateDataView", CreateDataView), DECLARE_NAPI_PROPERTY("CreateDataViewFromJSDataView", diff --git a/test/addons-napi/test_env_sharing/compare_env.c b/test/addons-napi/test_env_sharing/compare_env.c index 6a93ce52c64025..3326a34067219a 100644 --- a/test/addons-napi/test_env_sharing/compare_env.c +++ b/test/addons-napi/test_env_sharing/compare_env.c @@ -1,7 +1,7 @@ #include #include "../common.h" -napi_value compare(napi_env env, napi_callback_info info) { +static napi_value compare(napi_env env, napi_callback_info info) { napi_value external; size_t argc = 1; void* data; @@ -14,7 +14,7 @@ napi_value compare(napi_env env, napi_callback_info info) { return return_value; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { NAPI_CALL(env, napi_create_function( env, "exports", NAPI_AUTO_LENGTH, compare, NULL, &exports)); return exports; diff --git a/test/addons-napi/test_env_sharing/store_env.c b/test/addons-napi/test_env_sharing/store_env.c index 809f5f7a4b2eed..0559b178cba68b 100644 --- a/test/addons-napi/test_env_sharing/store_env.c +++ b/test/addons-napi/test_env_sharing/store_env.c @@ -1,7 +1,7 @@ #include #include "../common.h" -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_value external; NAPI_CALL(env, napi_create_external(env, env, NULL, NULL, &external)); return external; diff --git a/test/addons-napi/test_error/binding.gyp b/test/addons-napi/test_error/binding.gyp index c2defd9551a31b..2923e15adca1a1 100644 --- a/test/addons-napi/test_error/binding.gyp +++ b/test/addons-napi/test_error/binding.gyp @@ -2,7 +2,7 @@ "targets": [ { "target_name": "test_error", - "sources": [ "test_error.cc" ] + "sources": [ "test_error.c" ] } ] } diff --git a/test/addons-napi/test_error/test.js b/test/addons-napi/test_error/test.js index d5c92cb4c3cd2e..d4b1d8a971ee09 100644 --- a/test/addons-napi/test_error/test.js +++ b/test/addons-napi/test_error/test.js @@ -60,6 +60,25 @@ assert.throws(() => { test_error.throwTypeError(); }, /^TypeError: type error$/); +function testThrowArbitrary(value) { + assert.throws( + () => test_error.throwArbitrary(value), + (err) => { + assert.strictEqual(err, value); + return true; + }); +} + +testThrowArbitrary(42); +testThrowArbitrary({}); +testThrowArbitrary([]); +testThrowArbitrary(Symbol('xyzzy')); +testThrowArbitrary(true); +testThrowArbitrary('ball'); +testThrowArbitrary(undefined); +testThrowArbitrary(null); +testThrowArbitrary(NaN); + common.expectsError( () => test_error.throwErrorCode(), { diff --git a/test/addons-napi/test_error/test_error.cc b/test/addons-napi/test_error/test_error.c similarity index 64% rename from test/addons-napi/test_error/test_error.cc rename to test/addons-napi/test_error/test_error.c index 4ab20bd7522a3b..52a9ac7956954e 100644 --- a/test/addons-napi/test_error/test_error.cc +++ b/test/addons-napi/test_error/test_error.c @@ -1,10 +1,10 @@ #include #include "../common.h" -napi_value checkError(napi_env env, napi_callback_info info) { +static napi_value checkError(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); bool r; NAPI_CALL(env, napi_is_error(env, args[0], &r)); @@ -15,79 +15,79 @@ napi_value checkError(napi_env env, napi_callback_info info) { return result; } -napi_value throwExistingError(napi_env env, napi_callback_info info) { +static napi_value throwExistingError(napi_env env, napi_callback_info info) { napi_value message; napi_value error; NAPI_CALL(env, napi_create_string_utf8( env, "existing error", NAPI_AUTO_LENGTH, &message)); - NAPI_CALL(env, napi_create_error(env, nullptr, message, &error)); + NAPI_CALL(env, napi_create_error(env, NULL, message, &error)); NAPI_CALL(env, napi_throw(env, error)); - return nullptr; + return NULL; } -napi_value throwError(napi_env env, napi_callback_info info) { - NAPI_CALL(env, napi_throw_error(env, nullptr, "error")); - return nullptr; +static napi_value throwError(napi_env env, napi_callback_info info) { + NAPI_CALL(env, napi_throw_error(env, NULL, "error")); + return NULL; } -napi_value throwRangeError(napi_env env, napi_callback_info info) { - NAPI_CALL(env, napi_throw_range_error(env, nullptr, "range error")); - return nullptr; +static napi_value throwRangeError(napi_env env, napi_callback_info info) { + NAPI_CALL(env, napi_throw_range_error(env, NULL, "range error")); + return NULL; } -napi_value throwTypeError(napi_env env, napi_callback_info info) { - NAPI_CALL(env, napi_throw_type_error(env, nullptr, "type error")); - return nullptr; +static napi_value throwTypeError(napi_env env, napi_callback_info info) { + NAPI_CALL(env, napi_throw_type_error(env, NULL, "type error")); + return NULL; } -napi_value throwErrorCode(napi_env env, napi_callback_info info) { +static napi_value throwErrorCode(napi_env env, napi_callback_info info) { NAPI_CALL(env, napi_throw_error(env, "ERR_TEST_CODE", "Error [error]")); - return nullptr; + return NULL; } -napi_value throwRangeErrorCode(napi_env env, napi_callback_info info) { +static napi_value throwRangeErrorCode(napi_env env, napi_callback_info info) { NAPI_CALL(env, napi_throw_range_error(env, "ERR_TEST_CODE", "RangeError [range error]")); - return nullptr; + return NULL; } -napi_value throwTypeErrorCode(napi_env env, napi_callback_info info) { +static napi_value throwTypeErrorCode(napi_env env, napi_callback_info info) { NAPI_CALL(env, napi_throw_type_error(env, "ERR_TEST_CODE", "TypeError [type error]")); - return nullptr; + return NULL; } -napi_value createError(napi_env env, napi_callback_info info) { +static napi_value createError(napi_env env, napi_callback_info info) { napi_value result; napi_value message; NAPI_CALL(env, napi_create_string_utf8( env, "error", NAPI_AUTO_LENGTH, &message)); - NAPI_CALL(env, napi_create_error(env, nullptr, message, &result)); + NAPI_CALL(env, napi_create_error(env, NULL, message, &result)); return result; } -napi_value createRangeError(napi_env env, napi_callback_info info) { +static napi_value createRangeError(napi_env env, napi_callback_info info) { napi_value result; napi_value message; NAPI_CALL(env, napi_create_string_utf8( env, "range error", NAPI_AUTO_LENGTH, &message)); - NAPI_CALL(env, napi_create_range_error(env, nullptr, message, &result)); + NAPI_CALL(env, napi_create_range_error(env, NULL, message, &result)); return result; } -napi_value createTypeError(napi_env env, napi_callback_info info) { +static napi_value createTypeError(napi_env env, napi_callback_info info) { napi_value result; napi_value message; NAPI_CALL(env, napi_create_string_utf8( env, "type error", NAPI_AUTO_LENGTH, &message)); - NAPI_CALL(env, napi_create_type_error(env, nullptr, message, &result)); + NAPI_CALL(env, napi_create_type_error(env, NULL, message, &result)); return result; } -napi_value createErrorCode(napi_env env, napi_callback_info info) { +static napi_value createErrorCode(napi_env env, napi_callback_info info) { napi_value result; napi_value message; napi_value code; @@ -99,7 +99,7 @@ napi_value createErrorCode(napi_env env, napi_callback_info info) { return result; } -napi_value createRangeErrorCode(napi_env env, napi_callback_info info) { +static napi_value createRangeErrorCode(napi_env env, napi_callback_info info) { napi_value result; napi_value message; napi_value code; @@ -113,7 +113,7 @@ napi_value createRangeErrorCode(napi_env env, napi_callback_info info) { return result; } -napi_value createTypeErrorCode(napi_env env, napi_callback_info info) { +static napi_value createTypeErrorCode(napi_env env, napi_callback_info info) { napi_value result; napi_value message; napi_value code; @@ -127,7 +127,15 @@ napi_value createTypeErrorCode(napi_env env, napi_callback_info info) { return result; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value throwArbitrary(napi_env env, napi_callback_info info) { + napi_value arbitrary; + size_t argc = 1; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &arbitrary, NULL, NULL)); + NAPI_CALL(env, napi_throw(env, arbitrary)); + return NULL; +} + +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("checkError", checkError), DECLARE_NAPI_PROPERTY("throwExistingError", throwExistingError), @@ -137,6 +145,7 @@ napi_value Init(napi_env env, napi_value exports) { DECLARE_NAPI_PROPERTY("throwErrorCode", throwErrorCode), DECLARE_NAPI_PROPERTY("throwRangeErrorCode", throwRangeErrorCode), DECLARE_NAPI_PROPERTY("throwTypeErrorCode", throwTypeErrorCode), + DECLARE_NAPI_PROPERTY("throwArbitrary", throwArbitrary), DECLARE_NAPI_PROPERTY("createError", createError), DECLARE_NAPI_PROPERTY("createRangeError", createRangeError), DECLARE_NAPI_PROPERTY("createTypeError", createTypeError), diff --git a/test/addons-napi/test_fatal/test_fatal.c b/test/addons-napi/test_fatal/test_fatal.c index add8bebf3be7e3..b9248d40d49e6a 100644 --- a/test/addons-napi/test_fatal/test_fatal.c +++ b/test/addons-napi/test_fatal/test_fatal.c @@ -1,18 +1,18 @@ #include #include "../common.h" -napi_value Test(napi_env env, napi_callback_info info) { +static napi_value Test(napi_env env, napi_callback_info info) { napi_fatal_error("test_fatal::Test", NAPI_AUTO_LENGTH, "fatal message", NAPI_AUTO_LENGTH); return NULL; } -napi_value TestStringLength(napi_env env, napi_callback_info info) { +static napi_value TestStringLength(napi_env env, napi_callback_info info) { napi_fatal_error("test_fatal::TestStringLength", 16, "fatal message", 13); return NULL; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor properties[] = { DECLARE_NAPI_PROPERTY("Test", Test), DECLARE_NAPI_PROPERTY("TestStringLength", TestStringLength), diff --git a/test/addons-napi/test_fatal_exception/test_fatal_exception.c b/test/addons-napi/test_fatal_exception/test_fatal_exception.c index fd81c56d856db8..3cc810ccc0d10c 100644 --- a/test/addons-napi/test_fatal_exception/test_fatal_exception.c +++ b/test/addons-napi/test_fatal_exception/test_fatal_exception.c @@ -1,7 +1,7 @@ #include #include "../common.h" -napi_value Test(napi_env env, napi_callback_info info) { +static napi_value Test(napi_env env, napi_callback_info info) { napi_value err; size_t argc = 1; @@ -12,7 +12,7 @@ napi_value Test(napi_env env, napi_callback_info info) { return NULL; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor properties[] = { DECLARE_NAPI_PROPERTY("Test", Test), }; diff --git a/test/addons-napi/test_function/test_function.c b/test/addons-napi/test_function/test_function.c index b0350e6ee22876..2c361933cfa071 100644 --- a/test/addons-napi/test_function/test_function.c +++ b/test/addons-napi/test_function/test_function.c @@ -1,7 +1,7 @@ #include #include "../common.h" -napi_value TestCallFunction(napi_env env, napi_callback_info info) { +static napi_value TestCallFunction(napi_env env, napi_callback_info info) { size_t argc = 10; napi_value args[10]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -26,11 +26,11 @@ napi_value TestCallFunction(napi_env env, napi_callback_info info) { return result; } -napi_value TestFunctionName(napi_env env, napi_callback_info info) { +static napi_value TestFunctionName(napi_env env, napi_callback_info info) { return NULL; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_value fn1; NAPI_CALL(env, napi_create_function( env, NULL, NAPI_AUTO_LENGTH, TestCallFunction, NULL, &fn1)); diff --git a/test/addons-napi/test_general/test_general.c b/test/addons-napi/test_general/test_general.c index 05cdd76e3c1e64..8f429f939fb89e 100644 --- a/test/addons-napi/test_general/test_general.c +++ b/test/addons-napi/test_general/test_general.c @@ -2,7 +2,7 @@ #include #include "../common.h" -napi_value testStrictEquals(napi_env env, napi_callback_info info) { +static napi_value testStrictEquals(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -15,7 +15,7 @@ napi_value testStrictEquals(napi_env env, napi_callback_info info) { return result; } -napi_value testGetPrototype(napi_env env, napi_callback_info info) { +static napi_value testGetPrototype(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -26,7 +26,7 @@ napi_value testGetPrototype(napi_env env, napi_callback_info info) { return result; } -napi_value testGetVersion(napi_env env, napi_callback_info info) { +static napi_value testGetVersion(napi_env env, napi_callback_info info) { uint32_t version; napi_value result; NAPI_CALL(env, napi_get_version(env, &version)); @@ -34,7 +34,7 @@ napi_value testGetVersion(napi_env env, napi_callback_info info) { return result; } -napi_value testGetNodeVersion(napi_env env, napi_callback_info info) { +static napi_value testGetNodeVersion(napi_env env, napi_callback_info info) { const napi_node_version* node_version; napi_value result, major, minor, patch, release; NAPI_CALL(env, napi_get_node_version(env, &node_version)); @@ -53,7 +53,7 @@ napi_value testGetNodeVersion(napi_env env, napi_callback_info info) { return result; } -napi_value doInstanceOf(napi_env env, napi_callback_info info) { +static napi_value doInstanceOf(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -67,19 +67,19 @@ napi_value doInstanceOf(napi_env env, napi_callback_info info) { return result; } -napi_value getNull(napi_env env, napi_callback_info info) { +static napi_value getNull(napi_env env, napi_callback_info info) { napi_value result; NAPI_CALL(env, napi_get_null(env, &result)); return result; } -napi_value getUndefined(napi_env env, napi_callback_info info) { +static napi_value getUndefined(napi_env env, napi_callback_info info) { napi_value result; NAPI_CALL(env, napi_get_undefined(env, &result)); return result; } -napi_value createNapiError(napi_env env, napi_callback_info info) { +static napi_value createNapiError(napi_env env, napi_callback_info info) { napi_value value; NAPI_CALL(env, napi_create_string_utf8(env, "xyz", 3, &value)); @@ -99,7 +99,7 @@ napi_value createNapiError(napi_env env, napi_callback_info info) { return NULL; } -napi_value testNapiErrorCleanup(napi_env env, napi_callback_info info) { +static napi_value testNapiErrorCleanup(napi_env env, napi_callback_info info) { const napi_extended_error_info *error_info = 0; NAPI_CALL(env, napi_get_last_error_info(env, &error_info)); @@ -110,7 +110,7 @@ napi_value testNapiErrorCleanup(napi_env env, napi_callback_info info) { return result; } -napi_value testNapiTypeof(napi_env env, napi_callback_info info) { +static napi_value testNapiTypeof(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -157,7 +157,7 @@ static void deref_item(napi_env env, void* data, void* hint) { deref_item_called = true; } -napi_value deref_item_was_called(napi_env env, napi_callback_info info) { +static napi_value deref_item_was_called(napi_env env, napi_callback_info info) { napi_value it_was_called; NAPI_CALL(env, napi_get_boolean(env, deref_item_called, &it_was_called)); @@ -165,7 +165,7 @@ napi_value deref_item_was_called(napi_env env, napi_callback_info info) { return it_was_called; } -napi_value wrap(napi_env env, napi_callback_info info) { +static napi_value wrap(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value to_wrap; @@ -177,7 +177,7 @@ napi_value wrap(napi_env env, napi_callback_info info) { return NULL; } -napi_value remove_wrap(napi_env env, napi_callback_info info) { +static napi_value remove_wrap(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value wrapped; void* data; @@ -193,7 +193,7 @@ static void test_finalize(napi_env env, void* data, void* hint) { finalize_called = true; } -napi_value test_finalize_wrap(napi_env env, napi_callback_info info) { +static napi_value test_finalize_wrap(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value js_object; @@ -203,7 +203,7 @@ napi_value test_finalize_wrap(napi_env env, napi_callback_info info) { return NULL; } -napi_value finalize_was_called(napi_env env, napi_callback_info info) { +static napi_value finalize_was_called(napi_env env, napi_callback_info info) { napi_value it_was_called; NAPI_CALL(env, napi_get_boolean(env, finalize_called, &it_was_called)); @@ -211,7 +211,7 @@ napi_value finalize_was_called(napi_env env, napi_callback_info info) { return it_was_called; } -napi_value testAdjustExternalMemory(napi_env env, napi_callback_info info) { +static napi_value testAdjustExternalMemory(napi_env env, napi_callback_info info) { napi_value result; int64_t adjustedValue; @@ -221,7 +221,7 @@ napi_value testAdjustExternalMemory(napi_env env, napi_callback_info info) { return result; } -napi_value testNapiRun(napi_env env, napi_callback_info info) { +static napi_value testNapiRun(napi_env env, napi_callback_info info) { napi_value script, result; size_t argc = 1; @@ -232,7 +232,7 @@ napi_value testNapiRun(napi_env env, napi_callback_info info) { return result; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("testStrictEquals", testStrictEquals), DECLARE_NAPI_PROPERTY("testGetPrototype", testGetPrototype), diff --git a/test/addons-napi/test_handle_scope/test_handle_scope.c b/test/addons-napi/test_handle_scope/test_handle_scope.c index 31efbcf3dd4d7b..76f31f7882b61b 100644 --- a/test/addons-napi/test_handle_scope/test_handle_scope.c +++ b/test/addons-napi/test_handle_scope/test_handle_scope.c @@ -7,7 +7,7 @@ // the right right thing would be quite hard so we keep it // simple for now. -napi_value NewScope(napi_env env, napi_callback_info info) { +static napi_value NewScope(napi_env env, napi_callback_info info) { napi_handle_scope scope; napi_value output = NULL; @@ -17,7 +17,7 @@ napi_value NewScope(napi_env env, napi_callback_info info) { return NULL; } -napi_value NewScopeEscape(napi_env env, napi_callback_info info) { +static napi_value NewScopeEscape(napi_env env, napi_callback_info info) { napi_escapable_handle_scope scope; napi_value output = NULL; napi_value escapee = NULL; @@ -29,7 +29,7 @@ napi_value NewScopeEscape(napi_env env, napi_callback_info info) { return escapee; } -napi_value NewScopeEscapeTwice(napi_env env, napi_callback_info info) { +static napi_value NewScopeEscapeTwice(napi_env env, napi_callback_info info) { napi_escapable_handle_scope scope; napi_value output = NULL; napi_value escapee = NULL; @@ -44,7 +44,7 @@ napi_value NewScopeEscapeTwice(napi_env env, napi_callback_info info) { return NULL; } -napi_value NewScopeWithException(napi_env env, napi_callback_info info) { +static napi_value NewScopeWithException(napi_env env, napi_callback_info info) { napi_handle_scope scope; size_t argc; napi_value exception_function; @@ -68,7 +68,7 @@ napi_value NewScopeWithException(napi_env env, napi_callback_info info) { return NULL; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor properties[] = { DECLARE_NAPI_PROPERTY("NewScope", NewScope), DECLARE_NAPI_PROPERTY("NewScopeEscape", NewScopeEscape), diff --git a/test/addons-napi/test_make_callback/binding.c b/test/addons-napi/test_make_callback/binding.c index 23750f56b838fc..8eedd5b1b3b167 100644 --- a/test/addons-napi/test_make_callback/binding.c +++ b/test/addons-napi/test_make_callback/binding.c @@ -3,8 +3,7 @@ #define MAX_ARGUMENTS 10 -static -napi_value MakeCallback(napi_env env, napi_callback_info info) { +static napi_value MakeCallback(napi_env env, napi_callback_info info) { size_t argc = MAX_ARGUMENTS; size_t n; napi_value args[MAX_ARGUMENTS]; diff --git a/test/addons-napi/test_new_target/binding.c b/test/addons-napi/test_new_target/binding.c index a74d4bb2f877be..0c542ebaba693d 100644 --- a/test/addons-napi/test_new_target/binding.c +++ b/test/addons-napi/test_new_target/binding.c @@ -1,7 +1,7 @@ #include #include "../common.h" -napi_value BaseClass(napi_env env, napi_callback_info info) { +static napi_value BaseClass(napi_env env, napi_callback_info info) { napi_value newTargetArg; NAPI_CALL(env, napi_get_new_target(env, info, &newTargetArg)); napi_value thisArg; @@ -22,7 +22,7 @@ napi_value BaseClass(napi_env env, napi_callback_info info) { return thisArg; } -napi_value Constructor(napi_env env, napi_callback_info info) { +static napi_value Constructor(napi_env env, napi_callback_info info) { bool result; napi_value newTargetArg; NAPI_CALL(env, napi_get_new_target(env, info, &newTargetArg)); @@ -45,7 +45,7 @@ napi_value Constructor(napi_env env, napi_callback_info info) { return thisArg; } -napi_value OrdinaryFunction(napi_env env, napi_callback_info info) { +static napi_value OrdinaryFunction(napi_env env, napi_callback_info info) { napi_value newTargetArg; NAPI_CALL(env, napi_get_new_target(env, info, &newTargetArg)); @@ -56,7 +56,7 @@ napi_value OrdinaryFunction(napi_env env, napi_callback_info info) { return _true; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { const napi_property_descriptor desc[] = { DECLARE_NAPI_PROPERTY("BaseClass", BaseClass), DECLARE_NAPI_PROPERTY("OrdinaryFunction", OrdinaryFunction), diff --git a/test/addons-napi/test_number/test_number.c b/test/addons-napi/test_number/test_number.c index a1a70950083324..19b0ae83f051df 100644 --- a/test/addons-napi/test_number/test_number.c +++ b/test/addons-napi/test_number/test_number.c @@ -1,7 +1,7 @@ #include #include "../common.h" -napi_value Test(napi_env env, napi_callback_info info) { +static napi_value Test(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -23,7 +23,7 @@ napi_value Test(napi_env env, napi_callback_info info) { return output; } -napi_value TestInt32Truncation(napi_env env, napi_callback_info info) { +static napi_value TestInt32Truncation(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -45,7 +45,7 @@ napi_value TestInt32Truncation(napi_env env, napi_callback_info info) { return output; } -napi_value TestInt64Truncation(napi_env env, napi_callback_info info) { +static napi_value TestInt64Truncation(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -67,7 +67,7 @@ napi_value TestInt64Truncation(napi_env env, napi_callback_info info) { return output; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("Test", Test), DECLARE_NAPI_PROPERTY("TestInt32Truncation", TestInt32Truncation), diff --git a/test/addons-napi/test_object/test_object.c b/test/addons-napi/test_object/test_object.c index ccf1573114a6f1..046f71fa414735 100644 --- a/test/addons-napi/test_object/test_object.c +++ b/test/addons-napi/test_object/test_object.c @@ -4,7 +4,7 @@ static int test_value = 3; -napi_value Get(napi_env env, napi_callback_info info) { +static napi_value Get(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -30,7 +30,7 @@ napi_value Get(napi_env env, napi_callback_info info) { return output; } -napi_value Set(napi_env env, napi_callback_info info) { +static napi_value Set(napi_env env, napi_callback_info info) { size_t argc = 3; napi_value args[3]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -57,7 +57,7 @@ napi_value Set(napi_env env, napi_callback_info info) { return valuetrue; } -napi_value Has(napi_env env, napi_callback_info info) { +static napi_value Has(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -85,7 +85,7 @@ napi_value Has(napi_env env, napi_callback_info info) { return ret; } -napi_value HasOwn(napi_env env, napi_callback_info info) { +static napi_value HasOwn(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -113,7 +113,7 @@ napi_value HasOwn(napi_env env, napi_callback_info info) { return ret; } -napi_value Delete(napi_env env, napi_callback_info info) { +static napi_value Delete(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; @@ -138,7 +138,7 @@ napi_value Delete(napi_env env, napi_callback_info info) { return ret; } -napi_value New(napi_env env, napi_callback_info info) { +static napi_value New(napi_env env, napi_callback_info info) { napi_value ret; NAPI_CALL(env, napi_create_object(env, &ret)); @@ -157,7 +157,7 @@ napi_value New(napi_env env, napi_callback_info info) { return ret; } -napi_value Inflate(napi_env env, napi_callback_info info) { +static napi_value Inflate(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -193,7 +193,7 @@ napi_value Inflate(napi_env env, napi_callback_info info) { return obj; } -napi_value Wrap(napi_env env, napi_callback_info info) { +static napi_value Wrap(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value arg; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &arg, NULL, NULL)); @@ -202,7 +202,7 @@ napi_value Wrap(napi_env env, napi_callback_info info) { return NULL; } -napi_value Unwrap(napi_env env, napi_callback_info info) { +static napi_value Unwrap(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value arg; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &arg, NULL, NULL)); @@ -216,7 +216,7 @@ napi_value Unwrap(napi_env env, napi_callback_info info) { return result; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("Get", Get), DECLARE_NAPI_PROPERTY("Set", Set), diff --git a/test/addons-napi/test_promise/test_promise.c b/test/addons-napi/test_promise/test_promise.c index aa89c022bc1a4a..3e2ec48572af4c 100644 --- a/test/addons-napi/test_promise/test_promise.c +++ b/test/addons-napi/test_promise/test_promise.c @@ -3,7 +3,7 @@ napi_deferred deferred = NULL; -napi_value createPromise(napi_env env, napi_callback_info info) { +static napi_value createPromise(napi_env env, napi_callback_info info) { napi_value promise; // We do not overwrite an existing deferred. @@ -16,7 +16,8 @@ napi_value createPromise(napi_env env, napi_callback_info info) { return promise; } -napi_value concludeCurrentPromise(napi_env env, napi_callback_info info) { +static napi_value +concludeCurrentPromise(napi_env env, napi_callback_info info) { napi_value argv[2]; size_t argc = 2; bool resolution; @@ -34,7 +35,7 @@ napi_value concludeCurrentPromise(napi_env env, napi_callback_info info) { return NULL; } -napi_value isPromise(napi_env env, napi_callback_info info) { +static napi_value isPromise(napi_env env, napi_callback_info info) { napi_value promise, result; size_t argc = 1; bool is_promise; @@ -46,7 +47,7 @@ napi_value isPromise(napi_env env, napi_callback_info info) { return result; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("createPromise", createPromise), DECLARE_NAPI_PROPERTY("concludeCurrentPromise", concludeCurrentPromise), diff --git a/test/addons-napi/test_properties/test_properties.c b/test/addons-napi/test_properties/test_properties.c index a95c7013c2cabb..2754812f4dad27 100644 --- a/test/addons-napi/test_properties/test_properties.c +++ b/test/addons-napi/test_properties/test_properties.c @@ -3,7 +3,7 @@ static double value_ = 1; -napi_value GetValue(napi_env env, napi_callback_info info) { +static napi_value GetValue(napi_env env, napi_callback_info info) { size_t argc = 0; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, NULL, NULL, NULL)); @@ -15,7 +15,7 @@ napi_value GetValue(napi_env env, napi_callback_info info) { return number; } -napi_value SetValue(napi_env env, napi_callback_info info) { +static napi_value SetValue(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -27,7 +27,7 @@ napi_value SetValue(napi_env env, napi_callback_info info) { return NULL; } -napi_value Echo(napi_env env, napi_callback_info info) { +static napi_value Echo(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -37,7 +37,7 @@ napi_value Echo(napi_env env, napi_callback_info info) { return args[0]; } -napi_value HasNamedProperty(napi_env env, napi_callback_info info) { +static napi_value HasNamedProperty(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -59,7 +59,7 @@ napi_value HasNamedProperty(napi_env env, napi_callback_info info) { return result; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_value number; NAPI_CALL(env, napi_create_double(env, value_, &number)); diff --git a/test/addons-napi/test_reference/test_reference.c b/test/addons-napi/test_reference/test_reference.c index f34adc6693b6fe..75abc49ad3280e 100644 --- a/test/addons-napi/test_reference/test_reference.c +++ b/test/addons-napi/test_reference/test_reference.c @@ -5,20 +5,20 @@ static int test_value = 1; static int finalize_count = 0; static napi_ref test_reference = NULL; -napi_value GetFinalizeCount(napi_env env, napi_callback_info info) { +static napi_value GetFinalizeCount(napi_env env, napi_callback_info info) { napi_value result; NAPI_CALL(env, napi_create_int32(env, finalize_count, &result)); return result; } -void FinalizeExternal(napi_env env, void* data, void* hint) { +static void FinalizeExternal(napi_env env, void* data, void* hint) { int *actual_value = data; NAPI_ASSERT_RETURN_VOID(env, actual_value == &test_value, "The correct pointer was passed to the finalizer"); finalize_count++; } -napi_value CreateExternal(napi_env env, napi_callback_info info) { +static napi_value CreateExternal(napi_env env, napi_callback_info info) { int* data = &test_value; napi_value result; @@ -33,7 +33,8 @@ napi_value CreateExternal(napi_env env, napi_callback_info info) { return result; } -napi_value CreateExternalWithFinalize(napi_env env, napi_callback_info info) { +static napi_value +CreateExternalWithFinalize(napi_env env, napi_callback_info info) { napi_value result; NAPI_CALL(env, napi_create_external(env, @@ -46,7 +47,7 @@ napi_value CreateExternalWithFinalize(napi_env env, napi_callback_info info) { return result; } -napi_value CheckExternal(napi_env env, napi_callback_info info) { +static napi_value CheckExternal(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value arg; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &arg, NULL, NULL)); @@ -67,7 +68,7 @@ napi_value CheckExternal(napi_env env, napi_callback_info info) { return NULL; } -napi_value CreateReference(napi_env env, napi_callback_info info) { +static napi_value CreateReference(napi_env env, napi_callback_info info) { NAPI_ASSERT(env, test_reference == NULL, "The test allows only one reference at a time."); @@ -88,7 +89,7 @@ napi_value CreateReference(napi_env env, napi_callback_info info) { return NULL; } -napi_value DeleteReference(napi_env env, napi_callback_info info) { +static napi_value DeleteReference(napi_env env, napi_callback_info info) { NAPI_ASSERT(env, test_reference != NULL, "A reference must have been created."); @@ -97,7 +98,7 @@ napi_value DeleteReference(napi_env env, napi_callback_info info) { return NULL; } -napi_value IncrementRefcount(napi_env env, napi_callback_info info) { +static napi_value IncrementRefcount(napi_env env, napi_callback_info info) { NAPI_ASSERT(env, test_reference != NULL, "A reference must have been created."); @@ -109,7 +110,7 @@ napi_value IncrementRefcount(napi_env env, napi_callback_info info) { return result; } -napi_value DecrementRefcount(napi_env env, napi_callback_info info) { +static napi_value DecrementRefcount(napi_env env, napi_callback_info info) { NAPI_ASSERT(env, test_reference != NULL, "A reference must have been created."); @@ -121,7 +122,7 @@ napi_value DecrementRefcount(napi_env env, napi_callback_info info) { return result; } -napi_value GetReferenceValue(napi_env env, napi_callback_info info) { +static napi_value GetReferenceValue(napi_env env, napi_callback_info info) { NAPI_ASSERT(env, test_reference != NULL, "A reference must have been created."); @@ -130,7 +131,7 @@ napi_value GetReferenceValue(napi_env env, napi_callback_info info) { return result; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_GETTER("finalizeCount", GetFinalizeCount), DECLARE_NAPI_PROPERTY("createExternal", CreateExternal), diff --git a/test/addons-napi/test_string/test_string.c b/test/addons-napi/test_string/test_string.c index 99a3f7d3545a20..4e6da7bf86849f 100644 --- a/test/addons-napi/test_string/test_string.c +++ b/test/addons-napi/test_string/test_string.c @@ -2,7 +2,7 @@ #include #include "../common.h" -napi_value TestLatin1(napi_env env, napi_callback_info info) { +static napi_value TestLatin1(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -28,7 +28,7 @@ napi_value TestLatin1(napi_env env, napi_callback_info info) { return output; } -napi_value TestUtf8(napi_env env, napi_callback_info info) { +static napi_value TestUtf8(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -54,7 +54,7 @@ napi_value TestUtf8(napi_env env, napi_callback_info info) { return output; } -napi_value TestUtf16(napi_env env, napi_callback_info info) { +static napi_value TestUtf16(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -80,7 +80,8 @@ napi_value TestUtf16(napi_env env, napi_callback_info info) { return output; } -napi_value TestLatin1Insufficient(napi_env env, napi_callback_info info) { +static napi_value +TestLatin1Insufficient(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -106,7 +107,7 @@ napi_value TestLatin1Insufficient(napi_env env, napi_callback_info info) { return output; } -napi_value TestUtf8Insufficient(napi_env env, napi_callback_info info) { +static napi_value TestUtf8Insufficient(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -132,7 +133,7 @@ napi_value TestUtf8Insufficient(napi_env env, napi_callback_info info) { return output; } -napi_value TestUtf16Insufficient(napi_env env, napi_callback_info info) { +static napi_value TestUtf16Insufficient(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -158,7 +159,7 @@ napi_value TestUtf16Insufficient(napi_env env, napi_callback_info info) { return output; } -napi_value Utf16Length(napi_env env, napi_callback_info info) { +static napi_value Utf16Length(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -180,7 +181,7 @@ napi_value Utf16Length(napi_env env, napi_callback_info info) { return output; } -napi_value Utf8Length(napi_env env, napi_callback_info info) { +static napi_value Utf8Length(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -202,7 +203,7 @@ napi_value Utf8Length(napi_env env, napi_callback_info info) { return output; } -napi_value TestLargeUtf8(napi_env env, napi_callback_info info) { +static napi_value TestLargeUtf8(napi_env env, napi_callback_info info) { napi_value output; if (SIZE_MAX > INT_MAX) { NAPI_CALL(env, napi_create_string_utf8(env, "", ((size_t)INT_MAX) + 1, &output)); @@ -215,7 +216,7 @@ napi_value TestLargeUtf8(napi_env env, napi_callback_info info) { return output; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor properties[] = { DECLARE_NAPI_PROPERTY("TestLatin1", TestLatin1), DECLARE_NAPI_PROPERTY("TestLatin1Insufficient", TestLatin1Insufficient), diff --git a/test/addons-napi/test_symbol/test_symbol.c b/test/addons-napi/test_symbol/test_symbol.c index c91b6ae54f4932..e2c969b3b6aba6 100644 --- a/test/addons-napi/test_symbol/test_symbol.c +++ b/test/addons-napi/test_symbol/test_symbol.c @@ -1,32 +1,7 @@ #include #include "../common.h" -napi_value Test(napi_env env, napi_callback_info info) { - size_t argc = 1; - napi_value args[1]; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); - - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); - - napi_valuetype valuetype; - NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); - - NAPI_ASSERT(env, valuetype == napi_symbol, - "Wrong type of arguments. Expects a symbol."); - - char buffer[128]; - size_t buffer_size = 128; - - NAPI_CALL(env, napi_get_value_string_utf8( - env, args[0], buffer, buffer_size, NULL)); - - napi_value output; - NAPI_CALL(env, napi_create_string_utf8(env, buffer, buffer_size, &output)); - - return output; -} - -napi_value New(napi_env env, napi_callback_info info) { +static napi_value New(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value args[1]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -48,7 +23,7 @@ napi_value New(napi_env env, napi_callback_info info) { return symbol; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor properties[] = { DECLARE_NAPI_PROPERTY("New", New), }; diff --git a/test/addons-napi/test_typedarray/test_typedarray.c b/test/addons-napi/test_typedarray/test_typedarray.c index 2758a6f53298fe..a0ac02665864f1 100644 --- a/test/addons-napi/test_typedarray/test_typedarray.c +++ b/test/addons-napi/test_typedarray/test_typedarray.c @@ -2,7 +2,7 @@ #include #include "../common.h" -napi_value Multiply(napi_env env, napi_callback_info info) { +static napi_value Multiply(napi_env env, napi_callback_info info) { size_t argc = 2; napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -73,7 +73,7 @@ napi_value Multiply(napi_env env, napi_callback_info info) { return output_array; } -napi_value External(napi_env env, napi_callback_info info) { +static napi_value External(napi_env env, napi_callback_info info) { static int8_t externalData[] = {0, 1, 2}; napi_value output_buffer; @@ -96,7 +96,7 @@ napi_value External(napi_env env, napi_callback_info info) { return output_array; } -napi_value CreateTypedArray(napi_env env, napi_callback_info info) { +static napi_value CreateTypedArray(napi_env env, napi_callback_info info) { size_t argc = 4; napi_value args[4]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); @@ -165,7 +165,7 @@ napi_value CreateTypedArray(napi_env env, napi_callback_info info) { return output_array; } -napi_value Init(napi_env env, napi_value exports) { +static napi_value Init(napi_env env, napi_value exports) { napi_property_descriptor descriptors[] = { DECLARE_NAPI_PROPERTY("Multiply", Multiply), DECLARE_NAPI_PROPERTY("External", External), diff --git a/test/cctest/test_node_postmortem_metadata.cc b/test/cctest/test_node_postmortem_metadata.cc index 335f3e85812547..f69df3ed227717 100644 --- a/test/cctest/test_node_postmortem_metadata.cc +++ b/test/cctest/test_node_postmortem_metadata.cc @@ -72,7 +72,11 @@ TEST_F(DebugSymbolsTest, BaseObjectPersistentHandle) { const Argv argv; Env env{handle_scope, argv}; - v8::Local object = v8::Object::New(isolate_); + v8::Local obj_templ = v8::ObjectTemplate::New(isolate_); + obj_templ->SetInternalFieldCount(1); + + v8::Local object = + obj_templ->NewInstance(env.context()).ToLocalChecked(); node::BaseObject obj(*env, object); auto expected = reinterpret_cast(&obj.persistent()); diff --git a/test/cctest/test_platform.cc b/test/cctest/test_platform.cc new file mode 100644 index 00000000000000..876547480b7032 --- /dev/null +++ b/test/cctest/test_platform.cc @@ -0,0 +1,55 @@ +#include "node_internals.h" +#include "libplatform/libplatform.h" + +#include +#include "gtest/gtest.h" +#include "node_test_fixture.h" + +// This task increments the given run counter and reposts itself until the +// repost counter reaches zero. +class RepostingTask : public v8::Task { + public: + explicit RepostingTask(int repost_count, + int* run_count, + v8::Isolate* isolate, + node::NodePlatform* platform) + : repost_count_(repost_count), + run_count_(run_count), + isolate_(isolate), + platform_(platform) {} + + // v8::Task implementation + void Run() final { + ++*run_count_; + if (repost_count_ > 0) { + --repost_count_; + platform_->CallOnForegroundThread(isolate_, + new RepostingTask(repost_count_, run_count_, isolate_, platform_)); + } + } + + private: + int repost_count_; + int* run_count_; + v8::Isolate* isolate_; + node::NodePlatform* platform_; +}; + +class PlatformTest : public EnvironmentTestFixture {}; + +TEST_F(PlatformTest, SkipNewTasksInFlushForegroundTasks) { + v8::Isolate::Scope isolate_scope(isolate_); + const v8::HandleScope handle_scope(isolate_); + const Argv argv; + Env env {handle_scope, argv}; + int run_count = 0; + platform->CallOnForegroundThread( + isolate_, new RepostingTask(2, &run_count, isolate_, platform.get())); + EXPECT_TRUE(platform->FlushForegroundTasks(isolate_)); + EXPECT_EQ(1, run_count); + EXPECT_TRUE(platform->FlushForegroundTasks(isolate_)); + EXPECT_EQ(2, run_count); + EXPECT_TRUE(platform->FlushForegroundTasks(isolate_)); + EXPECT_EQ(3, run_count); + EXPECT_FALSE(platform->FlushForegroundTasks(isolate_)); +} diff --git a/test/common/index.js b/test/common/index.js index 95bb8dd804881f..07c0992d65e8d2 100644 --- a/test/common/index.js +++ b/test/common/index.js @@ -494,7 +494,7 @@ exports.fileExists = function(pathname) { exports.skipIfEslintMissing = function() { if (!exports.fileExists( - path.join('..', '..', 'tools', 'node_modules', 'eslint') + path.join(__dirname, '..', '..', 'tools', 'node_modules', 'eslint') )) { exports.skip('missing ESLint'); } @@ -518,6 +518,8 @@ exports.canCreateSymLink = function() { return false; } } + // On non-Windows platforms, this always returns `true` + return true; }; exports.getCallSite = function getCallSite(top) { @@ -708,6 +710,11 @@ exports.expectsError = function expectsError(fn, settings, exact) { } function innerFn(error) { + if (arguments.length !== 1) { + // Do not use `assert.strictEqual()` to prevent `util.inspect` from + // always being called. + assert.fail(`Expected one argument, got ${util.inspect(arguments)}`); + } const descriptor = Object.getOwnPropertyDescriptor(error, 'message'); assert.strictEqual(descriptor.enumerable, false, 'The error message should be non-enumerable'); diff --git a/test/common/inspector-helper.js b/test/common/inspector-helper.js index 1bc16e3714cffa..e590349f9c2b71 100644 --- a/test/common/inspector-helper.js +++ b/test/common/inspector-helper.js @@ -154,8 +154,9 @@ class InspectorSession { return this._terminationPromise; } - disconnect() { + async disconnect() { this._socket.destroy(); + return this.waitForServerDisconnect(); } _onMessage(message) { @@ -444,6 +445,7 @@ class NodeInstance { kill() { this._process.kill(); + return this.expectShutdown(); } scriptPath() { diff --git a/test/doctool/test-doctool-html.js b/test/doctool/test-doctool-html.js index bd1c5ddecac321..91a18d536a6992 100644 --- a/test/doctool/test-doctool-html.js +++ b/test/doctool/test-doctool-html.js @@ -10,7 +10,6 @@ try { const assert = require('assert'); const fs = require('fs'); -const path = require('path'); const fixtures = require('../common/fixtures'); const processIncludes = require('../../tools/doc/preprocess.js'); const html = require('../../tools/doc/html.js'); @@ -30,11 +29,11 @@ const testData = [ file: fixtures.path('order_of_end_tags_5873.md'), html: '

ClassMethod: Buffer.from(array) ' + '#

' }, { file: fixtures.path('doc_with_yaml.md'), @@ -107,7 +106,6 @@ testData.forEach((item) => { { input: preprocessed, filename: 'foo', - template: path.resolve(__dirname, '../../doc/template.html'), nodeVersion: process.version, analytics: item.analyticsId, }, diff --git a/test/fixtures/person-large.jpg b/test/fixtures/person-large.jpg new file mode 100644 index 00000000000000..3d0d0af42375c3 Binary files /dev/null and b/test/fixtures/person-large.jpg differ diff --git a/test/parallel/test-accessor-properties.js b/test/parallel/test-accessor-properties.js index 713be7eac203a6..064ef844c38e6c 100644 --- a/test/parallel/test-accessor-properties.js +++ b/test/parallel/test-accessor-properties.js @@ -1,6 +1,6 @@ 'use strict'; -const common = require('../common'); +require('../common'); // This tests that the accessor properties do not raise assertions // when called with incompatible receivers. @@ -50,19 +50,4 @@ const UDP = process.binding('udp_wrap').UDP; typeof Object.getOwnPropertyDescriptor(UDP.prototype, 'fd'), 'object' ); - - if (common.hasCrypto) { // eslint-disable-line node-core/crypto-check - // There are accessor properties in crypto too - const crypto = process.binding('crypto'); - - assert.throws(() => { - crypto.SecureContext.prototype._external; - }, TypeError); - - assert.strictEqual( - typeof Object.getOwnPropertyDescriptor( - crypto.SecureContext.prototype, '_external'), - 'object' - ); - } } diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index b871cd7265d288..d892122ed62ff2 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -599,14 +599,13 @@ assert.throws( }); // notDeepEqual tests - message = 'Identical input passed to notDeepStrictEqual:\n\n' + - ' [\n 1\n ]\n'; + message = 'Identical input passed to notDeepStrictEqual:\n\n[\n 1\n]\n'; assert.throws( () => assert.notDeepEqual([1], [1]), { message }); message = 'Identical input passed to notDeepStrictEqual:' + - `\n\n [${'\n 1,'.repeat(25)}\n ...\n`; + `\n\n[${'\n 1,'.repeat(25)}\n...\n`; const data = Array(31).fill(1); assert.throws( () => assert.notDeepEqual(data, data), @@ -901,7 +900,7 @@ assert.throws(() => { throw null; }, 'foo'); assert.throws( () => assert.strictEqual([], []), { - message: 'Input object identical but not reference equal:\n\n []\n' + message: 'Input objects identical but not reference equal:\n\n[]\n' } ); diff --git a/test/parallel/test-benchmark-util.js b/test/parallel/test-benchmark-util.js index 9a6ae370b7d312..838e51daac26b4 100644 --- a/test/parallel/test-benchmark-util.js +++ b/test/parallel/test-benchmark-util.js @@ -10,6 +10,8 @@ runBenchmark('util', 'method=Array', 'n=1', 'option=none', + 'pos=start', + 'size=1', 'type=', 'version=native'], { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); diff --git a/test/parallel/test-benchmark-zlib.js b/test/parallel/test-benchmark-zlib.js index 350d05552cda39..25b7d1a4d5f905 100644 --- a/test/parallel/test-benchmark-zlib.js +++ b/test/parallel/test-benchmark-zlib.js @@ -9,5 +9,10 @@ runBenchmark('zlib', 'method=deflate', 'n=1', 'options=true', - 'type=Deflate' - ]); + 'type=Deflate', + 'inputLen=1024', + 'duration=0.001' + ], + { + 'NODEJS_BENCHMARK_ZERO_ALLOWED': 1 + }); diff --git a/test/parallel/test-buffer-constructor-deprecation-error.js b/test/parallel/test-buffer-constructor-deprecation-error.js new file mode 100644 index 00000000000000..46535e103b33ee --- /dev/null +++ b/test/parallel/test-buffer-constructor-deprecation-error.js @@ -0,0 +1,17 @@ +'use strict'; + +const common = require('../common'); + +const bufferWarning = 'Buffer() is deprecated due to security and usability ' + + 'issues. Please use the Buffer.alloc(), ' + + 'Buffer.allocUnsafe(), or Buffer.from() methods instead.'; + +common.expectWarning('DeprecationWarning', bufferWarning, 'DEP0005'); + +// This is used to make sure that a warning is only emitted once even though +// `new Buffer()` is called twice. +process.on('warning', common.mustCall()); + +Error.prepareStackTrace = (err, trace) => new Buffer(10); + +new Error().stack; diff --git a/test/parallel/test-buffer-fill.js b/test/parallel/test-buffer-fill.js index b2f14c3e428e55..4eef0edefcbb22 100644 --- a/test/parallel/test-buffer-fill.js +++ b/test/parallel/test-buffer-fill.js @@ -2,7 +2,7 @@ 'use strict'; const common = require('../common'); const assert = require('assert'); -const errors = require('internal/errors'); +const { codes: { ERR_INDEX_OUT_OF_RANGE } } = require('internal/errors'); const SIZE = 28; const buf1 = Buffer.allocUnsafe(SIZE); @@ -214,13 +214,11 @@ function genBuffer(size, args) { return b.fill(0).fill.apply(b, args); } - function bufReset() { buf1.fill(0); buf2.fill(0); } - // This is mostly accurate. Except write() won't write partial bytes to the // string while fill() blindly copies bytes into memory. To account for that an // error will be thrown if not all the data can be written, and the SIZE has @@ -237,8 +235,9 @@ function writeToFill(string, offset, end, encoding) { end = buf2.length; } + // Should never be reached. if (offset < 0 || end > buf2.length) - throw new errors.RangeError('ERR_INDEX_OUT_OF_RANGE'); + throw new ERR_INDEX_OUT_OF_RANGE(); if (end <= offset) return buf2; @@ -266,7 +265,6 @@ function writeToFill(string, offset, end, encoding) { return buf2; } - function testBufs(string, offset, length, encoding) { bufReset(); buf1.fill.apply(buf1, arguments); diff --git a/test/parallel/test-buffer-writedouble.js b/test/parallel/test-buffer-writedouble.js index 0dc26dbd3b23f1..8a17d536909dce 100644 --- a/test/parallel/test-buffer-writedouble.js +++ b/test/parallel/test-buffer-writedouble.js @@ -67,10 +67,19 @@ assert.strictEqual(buffer.readDoubleLE(8), -Infinity); buffer.writeDoubleBE(NaN, 0); buffer.writeDoubleLE(NaN, 8); -assert.ok(buffer.equals(new Uint8Array([ - 0x7F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x7F -]))); +// JS only knows a single NaN but there exist two platform specific +// implementations. Therefore, allow both quiet and signalling NaNs. +if (buffer[1] === 0xF7) { + assert.ok(buffer.equals(new Uint8Array([ + 0x7F, 0xF7, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF7, 0x7F + ]))); +} else { + assert.ok(buffer.equals(new Uint8Array([ + 0x7F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x7F + ]))); +} assert.ok(Number.isNaN(buffer.readDoubleBE(0))); assert.ok(Number.isNaN(buffer.readDoubleLE(8))); diff --git a/test/parallel/test-buffer-writefloat.js b/test/parallel/test-buffer-writefloat.js index 77dd4793e5e749..4c2c7539eaafcb 100644 --- a/test/parallel/test-buffer-writefloat.js +++ b/test/parallel/test-buffer-writefloat.js @@ -50,8 +50,18 @@ assert.strictEqual(buffer.readFloatLE(4), -Infinity); buffer.writeFloatBE(NaN, 0); buffer.writeFloatLE(NaN, 4); -assert.ok(buffer.equals( - new Uint8Array([ 0x7F, 0xC0, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x7F ]))); + +// JS only knows a single NaN but there exist two platform specific +// implementations. Therefore, allow both quiet and signalling NaNs. +if (buffer[1] === 0xBF) { + assert.ok( + buffer.equals(new Uint8Array( + [ 0x7F, 0xBF, 0xFF, 0xFF, 0xFF, 0xFF, 0xBF, 0x7F ]))); +} else { + assert.ok( + buffer.equals(new Uint8Array( + [ 0x7F, 0xC0, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x7F ]))); +} assert.ok(Number.isNaN(buffer.readFloatBE(0))); assert.ok(Number.isNaN(buffer.readFloatLE(4))); diff --git a/test/parallel/test-child-process-exec-kill-throws.js b/test/parallel/test-child-process-exec-kill-throws.js index 35e5ff8b7bce0f..d6a0d4da19eae7 100644 --- a/test/parallel/test-child-process-exec-kill-throws.js +++ b/test/parallel/test-child-process-exec-kill-throws.js @@ -19,7 +19,8 @@ if (process.argv[2] === 'child') { }; const cmd = `"${process.execPath}" "${__filename}" child`; - const options = { maxBuffer: 0 }; + const options = { maxBuffer: 0, killSignal: 'SIGKILL' }; + const child = cp.exec(cmd, options, common.mustCall((err, stdout, stderr) => { // Verify that if ChildProcess#kill() throws, the error is reported. assert.strictEqual(err.message, 'mock error', err); diff --git a/test/parallel/test-child-process-fork-exec-path.js b/test/parallel/test-child-process-fork-exec-path.js index 8b94ef62a93bc8..cabd8893475630 100644 --- a/test/parallel/test-child-process-fork-exec-path.js +++ b/test/parallel/test-child-process-fork-exec-path.js @@ -23,6 +23,7 @@ const common = require('../common'); const assert = require('assert'); const fs = require('fs'); +const { COPYFILE_FICLONE } = fs.constants; const path = require('path'); const tmpdir = require('../common/tmpdir'); const msg = { test: 'this' }; @@ -44,7 +45,7 @@ if (process.env.FORK) { } catch (e) { if (e.code !== 'ENOENT') throw e; } - fs.writeFileSync(copyPath, fs.readFileSync(nodePath)); + fs.copyFileSync(nodePath, copyPath, COPYFILE_FICLONE); fs.chmodSync(copyPath, '0755'); // slow but simple diff --git a/test/parallel/test-child-process-http-socket-leak.js b/test/parallel/test-child-process-http-socket-leak.js new file mode 100644 index 00000000000000..30d8601b840626 --- /dev/null +++ b/test/parallel/test-child-process-http-socket-leak.js @@ -0,0 +1,56 @@ +// Flags: --expose_internals + +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const { fork } = require('child_process'); +const http = require('http'); +const { kTimeout } = require('internal/timers'); + +if (process.argv[2] === 'child') { + process.once('message', (req, socket) => { + const res = new http.ServerResponse(req); + res.assignSocket(socket); + res.end(); + }); + + process.send('ready'); + return; +} + +let child; +let socket; + +const server = http.createServer(common.mustCall((req, res) => { + const r = { + method: req.method, + headers: req.headers, + path: req.path, + httpVersionMajor: req.httpVersionMajor, + query: req.query, + }; + + socket = res.socket; + child.send(r, socket); + server.close(); +})); + +server.listen(0, common.mustCall(() => { + child = fork(__filename, [ 'child' ]); + child.once('message', (msg) => { + assert.strictEqual(msg, 'ready'); + const req = http.request({ + port: server.address().port, + }, common.mustCall((res) => { + res.on('data', () => {}); + res.on('end', common.mustCall(() => { + assert.strictEqual(socket[kTimeout]._idleTimeout, -1); + assert.strictEqual(socket.parser, null); + assert.strictEqual(socket._httpMessage, null); + })); + })); + + req.end(); + }); +})); diff --git a/test/parallel/test-cli-node-options.js b/test/parallel/test-cli-node-options.js index 8eae27b1a2a3a2..2383935f4bb7a3 100644 --- a/test/parallel/test-cli-node-options.js +++ b/test/parallel/test-cli-node-options.js @@ -32,7 +32,7 @@ if (!common.isWindows) { expect('--perf-basic-prof', 'B\n'); } -if (common.isLinux && ['arm', 'x64', 'mips'].includes(process.arch)) { +if (common.isLinux && ['arm', 'x64'].includes(process.arch)) { // PerfJitLogger is only implemented in Linux. expect('--perf-prof', 'B\n'); } diff --git a/test/parallel/test-cluster-http-pipe.js b/test/parallel/test-cluster-http-pipe.js index 9e58fb297b28fe..9e039541cd26f1 100644 --- a/test/parallel/test-cluster-http-pipe.js +++ b/test/parallel/test-cluster-http-pipe.js @@ -45,7 +45,6 @@ if (cluster.isMaster) { http.createServer(common.mustCall((req, res) => { assert.strictEqual(req.connection.remoteAddress, undefined); assert.strictEqual(req.connection.localAddress, undefined); - // TODO common.PIPE? res.writeHead(200); res.end('OK'); diff --git a/test/parallel/test-console-table.js b/test/parallel/test-console-table.js index 39e9099dd717d4..64e2533f175e1d 100644 --- a/test/parallel/test-console-table.js +++ b/test/parallel/test-console-table.js @@ -41,13 +41,13 @@ test([1, 2, 3], ` `); test([Symbol(), 5, [10]], ` -┌─────────┬──────────┐ -│ (index) │ Values │ -├─────────┼──────────┤ -│ 0 │ Symbol() │ -│ 1 │ 5 │ -│ 2 │ [ 10 ] │ -└─────────┴──────────┘ +┌─────────┬────┬──────────┐ +│ (index) │ 0 │ Values │ +├─────────┼────┼──────────┤ +│ 0 │ │ Symbol() │ +│ 1 │ │ 5 │ +│ 2 │ 10 │ │ +└─────────┴────┴──────────┘ `); test([undefined, 5], ` @@ -182,10 +182,10 @@ test({ a: undefined }, ['x'], ` `); test([], ` -┌─────────┬────────┐ -│ (index) │ Values │ -├─────────┼────────┤ -└─────────┴────────┘ +┌─────────┐ +│ (index) │ +├─────────┤ +└─────────┘ `); test(new Map(), ` @@ -194,3 +194,12 @@ test(new Map(), ` ├───────────────────┼─────┼────────┤ └───────────────────┴─────┴────────┘ `); + +test([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ` +┌─────────┬─────┬─────┐ +│ (index) │ a │ b │ +├─────────┼─────┼─────┤ +│ 0 │ 1 │ 'Y' │ +│ 1 │ 'Z' │ 2 │ +└─────────┴─────┴─────┘ +`); diff --git a/test/parallel/test-crypto-certificate.js b/test/parallel/test-crypto-certificate.js index f94c82474e95aa..3252e53aa4fd09 100644 --- a/test/parallel/test-crypto-certificate.js +++ b/test/parallel/test-crypto-certificate.js @@ -36,9 +36,7 @@ const spkacValid = fixtures.readSync('spkac.valid'); const spkacFail = fixtures.readSync('spkac.fail'); const spkacPem = fixtures.readSync('spkac.pem'); -{ - // Test instance methods - const certificate = new Certificate(); +function checkMethods(certificate) { assert.strictEqual(certificate.verifySpkac(spkacValid), true); assert.strictEqual(certificate.verifySpkac(spkacFail), false); @@ -57,21 +55,13 @@ const spkacPem = fixtures.readSync('spkac.pem'); } { - // Test static methods - assert.strictEqual(Certificate.verifySpkac(spkacValid), true); - assert.strictEqual(Certificate.verifySpkac(spkacFail), false); - - assert.strictEqual( - stripLineEndings(Certificate.exportPublicKey(spkacValid).toString('utf8')), - stripLineEndings(spkacPem.toString('utf8')) - ); - assert.strictEqual(Certificate.exportPublicKey(spkacFail), ''); + // Test instance methods + checkMethods(new Certificate()); +} - assert.strictEqual( - Certificate.exportChallenge(spkacValid).toString('utf8'), - 'fb9ab814-6677-42a4-a60c-f905d1a6924d' - ); - assert.strictEqual(Certificate.exportChallenge(spkacFail), ''); +{ + // Test static methods + checkMethods(Certificate); } function stripLineEndings(obj) { diff --git a/test/parallel/test-crypto-pbkdf2.js b/test/parallel/test-crypto-pbkdf2.js index b4ecd3c6061158..f65176132ae5c4 100644 --- a/test/parallel/test-crypto-pbkdf2.js +++ b/test/parallel/test-crypto-pbkdf2.js @@ -123,7 +123,8 @@ assert.throws( }); [1, {}, [], true, undefined, null].forEach((input) => { - const msgPart2 = `Buffer, or TypedArray. Received type ${typeof input}`; + const msgPart2 = 'Buffer, TypedArray, or DataView.' + + ` Received type ${typeof input}`; assert.throws( () => crypto.pbkdf2(input, 'salt', 8, 8, 'sha256', common.mustNotCall()), { diff --git a/test/parallel/test-env-newprotomethod-remove-unnecessary-prototypes.js b/test/parallel/test-env-newprotomethod-remove-unnecessary-prototypes.js new file mode 100644 index 00000000000000..bcc522cd45ad50 --- /dev/null +++ b/test/parallel/test-env-newprotomethod-remove-unnecessary-prototypes.js @@ -0,0 +1,18 @@ +'use strict'; +require('../common'); + +// This test ensures that unnecessary prototypes are no longer +// being generated by Environment::NewFunctionTemplate. + +const assert = require('assert'); + +[ + process.binding('udp_wrap').UDP.prototype.bind6, + process.binding('tcp_wrap').TCP.prototype.bind6, + process.binding('udp_wrap').UDP.prototype.send6, + process.binding('tcp_wrap').TCP.prototype.bind, + process.binding('udp_wrap').UDP.prototype.close, + process.binding('tcp_wrap').TCP.prototype.open +].forEach((binding, i) => { + assert.strictEqual('prototype' in binding, false, `Test ${i} failed`); +}); diff --git a/test/parallel/test-errors-systemerror.js b/test/parallel/test-errors-systemerror.js index a74d7b3846f59d..957a0dd7b22196 100644 --- a/test/parallel/test-errors-systemerror.js +++ b/test/parallel/test-errors-systemerror.js @@ -3,12 +3,10 @@ require('../common'); const assert = require('assert'); -const errors = require('internal/errors'); - -const { E, SystemError } = errors; +const { E, SystemError, codes } = require('internal/errors'); assert.throws( - () => { throw new errors.SystemError(); }, + () => { throw new SystemError(); }, { name: 'TypeError', message: 'Cannot read property \'match\' of undefined' @@ -16,7 +14,7 @@ assert.throws( ); E('ERR_TEST', 'custom message', SystemError); -const { ERR_TEST } = errors.codes; +const { ERR_TEST } = codes; { const ctx = { diff --git a/test/parallel/test-eslint-alphabetize-errors.js b/test/parallel/test-eslint-alphabetize-errors.js index 220f09d54eb69e..3f2a5b3fd35c8f 100644 --- a/test/parallel/test-eslint-alphabetize-errors.js +++ b/test/parallel/test-eslint-alphabetize-errors.js @@ -1,6 +1,7 @@ 'use strict'; -require('../common'); +const common = require('../common'); +common.skipIfEslintMissing(); const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/alphabetize-errors'); diff --git a/test/parallel/test-eslint-buffer-constructor.js b/test/parallel/test-eslint-buffer-constructor.js index 6b9254f9379b06..daa1a527673c1a 100644 --- a/test/parallel/test-eslint-buffer-constructor.js +++ b/test/parallel/test-eslint-buffer-constructor.js @@ -1,6 +1,7 @@ 'use strict'; -require('../common'); +const common = require('../common'); +common.skipIfEslintMissing(); const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/buffer-constructor'); diff --git a/test/parallel/test-eslint-documented-errors.js b/test/parallel/test-eslint-documented-errors.js index 50c92acd151215..533b829e78a298 100644 --- a/test/parallel/test-eslint-documented-errors.js +++ b/test/parallel/test-eslint-documented-errors.js @@ -1,6 +1,7 @@ 'use strict'; -require('../common'); +const common = require('../common'); +common.skipIfEslintMissing(); const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/documented-errors'); diff --git a/test/parallel/test-eslint-eslint-check.js b/test/parallel/test-eslint-eslint-check.js new file mode 100644 index 00000000000000..46e2a6a4a2ce47 --- /dev/null +++ b/test/parallel/test-eslint-eslint-check.js @@ -0,0 +1,31 @@ +'use strict'; + +const common = require('../common'); + +common.skipIfEslintMissing(); + +const RuleTester = require('../../tools/node_modules/eslint').RuleTester; +const rule = require('../../tools/eslint-rules/eslint-check'); + +const message = 'Please add a skipIfEslintMissing() call to allow this ' + + 'test to be skipped when Node.js is built ' + + 'from a source tarball.'; + +new RuleTester().run('eslint-check', rule, { + valid: [ + 'foo;', + 'require("common")\n' + + 'common.skipIfEslintMissing();\n' + + 'require("../../tools/node_modules/eslint")' + ], + invalid: [ + { + code: 'require("common")\n' + + 'require("../../tools/node_modules/eslint").RuleTester', + errors: [{ message }], + output: 'require("common")\n' + + 'common.skipIfEslintMissing();\n' + + 'require("../../tools/node_modules/eslint").RuleTester' + } + ] +}); diff --git a/test/parallel/test-eslint-inspector-check.js b/test/parallel/test-eslint-inspector-check.js index bdec596f8d128e..ae71c004029771 100644 --- a/test/parallel/test-eslint-inspector-check.js +++ b/test/parallel/test-eslint-inspector-check.js @@ -1,12 +1,13 @@ 'use strict'; -require('../common'); +const common = require('../common'); +common.skipIfEslintMissing(); const RuleTester = require('../../tools/node_modules/eslint').RuleTester; const rule = require('../../tools/eslint-rules/inspector-check'); const message = 'Please add a skipIfInspectorDisabled() call to allow this ' + - 'test to be skippped when Node is built ' + + 'test to be skipped when Node is built ' + '\'--without-inspector\'.'; new RuleTester().run('inspector-check', rule, { diff --git a/test/parallel/test-eslint-require-buffer.js b/test/parallel/test-eslint-require-buffer.js index bdc794dd594240..da17d44c7f600d 100644 --- a/test/parallel/test-eslint-require-buffer.js +++ b/test/parallel/test-eslint-require-buffer.js @@ -11,7 +11,7 @@ const ruleTester = new RuleTester({ env: { node: true } }); -const message = "Use const Buffer = require('buffer').Buffer; " + +const message = "Use const { Buffer } = require('buffer'); " + 'at the beginning of this file'; const useStrict = '\'use strict\';\n\n'; diff --git a/test/parallel/test-fixed-queue.js b/test/parallel/test-fixed-queue.js new file mode 100644 index 00000000000000..a50be1309a5ea8 --- /dev/null +++ b/test/parallel/test-fixed-queue.js @@ -0,0 +1,34 @@ +// Flags: --expose-internals +'use strict'; + +require('../common'); + +const assert = require('assert'); +const FixedQueue = require('internal/fixed_queue'); + +{ + const queue = new FixedQueue(); + assert.strictEqual(queue.head, queue.tail); + assert(queue.isEmpty()); + queue.push('a'); + assert(!queue.isEmpty()); + assert.strictEqual(queue.shift(), 'a'); + assert.strictEqual(queue.shift(), null); +} + +{ + const queue = new FixedQueue(); + for (let i = 0; i < 2047; i++) + queue.push('a'); + assert(queue.head.isFull()); + queue.push('a'); + assert(!queue.head.isFull()); + + assert.notStrictEqual(queue.head, queue.tail); + for (let i = 0; i < 2047; i++) + assert.strictEqual(queue.shift(), 'a'); + assert.strictEqual(queue.head, queue.tail); + assert(!queue.isEmpty()); + assert.strictEqual(queue.shift(), 'a'); + assert(queue.isEmpty()); +} diff --git a/test/parallel/test-fs-error-messages.js b/test/parallel/test-fs-error-messages.js index 61e51585a028c2..28141f33f62965 100644 --- a/test/parallel/test-fs-error-messages.js +++ b/test/parallel/test-fs-error-messages.js @@ -636,22 +636,21 @@ if (!common.isAIX) { ); } -// copyFile with invalid flags +// Check copyFile with invalid flags. { - const validateError = (err) => { - assert.strictEqual(err.message, - 'EINVAL: invalid argument, copyfile ' + - `'${existingFile}' -> '${nonexistentFile}'`); - assert.strictEqual(err.errno, uv.UV_EINVAL); - assert.strictEqual(err.code, 'EINVAL'); - assert.strictEqual(err.syscall, 'copyfile'); - return true; + const validateError = { + // TODO: Make sure the error message always also contains the src. + message: `EINVAL: invalid argument, copyfile -> '${nonexistentFile}'`, + errno: uv.UV_EINVAL, + code: 'EINVAL', + syscall: 'copyfile' }; - // TODO(joyeecheung): test fs.copyFile() when uv_fs_copyfile does not - // keep the loop open when the flags are invalid. - // See https://github.com/libuv/libuv/pull/1747 + fs.copyFile(existingFile, nonexistentFile, -1, + common.expectsError(validateError)); + validateError.message = 'EINVAL: invalid argument, copyfile ' + + `'${existingFile}' -> '${nonexistentFile}'`; assert.throws( () => fs.copyFileSync(existingFile, nonexistentFile, -1), validateError diff --git a/test/parallel/test-fs-filehandle.js b/test/parallel/test-fs-filehandle.js index 8ddc11ec3e0e07..84b462aa90914d 100644 --- a/test/parallel/test-fs-filehandle.js +++ b/test/parallel/test-fs-filehandle.js @@ -5,7 +5,7 @@ const common = require('../common'); const assert = require('assert'); const path = require('path'); const fs = process.binding('fs'); -const { stringToFlags } = require('internal/fs'); +const { stringToFlags } = require('internal/fs/utils'); // Verifies that the FileHandle object is garbage collected and that a // warning is emitted if it is not closed. diff --git a/test/parallel/test-fs-open-flags.js b/test/parallel/test-fs-open-flags.js index 7f70885861ffd1..546d68e31274f4 100644 --- a/test/parallel/test-fs-open-flags.js +++ b/test/parallel/test-fs-open-flags.js @@ -39,7 +39,7 @@ const O_DSYNC = fs.constants.O_DSYNC || 0; const O_TRUNC = fs.constants.O_TRUNC || 0; const O_WRONLY = fs.constants.O_WRONLY || 0; -const { stringToFlags } = require('internal/fs'); +const { stringToFlags } = require('internal/fs/utils'); assert.strictEqual(stringToFlags('r'), O_RDONLY); assert.strictEqual(stringToFlags('r+'), O_RDWR); diff --git a/test/parallel/test-fs-promises-file-handle-append-file.js b/test/parallel/test-fs-promises-file-handle-append-file.js index 38336a2b43a57e..7766ac4c904642 100644 --- a/test/parallel/test-fs-promises-file-handle-append-file.js +++ b/test/parallel/test-fs-promises-file-handle-append-file.js @@ -2,11 +2,11 @@ const common = require('../common'); -// The following tests validate base functionality for the fs/promises +// The following tests validate base functionality for the fs.promises // FileHandle.appendFile method. const fs = require('fs'); -const { open } = require('fs/promises'); +const { open } = fs.promises; const path = require('path'); const tmpdir = require('../common/tmpdir'); const assert = require('assert'); diff --git a/test/parallel/test-fs-promises-file-handle-chmod.js b/test/parallel/test-fs-promises-file-handle-chmod.js index c2a44fba7bd32c..8b9d8b1c0d193d 100644 --- a/test/parallel/test-fs-promises-file-handle-chmod.js +++ b/test/parallel/test-fs-promises-file-handle-chmod.js @@ -2,11 +2,11 @@ const common = require('../common'); -// The following tests validate base functionality for the fs/promises +// The following tests validate base functionality for the fs.promises // FileHandle.chmod method. const fs = require('fs'); -const { open } = require('fs/promises'); +const { open } = fs.promises; const path = require('path'); const tmpdir = require('../common/tmpdir'); const assert = require('assert'); diff --git a/test/parallel/test-fs-promises-file-handle-read.js b/test/parallel/test-fs-promises-file-handle-read.js index 5a9bc4558cf15f..a397b0e260aff4 100644 --- a/test/parallel/test-fs-promises-file-handle-read.js +++ b/test/parallel/test-fs-promises-file-handle-read.js @@ -2,11 +2,11 @@ const common = require('../common'); -// The following tests validate base functionality for the fs/promises +// The following tests validate base functionality for the fs.promises // FileHandle.read method. const fs = require('fs'); -const { open } = require('fs/promises'); +const { open } = fs.promises; const path = require('path'); const tmpdir = require('../common/tmpdir'); const assert = require('assert'); diff --git a/test/parallel/test-fs-promises-file-handle-readFile.js b/test/parallel/test-fs-promises-file-handle-readFile.js index 9308c299092714..316fd6581fa446 100644 --- a/test/parallel/test-fs-promises-file-handle-readFile.js +++ b/test/parallel/test-fs-promises-file-handle-readFile.js @@ -2,11 +2,11 @@ const common = require('../common'); -// The following tests validate base functionality for the fs/promises +// The following tests validate base functionality for the fs.promises // FileHandle.readFile method. const fs = require('fs'); -const { open } = require('fs/promises'); +const { open } = fs.promises; const path = require('path'); const tmpdir = require('../common/tmpdir'); const assert = require('assert'); diff --git a/test/parallel/test-fs-promises-file-handle-stat.js b/test/parallel/test-fs-promises-file-handle-stat.js new file mode 100644 index 00000000000000..7d44b8e3dae2b7 --- /dev/null +++ b/test/parallel/test-fs-promises-file-handle-stat.js @@ -0,0 +1,24 @@ +'use strict'; + +const common = require('../common'); + +// The following tests validate base functionality for the fs.promises +// FileHandle.stat method. + +const { open } = require('fs').promises; +const path = require('path'); +const tmpdir = require('../common/tmpdir'); +const assert = require('assert'); + +tmpdir.refresh(); +common.crashOnUnhandledRejection(); + +async function validateStat() { + const filePath = path.resolve(tmpdir.path, 'tmp-read-file.txt'); + const fileHandle = await open(filePath, 'w+'); + const stats = await fileHandle.stat(); + assert.ok(stats.mtime instanceof Date); +} + +validateStat() + .then(common.mustCall()); diff --git a/test/parallel/test-fs-promises-file-handle-write.js b/test/parallel/test-fs-promises-file-handle-write.js index 842095a214c2ef..d7812745c5439e 100644 --- a/test/parallel/test-fs-promises-file-handle-write.js +++ b/test/parallel/test-fs-promises-file-handle-write.js @@ -2,11 +2,11 @@ const common = require('../common'); -// The following tests validate base functionality for the fs/promises +// The following tests validate base functionality for the fs.promises // FileHandle.read method. const fs = require('fs'); -const { open } = require('fs/promises'); +const { open } = fs.promises; const path = require('path'); const tmpdir = require('../common/tmpdir'); const assert = require('assert'); @@ -35,6 +35,18 @@ async function validateEmptyWrite() { assert.deepStrictEqual(buffer, readFileData); } -validateWrite() - .then(validateEmptyWrite) - .then(common.mustCall()); +async function validateNonUint8ArrayWrite() { + const filePathForHandle = path.resolve(tmpDir, 'tmp-data-write.txt'); + const fileHandle = await open(filePathForHandle, 'w+'); + const buffer = Buffer.from('Hello world', 'utf8').toString('base64'); + + await fileHandle.write(buffer, 0, buffer.length); + const readFileData = fs.readFileSync(filePathForHandle); + assert.deepStrictEqual(Buffer.from(buffer, 'utf8'), readFileData); +} + +Promise.all([ + validateWrite(), + validateEmptyWrite(), + validateNonUint8ArrayWrite() +]).then(common.mustCall()); diff --git a/test/parallel/test-fs-promises-file-handle-writeFile.js b/test/parallel/test-fs-promises-file-handle-writeFile.js index 196b6f8db8cd58..a53384cc221645 100644 --- a/test/parallel/test-fs-promises-file-handle-writeFile.js +++ b/test/parallel/test-fs-promises-file-handle-writeFile.js @@ -2,11 +2,11 @@ const common = require('../common'); -// The following tests validate base functionality for the fs/promises +// The following tests validate base functionality for the fs.promises // FileHandle.readFile method. const fs = require('fs'); -const { open } = require('fs/promises'); +const { open } = fs.promises; const path = require('path'); const tmpdir = require('../common/tmpdir'); const assert = require('assert'); diff --git a/test/parallel/test-fs-promises-readfile.js b/test/parallel/test-fs-promises-readfile.js index 1bf49503c312c0..4334673c30f5fb 100644 --- a/test/parallel/test-fs-promises-readfile.js +++ b/test/parallel/test-fs-promises-readfile.js @@ -4,7 +4,7 @@ const common = require('../common'); const assert = require('assert'); const path = require('path'); -const { writeFile, readFile } = require('fs/promises'); +const { writeFile, readFile } = require('fs').promises; const tmpdir = require('../common/tmpdir'); tmpdir.refresh(); diff --git a/test/parallel/test-fs-promises-writefile.js b/test/parallel/test-fs-promises-writefile.js index 280bce864229ce..1bb6945c6782da 100644 --- a/test/parallel/test-fs-promises-writefile.js +++ b/test/parallel/test-fs-promises-writefile.js @@ -2,7 +2,7 @@ const common = require('../common'); const fs = require('fs'); -const fsPromises = require('fs/promises'); +const fsPromises = fs.promises; const path = require('path'); const tmpdir = require('../common/tmpdir'); const assert = require('assert'); diff --git a/test/parallel/test-fs-promises.js b/test/parallel/test-fs-promises.js index ba3a91d5b39f8a..43b5da700484ff 100644 --- a/test/parallel/test-fs-promises.js +++ b/test/parallel/test-fs-promises.js @@ -5,7 +5,7 @@ const assert = require('assert'); const tmpdir = require('../common/tmpdir'); const fixtures = require('../common/fixtures'); const path = require('path'); -const fsPromises = require('fs/promises'); +const fsPromises = require('fs').promises; const { access, chmod, diff --git a/test/parallel/test-fs-realpath.js b/test/parallel/test-fs-realpath.js index 6cfd79cecfb694..d7efc748bc9662 100644 --- a/test/parallel/test-fs-realpath.js +++ b/test/parallel/test-fs-realpath.js @@ -27,11 +27,10 @@ const tmpdir = require('../common/tmpdir'); const assert = require('assert'); const fs = require('fs'); const path = require('path'); -const exec = require('child_process').exec; let async_completed = 0; let async_expected = 0; const unlink = []; -let skipSymlinks = false; +const skipSymlinks = !common.canCreateSymLink(); const tmpDir = tmpdir.path; tmpdir.refresh(); @@ -45,25 +44,9 @@ if (common.isWindows) { assert .strictEqual(path_left.toLowerCase(), path_right.toLowerCase(), message); }; - - // On Windows, creating symlinks requires admin privileges. - // We'll only try to run symlink test if we have enough privileges. - try { - exec('whoami /priv', function(err, o) { - if (err || !o.includes('SeCreateSymbolicLinkPrivilege')) { - skipSymlinks = true; - } - runTest(); - }); - } catch (er) { - // better safe than sorry - skipSymlinks = true; - process.nextTick(runTest); - } -} else { - process.nextTick(runTest); } +process.nextTick(runTest); function tmp(p) { return path.join(tmpDir, p); diff --git a/test/parallel/test-fs-syncwritestream.js b/test/parallel/test-fs-syncwritestream.js index a014277a6ba259..8fbe665a4047d0 100644 --- a/test/parallel/test-fs-syncwritestream.js +++ b/test/parallel/test-fs-syncwritestream.js @@ -6,8 +6,8 @@ const stream = require('stream'); const fs = require('fs'); const path = require('path'); -// require('internal/fs').SyncWriteStream is used as a stdio implementation -// when stdout/stderr point to files. +// require('internal/fs/utils').SyncWriteStream is used as a stdio +// implementation when stdout/stderr point to files. if (process.argv[2] === 'child') { // Note: Calling console.log() is part of this test as it exercises the diff --git a/test/parallel/test-http-aborted.js b/test/parallel/test-http-aborted.js new file mode 100644 index 00000000000000..c3d7e4641f4501 --- /dev/null +++ b/test/parallel/test-http-aborted.js @@ -0,0 +1,26 @@ +'use strict'; + +const common = require('../common'); +const http = require('http'); +const assert = require('assert'); + +const server = http.createServer(common.mustCall(function(req, res) { + req.on('aborted', common.mustCall(function() { + assert.strictEqual(this.aborted, true); + server.close(); + })); + assert.strictEqual(req.aborted, false); + res.write('hello'); +})); + +server.listen(0, common.mustCall(() => { + const req = http.get({ + port: server.address().port, + headers: { connection: 'keep-alive' } + }, common.mustCall((res) => { + res.on('aborted', common.mustCall(() => { + assert.strictEqual(res.aborted, true); + })); + req.abort(); + })); +})); diff --git a/test/parallel/test-http-agent-keepalive.js b/test/parallel/test-http-agent-keepalive.js index 8ac8d79df192b0..917c4ee8101f9e 100644 --- a/test/parallel/test-http-agent-keepalive.js +++ b/test/parallel/test-http-agent-keepalive.js @@ -92,8 +92,7 @@ function remoteClose() { // waiting remote server close the socket setTimeout(common.mustCall(() => { assert.strictEqual(agent.sockets[name], undefined); - assert.strictEqual(agent.freeSockets[name], undefined, - 'freeSockets is not empty'); + assert.strictEqual(agent.freeSockets[name], undefined); remoteError(); }), common.platformTimeout(200)); })); diff --git a/test/parallel/test-http-outgoing-internal-headers.js b/test/parallel/test-http-outgoing-internal-headers.js index e36917a970d987..de75a44e8a05d7 100644 --- a/test/parallel/test-http-outgoing-internal-headers.js +++ b/test/parallel/test-http-outgoing-internal-headers.js @@ -21,8 +21,10 @@ const { OutgoingMessage } = require('http'); Origin: 'localhost' }; - assert.deepStrictEqual(outgoingMessage[outHeadersKey], { - host: ['host', 'risingstack.com'], - origin: ['Origin', 'localhost'] - }); + assert.deepStrictEqual( + Object.entries(outgoingMessage[outHeadersKey]), + Object.entries({ + host: ['host', 'risingstack.com'], + origin: ['Origin', 'localhost'] + })); } diff --git a/test/parallel/test-http2-client-destroy.js b/test/parallel/test-http2-client-destroy.js index 09ca011c736c96..6238363511a791 100644 --- a/test/parallel/test-http2-client-destroy.js +++ b/test/parallel/test-http2-client-destroy.js @@ -95,6 +95,7 @@ const Countdown = require('../common/countdown'); }); req.resume(); + req.on('end', common.mustCall()); req.on('close', common.mustCall(() => server.close())); })); } @@ -124,3 +125,21 @@ const Countdown = require('../common/countdown'); req.on('error', () => {}); })); } + +// test destroy before connect +{ + const server = h2.createServer(); + server.on('stream', common.mustNotCall()); + + server.listen(0, common.mustCall(() => { + const client = h2.connect(`http://localhost:${server.address().port}`); + + server.on('connection', common.mustCall(() => { + server.close(); + client.close(); + })); + + const req = client.request(); + req.destroy(); + })); +} diff --git a/test/parallel/test-http2-client-onconnect-errors.js b/test/parallel/test-http2-client-onconnect-errors.js index f427bfb4907339..a75dc590c669a1 100644 --- a/test/parallel/test-http2-client-onconnect-errors.js +++ b/test/parallel/test-http2-client-onconnect-errors.js @@ -101,6 +101,7 @@ function runTest(test) { }); } + req.on('end', common.mustCall()); req.on('close', common.mustCall(() => { client.destroy(); diff --git a/test/parallel/test-http2-client-rststream-before-connect.js b/test/parallel/test-http2-client-rststream-before-connect.js index 7bace941d1a0af..33e22130aad19b 100644 --- a/test/parallel/test-http2-client-rststream-before-connect.js +++ b/test/parallel/test-http2-client-rststream-before-connect.js @@ -63,8 +63,14 @@ server.listen(0, common.mustCall(() => { message: 'Stream closed with error code NGHTTP2_PROTOCOL_ERROR' })); - req.on('response', common.mustCall()); - req.resume(); + // The `response` event should not fire as the server should receive the + // RST_STREAM frame before it ever has a chance to reply. + req.on('response', common.mustNotCall()); + + // The `end` event should still fire as we close the readable stream by + // pushing a `null` chunk. req.on('end', common.mustCall()); + + req.resume(); req.end(); })); diff --git a/test/parallel/test-http2-client-stream-destroy-before-connect.js b/test/parallel/test-http2-client-stream-destroy-before-connect.js index 9e81015ec58d28..d834de5d11ebe7 100644 --- a/test/parallel/test-http2-client-stream-destroy-before-connect.js +++ b/test/parallel/test-http2-client-stream-destroy-before-connect.js @@ -45,4 +45,5 @@ server.listen(0, common.mustCall(() => { req.on('response', common.mustNotCall()); req.resume(); + req.on('end', common.mustCall()); })); diff --git a/test/parallel/test-http2-client-upload-reject.js b/test/parallel/test-http2-client-upload-reject.js new file mode 100644 index 00000000000000..ece7cbdf233f1f --- /dev/null +++ b/test/parallel/test-http2-client-upload-reject.js @@ -0,0 +1,48 @@ +'use strict'; + +// Verifies that uploading data from a client works + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const assert = require('assert'); +const http2 = require('http2'); +const fs = require('fs'); +const fixtures = require('../common/fixtures'); + +const loc = fixtures.path('person-large.jpg'); + +assert(fs.existsSync(loc)); + +fs.readFile(loc, common.mustCall((err, data) => { + assert.ifError(err); + + const server = http2.createServer(); + + server.on('stream', common.mustCall((stream) => { + stream.on('close', common.mustCall(() => { + assert.strictEqual(stream.rstCode, 0); + })); + + stream.respond({ ':status': 400 }); + stream.end(); + })); + + server.listen(0, common.mustCall(() => { + const client = http2.connect(`http://localhost:${server.address().port}`); + + const req = client.request({ ':method': 'POST' }); + req.on('response', common.mustCall((headers) => { + assert.strictEqual(headers[':status'], 400); + })); + + req.resume(); + req.on('end', common.mustCall(() => { + server.close(); + client.close(); + })); + + const str = fs.createReadStream(loc); + str.pipe(req); + })); +})); diff --git a/test/parallel/test-http2-client-upload.js b/test/parallel/test-http2-client-upload.js index 70a8ff3ced01c6..78c6d47cbb4f44 100644 --- a/test/parallel/test-http2-client-upload.js +++ b/test/parallel/test-http2-client-upload.js @@ -11,7 +11,7 @@ const fs = require('fs'); const fixtures = require('../common/fixtures'); const Countdown = require('../common/countdown'); -const loc = fixtures.path('person.jpg'); +const loc = fixtures.path('person-large.jpg'); let fileData; assert(fs.existsSync(loc)); diff --git a/test/parallel/test-http2-compat-aborted.js b/test/parallel/test-http2-compat-aborted.js new file mode 100644 index 00000000000000..01caf95f98688a --- /dev/null +++ b/test/parallel/test-http2-compat-aborted.js @@ -0,0 +1,27 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const h2 = require('http2'); +const assert = require('assert'); + + +const server = h2.createServer(common.mustCall(function(req, res) { + req.on('aborted', common.mustCall(function() { + assert.strictEqual(this.aborted, true); + })); + assert.strictEqual(req.aborted, false); + res.write('hello'); + server.close(); +})); + +server.listen(0, common.mustCall(function() { + const url = `http://localhost:${server.address().port}`; + const client = h2.connect(url, common.mustCall(() => { + const request = client.request(); + request.on('data', common.mustCall((chunk) => { + client.destroy(); + })); + })); +})); diff --git a/test/parallel/test-http2-compat-serverresponse-destroy.js b/test/parallel/test-http2-compat-serverresponse-destroy.js index 49822082979a01..8ee52a74ab4e81 100644 --- a/test/parallel/test-http2-compat-serverresponse-destroy.js +++ b/test/parallel/test-http2-compat-serverresponse-destroy.js @@ -63,6 +63,7 @@ server.listen(0, common.mustCall(() => { req.on('close', common.mustCall(() => countdown.dec())); req.resume(); + req.on('end', common.mustCall()); } { @@ -77,5 +78,6 @@ server.listen(0, common.mustCall(() => { req.on('close', common.mustCall(() => countdown.dec())); req.resume(); + req.on('end', common.mustCall()); } })); diff --git a/test/parallel/test-http2-create-client-session.js b/test/parallel/test-http2-create-client-session.js index 34e4e975d92d81..35de927ea7924e 100644 --- a/test/parallel/test-http2-create-client-session.js +++ b/test/parallel/test-http2-create-client-session.js @@ -55,9 +55,8 @@ server.on('listening', common.mustCall(() => { const req = client.request(); req.on('response', common.mustCall(function(headers) { - assert.strictEqual(headers[':status'], 200, 'status code is set'); - assert.strictEqual(headers['content-type'], 'text/html', - 'content type is set'); + assert.strictEqual(headers[':status'], 200); + assert.strictEqual(headers['content-type'], 'text/html'); assert(headers.date); })); diff --git a/test/parallel/test-http2-large-write-close.js b/test/parallel/test-http2-large-write-close.js new file mode 100644 index 00000000000000..f9dee357d6da7b --- /dev/null +++ b/test/parallel/test-http2-large-write-close.js @@ -0,0 +1,44 @@ +'use strict'; +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const assert = require('assert'); +const fixtures = require('../common/fixtures'); +const http2 = require('http2'); + +const content = Buffer.alloc(1e5, 0x44); + +const server = http2.createSecureServer({ + key: fixtures.readKey('agent1-key.pem'), + cert: fixtures.readKey('agent1-cert.pem') +}); +server.on('stream', common.mustCall((stream) => { + stream.respond({ + 'Content-Type': 'application/octet-stream', + 'Content-Length': (content.length.toString() * 2), + 'Vary': 'Accept-Encoding' + }); + + stream.write(content); + stream.write(content); + stream.end(); + stream.close(); +})); + +server.listen(0, common.mustCall(() => { + const client = http2.connect(`https://localhost:${server.address().port}`, + { rejectUnauthorized: false }); + + const req = client.request({ ':path': '/' }); + req.end(); + + let receivedBufferLength = 0; + req.on('data', common.mustCallAtLeast((buf) => { + receivedBufferLength += buf.length; + }, 1)); + req.on('close', common.mustCall(() => { + assert.strictEqual(receivedBufferLength, content.length * 2); + client.close(); + server.close(); + })); +})); diff --git a/test/parallel/test-http2-max-concurrent-streams.js b/test/parallel/test-http2-max-concurrent-streams.js index 2b576700aa4e00..b270d6cc6aff31 100644 --- a/test/parallel/test-http2-max-concurrent-streams.js +++ b/test/parallel/test-http2-max-concurrent-streams.js @@ -45,6 +45,7 @@ server.listen(0, common.mustCall(() => { req.on('aborted', common.mustCall()); req.on('response', common.mustNotCall()); req.resume(); + req.on('end', common.mustCall()); req.on('close', common.mustCall(() => countdown.dec())); req.on('error', common.expectsError({ code: 'ERR_HTTP2_STREAM_ERROR', diff --git a/test/parallel/test-http2-misbehaving-flow-control-paused.js b/test/parallel/test-http2-misbehaving-flow-control-paused.js index 60a2cdabf847d9..26d2ed5dd244a2 100644 --- a/test/parallel/test-http2-misbehaving-flow-control-paused.js +++ b/test/parallel/test-http2-misbehaving-flow-control-paused.js @@ -70,8 +70,6 @@ server.on('stream', (stream) => { client.destroy(); })); stream.on('end', common.mustNotCall()); - stream.respond(); - stream.end('ok'); }); server.listen(0, () => { diff --git a/test/parallel/test-http2-misused-pseudoheaders.js b/test/parallel/test-http2-misused-pseudoheaders.js index 0b7becef5f6f0a..c1ae37b9a36938 100644 --- a/test/parallel/test-http2-misused-pseudoheaders.js +++ b/test/parallel/test-http2-misused-pseudoheaders.js @@ -41,6 +41,7 @@ server.listen(0, common.mustCall(() => { req.on('response', common.mustCall()); req.resume(); + req.on('end', common.mustCall()); req.on('close', common.mustCall(() => { server.close(); client.close(); diff --git a/test/parallel/test-http2-multi-content-length.js b/test/parallel/test-http2-multi-content-length.js index 908f6ecd64fea1..7d8ff4858fedbb 100644 --- a/test/parallel/test-http2-multi-content-length.js +++ b/test/parallel/test-http2-multi-content-length.js @@ -53,6 +53,7 @@ server.listen(0, common.mustCall(() => { // header to be set for non-payload bearing requests... const req = client.request({ 'content-length': 1 }); req.resume(); + req.on('end', common.mustCall()); req.on('close', common.mustCall(() => countdown.dec())); req.on('error', common.expectsError({ code: 'ERR_HTTP2_STREAM_ERROR', diff --git a/test/parallel/test-http2-perf_hooks.js b/test/parallel/test-http2-perf_hooks.js index 07d9c55ed7e0d2..5dd8ad0f6d883b 100644 --- a/test/parallel/test-http2-perf_hooks.js +++ b/test/parallel/test-http2-perf_hooks.js @@ -26,7 +26,7 @@ const obs = new PerformanceObserver(common.mustCall((items) => { switch (entry.type) { case 'server': assert.strictEqual(entry.streamCount, 1); - assert.strictEqual(entry.framesReceived, 5); + assert(entry.framesReceived >= 3); break; case 'client': assert.strictEqual(entry.streamCount, 1); diff --git a/test/parallel/test-http2-respond-file-fd-invalid.js b/test/parallel/test-http2-respond-file-fd-invalid.js index 28d1c0f057dd23..21fcf790b449eb 100644 --- a/test/parallel/test-http2-respond-file-fd-invalid.js +++ b/test/parallel/test-http2-respond-file-fd-invalid.js @@ -40,7 +40,7 @@ server.listen(0, () => { req.on('response', common.mustCall()); req.on('error', common.mustCall(errorCheck)); req.on('data', common.mustNotCall()); - req.on('close', common.mustCall(() => { + req.on('end', common.mustCall(() => { assert.strictEqual(req.rstCode, NGHTTP2_INTERNAL_ERROR); client.close(); server.close(); diff --git a/test/parallel/test-http2-respond-nghttperrors.js b/test/parallel/test-http2-respond-nghttperrors.js index 4adf678b681b09..ad9eee0d59fecc 100644 --- a/test/parallel/test-http2-respond-nghttperrors.js +++ b/test/parallel/test-http2-respond-nghttperrors.js @@ -87,7 +87,7 @@ function runTest(test) { req.resume(); req.end(); - req.on('close', common.mustCall(() => { + req.on('end', common.mustCall(() => { client.close(); if (!tests.length) { diff --git a/test/parallel/test-http2-respond-with-fd-errors.js b/test/parallel/test-http2-respond-with-fd-errors.js index 7e7394d29305cc..3a671a3e36490a 100644 --- a/test/parallel/test-http2-respond-with-fd-errors.js +++ b/test/parallel/test-http2-respond-with-fd-errors.js @@ -95,7 +95,7 @@ function runTest(test) { req.resume(); req.end(); - req.on('close', common.mustCall(() => { + req.on('end', common.mustCall(() => { client.close(); if (!tests.length) { diff --git a/test/parallel/test-http2-server-shutdown-before-respond.js b/test/parallel/test-http2-server-shutdown-before-respond.js index 50b3a5572a58e6..33f224fc69a9d5 100644 --- a/test/parallel/test-http2-server-shutdown-before-respond.js +++ b/test/parallel/test-http2-server-shutdown-before-respond.js @@ -32,5 +32,5 @@ server.on('listening', common.mustCall(() => { })); req.resume(); req.on('data', common.mustNotCall()); - req.on('close', common.mustCall(() => server.close())); + req.on('end', common.mustCall(() => server.close())); })); diff --git a/test/parallel/test-http2-server-socket-destroy.js b/test/parallel/test-http2-server-socket-destroy.js index d631ef032b823b..03afc1957b8af4 100644 --- a/test/parallel/test-http2-server-socket-destroy.js +++ b/test/parallel/test-http2-server-socket-destroy.js @@ -52,4 +52,5 @@ server.on('listening', common.mustCall(() => { req.on('aborted', common.mustCall()); req.resume(); + req.on('end', common.mustCall()); })); diff --git a/test/parallel/test-https-max-headers-count.js b/test/parallel/test-https-max-headers-count.js new file mode 100644 index 00000000000000..8c099d1e5fb841 --- /dev/null +++ b/test/parallel/test-https-max-headers-count.js @@ -0,0 +1,73 @@ +'use strict'; +const common = require('../common'); +const fixtures = require('../common/fixtures'); + +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const https = require('https'); + +const serverOptions = { + key: fixtures.readKey('agent1-key.pem'), + cert: fixtures.readKey('agent1-cert.pem') +}; + +let requests = 0; +let responses = 0; + +const headers = {}; +const N = 2000; +for (let i = 0; i < N; ++i) { + headers[`key${i}`] = i; +} + +const maxAndExpected = [ // for server + [50, 50], + [1500, 1500], + [0, N + 2] // Host and Connection +]; +let max = maxAndExpected[requests][0]; +let expected = maxAndExpected[requests][1]; + +const server = https.createServer(serverOptions, common.mustCall((req, res) => { + assert.strictEqual(Object.keys(req.headers).length, expected); + if (++requests < maxAndExpected.length) { + max = maxAndExpected[requests][0]; + expected = maxAndExpected[requests][1]; + server.maxHeadersCount = max; + } + res.writeHead(200, headers); + res.end(); +}, 3)); +server.maxHeadersCount = max; + +server.listen(0, common.mustCall(() => { + const maxAndExpected = [ // for client + [20, 20], + [1200, 1200], + [0, N + 3] // Connection, Date and Transfer-Encoding + ]; + const doRequest = common.mustCall(() => { + const max = maxAndExpected[responses][0]; + const expected = maxAndExpected[responses][1]; + const req = https.request({ + port: server.address().port, + headers: headers, + rejectUnauthorized: false + }, (res) => { + assert.strictEqual(Object.keys(res.headers).length, expected); + res.on('end', () => { + if (++responses < maxAndExpected.length) { + doRequest(); + } else { + server.close(); + } + }); + res.resume(); + }); + req.maxHeadersCount = max; + req.end(); + }, 3); + doRequest(); +})); diff --git a/test/parallel/test-https-options-boolean-check.js b/test/parallel/test-https-options-boolean-check.js index cefa9c1d0a3769..bed5fb03253f7f 100644 --- a/test/parallel/test-https-options-boolean-check.js +++ b/test/parallel/test-https-options-boolean-check.js @@ -88,7 +88,7 @@ const caArrDataView = toDataView(caCert); }, { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError [ERR_INVALID_ARG_TYPE]', - message: 'The "key" argument must be one of type string, Buffer, ' + + message: 'The "options.key" property must be one of type string, Buffer, ' + `TypedArray, or DataView. Received type ${type}` }); }); @@ -113,8 +113,8 @@ const caArrDataView = toDataView(caCert); }, { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError [ERR_INVALID_ARG_TYPE]', - message: 'The "cert" argument must be one of type string, Buffer, ' + - `TypedArray, or DataView. Received type ${type}` + message: 'The "options.cert" property must be one of type string, Buffer,' + + ` TypedArray, or DataView. Received type ${type}` }); }); @@ -147,7 +147,7 @@ const caArrDataView = toDataView(caCert); }, { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError [ERR_INVALID_ARG_TYPE]', - message: 'The "ca" argument must be one of type string, Buffer, ' + + message: 'The "options.ca" property must be one of type string, Buffer, ' + `TypedArray, or DataView. Received type ${type}` }); }); diff --git a/test/parallel/test-inspector-esm.js b/test/parallel/test-inspector-esm.js index 3171da58cf7a4c..62f0feefade88d 100644 --- a/test/parallel/test-inspector-esm.js +++ b/test/parallel/test-inspector-esm.js @@ -9,12 +9,6 @@ const { resolve: UrlResolve } = require('url'); const fixtures = require('../common/fixtures'); const { NodeInstance } = require('../common/inspector-helper.js'); -function assertNoUrlsWhileConnected(response) { - assert.strictEqual(response.length, 1); - assert.ok(!response[0].hasOwnProperty('devtoolsFrontendUrl')); - assert.ok(!response[0].hasOwnProperty('webSocketDebuggerUrl')); -} - function assertScopeValues({ result }, expected) { const unmatched = new Set(Object.keys(expected)); for (const actual of result) { @@ -110,7 +104,6 @@ async function runTest() { '', fixtures.path('es-modules/loop.mjs')); const session = await child.connectInspectorSession(); - assertNoUrlsWhileConnected(await child.httpGet(null, '/json/list')); await testBreakpointOnStart(session); await testBreakpoint(session); await session.runToCompletion(); diff --git a/test/parallel/test-inspector-multisession-js.js b/test/parallel/test-inspector-multisession-js.js new file mode 100644 index 00000000000000..58533f4cd6241e --- /dev/null +++ b/test/parallel/test-inspector-multisession-js.js @@ -0,0 +1,59 @@ +'use strict'; +const common = require('../common'); + +common.skipIfInspectorDisabled(); + +const assert = require('assert'); +const { Session } = require('inspector'); +const path = require('path'); + +function debugged() { + return 42; +} + +async function test() { + const session1 = new Session(); + const session2 = new Session(); + + session1.connect(); + session2.connect(); + + let session1Paused = false; + let session2Paused = false; + + session1.on('Debugger.paused', () => session1Paused = true); + session2.on('Debugger.paused', () => session2Paused = true); + + console.log('Connected'); + + session1.post('Debugger.enable'); + session2.post('Debugger.enable'); + console.log('Debugger was enabled'); + + await new Promise((resolve, reject) => { + session1.post('Debugger.setBreakpointByUrl', { + 'lineNumber': 9, + 'url': path.resolve(__dirname, __filename), + 'columnNumber': 0, + 'condition': '' + }, (error, result) => { + return error ? reject(error) : resolve(result); + }); + }); + console.log('Breakpoint was set'); + + debugged(); + + // Both sessions will receive the paused event + assert(session1Paused); + assert(session2Paused); + console.log('Breakpoint was hit'); + + session1.disconnect(); + session2.disconnect(); + console.log('Sessions were disconnected'); +} + +common.crashOnUnhandledRejection(); + +test(); diff --git a/test/parallel/test-inspector-multisession-ws.js b/test/parallel/test-inspector-multisession-ws.js new file mode 100644 index 00000000000000..d17adab2f486cc --- /dev/null +++ b/test/parallel/test-inspector-multisession-ws.js @@ -0,0 +1,75 @@ +// Flags: --expose-internals +'use strict'; +const common = require('../common'); + +common.skipIfInspectorDisabled(); + +const { NodeInstance } = require('../common/inspector-helper.js'); + +// Sets up JS bindings session and runs till the "paused" event +const script = ` +const { Session } = require('inspector'); +const session = new Session(); +let done = false; +const interval = setInterval(() => { + if (done) + clearInterval(interval); +}, 150); +session.on('Debugger.paused', () => { + done = true; +}); +session.connect(); +session.post('Debugger.enable'); +console.log('Ready'); +`; + +async function setupSession(node) { + const session = await node.connectInspectorSession(); + await session.send([ + { 'method': 'Runtime.enable' }, + { 'method': 'Debugger.enable' }, + { 'method': 'Debugger.setPauseOnExceptions', + 'params': { 'state': 'none' } }, + { 'method': 'Debugger.setAsyncCallStackDepth', + 'params': { 'maxDepth': 0 } }, + { 'method': 'Profiler.enable' }, + { 'method': 'Profiler.setSamplingInterval', + 'params': { 'interval': 100 } }, + { 'method': 'Debugger.setBlackboxPatterns', + 'params': { 'patterns': [] } }, + { 'method': 'Runtime.runIfWaitingForDebugger' } + ]); + return session; +} + +async function testSuspend(sessionA, sessionB) { + console.log('[test]', 'Breaking in code and verifying events are fired'); + await sessionA.waitForNotification('Debugger.paused', 'Initial pause'); + sessionA.send({ 'method': 'Debugger.resume' }); + + await sessionA.waitForNotification('Runtime.consoleAPICalled', + 'Console output'); + sessionA.send({ 'method': 'Debugger.pause' }); + return Promise.all([ + sessionA.waitForNotification('Debugger.paused', 'SessionA paused'), + sessionB.waitForNotification('Debugger.paused', 'SessionB paused') + ]); +} + +async function runTest() { + const child = new NodeInstance(undefined, script); + + const [session1, session2] = + await Promise.all([setupSession(child), setupSession(child)]); + await testSuspend(session2, session1); + console.log('[test]', 'Should shut down after both sessions disconnect'); + + await session1.runToCompletion(); + await session2.send({ 'method': 'Debugger.disable' }); + await session2.disconnect(); + return child.expectShutdown(); +} + +common.crashOnUnhandledRejection(); + +runTest(); diff --git a/test/parallel/test-inspector-no-crash-ws-after-bindings.js b/test/parallel/test-inspector-no-crash-ws-after-bindings.js deleted file mode 100644 index 15fa96952ed125..00000000000000 --- a/test/parallel/test-inspector-no-crash-ws-after-bindings.js +++ /dev/null @@ -1,31 +0,0 @@ -// Flags: --expose-internals -'use strict'; -const common = require('../common'); -common.skipIfInspectorDisabled(); -common.crashOnUnhandledRejection(); -const { NodeInstance } = require('../common/inspector-helper.js'); -const assert = require('assert'); - -const expected = 'Can connect now!'; - -const script = ` - 'use strict'; - const { Session } = require('inspector'); - - const s = new Session(); - s.connect(); - console.error('${expected}'); - process.stdin.on('data', () => process.exit(0)); -`; - -async function runTests() { - const instance = new NodeInstance(['--inspect=0', '--expose-internals'], - script); - while (await instance.nextStderrString() !== expected); - assert.strictEqual(400, await instance.expectConnectionDeclined()); - instance.write('Stop!\n'); - assert.deepStrictEqual({ exitCode: 0, signal: null }, - await instance.expectShutdown()); -} - -runTests(); diff --git a/test/parallel/test-inspector-stress-http.js b/test/parallel/test-inspector-stress-http.js new file mode 100644 index 00000000000000..4787c35e32c899 --- /dev/null +++ b/test/parallel/test-inspector-stress-http.js @@ -0,0 +1,34 @@ +// Flags: --expose-internals +'use strict'; +const common = require('../common'); + +common.skipIfInspectorDisabled(); + +const assert = require('assert'); +const { NodeInstance } = require('../common/inspector-helper.js'); + +async function testHttp(child, number) { + try { + await child.httpGet(null, '/json/list'); + return true; + } catch (e) { + console.error(`Attempt ${number} failed`, e); + return false; + } +} + +async function runTest() { + const child = new NodeInstance(undefined, ''); + + const promises = []; + for (let i = 0; i < 100; i++) { + promises.push(testHttp(child, i)); + } + const result = await Promise.all(promises); + assert(!result.some((a) => !a), 'Some attempts failed'); + return child.kill(); +} + +common.crashOnUnhandledRejection(); + +runTest(); diff --git a/test/parallel/test-internal-errors.js b/test/parallel/test-internal-errors.js index cd2028c0f29b95..8fda4b25f2f5e2 100644 --- a/test/parallel/test-internal-errors.js +++ b/test/parallel/test-internal-errors.js @@ -93,20 +93,22 @@ common.expectsError(() => { }); // Test ERR_INVALID_FD_TYPE -assert.strictEqual(errors.message('ERR_INVALID_FD_TYPE', ['a']), +assert.strictEqual(errors.getMessage('ERR_INVALID_FD_TYPE', ['a']), 'Unsupported fd type: a'); // Test ERR_INVALID_URL_SCHEME -assert.strictEqual(errors.message('ERR_INVALID_URL_SCHEME', ['file']), +assert.strictEqual(errors.getMessage('ERR_INVALID_URL_SCHEME', ['file']), 'The URL must be of scheme file'); -assert.strictEqual(errors.message('ERR_INVALID_URL_SCHEME', [['file']]), +assert.strictEqual(errors.getMessage('ERR_INVALID_URL_SCHEME', [['file']]), 'The URL must be of scheme file'); -assert.strictEqual(errors.message('ERR_INVALID_URL_SCHEME', [['http', 'ftp']]), +assert.strictEqual(errors.getMessage('ERR_INVALID_URL_SCHEME', + [['http', 'ftp']]), 'The URL must be one of scheme http or ftp'); -assert.strictEqual(errors.message('ERR_INVALID_URL_SCHEME', [['a', 'b', 'c']]), +assert.strictEqual(errors.getMessage('ERR_INVALID_URL_SCHEME', + [['a', 'b', 'c']]), 'The URL must be one of scheme a, b, or c'); common.expectsError( - () => errors.message('ERR_INVALID_URL_SCHEME', [[]]), + () => errors.getMessage('ERR_INVALID_URL_SCHEME', [[]]), { code: 'ERR_ASSERTION', type: assert.AssertionError, @@ -114,79 +116,72 @@ common.expectsError( }); // Test ERR_MISSING_ARGS -assert.strictEqual(errors.message('ERR_MISSING_ARGS', ['name']), +assert.strictEqual(errors.getMessage('ERR_MISSING_ARGS', ['name']), 'The "name" argument must be specified'); -assert.strictEqual(errors.message('ERR_MISSING_ARGS', ['name', 'value']), +assert.strictEqual(errors.getMessage('ERR_MISSING_ARGS', ['name', 'value']), 'The "name" and "value" arguments must be specified'); -assert.strictEqual(errors.message('ERR_MISSING_ARGS', ['a', 'b', 'c']), +assert.strictEqual(errors.getMessage('ERR_MISSING_ARGS', ['a', 'b', 'c']), 'The "a", "b", and "c" arguments must be specified'); -common.expectsError( - () => errors.message('ERR_MISSING_ARGS'), - { - code: 'ERR_ASSERTION', - type: assert.AssertionError, - message: /^At least one arg needs to be specified$/ - }); // Test ERR_SOCKET_BAD_PORT assert.strictEqual( - errors.message('ERR_SOCKET_BAD_PORT', [0]), + errors.getMessage('ERR_SOCKET_BAD_PORT', [0]), 'Port should be > 0 and < 65536. Received 0.'); // Test ERR_TLS_CERT_ALTNAME_INVALID assert.strictEqual( - errors.message('ERR_TLS_CERT_ALTNAME_INVALID', ['altname']), + errors.getMessage('ERR_TLS_CERT_ALTNAME_INVALID', ['altname']), 'Hostname/IP does not match certificate\'s altnames: altname'); assert.strictEqual( - errors.message('ERR_INVALID_PROTOCOL', ['bad protocol', 'http']), + errors.getMessage('ERR_INVALID_PROTOCOL', ['bad protocol', 'http']), 'Protocol "bad protocol" not supported. Expected "http"' ); assert.strictEqual( - errors.message('ERR_HTTP_HEADERS_SENT', ['render']), + errors.getMessage('ERR_HTTP_HEADERS_SENT', ['render']), 'Cannot render headers after they are sent to the client' ); assert.strictEqual( - errors.message('ERR_INVALID_DOMAIN_NAME'), + errors.getMessage('ERR_INVALID_DOMAIN_NAME', []), 'Unable to determine the domain name' ); assert.strictEqual( - errors.message('ERR_INVALID_HTTP_TOKEN', ['Method', 'foo']), + errors.getMessage('ERR_INVALID_HTTP_TOKEN', ['Method', 'foo']), 'Method must be a valid HTTP token ["foo"]' ); assert.strictEqual( - errors.message('ERR_OUT_OF_RANGE', ['A', 'some values', 'B']), + errors.getMessage('ERR_OUT_OF_RANGE', ['A', 'some values', 'B']), 'The value of "A" is out of range. It must be some values. Received B' ); assert.strictEqual( - errors.message('ERR_UNESCAPED_CHARACTERS', ['Request path']), + errors.getMessage('ERR_UNESCAPED_CHARACTERS', ['Request path']), 'Request path contains unescaped characters' ); // Test ERR_DNS_SET_SERVERS_FAILED assert.strictEqual( - errors.message('ERR_DNS_SET_SERVERS_FAILED', ['err', 'servers']), + errors.getMessage('ERR_DNS_SET_SERVERS_FAILED', ['err', 'servers']), 'c-ares failed to set servers: "err" [servers]'); // Test ERR_ENCODING_NOT_SUPPORTED assert.strictEqual( - errors.message('ERR_ENCODING_NOT_SUPPORTED', ['enc']), + errors.getMessage('ERR_ENCODING_NOT_SUPPORTED', ['enc']), 'The "enc" encoding is not supported'); // Test error messages for async_hooks assert.strictEqual( - errors.message('ERR_ASYNC_CALLBACK', ['init']), + errors.getMessage('ERR_ASYNC_CALLBACK', ['init']), 'init must be a function'); assert.strictEqual( - errors.message('ERR_ASYNC_TYPE', [{}]), + errors.getMessage('ERR_ASYNC_TYPE', [{}]), 'Invalid name for async "type": [object Object]'); assert.strictEqual( - errors.message('ERR_INVALID_ASYNC_ID', ['asyncId', undefined]), + errors.getMessage('ERR_INVALID_ASYNC_ID', ['asyncId', undefined]), 'Invalid asyncId value: undefined'); { diff --git a/test/parallel/test-internal-fs-syncwritestream.js b/test/parallel/test-internal-fs-syncwritestream.js index c474d21cb43826..c751baf555d20f 100644 --- a/test/parallel/test-internal-fs-syncwritestream.js +++ b/test/parallel/test-internal-fs-syncwritestream.js @@ -5,7 +5,7 @@ const common = require('../common'); const assert = require('assert'); const fs = require('fs'); const path = require('path'); -const SyncWriteStream = require('internal/fs').SyncWriteStream; +const SyncWriteStream = require('internal/fs/utils').SyncWriteStream; const tmpdir = require('../common/tmpdir'); tmpdir.refresh(); diff --git a/test/parallel/test-internal-fs.js b/test/parallel/test-internal-fs.js index 9bc0a98b099f75..2e47e2a3823a9c 100644 --- a/test/parallel/test-internal-fs.js +++ b/test/parallel/test-internal-fs.js @@ -2,7 +2,7 @@ 'use strict'; const common = require('../common'); -const fs = require('internal/fs'); +const fs = require('internal/fs/utils'); // Valid encodings and no args should not throw. fs.assertEncoding(); diff --git a/test/parallel/test-module-loading-globalpaths.js b/test/parallel/test-module-loading-globalpaths.js index 798b7765bb6d5b..284dbb0b3cd564 100644 --- a/test/parallel/test-module-loading-globalpaths.js +++ b/test/parallel/test-module-loading-globalpaths.js @@ -4,6 +4,7 @@ const fixtures = require('../common/fixtures'); const assert = require('assert'); const path = require('path'); const fs = require('fs'); +const { COPYFILE_FICLONE } = fs.constants; const child_process = require('child_process'); const pkgName = 'foo'; const { addLibraryPath } = require('../common/shared-lib-util'); @@ -28,7 +29,7 @@ if (process.argv[2] === 'child') { testExecPath = path.join(prefixBinPath, path.basename(process.execPath)); } const mode = fs.statSync(process.execPath).mode; - fs.writeFileSync(testExecPath, fs.readFileSync(process.execPath)); + fs.copyFileSync(process.execPath, testExecPath, COPYFILE_FICLONE); fs.chmodSync(testExecPath, mode); const runTest = (expectedString, env) => { diff --git a/test/parallel/test-next-tick-fixed-queue-regression.js b/test/parallel/test-next-tick-fixed-queue-regression.js new file mode 100644 index 00000000000000..1fe82d02b10907 --- /dev/null +++ b/test/parallel/test-next-tick-fixed-queue-regression.js @@ -0,0 +1,18 @@ +'use strict'; + +const common = require('../common'); + +// This tests a highly specific regression tied to the FixedQueue size, which +// was introduced in Node.js 9.7.0: https://github.com/nodejs/node/pull/18617 +// More specifically, a nextTick list could potentially end up not fully +// clearing in one run through if exactly 2048 ticks were added after +// microtasks were executed within the nextTick loop. + +process.nextTick(() => { + Promise.resolve(1).then(() => { + for (let i = 0; i < 2047; i++) + process.nextTick(common.mustCall()); + const immediate = setImmediate(common.mustNotCall()); + process.nextTick(common.mustCall(() => clearImmediate(immediate))); + }); +}); diff --git a/test/parallel/test-fs-chdir-errormessage.js b/test/parallel/test-process-chdir-errormessage.js similarity index 100% rename from test/parallel/test-fs-chdir-errormessage.js rename to test/parallel/test-process-chdir-errormessage.js diff --git a/test/parallel/test-stream-duplex-error-write.js b/test/parallel/test-stream-duplex-error-write.js deleted file mode 100644 index 5a80ce5c3e4989..00000000000000 --- a/test/parallel/test-stream-duplex-error-write.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -const common = require('../common'); -const { Duplex } = require('stream'); -const { strictEqual } = require('assert'); - -const duplex = new Duplex({ - write(chunk, enc, cb) { - cb(new Error('kaboom')); - }, - read() { - this.push(null); - } -}); - -duplex.on('error', common.mustCall(function() { - strictEqual(this._readableState.errorEmitted, true); - strictEqual(this._writableState.errorEmitted, true); -})); - -duplex.on('end', common.mustNotCall()); - -duplex.end('hello'); -duplex.resume(); diff --git a/test/parallel/test-stream-readable-async-iterators.js b/test/parallel/test-stream-readable-async-iterators.js index b1801a1db3e580..39761b413260f1 100644 --- a/test/parallel/test-stream-readable-async-iterators.js +++ b/test/parallel/test-stream-readable-async-iterators.js @@ -115,6 +115,18 @@ async function tests() { readable.destroy(new Error('kaboom')); })(); + await (async function() { + console.log('call next() after error'); + const readable = new Readable({ + read() {} + }); + const iterator = readable[Symbol.asyncIterator](); + + const err = new Error('kaboom'); + readable.destroy(new Error('kaboom')); + await assert.rejects(iterator.next.bind(iterator), err); + })(); + await (async function() { console.log('read object mode'); const max = 42; diff --git a/test/parallel/test-stream-readable-destroy.js b/test/parallel/test-stream-readable-destroy.js index eecee04294e6fe..026aa8ca1603b8 100644 --- a/test/parallel/test-stream-readable-destroy.js +++ b/test/parallel/test-stream-readable-destroy.js @@ -189,18 +189,3 @@ const { inherits } = require('util'); read.push('hi'); read.on('data', common.mustNotCall()); } - -{ - // double error case - const read = new Readable({ - read() {} - }); - - read.on('close', common.mustCall()); - read.on('error', common.mustCall()); - - read.destroy(new Error('kaboom 1')); - read.destroy(new Error('kaboom 2')); - assert.strictEqual(read._readableState.errorEmitted, true); - assert.strictEqual(read.destroyed, true); -} diff --git a/test/parallel/test-tls-client-getephemeralkeyinfo.js b/test/parallel/test-tls-client-getephemeralkeyinfo.js index be6777b1ae0049..9432a277ac0fd0 100644 --- a/test/parallel/test-tls-client-getephemeralkeyinfo.js +++ b/test/parallel/test-tls-client-getephemeralkeyinfo.js @@ -82,7 +82,12 @@ function testECDHE256() { } function testECDHE512() { - test(521, 'ECDH', 'secp521r1', null); + test(521, 'ECDH', 'secp521r1', testX25519); + ntests++; +} + +function testX25519() { + test(253, 'ECDH', 'X25519', null); ntests++; } @@ -90,5 +95,5 @@ testNOT_PFS(); process.on('exit', function() { assert.strictEqual(ntests, nsuccess); - assert.strictEqual(ntests, 5); + assert.strictEqual(ntests, 6); }); diff --git a/test/parallel/test-tls-external-accessor.js b/test/parallel/test-tls-external-accessor.js deleted file mode 100644 index 33d371923a600c..00000000000000 --- a/test/parallel/test-tls-external-accessor.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -const common = require('../common'); -if (!common.hasCrypto) - common.skip('missing crypto'); - -const assert = require('assert'); -const tls = require('tls'); - -// Ensure accessing ._external doesn't hit an assert in the accessor method. -{ - const pctx = tls.createSecureContext().context; - const cctx = Object.create(pctx); - assert.throws(() => cctx._external, TypeError); - pctx._external; -} -{ - const pctx = tls.createSecurePair().credentials.context; - const cctx = Object.create(pctx); - assert.throws(() => cctx._external, TypeError); - pctx._external; -} diff --git a/test/parallel/test-tls-options-boolean-check.js b/test/parallel/test-tls-options-boolean-check.js index de21da63ff4983..242df1140e41c2 100644 --- a/test/parallel/test-tls-options-boolean-check.js +++ b/test/parallel/test-tls-options-boolean-check.js @@ -86,7 +86,7 @@ const caArrDataView = toDataView(caCert); }, { code: 'ERR_INVALID_ARG_TYPE', type: TypeError, - message: 'The "key" argument must be one of type string, Buffer, ' + + message: 'The "options.key" property must be one of type string, Buffer, ' + `TypedArray, or DataView. Received type ${type}` }); }); @@ -111,8 +111,8 @@ const caArrDataView = toDataView(caCert); }, { code: 'ERR_INVALID_ARG_TYPE', type: TypeError, - message: 'The "cert" argument must be one of type string, Buffer, ' + - `TypedArray, or DataView. Received type ${type}` + message: 'The "options.cert" property must be one of type string, Buffer,' + + ` TypedArray, or DataView. Received type ${type}` }); }); @@ -145,7 +145,7 @@ const caArrDataView = toDataView(caCert); }, { code: 'ERR_INVALID_ARG_TYPE', type: TypeError, - message: 'The "ca" argument must be one of type string, Buffer, ' + + message: 'The "options.ca" property must be one of type string, Buffer, ' + `TypedArray, or DataView. Received type ${type}` }); }); diff --git a/test/parallel/test-trace-events-fs-sync.js b/test/parallel/test-trace-events-fs-sync.js index 5bd9b99ba3fedf..60ab5efa3a1d3d 100644 --- a/test/parallel/test-trace-events-fs-sync.js +++ b/test/parallel/test-trace-events-fs-sync.js @@ -9,21 +9,8 @@ const traceFile = 'node_trace.1.log'; let gid = 1; let uid = 1; -let skipSymlinks = false; -// On Windows, creating symlinks requires admin privileges. -// We'll check if we have enough privileges. -if (common.isWindows) { - try { - const o = cp.execSync('whoami /priv'); - if (!o.includes('SeCreateSymbolicLinkPrivilege')) { - skipSymlinks = true; - } - } catch (er) { - // better safe than sorry - skipSymlinks = true; - } -} else { +if (!common.isWindows) { gid = process.getgid(); uid = process.getuid(); } @@ -111,7 +98,7 @@ tests['fs.sync.write'] = 'fs.writeFileSync("fs.txt", "123", "utf8");' + // On windows, we need permissions to test symlink and readlink. // We'll only try to run these tests if we have enough privileges. -if (!skipSymlinks) { +if (common.canCreateSymLink()) { tests['fs.sync.symlink'] = 'fs.writeFileSync("fs.txt", "123", "utf8");' + 'fs.symlinkSync("fs.txt", "linkx");' + 'fs.unlinkSync("linkx");' + diff --git a/test/parallel/test-url-format-whatwg.js b/test/parallel/test-url-format-whatwg.js index 26cef6063c212f..e5c3e369e80390 100644 --- a/test/parallel/test-url-format-whatwg.js +++ b/test/parallel/test-url-format-whatwg.js @@ -111,3 +111,8 @@ assert.strictEqual( url.format(myURL, { unicode: 0 }), 'http://xn--lck1c3crb1723bpq4a.com/a?a=b#c' ); + +assert.strictEqual( + url.format(new URL('http://xn--0zwm56d.com:8080/path'), { unicode: true }), + 'http://测试.com:8080/path' +); diff --git a/test/parallel/test-util-isDeepStrictEqual.js b/test/parallel/test-util-isDeepStrictEqual.js index 356a9a71324971..938781a43084a5 100644 --- a/test/parallel/test-util-isDeepStrictEqual.js +++ b/test/parallel/test-util-isDeepStrictEqual.js @@ -419,8 +419,6 @@ notUtilIsDeepStrict([1, , , 3], [1, , , 3, , , ]); const err3 = new TypeError('foo1'); notUtilIsDeepStrict(err1, err2, assert.AssertionError); notUtilIsDeepStrict(err1, err3, assert.AssertionError); - // TODO: evaluate if this should throw or not. The same applies for RegExp - // Date and any object that has the same keys but not the same prototype. notUtilIsDeepStrict(err1, {}, assert.AssertionError); } diff --git a/test/pseudo-tty/test-assert-colors.js b/test/pseudo-tty/test-assert-colors.js index 39bee740d2ea15..75d3af55796e1b 100644 --- a/test/pseudo-tty/test-assert-colors.js +++ b/test/pseudo-tty/test-assert-colors.js @@ -5,13 +5,16 @@ const assert = require('assert').strict; try { // Activate colors even if the tty does not support colors. process.env.COLORTERM = '1'; - assert.deepStrictEqual([1, 2], [2, 2]); + assert.deepStrictEqual([1, 2, 2, 2], [2, 2, 2, 2]); } catch (err) { const expected = 'Input A expected to strictly deep-equal input B:\n' + - '\u001b[32m+ expected\u001b[39m \u001b[31m- actual\u001b[39m\n\n' + + '\u001b[32m+ expected\u001b[39m \u001b[31m- actual\u001b[39m' + + ' \u001b[34m...\u001b[39m Lines skipped\n\n' + ' [\n' + '\u001b[31m-\u001b[39m 1,\n' + '\u001b[32m+\u001b[39m 2,\n' + + ' 2,\n' + + '\u001b[34m...\u001b[39m\n' + ' 2\n' + ' ]'; assert.strictEqual(err.message, expected); diff --git a/test/pseudo-tty/test-tty-stdin-end.js b/test/pseudo-tty/test-tty-stdin-end.js new file mode 100644 index 00000000000000..c78f58446d03e9 --- /dev/null +++ b/test/pseudo-tty/test-tty-stdin-end.js @@ -0,0 +1,7 @@ +'use strict'; +require('../common'); + +// This test ensures that Node.js doesn't crash on `process.stdin.emit("end")`. +// https://github.com/nodejs/node/issues/1068 + +process.stdin.emit('end'); diff --git a/test/pseudo-tty/test-tty-stdin-end.out b/test/pseudo-tty/test-tty-stdin-end.out new file mode 100644 index 00000000000000..e69de29bb2d1d6 diff --git a/test/sequential/test-async-wrap-getasyncid.js b/test/sequential/test-async-wrap-getasyncid.js index 64c4fd5cd8ab50..971296915ceecb 100644 --- a/test/sequential/test-async-wrap-getasyncid.js +++ b/test/sequential/test-async-wrap-getasyncid.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); const fs = require('fs'); -const fsPromises = require('fs/promises'); +const fsPromises = fs.promises; const net = require('net'); const providers = Object.assign({}, process.binding('async_wrap').Providers); const fixtures = require('../common/fixtures'); diff --git a/test/sequential/test-benchmark-http.js b/test/sequential/test-benchmark-http.js index 13d0e4d16aaf8f..22efce51909481 100644 --- a/test/sequential/test-benchmark-http.js +++ b/test/sequential/test-benchmark-http.js @@ -18,6 +18,7 @@ runBenchmark('http', 'chunkedEnc=true', 'chunks=0', 'dur=0.1', + 'duplicates=1', 'input=keep-alive', 'key=""', 'len=1', diff --git a/test/sequential/test-inspector-bindings.js b/test/sequential/test-inspector-bindings.js index bf97d8b5124e86..c23c8520e0601d 100644 --- a/test/sequential/test-inspector-bindings.js +++ b/test/sequential/test-inspector-bindings.js @@ -76,15 +76,6 @@ function testSampleDebugSession() { }; const session = new inspector.Session(); session.connect(); - let secondSessionOpened = false; - const secondSession = new inspector.Session(); - try { - secondSession.connect(); - secondSessionOpened = true; - } catch (error) { - // expected as the session already exists - } - assert.strictEqual(secondSessionOpened, false); session.on('Debugger.paused', (notification) => debuggerPausedCallback(session, notification)); let cbAsSecondArgCalled = false; diff --git a/test/sequential/test-inspector-module.js b/test/sequential/test-inspector-module.js index 2435347e798248..eaecd49c982311 100644 --- a/test/sequential/test-inspector-module.js +++ b/test/sequential/test-inspector-module.js @@ -55,16 +55,6 @@ common.expectsError( } ); -const session2 = new Session(); -common.expectsError( - () => session2.connect(), - { - code: 'ERR_INSPECTOR_ALREADY_CONNECTED', - type: Error, - message: 'Another inspector session is already connected' - } -); - session.disconnect(); // Calling disconnect twice should not throw. session.disconnect(); diff --git a/test/sequential/test-inspector.js b/test/sequential/test-inspector.js index 4e0315807b628a..0a9b2ccd1abd3d 100644 --- a/test/sequential/test-inspector.js +++ b/test/sequential/test-inspector.js @@ -37,12 +37,6 @@ function checkException(message) { 'An exception occurred during execution'); } -function assertNoUrlsWhileConnected(response) { - assert.strictEqual(1, response.length); - assert.ok(!response[0].hasOwnProperty('devtoolsFrontendUrl')); - assert.ok(!response[0].hasOwnProperty('webSocketDebuggerUrl')); -} - function assertScopeValues({ result }, expected) { const unmatched = new Set(Object.keys(expected)); for (const actual of result) { @@ -290,7 +284,6 @@ async function runTest() { await child.httpGet(null, '/json/badpath').catch(checkBadPath); const session = await child.connectInspectorSession(); - assertNoUrlsWhileConnected(await child.httpGet(null, '/json/list')); await testBreakpointOnStart(session); await testBreakpoint(session); await testI18NCharacters(session); diff --git a/tools/doc/addon-verify.js b/tools/doc/addon-verify.js index 9fcc71ed93f0c9..a3d1beb4b8e12e 100644 --- a/tools/doc/addon-verify.js +++ b/tools/doc/addon-verify.js @@ -1,68 +1,52 @@ 'use strict'; -const fs = require('fs'); -const path = require('path'); -const marked = require('marked'); +const { mkdir, readFileSync, writeFile } = require('fs'); +const { resolve } = require('path'); +const { lexer } = require('marked'); -const rootDir = path.resolve(__dirname, '..', '..'); -const doc = path.resolve(rootDir, 'doc', 'api', 'addons.md'); -const verifyDir = path.resolve(rootDir, 'test', 'addons'); +const rootDir = resolve(__dirname, '..', '..'); +const doc = resolve(rootDir, 'doc', 'api', 'addons.md'); +const verifyDir = resolve(rootDir, 'test', 'addons'); -const contents = fs.readFileSync(doc).toString(); - -const tokens = marked.lexer(contents); +const tokens = lexer(readFileSync(doc, 'utf8')); +const addons = {}; let id = 0; - let currentHeader; -const addons = {}; -tokens.forEach((token) => { - if (token.type === 'heading' && token.text) { - currentHeader = token.text; - addons[currentHeader] = { - files: {} - }; + +const validNames = /^\/\/\s+(.*\.(?:cc|h|js))[\r\n]/; +tokens.forEach(({ type, text }) => { + if (type === 'heading') { + currentHeader = text; + addons[currentHeader] = { files: {} }; } - if (token.type === 'code') { - var match = token.text.match(/^\/\/\s+(.*\.(?:cc|h|js))[\r\n]/); + if (type === 'code') { + const match = text.match(validNames); if (match !== null) { - addons[currentHeader].files[match[1]] = token.text; + addons[currentHeader].files[match[1]] = text; } } }); -for (var header in addons) { - verifyFiles(addons[header].files, - header, - console.log.bind(null, 'wrote'), - function(err) { if (err) throw err; }); -} -function once(fn) { - var once = false; - return function() { - if (once) - return; - once = true; - fn.apply(this, arguments); - }; -} +Object.keys(addons).forEach((header) => { + verifyFiles(addons[header].files, header); +}); + +function verifyFiles(files, blockName) { + const fileNames = Object.keys(files); -function verifyFiles(files, blockName, onprogress, ondone) { // Must have a .cc and a .js to be a valid test. - if (!Object.keys(files).some((name) => /\.cc$/.test(name)) || - !Object.keys(files).some((name) => /\.js$/.test(name))) { + if (!fileNames.some((name) => name.endsWith('.cc')) || + !fileNames.some((name) => name.endsWith('.js'))) { return; } - blockName = blockName - .toLowerCase() - .replace(/\s/g, '_') - .replace(/[^a-z\d_]/g, ''); - const dir = path.resolve( + blockName = blockName.toLowerCase().replace(/\s/g, '_').replace(/\W/g, ''); + const dir = resolve( verifyDir, - `${(++id < 10 ? '0' : '') + id}_${blockName}` + `${String(++id).padStart(2, '0')}_${blockName}` ); - files = Object.keys(files).map(function(name) { + files = fileNames.map((name) => { if (name === 'test.js') { files[name] = `'use strict'; const common = require('../../common'); @@ -73,42 +57,34 @@ ${files[name].replace( `; } return { - path: path.resolve(dir, name), + path: resolve(dir, name), name: name, content: files[name] }; }); files.push({ - path: path.resolve(dir, 'binding.gyp'), + path: resolve(dir, 'binding.gyp'), content: JSON.stringify({ targets: [ { target_name: 'addon', defines: [ 'V8_DEPRECATION_WARNINGS=1' ], - sources: files.map(function(file) { - return file.name; - }) + sources: files.map(({ name }) => name) } ] }) }); - fs.mkdir(dir, function() { + mkdir(dir, () => { // Ignore errors. - const done = once(ondone); - var waiting = files.length; - files.forEach(function(file) { - fs.writeFile(file.path, file.content, function(err) { + files.forEach(({ path, content }) => { + writeFile(path, content, (err) => { if (err) - return done(err); - - if (onprogress) - onprogress(file.path); + throw err; - if (--waiting === 0) - done(); + console.log(`Wrote ${path}`); }); }); }); diff --git a/tools/doc/generate.js b/tools/doc/generate.js index 0da9dba4e6558f..9f217b19c7225f 100644 --- a/tools/doc/generate.js +++ b/tools/doc/generate.js @@ -29,7 +29,6 @@ const fs = require('fs'); const args = process.argv.slice(2); let format = 'json'; -let template = null; let filename = null; let nodeVersion = null; let analytics = null; @@ -39,8 +38,6 @@ args.forEach(function(arg) { filename = arg; } else if (arg.startsWith('--format=')) { format = arg.replace(/^--format=/, ''); - } else if (arg.startsWith('--template=')) { - template = arg.replace(/^--template=/, ''); } else if (arg.startsWith('--node-version=')) { nodeVersion = arg.replace(/^--node-version=/, ''); } else if (arg.startsWith('--analytics=')) { @@ -71,7 +68,7 @@ function next(er, input) { break; case 'html': - require('./html')({ input, filename, template, nodeVersion, analytics }, + require('./html')({ input, filename, nodeVersion, analytics }, (err, html) => { if (err) throw err; console.log(html); diff --git a/tools/doc/html.js b/tools/doc/html.js index ff0230309ee99a..7712290b4c61ed 100644 --- a/tools/doc/html.js +++ b/tools/doc/html.js @@ -25,7 +25,6 @@ const common = require('./common.js'); const fs = require('fs'); const marked = require('marked'); const path = require('path'); -const preprocess = require('./preprocess.js'); const typeParser = require('./type-parser.js'); module.exports = toHTML; @@ -42,76 +41,36 @@ marked.setOptions({ renderer: renderer }); -// TODO(chrisdickinson): never stop vomiting / fix this. -const gtocPath = path.resolve(path.join( - __dirname, - '..', - '..', - 'doc', - 'api', - '_toc.md' -)); -var gtocLoading = null; -var gtocData = null; +const docPath = path.resolve(__dirname, '..', '..', 'doc'); + +const gtocPath = path.join(docPath, 'api', '_toc.md'); +const gtocMD = fs.readFileSync(gtocPath, 'utf8').replace(/^@\/\/.*$/gm, ''); +const gtocHTML = marked(gtocMD).replace( + / `' }); - } - depth++; - output.push(tok); - return; - } - if (tok.type === 'html' && common.isYAMLBlock(tok.text)) { - tok.text = parseYAML(tok.text); - } - state = null; - output.push(tok); - return; - } - if (state === 'LIST') { - if (tok.type === 'list_start') { - depth++; - output.push(tok); - return; - } - if (tok.type === 'list_end') { - depth--; - output.push(tok); - if (depth === 0) { - state = null; - output.push({ type: 'html', text: '' }); - } - return; + state = null; } } output.push(tok); diff --git a/tools/doc/preprocess.js b/tools/doc/preprocess.js index f8d394735dd30b..554af2ccb77ae0 100644 --- a/tools/doc/preprocess.js +++ b/tools/doc/preprocess.js @@ -6,7 +6,7 @@ const path = require('path'); const fs = require('fs'); const includeExpr = /^@include\s+([\w-]+)(?:\.md)?$/gmi; -const commentExpr = /^@\/\/.*$/gmi; +const commentExpr = /^@\/\/.*$/gm; function processIncludes(inputFile, input, cb) { const includes = input.match(includeExpr); diff --git a/tools/doc/type-parser.js b/tools/doc/type-parser.js index 6314a4889f06e6..e7a2c2576e3b66 100644 --- a/tools/doc/type-parser.js +++ b/tools/doc/type-parser.js @@ -130,7 +130,7 @@ function toLink(typeInput) { typeTexts.forEach((typeText) => { typeText = typeText.trim(); if (typeText) { - let typeUrl = null; + let typeUrl; // To support type[], type[][] etc., we store the full string // and use the bracket-less version to lookup the type URL. @@ -143,7 +143,7 @@ function toLink(typeInput) { typeUrl = `${jsDataStructuresUrl}#${primitive}_type`; } else if (jsGlobalTypes.includes(typeText)) { typeUrl = `${jsGlobalObjectsUrl}${typeText}`; - } else if (customTypesMap[typeText]) { + } else { typeUrl = customTypesMap[typeText]; } diff --git a/tools/eslint-rules/eslint-check.js b/tools/eslint-rules/eslint-check.js new file mode 100644 index 00000000000000..00a5234733ec05 --- /dev/null +++ b/tools/eslint-rules/eslint-check.js @@ -0,0 +1,60 @@ +/** + * @fileoverview Check that common.skipIfEslintMissing is used if + * the eslint module is required. + */ +'use strict'; + +const utils = require('./rules-utils.js'); + +//------------------------------------------------------------------------------ +// Rule Definition +//------------------------------------------------------------------------------ +const msg = 'Please add a skipIfEslintMissing() call to allow this test to ' + + 'be skipped when Node.js is built from a source tarball.'; + +module.exports = function(context) { + const missingCheckNodes = []; + var commonModuleNode = null; + var hasEslintCheck = false; + + function testEslintUsage(context, node) { + if (utils.isRequired(node, ['../../tools/node_modules/eslint'])) { + missingCheckNodes.push(node); + } + + if (utils.isCommonModule(node)) { + commonModuleNode = node; + } + } + + function checkMemberExpression(context, node) { + if (utils.usesCommonProperty(node, ['skipIfEslintMissing'])) { + hasEslintCheck = true; + } + } + + function reportIfMissing(context) { + if (!hasEslintCheck) { + missingCheckNodes.forEach((node) => { + context.report({ + node, + message: msg, + fix: (fixer) => { + if (commonModuleNode) { + return fixer.insertTextAfter( + commonModuleNode, + '\ncommon.skipIfEslintMissing();' + ); + } + } + }); + }); + } + } + + return { + 'CallExpression': (node) => testEslintUsage(context, node), + 'MemberExpression': (node) => checkMemberExpression(context, node), + 'Program:exit': (node) => reportIfMissing(context, node) + }; +}; diff --git a/tools/eslint-rules/inspector-check.js b/tools/eslint-rules/inspector-check.js index 00a2dd02963558..189b023efc6195 100644 --- a/tools/eslint-rules/inspector-check.js +++ b/tools/eslint-rules/inspector-check.js @@ -11,7 +11,7 @@ const utils = require('./rules-utils.js'); // Rule Definition //------------------------------------------------------------------------------ const msg = 'Please add a skipIfInspectorDisabled() call to allow this ' + - 'test to be skippped when Node is built \'--without-inspector\'.'; + 'test to be skipped when Node is built \'--without-inspector\'.'; module.exports = function(context) { const missingCheckNodes = []; diff --git a/tools/test.py b/tools/test.py index 9bee9c2a222bc7..66b9c7291f36af 100755 --- a/tools/test.py +++ b/tools/test.py @@ -298,10 +298,8 @@ def HasRun(self, output): if output.HasCrashed(): self.severity = 'crashed' - exit_code = output.output.exit_code - self.traceback = "oh no!\nexit code: " + PrintCrashed(exit_code) - if output.HasTimedOut(): + elif output.HasTimedOut(): self.severity = 'fail' else: @@ -333,7 +331,7 @@ def HasRun(self, output): (total_seconds, duration.microseconds / 1000)) if self.severity is not 'ok' or self.traceback is not '': if output.HasTimedOut(): - self.traceback = 'timeout' + self.traceback = 'timeout\n' + output.output.stdout + output.output.stderr self._printDiagnostic() logger.info(' ...') @@ -1749,7 +1747,7 @@ def DoSkip(case): timed_tests.sort(lambda a, b: a.CompareTime(b)) index = 1 for entry in timed_tests[:20]: - t = FormatTime(entry.duration) + t = FormatTime(entry.duration.total_seconds()) sys.stderr.write("%4i (%s) %s\n" % (index, t, entry.GetLabel())) index += 1