From da3265ad82e3e8ede3246e9c5e086ab6620d0702 Mon Sep 17 00:00:00 2001 From: Myles Borins Date: Wed, 13 Sep 2017 13:29:42 +0200 Subject: [PATCH 001/145] errors: backport ERR_INVALID_PROTOCOL to v8.x This error code originally landed in a semver-major commit and is used by the ESM implementation. This backport includes the error message and the documentation for the error. I did attempt to write a test for this, but it did not seem possible to catch an exception during import, I was also unable to execute `node --experimental-modules` properly inside of a child_process. I'll dig more into getting a test together, but we should backport this fix in the mean time. Refs: https://github.com/nodejs/node/pull/14423 Fixes: https://github.com/nodejs/node/issues/15374 PR-URL: https://github.com/nodejs/node/pull/15388 Reviewed-By: Bradley Farias Reviewed-By: James M Snell --- doc/api/errors.md | 5 +++++ lib/internal/errors.js | 2 ++ 2 files changed, 7 insertions(+) diff --git a/doc/api/errors.md b/doc/api/errors.md index 0df38e69f71815..81e7cc6d73492e 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -835,6 +835,11 @@ communication channel to a child process. See [`subprocess.send()`] and Used generically to identify when an invalid or unexpected value has been passed in an options object. + +### ERR_INVALID_PROTOCOL + +Used when an invalid `options.protocol` is passed. + ### ERR_INVALID_SYNC_FORK_INPUT diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 3afbc68d963841..3029f504ba6839 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -196,6 +196,8 @@ E('ERR_INVALID_OPT_VALUE', return `The value "${String(value)}" is invalid for option "${name}"`; }); E('ERR_INVALID_PERFORMANCE_MARK', 'The "%s" performance mark has not been set'); +E('ERR_INVALID_PROTOCOL', (protocol, expectedProtocol) => + `Protocol "${protocol}" not supported. Expected "${expectedProtocol}"`); E('ERR_INVALID_SYNC_FORK_INPUT', (value) => { return 'Asynchronous forks do not support Buffer, Uint8Array or string' + From a792ea770953b601dd20ead778258bd238718a9f Mon Sep 17 00:00:00 2001 From: Myles Borins Date: Wed, 13 Sep 2017 10:50:43 +0200 Subject: [PATCH 002/145] docs: update 8.5.0 changelog MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The original changelog included incorrect information regarding the new perf_hooks api. refs: https://github.com/nodejs/node/pull/15308#issuecomment-328874385 PR-URL: https://github.com/nodejs/node/pull/15384 Reviewed-By: Anna Henningsen Reviewed-By: Michaël Zasso Reviewed-By: Evan Lucas Reviewed-By: James M Snell --- doc/api/assert.md | 2 +- doc/changelogs/CHANGELOG_V8.md | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/doc/api/assert.md b/doc/api/assert.md index d019540ee6c9bf..b1175e5e489e5d 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -105,7 +105,7 @@ parameter is undefined, a default error message is assigned. added: v1.2.0 changes: - version: v8.5.0 - pr-url: https://github.com/nodejs/node/pull/12142 + pr-url: https://github.com/nodejs/node/pull/15001 description: Error names and messages are now properly compared - version: v8.0.0 pr-url: https://github.com/nodejs/node/pull/12142 diff --git a/doc/changelogs/CHANGELOG_V8.md b/doc/changelogs/CHANGELOG_V8.md index 02cf749e3cbf76..e350a21d8c2692 100644 --- a/doc/changelogs/CHANGELOG_V8.md +++ b/doc/changelogs/CHANGELOG_V8.md @@ -72,8 +72,7 @@ * **perf_hooks** * An initial implementation of the Performance Timing API for Node.js. This is the same Performance Timing API implemented by modern browsers with a number of Node.js - specific properties. The User Timing mark() and measure() APIs are implemented, - as is a Node.js specific flavor of the Frame Timing for measuring event loop duration. + specific properties. The User Timing mark() and measure() APIs are implemented. [#14680](https://github.com/nodejs/node/pull/14680) * **tls** * multiple PFX in createSecureContext From d82ae0cb6e58783dafeecfa0f9463fdd6ce05b93 Mon Sep 17 00:00:00 2001 From: Gergely Nemeth Date: Thu, 7 Sep 2017 09:21:20 +0200 Subject: [PATCH 003/145] test: backward compatible api for tty PR-URL: https://github.com/nodejs/node/pull/15235 Reviewed-By: Luigi Pinca Reviewed-By: James M Snell Reviewed-By: Daijiro Wachi --- test/parallel/test-tty-backwards-api.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 test/parallel/test-tty-backwards-api.js diff --git a/test/parallel/test-tty-backwards-api.js b/test/parallel/test-tty-backwards-api.js new file mode 100644 index 00000000000000..547184728ebaf8 --- /dev/null +++ b/test/parallel/test-tty-backwards-api.js @@ -0,0 +1,25 @@ +'use strict'; +const common = require('../common'); + +const noop = () => {}; +const TTY = process.binding('tty_wrap').TTY = function() {}; + +TTY.prototype = { + setBlocking: noop, + getWindowSize: noop +}; + +const { WriteStream } = require('tty'); + +const methods = [ + 'cursorTo', + 'moveCursor', + 'clearLine', + 'clearScreenDown' +]; + +methods.forEach((method) => { + require('readline')[method] = common.mustCall(); + const writeStream = new WriteStream(1); + writeStream[method](1, 2); +}); From 7fa2bee5e779faec025837e78a6837bb32bd07fc Mon Sep 17 00:00:00 2001 From: Luigi Pinca Date: Sun, 17 Sep 2017 09:30:16 +0200 Subject: [PATCH 004/145] doc: add documentation for the 'timeout' event Adds the `'timeout'` event to the `http.ClientRequest` documentation. PR-URL: https://github.com/nodejs/node/pull/15443 Fixes: https://github.com/nodejs/node/issues/14856 Reviewed-By: Gibson Fahnestock Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Ruben Bridgewater --- doc/api/http.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/doc/api/http.md b/doc/api/http.md index e646e291ac724c..f7355e0fbe6630 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -427,6 +427,16 @@ added: v0.5.3 Emitted after a socket is assigned to this request. +### Event: 'timeout' + + +Emitted when the underlying socket times out from inactivity. This only notifies +that the socket has been idle. The request must be aborted manually. + +See also: [`request.setTimeout()`][] + ### Event: 'upgrade' + +* `name` {string} +* Returns: {string} + +Reads out a header on the request. Note that the name is case insensitive. + +Example: +```js +const contentType = request.getHeader('Content-Type'); +``` + +### request.removeHeader(name) + + +* `name` {string} + +Removes a header that's already defined into headers object. + +Example: +```js +request.removeHeader('Content-Type'); +``` + +### request.setHeader(name, value) + + +* `name` {string} +* `value` {string} + +Sets a single header value for headers object. If this header already exists in +the to-be-sent headers, its value will be replaced. Use an array of strings +here to send multiple headers with the same name. + +Example: +```js +request.setHeader('Content-Type', 'application/json'); +``` + +or + +```js +request.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); +``` + ### request.setNoDelay([noDelay]) -* `callbacks` {Object} the callbacks to register +* `callbacks` {Object} the [Hook Callbacks][] to register + * `init` {Function} The [`init` callback][]. + * `before` {Function} The [`before` callback][]. + * `after` {Function} The [`after` callback][]. + * `destroy` {Function} The [`destroy` callback][]. * Returns: `{AsyncHook}` instance used for disabling and enabling hooks Registers functions to be called for different lifetime events of each async @@ -87,6 +91,31 @@ be tracked then only the `destroy` callback needs to be passed. The specifics of all functions that can be passed to `callbacks` is in the section [`Hook Callbacks`][]. +```js +const async_hooks = require('async_hooks'); + +const asyncHook = async_hooks.createHook({ + init(asyncId, type, triggerAsyncId, resource) { }, + destroy(asyncId) { } +}); +``` + +Note that the callbacks will be inherited via the prototype chain: + +```js +class MyAsyncCallbacks { + init(asyncId, type, triggerAsyncId, resource) { } + destroy(asyncId) {} +} + +class MyAddedCallbacks extends MyAsyncCallbacks { + before(asyncId) { } + after(asyncId) { } +} + +const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); +``` + ##### Error Handling If any `AsyncHook` callbacks throw, the application will print the stack trace @@ -187,11 +216,12 @@ require('net').createServer().listen(function() { this.close(); }); clearTimeout(setTimeout(() => {}, 10)); ``` -Every new resource is assigned a unique ID. +Every new resource is assigned an ID that is unique within the scope of the +current process. ###### `type` -The `type` is a string that represents the type of resource that caused +The `type` is a string identifying the type of resource that caused `init` to be called. Generally, it will correspond to the name of the resource's constructor. @@ -214,8 +244,8 @@ when listening to the hooks. ###### `triggerId` -`triggerAsyncId` is the `asyncId` of the resource that caused (or "triggered") the -new resource to initialize and that caused `init` to call. This is different +`triggerAsyncId` is the `asyncId` of the resource that caused (or "triggered") +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. @@ -253,26 +283,27 @@ propagating what resource is responsible for the new resource's existence. ###### `resource` -`resource` is an object that represents the actual resource. This can contain -useful information such as the hostname for the `GETADDRINFOREQWRAP` resource -type, which will be used when looking up the ip for the hostname in -`net.Server.listen`. The API for getting this information is currently not -considered public, but using the Embedder API users can provide and document -their own resource objects. Such as resource object could for example contain -the SQL query being executed. +`resource` is an object that represents the actual async resource that has +been initialized. This can contain useful information that can vary based on +the value of `type`. For instance, for the `GETADDRINFOREQWRAP` resource type, +`resource` provides the hostname used when looking up the IP address for the +hostname in `net.Server.listen()`. The API for accessing this information is +currently not considered public, but using the Embedder API, users can provide +and document their own resource objects. Such a resource object could for +example 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 `parentId` property -that equals the `asyncId` of a parent Promise, if there is one, and -`undefined` otherwise. For example, in the case of `b = a.then(handler)`, -`a` is considered a parent Promise of `b`. +set to the `asyncId` of a parent Promise, if there is one, and `undefined` +otherwise. For example, in the case of `b = a.then(handler)`, `a` is considered +a parent Promise of `b`. *Note*: 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. -###### asynchronous context example +###### Asynchronous context example -Below is another example with additional information about the calls to +The following is an example with additional information about the calls to `init` between the `before` and `after` calls, specifically what the callback to `listen()` will look like. The output formatting is slightly more elaborate to make calling context easier to see. @@ -348,10 +379,10 @@ Only using `execution` to graph resource allocation results in the following: TTYWRAP(6) -> Timeout(4) -> TIMERWRAP(5) -> TickObject(3) -> root(1) ``` -The `TCPWRAP` isn't part of this graph; even though it was the reason for +The `TCPWRAP` is not part of this graph; even though it was the reason for `console.log()` being called. This is because binding to a port without a -hostname is actually synchronous, but to maintain a completely asynchronous API -the user's callback is placed in a `process.nextTick()`. +hostname is a *synchronous* operation, but to maintain a completely asynchronous +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`. @@ -369,9 +400,10 @@ resource about to execute the callback. The `before` callback will be called 0 to N times. The `before` callback will typically be called 0 times if the asynchronous operation was cancelled -or for example if no connections are received by a TCP server. Asynchronous -like the TCP server will typically call the `before` callback multiple times, -while other operations like `fs.open()` will only call it once. +or, for example, if no connections are received by a TCP server. Persistent +asynchronous resources like a TCP server will typically call the `before` +callback multiple times, while other operations like `fs.open()` will only call +it only once. ##### `after(asyncId)` @@ -381,7 +413,7 @@ while other operations like `fs.open()` will only call it once. Called immediately after the callback specified in `before` is completed. *Note:* If an uncaught exception occurs during execution of the callback then -`after` will run after the `'uncaughtException'` event is emitted or a +`after` will run *after* the `'uncaughtException'` event is emitted or a `domain`'s handler runs. @@ -389,22 +421,25 @@ Called immediately after the callback specified in `before` is completed. * `asyncId` {number} -Called after the resource corresponding to `asyncId` is destroyed. It is also called -asynchronously from the embedder API `emitDestroy()`. +Called after the resource corresponding to `asyncId` is destroyed. It is also +called asynchronously from the embedder API `emitDestroy()`. -*Note:* Some resources depend on GC for cleanup, so if a reference is made to -the `resource` object passed to `init` it's possible that `destroy` is -never called, causing a memory leak in the application. Of course if -the resource doesn't depend on GC then this isn't an issue. +*Note:* Some resources depend on garbage collection for cleanup, so if a +reference is made to the `resource` object passed to `init` it is possible that +`destroy` will never be called, causing a memory leak in the application. If +the resource does not depend on garbage collection, then this will not be an +issue. #### `async_hooks.executionAsyncId()` -* Returns {number} the `asyncId` of the current execution context. Useful to track - when something calls. +* Returns {number} the `asyncId` of the current execution context. Useful to + track when something calls. For example: ```js +const async_hooks = require('async_hooks'); + console.log(async_hooks.executionAsyncId()); // 1 - bootstrap fs.open(path, 'r', (err, fd) => { console.log(async_hooks.executionAsyncId()); // 6 - open() @@ -453,10 +488,9 @@ const server = net.createServer((conn) => { ## JavaScript Embedder API -Library developers that handle their own I/O, a connection pool, or -callback queues will need to hook into the AsyncWrap API so that all the -appropriate callbacks are called. To accommodate this a JavaScript API is -provided. +Library developers that handle their own asychronous resources performing tasks +like I/O, connection pooling, or managing callback queues may use the `AsyncWrap` +JavaScript API so that all the appropriate callbacks are called. ### `class AsyncResource()` @@ -466,9 +500,9 @@ own resources. The `init` hook will trigger when an `AsyncResource` is instantiated. -It is important that `before`/`after` calls are unwound +*Note*: It is important that `before`/`after` calls are unwound in the same order they are called. Otherwise an unrecoverable exception -will occur and node will abort. +will occur and the process will abort. The following is an overview of the `AsyncResource` API. @@ -499,9 +533,9 @@ asyncResource.triggerAsyncId(); #### `AsyncResource(type[, triggerAsyncId])` * arguments - * `type` {string} the type of ascyc event - * `triggerAsyncId` {number} the ID of the execution context that created this async - event + * `type` {string} the type of async event + * `triggerAsyncId` {number} the ID of the execution context that created this + async event Example usage: @@ -531,9 +565,9 @@ class DBQuery extends AsyncResource { * Returns {undefined} -Call all `before` callbacks and let them know a new asynchronous execution -context is being entered. If nested calls to `emitBefore()` are made, the stack -of `asyncId`s will be tracked and properly unwound. +Call all `before` callbacks to notify that a new asynchronous execution context +is being entered. If nested calls to `emitBefore()` are made, the stack of +`asyncId`s will be tracked and properly unwound. #### `asyncResource.emitAfter()` @@ -542,9 +576,9 @@ of `asyncId`s will be tracked and properly unwound. Call all `after` callbacks. If nested calls to `emitBefore()` were made, then make sure the stack is unwound properly. Otherwise an error will be thrown. -If the user's callback throws an exception then `emitAfter()` will -automatically be called for all `asyncId`s on the stack if the error is handled by -a domain or `'uncaughtException'` handler. +If the user's callback throws an exception, `emitAfter()` will automatically be +called for all `asyncId`s on the stack if the error is handled by a domain or +`'uncaughtException'` handler. #### `asyncResource.emitDestroy()` @@ -564,4 +598,8 @@ never be called. * Returns {number} the same `triggerAsyncId` that is passed to the `AsyncResource` constructor. +[`after` callback]: #async_hooks_after_asyncid +[`before` callback]: #async_hooks_before_asyncid +[`destroy` callback]: #async_hooks_before_asyncid [`Hook Callbacks`]: #async_hooks_hook_callbacks +[`init` callback]: #async_hooks_init_asyncid_type_triggerasyncid_resource diff --git a/lib/async_hooks.js b/lib/async_hooks.js index 67e81ecaecb28a..a7a2a4f9e4d99e 100644 --- a/lib/async_hooks.js +++ b/lib/async_hooks.js @@ -235,6 +235,9 @@ function triggerAsyncId() { class AsyncResource { constructor(type, triggerAsyncId = initTriggerId()) { + if (typeof type !== 'string') + throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'type', 'string'); + // Unlike emitInitScript, AsyncResource doesn't supports null as the // triggerAsyncId. if (!Number.isSafeInteger(triggerAsyncId) || triggerAsyncId < -1) { diff --git a/test/async-hooks/test-embedder.api.async-resource-no-type.js b/test/async-hooks/test-embedder.api.async-resource-no-type.js new file mode 100644 index 00000000000000..69b6667edb674c --- /dev/null +++ b/test/async-hooks/test-embedder.api.async-resource-no-type.js @@ -0,0 +1,34 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const async_hooks = require('async_hooks'); +const { AsyncResource } = async_hooks; +const { spawn } = require('child_process'); + +const initHooks = require('./init-hooks'); + +if (process.argv[2] === 'child') { + initHooks().enable(); + + class Foo extends AsyncResource { + constructor(type) { + super(type, async_hooks.executionAsyncId()); + } + } + + [null, undefined, 1, Date, {}, []].forEach((i) => { + common.expectsError(() => new Foo(i), { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError + }); + }); + +} else { + const args = process.argv.slice(1).concat('child'); + spawn(process.execPath, args) + .on('close', common.mustCall((code) => { + // No error because the type was defaulted + assert.strictEqual(code, 0); + })); +} diff --git a/test/async-hooks/test-embedder.api.async-resource.js b/test/async-hooks/test-embedder.api.async-resource.js index 533df6a5c84549..f4dfba89557871 100644 --- a/test/async-hooks/test-embedder.api.async-resource.js +++ b/test/async-hooks/test-embedder.api.async-resource.js @@ -12,12 +12,11 @@ const { checkInvocations } = require('./hook-checks'); const hooks = initHooks(); hooks.enable(); -assert.throws(() => { - new AsyncResource(); -}, common.expectsError({ - code: 'ERR_ASYNC_TYPE', - type: TypeError, -})); +common.expectsError( + () => new AsyncResource(), { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError, + }); assert.throws(() => { new AsyncResource('invalid_trigger_id', null); }, common.expectsError({ diff --git a/test/parallel/test-async-hooks-asyncresource-constructor.js b/test/parallel/test-async-hooks-asyncresource-constructor.js index 2ab5f067ca6c76..ba6c1166bf6bd8 100644 --- a/test/parallel/test-async-hooks-asyncresource-constructor.js +++ b/test/parallel/test-async-hooks-asyncresource-constructor.js @@ -15,7 +15,7 @@ async_hooks.createHook({ assert.throws(() => { return new AsyncResource(); }, common.expectsError({ - code: 'ERR_ASYNC_TYPE', + code: 'ERR_INVALID_ARG_TYPE', type: TypeError, })); From 4d26c68b6bc22ce56d73b32bb5cd2507d568fc93 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Tue, 12 Sep 2017 13:07:02 -0700 Subject: [PATCH 027/145] test: move test-benchmark-buffer to sequential `test-benchmark-buffer` has been observed to timeout on CI on SmartOS. Move the test to `sequential` so it is not competing with other tests for resources. PR-URL: https://github.com/nodejs/node/pull/15373 Fixes: https://github.com/nodejs/node/issues/15372 Reviewed-By: Colin Ihrig Reviewed-By: Ruben Bridgewater Reviewed-By: Evan Lucas Reviewed-By: Refael Ackermann Reviewed-By: Yuta Hiroto Reviewed-By: James M Snell --- test/{parallel => sequential}/test-benchmark-buffer.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename test/{parallel => sequential}/test-benchmark-buffer.js (100%) diff --git a/test/parallel/test-benchmark-buffer.js b/test/sequential/test-benchmark-buffer.js similarity index 100% rename from test/parallel/test-benchmark-buffer.js rename to test/sequential/test-benchmark-buffer.js From a2d340fb0083fa92c1e054de4c986fc7cbbac18e Mon Sep 17 00:00:00 2001 From: Sampson Gao Date: Tue, 8 Aug 2017 16:21:56 -0400 Subject: [PATCH 028/145] n-api: napi_is_construct_call->napi_get_new_target Remove napi_is_construct_call and introduce napi_get_new_target. PR-URL: https://github.com/nodejs/node/pull/14698 Reviewed-By: Jason Ginchereau Reviewed-By: Colin Ihrig Reviewed-By: Michael Dawson Reviewed-By: James M Snell Reviewed-By: Kyle Farnung --- doc/api/n-api.md | 17 ++++++++-------- src/node_api.cc | 23 ++++++++++++---------- src/node_api.h | 6 +++--- test/addons-napi/6_object_wrap/myobject.cc | 5 +++-- 4 files changed, 27 insertions(+), 24 deletions(-) diff --git a/doc/api/n-api.md b/doc/api/n-api.md index e3d7dcce32256b..9204017c7e1233 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -2918,25 +2918,24 @@ Returns `napi_ok` if the API succeeded. This method is used within a callback function to retrieve details about the call like the arguments and the `this` pointer from a given callback info. -### *napi_is_construct_call* +### *napi_get_new_target* ```C -napi_status napi_is_construct_call(napi_env env, - napi_callback_info cbinfo, - bool* result) +napi_status napi_get_new_target(napi_env env, + napi_callback_info cbinfo, + napi_value* result) ``` - `[in] env`: The environment that the API is invoked under. - `[in] cbinfo`: The callback info passed into the callback function. -- `[out] result`: Whether the native function is being invoked as -a constructor call. +- `[out] result`: The `new.target` of the constructor call. Returns `napi_ok` if the API succeeded. -This API checks if the the current callback was due to a -consructor call. +This API returns the `new.target` of the constructor call. If the current +callback is not a constructor call, the result is `nullptr`. ### *napi_new_instance* ```C NAPI_EXTERN napi_status napi_create_async_work(napi_env env, + napi_value async_resource, + const char* async_resource_name, napi_async_execute_callback execute, napi_async_complete_callback complete, void* data, @@ -3275,6 +3281,10 @@ napi_status napi_create_async_work(napi_env env, ``` - `[in] env`: The environment that the API is invoked under. +- `[in] async_resource`: An optional object associated with the async work + that will be passed to possible async_hooks [`init` hooks][]. +- `[in] async_resource_name`: An identifier for the kind of resource that is +being provided for diagnostic information exposed by the `async_hooks` API. - `[in] execute`: The native function which should be called to excute the logic asynchronously. - `[in] complete`: The native function which will be called when the @@ -3290,6 +3300,14 @@ This API allocates a work object that is used to execute logic asynchronously. It should be freed using [`napi_delete_async_work`][] once the work is no longer required. +`async_resource_name` should be a null-terminated, UTF-8-encoded string. + +*Note*: The `async_resource_name` identifier is provided by the user and should +be representative of the type of async work being performed. It is also +recommended to apply namespacing to the identifier, e.g. by including the +module name. See the [`async_hooks` documentation][async_hooks `type`] +for more information. + ### napi_delete_async_work + +* `multicastInterface` {String} + +*Note: All references to scope in this section are refering to +[IPv6 Zone Indices][], which are defined by [RFC 4007][]. In string form, an IP +with a scope index is written as `'IP%scope'` where scope is an interface name or +interface number.* + +Sets the default outgoing multicast interface of the socket to a chosen +interface or back to system interface selection. The `multicastInterface` must +be a valid string representation of an IP from the socket's family. + +For IPv4 sockets, this should be the IP configured for the desired physical +interface. All packets sent to multicast on the socket will be sent on the +interface determined by the most recent successful use of this call. + +For IPv6 sockets, `multicastInterface` should include a scope to indicate the +interface as in the examples that follow. In IPv6, individual `send` calls can +also use explicit scope in addresses, so only packets sent to a multicast +address without specifying an explicit scope are affected by the most recent +successful use of this call. + +#### Examples: IPv6 Outgoing Multicast Interface + +On most systems, where scope format uses the interface name: + +```js +const socket = dgram.createSocket('udp6'); + +socket.bind(1234, () => { + socket.setMulticastInterface('::%eth1'); +}); +``` + +On Windows, where scope format uses an interface number: + +```js +const socket = dgram.createSocket('udp6'); + +socket.bind(1234, () => { + socket.setMulticastInterface('::%2'); +}); +``` + +#### Example: IPv4 Outgoing Multicast Interface +All systems use an IP of the host on the desired physical interface: +```js +const socket = dgram.createSocket('udp4'); + +socket.bind(1234, () => { + socket.setMulticastInterface('10.0.0.2'); +}); +``` + +#### Call Results + +A call on a socket that is not ready to send or no longer open may throw a *Not +running* [`Error`][]. + +If `multicastInterface` can not be parsed into an IP then an *EINVAL* +[`System Error`][] is thrown. + +On IPv4, if `multicastInterface` is a valid address but does not match any +interface, or if the address does not match the family then +a [`System Error`][] such as `EADDRNOTAVAIL` or `EPROTONOSUP` is thrown. + +On IPv6, most errors with specifying or omiting scope will result in the socket +continuing to use (or returning to) the system's default interface selection. + +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) + +* `err` {Error} An error. +* `callback` {Function} A callback function that takes an optional error + argument which is invoked when the readable is destroyed. + #### readable.push(chunk[, encoding]) + +* **Version**: +* **Platform**: +* **Subsystem**: + + ``` -#### Which branch? +If you believe that you have uncovered a bug in Node.js, please fill out this +form, following the template to the best of your ability. Do not worry if you +cannot answer every detail, just fill in what you can. + +The two most important pieces of information we need in order to properly +evaluate the report is a description of the behavior you are seeing and a simple +test case we can use to recreate the problem on our own. If we cannot recreate +the issue, it becomes impossible for us to fix. -For developing new features and bug fixes, the `master` branch should be pulled -and built upon. +In order to rule out the possibility of bugs introduced by userland code, test +cases should be limited, as much as possible, to using *only* Node.js APIs. +If the bug occurs only when you're using a specific userland module, there is +a very good chance that either (a) the module has a bug or (b) something in +Node.js changed that broke the module. -#### Dependencies +### Triaging a Bug Report + +Once an issue has been opened, it is not uncommon for there to be discussion +around it. Some contributors may have differing opinions about the issue, +including whether the behavior being seen is a bug or a feature. This discussion +is part of the process and should be kept focused, helpful and professional. + +Short, clipped responses—that provide neither additional context nor supporting +detail—are not helpful or professional. To many, such responses are simply +annoying and unfriendly. + +Contributors are encouraged to help one another make forward progress as much +as possible, empowering one another to solve issues collaboratively. If you +choose to comment on an issue that you feel either is not a problem that needs +to be fixed, or if you encounter information in an issue that you feel is +incorrect, explain *why* you feel that way with additional supporting context, +and be willing to be convinced that you may be wrong. By doing so, we can often +reach the correct outcome much faster. + +### Resolving a Bug Report + +In the vast majority of cases, issues are resolved by opening a Pull Request. +The process for opening and reviewing a Pull Request is similar to that of +opening and triaging issues, but carries with it a necessary review and approval +workflow that ensures that the proposed changes meet the minimal quality and +functional guidelines of the Node.js project. + +## Pull Requests + +Pull Requests are the way in which concrete changes are made to the code, +documentation, dependencies, and tools contained with the `nodejs/node` +repository. + +There are two fundamental components of the Pull Request process: one concrete +and technical, and one more process oriented. The concrete and technical +component involves the specific details of setting up your local environment +so that you can make the actual changes. This is where we will start. + +### Dependencies Node.js has several bundled dependencies in the *deps/* and the *tools/* directories that are not part of the project proper. Changes to files in those @@ -54,36 +225,80 @@ questions, and [#Node-dev](http://webchat.freenode.net/?channels=node-dev) for development of Node.js core specifically. -### Step 2: Branch +### Setting up your local environment + +To get started, you will need to have `git` installed locally. Depending on +your operating system, there are also a number of other dependencies required. +These are detailed in the [Building guide][]. + +Once you have `git` and are sure you have all of the necessary dependencies, +it's time to create a fork. -Create a branch and start hacking: +Before getting started, it is recommended to configure `git` so that it knows +who you are: ```text -$ git checkout -b my-branch -t origin/master +$ git config --global user.name "J. Random User" +$ git config --global user.email "j.random.user@example.com" ``` -Any text you write should follow the [Style Guide](doc/STYLE_GUIDE.md), -including comments and API documentation. +#### Step 1: Fork + +Fork the project [on GitHub](https://github.com/nodejs/node) and clone your fork +locally. + +```text +$ git clone git@github.com:username/node.git +$ cd node +$ git remote add upstream https://github.com/nodejs/node.git +$ git fetch upstream +``` -### Step 3: Commit +#### Step 2: Branch -Make sure git knows your name and email address: +As a best practice to keep your development environment as organized as +possible, create local branches to work within. These should also be created +directly off of the `master` branch. ```text -$ git config --global user.name "J. Random User" -$ git config --global user.email "j.random.user@example.com" +$ git checkout -b my-branch -t upstream/master ``` -Add and commit: +### The Process of Making Changes + +#### Step 3: Code + +The vast majority of Pull Requests opened against the `nodejs/node` +repository includes changes to either the C/C++ code contained in the `src` +directory, the JavaScript code contained in the `lib` directory, the +documentation in `docs/api` or tests within the `test` directory. + +If you are modifying code, please be sure to run `make lint` from time to +time to ensure that the changes follow the Node.js code style guide. + +Any documentation you write (including code comments and API documentation) +should follow the [Style Guide](doc/STYLE_GUIDE.md). Code samples included +in the API docs will also be checked when running `make lint` (or +`vcbuild.bat lint` on Windows). + +#### Step 4: Commit + +It is a recommended best practice to keep your changes as logically grouped +as possible within individual commits. There is no limit to the number of +commits any single Pull Request may have, and many contributors find it easier +to review changes that are split across multiple commits. ```text $ git add my/changed/files $ git commit ``` -### Commit message guidelines +Note that multiple commits often get squashed when they are landed (see the +notes about [commit squashing](#commit-squashing)). -The commit message should describe what changed and why. +##### Commit message guidelines + +A good commit message should describe what changed and why. 1. The first line should: - contain a short description of the change @@ -129,9 +344,16 @@ Fixes: https://github.com/nodejs/node/issues/1337 Refs: http://eslint.org/docs/rules/space-in-parens.html ``` -### Step 4: Rebase +If you are new to contributing to Node.js, please try to do your best at +conforming to these guidelines, but do not worry if you get something wrong. +One of the existing contributors will help get things situated and the +contributor landing the Pull Request will ensure that everything follows +the project guidelines. + +#### Step 5: Rebase -Use `git rebase` (not `git merge`) to synchronize your work with the main +As a best practice, once you have committed your changes, it is a good idea +to use `git rebase` (not `git merge`) to synchronize your work with the main repository. ```text @@ -139,20 +361,29 @@ $ git fetch upstream $ git rebase upstream/master ``` -### Step 5: Test +This ensures that your working branch has the latest changes from `nodejs/node` +master. -Bug fixes and features should come with tests. Read the -[guide for writing tests in Node.js](./doc/guides/writing-tests.md). Looking at -other tests to see how they should be structured can also help. Add your -tests in the `test/parallel/` directory if you are unsure where to put them. +#### Step 6: Test -To run the tests (including code linting) on Unix / macOS: +Bug fixes and features should always come with tests. A +[guide for writing tests in Node.js](./doc/guides/writing-tests.md) has been +provided to make the process easier. Looking at other tests to see how they +should be structured can also help. + +The `test` directory within the `nodejs/node` repository is complex and it is +often not clear where a new test file should go. When in doubt, add new tests +to the `test/parallel/` directory and the right location will be sorted out +later. + +Before submitting your changes in a Pull Request, always run the full Node.js +test suite. To run the tests (including code linting) on Unix / macOS: ```text $ ./configure && make -j4 test ``` -Windows: +And on Windows: ```text > vcbuild test @@ -189,24 +420,59 @@ $ ./node ./test/parallel/test-stream2-transform.js Remember to recompile with `make -j4` in between test runs if you change code in the `lib` or `src` directories. -### Step 6: Push +#### Step 7: Push + +Once you are sure your commits are ready to go, with passing tests and linting, +begin the process of opening a Pull Request by pushing your working branch to +your fork on GitHub. ```text $ git push origin my-branch ``` -Pull requests are usually reviewed within a few days. +#### Step 8: Opening the Pull Request -### Step 7: Discuss and update +From within GitHub, opening a new Pull Request will present you with a template +that should be filled out: -You will probably get feedback or requests for changes to your Pull Request. -This is a big part of the submission process so don't be discouraged! +```markdown + + +##### Checklist + + +- [ ] `make -j4 test` (UNIX), or `vcbuild test` (Windows) passes +- [ ] tests and/or benchmarks are included +- [ ] documentation is changed or added +- [ ] commit message follows [commit guidelines](https://github.com/nodejs/node/blob/master/CONTRIBUTING.md#commit-message-guidelines) + +##### Affected core subsystem(s) + +``` + +Please try to do your best at filling out the details, but feel free to skip +parts if you're not sure what to put. -To make changes to an existing Pull Request, make the changes to your branch. -When you push that branch to your fork, GitHub will automatically update the -Pull Request. +Once opened, Pull Requests are usually reviewed within a few days. -You can push more commits to your branch: +#### Step 9: Discuss and update + +You will probably get feedback or requests for changes to your Pull Request. +This is a big part of the submission process so don't be discouraged! Some +contributors may sign off on the Pull Request right away, others may have +more detailed comments or feedback. This is a necessary part of the process +in order to evaluate whether the changes are correct and necessary. + +To make changes to an existing Pull Request, make the changes to your local +branch, add a new commit with those changes, and push those to your fork. +GitHub will automatically update the Pull Request. ```text $ git add my/changed/files @@ -214,7 +480,8 @@ $ git commit $ git push origin my-branch ``` -Or you can rebase against master: +It is also frequently necessary to synchronize your Pull Request with other +changes that have landed in `master` by using `git rebase`: ```text $ git fetch --all @@ -222,8 +489,13 @@ $ git rebase origin/master $ git push --force-with-lease origin my-branch ``` -Or you can amend the last commit (for example if you want to change the commit -log). +**Important:** The `git push --force-with-lease` command is one of the few ways +to delete history in `git`. Before you use it, make sure you understand the +risks. If in doubt, you can always ask for guidance in the Pull Request or on +[IRC in the #node-dev channel][]. + +If you happen to make a mistake in any of your commits, do not worry. You can +amend the last commit (for example if you want to change the commit log). ```text $ git add any/changed/files @@ -231,28 +503,39 @@ $ git commit --amend $ git push --force-with-lease origin my-branch ``` -**Important:** The `git push --force-with-lease` command is one of the few ways -to delete history in git. Before you use it, make sure you understand the risks. -If in doubt, you can always ask for guidance in the Pull Request or on -[IRC in the #node-dev channel](https://webchat.freenode.net?channels=node-dev&uio=d4). +There are a number of more advanced mechanisms for managing commits using +`git rebase` that can be used, but are beyond the scope of this guide. Feel free to post a comment in the Pull Request to ping reviewers if you are awaiting an answer on something. If you encounter words or acronyms that seem unfamiliar, refer to this [glossary](https://sites.google.com/a/chromium.org/dev/glossary). -Note that multiple commits often get squashed when they are landed (see the -notes about [commit squashing](#commit-squashing)). +##### Approval and Request Changes Workflow -### Step 8: Landing +All Pull Requests require "sign off" in order to land. Whenever a contributor +reviews a Pull Request they may find specific details that they would like to +see changed or fixed. These may be as simple as fixing a typo, or may involve +substantive changes to the code you have written. In general, such requests +are intended to be helpful, but at times may come across as abrupt or unhelpful, +especially requests to change things that do not include concrete suggestions +on *how* to change them. -In order to land, a Pull Request needs to be reviewed and -[approved](#getting-approvals-for-your-pull-request) by +Try not to be discouraged. If you feel that a particular review is unfair, +say so, or contact one of the other contributors in the project and seek their +input. Often such comments are the result of the reviewer having only taken a +short amount of time to review and are not ill-intended. Such issues can often +be resolved with a bit of patience. That said, reviewers should be expected to +be helpful in their feedback, and feedback that is simply vague, dismissive and +unhelpful is likely safe to ignore. + +#### Step 10: Landing + +In order to land, a Pull Request needs to be reviewed and [approved][] by at least one Node.js Collaborator and pass a -[CI (Continuous Integration) test run](#ci-testing). -After that, as long as there are no objections -from a Collaborator, the Pull Request can be merged. If you find your -Pull Request waiting longer than you expect, see the +[CI (Continuous Integration) test run][]. After that, as long as there are no +objections from other contributors, the Pull Request can be merged. If you find +your Pull Request waiting longer than you expect, see the [notes about the waiting time](#waiting-until-the-pull-request-gets-landed). When a collaborator lands your Pull Request, they will post @@ -262,11 +545,178 @@ point, but don't worry. If you look at the branch you raised your Pull Request against (probably `master`), you should see a commit with your name on it. Congratulations and thanks for your contribution! +### Reviewing Pull Requests + +All Node.js contributors who choose to review and provide feedback on Pull +Requests have a responsibility to both the project and the individual making the +contribution. Reviews and feedback must be helpful, insightful, and geared +towards improving the contribution as opposed to simply blocking it or +stopping it. If there are reasons why you feel the PR should not land, explain +what those are. Do not expect to be able to block a Pull Request from advancing +simply because you say "No" without giving an explanation. It is also important +to be open to having your mind changed, and to being open to working with the +contributor to make the Pull Request better. + +Reviews that are dismissive or disrespectful of the contributor or any other +reviewers are strictly counter to the [Code of Conduct][]. + +When reviewing a Pull Request, the primary goals are for the codebase to improve +and for the person submitting the request to succeed. Even if a Pull Request +does not land, the submitters should come away from the experience feeling like +their effort was not wasted or unappreciated. Every Pull Request from a new +contributor is an opportunity to grow the community. + +#### Review a bit at a time. + +Do not overwhelm new contributors. + +It is tempting to micro-optimize and make everything about relative performance, +perfect grammar, or exact style matches. Do not succumb to that temptation. + +Focus first on the most significant aspects of the change: + +1. Does this change make sense for Node.js? +2. Does this change make Node.js better, even if only incrementally? +3. Are there clear bugs or larger scale issues that need attending to? + +When changes are necessary, *request* them, do not *demand* them, and do not +assume that the submitter already knows how to add a test or run a benchmark. + +Specific performance optimization techniques, coding styles and conventions +change over time. The first impression you give to a new contributor never does. + +Nits (requests for small changes that are not essential) are fine, but try to +avoid stalling the Pull Request. Most nits can typically be fixed by the +Node.js Collaborator landing the Pull Request but they can also be an +opportunity for the contributor to learn a bit more about the project. + +It is always good to clearly indicate nits when you comment: e.g. +`Nit: change foo() to bar(). But this is not blocking.` + +#### Be aware of the person behind the code + +Be aware that *how* you communicate requests and reviews in your feedback can +have a significant impact on the success of the Pull Request. Yes, we may land +a particular change that makes Node.js better, but the individual might just +not want to have anything to do with Node.js ever again. The goal is not just +having good code. + +#### Respect the minimum wait time for comments + +There is a minimum waiting time which we try to respect for non-trivial +changes, so that people who may have important input in such a distributed +project are able to respond. + +For non-trivial changes, Pull Requests must be left open for *at least* 48 +hours during the week, and 72 hours on a weekend. In most cases, when the +PR is relatively small and focused on a narrow set of changes, these periods +provide more than enough time to adequately review. Sometimes changes take far +longer to review, or need more specialized review from subject matter experts. +When in doubt, do not rush. + +Trivial changes, typically limited to small formatting changes or fixes to +documentation, may be landed within the minimum 48 hour window. + +#### Abandoned or Stalled Pull Requests + +If a Pull Request appears to be abandoned or stalled, it is polite to first +check with the contributor to see if they intend to continue the work before +checking if they would mind if you took it over (especially if it just has +nits left). When doing so, it is courteous to give the original contributor +credit for the work they started (either by preserving their name and email +address in the commit log, or by using an `Author: ` meta-data tag in the +commit. + +#### Approving a change + +Any Node.js core Collaborator (any GitHub user with commit rights in the +`nodejs/node` repository) is authorized to approve any other contributor's +work. Collaborators are not permitted to approve their own Pull Requests. + +Collaborators indicate that they have reviewed and approve of the changes in +a Pull Request either by using GitHub's Approval Workflow, which is preferred, +or by leaving an `LGTM` ("Looks Good To Me") comment. + +When explicitly using the "Changes requested" component of the GitHub Approval +Workflow, show empathy. That is, do not be rude or abrupt with your feedback +and offer concrete suggestions for improvement, if possible. If you're not +sure *how* a particular change can be improved, say so. + +Most importantly, after leaving such requests, it is courteous to make yourself +available later to check whether your comments have been addressed. + +If you see that requested changes have been made, you can clear another +collaborator's `Changes requested` review. + +Change requests that are vague, dismissive, or unconstructive may also be +dismissed if requests for greater clarification go unanswered within a +reasonable period of time. + +If you do not believe that the Pull Request should land at all, use +`Changes requested` to indicate that you are considering some of your comments +to block the PR from landing. When doing so, explain *why* you believe the +Pull Request should not land along with an explanation of what may be an +acceptable alternative course, if any. + +#### Accept that there are different opinions about what belongs in Node.js + +Opinions on this vary, even among the members of the Technical Steering +Committee. + +One general rule of thumb is that if Node.js itself needs it (due to historic +or functional reasons), then it belongs in Node.js. For instance, `url` +parsing is in Node.js because of HTTP protocol support. + +Also, functionality that either cannot be implemented outside of core in any +reasonable way, or only with significant pain. + +It is not uncommon for contributors to suggest new features they feel would +make Node.js better. These may or may not make sense to add, but as with all +changes, be courteous in how you communicate your stance on these. Comments +that make the contributor feel like they should have "known better" or +ridiculed for even trying run counter to the [Code of Conduct][]. + +#### Performance is not everything + +Node.js has always optimized for speed of execution. If a particular change +can be shown to make some part of Node.js faster, it's quite likely to be +accepted. Claims that a particular Pull Request will make things faster will +almost always be met by requests for performance [benchmark results][] that +demonstrate the improvement. + +That said, performance is not the only factor to consider. Node.js also +optimizes in favor of not breaking existing code in the ecosystem, and not +changing working functional code just for the sake of changing. + +If a particular Pull Request introduces a performance or functional +regression, rather than simply rejecting the Pull Request, take the time to +work *with* the contributor on improving the change. Offer feedback and +advice on what would make the Pull Request acceptable, and do not assume that +the contributor should already know how to do that. Be explicit in your +feedback. + +#### Continuous Integration Testing + +All Pull Requests that contain changes to code must be run through +continuous integration (CI) testing at [https://ci.nodejs.org/][]. + +Only Node.js core Collaborators with commit rights to the `nodejs/node` +repository may start a CI testing run. The specific details of how to do +this are included in the new Collaborator [Onboarding guide][]. + +Ideally, the code change will pass ("be green") on all platform configurations +supported by Node.js (there are over 30 platform configurations currently). +This means that all tests pass and there are no linting errors. In reality, +however, it is not uncommon for the CI infrastructure itself to fail on +specific platforms or for so-called "flaky" tests to fail ("be red"). It is +vital to visually inspect the results of all failed ("red") tests to determine +whether the failure was caused by the changes in the Pull Request. + ## Additional Notes ### Commit Squashing -When the commits in your Pull Request land, they will be squashed +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, @@ -317,6 +767,14 @@ 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). +### Helpful Resources + +The following additional resources may be of assistance: + +* [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) +* [core-validate-commit](https://github.com/evanlucas/core-validate-commit) - + A utility that ensures commits follow the commit formatting guidelines. + ## Developer's Certificate of Origin 1.1 @@ -343,3 +801,17 @@ By making a contribution to this project, I certify that: personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. + +[approved]: #getting-approvals-for-your-pull-request +[benchmark results]: ./doc/guides/writing-and-running-benchmarks.md +[Building guide]: ./BUILDING.md +[CI (Continuous Integration) test run]: #ci-testing +[Code of Conduct]: https://github.com/nodejs/TSC/blob/master/CODE_OF_CONDUCT.md +[guide for writing tests in Node.js]: ./doc/guides/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 +[Node.js help repository]: https://github.com/nodejs/help/issues +[notes about the waiting time]: #waiting-until-the-pull-request-gets-landed +[Onboarding guide]: ./doc/onboarding.md +[on GitHub]: https://github.com/nodejs/node +[Technical Steering Committee (TSC) repository]: https://github.com/nodejs/TSC/issues From a6879bfab66af6e8f986ec8b0aed84b4fa936772 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Fri, 1 Sep 2017 14:47:31 -0700 Subject: [PATCH 046/145] http2: custom promisify for http2.connect ... and some other cleanups PR-URL: https://github.com/nodejs/node/pull/15207 Reviewed-By: Matteo Collina --- lib/internal/http2/core.js | 14 +++++++- src/node_http2_core-inl.h | 16 +++++---- src/node_http2_core.h | 4 +-- .../test-http2-client-promisify-connect.js | 34 +++++++++++++++++++ 4 files changed, 59 insertions(+), 9 deletions(-) create mode 100644 test/parallel/test-http2-client-promisify-connect.js diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js index 12842e1f170a6e..8c3c6feea5d0a6 100644 --- a/lib/internal/http2/core.js +++ b/lib/internal/http2/core.js @@ -20,8 +20,9 @@ const { onServerStream, Http2ServerResponse, } = require('internal/http2/compat'); const { utcDate } = require('internal/http'); +const { promisify } = require('internal/util'); const { _connectionListener: httpConnectionListener } = require('http'); -const { isUint8Array } = process.binding('util'); +const { isUint8Array, createPromise, promiseResolve } = process.binding('util'); const debug = util.debuglog('http2'); @@ -2479,6 +2480,17 @@ function connect(authority, options, listener) { return session; } +// Support util.promisify +Object.defineProperty(connect, promisify.custom, { + value: (authority, options) => { + const promise = createPromise(); + const server = connect(authority, + options, + () => promiseResolve(promise, server)); + return promise; + } +}); + function createSecureServer(options, handler) { if (typeof options === 'function') { handler = options; diff --git a/src/node_http2_core-inl.h b/src/node_http2_core-inl.h index c6654123dda656..0d2a697a9d73e0 100644 --- a/src/node_http2_core-inl.h +++ b/src/node_http2_core-inl.h @@ -52,17 +52,19 @@ inline int Nghttp2Session::OnBeginHeadersCallback(nghttp2_session* session, const nghttp2_frame* frame, void* user_data) { Nghttp2Session* handle = static_cast(user_data); + // If this is a push promise frame, we want to grab the handle of + // the promised stream. int32_t id = (frame->hd.type == NGHTTP2_PUSH_PROMISE) ? - frame->push_promise.promised_stream_id : - frame->hd.stream_id; + frame->push_promise.promised_stream_id : + frame->hd.stream_id; DEBUG_HTTP2("Nghttp2Session %s: beginning headers for stream %d\n", handle->TypeName(handle->type()), id); Nghttp2Stream* stream = handle->FindStream(id); if (stream == nullptr) { - Nghttp2Stream::Init(id, handle, frame->headers.cat); + Nghttp2Stream::Init(id, handle, frame->headers.cat); } else { - stream->StartHeaders(frame->headers.cat); + stream->StartHeaders(frame->headers.cat); } return 0; } @@ -77,9 +79,11 @@ inline int Nghttp2Session::OnHeaderCallback(nghttp2_session* session, uint8_t flags, void* user_data) { Nghttp2Session* handle = static_cast(user_data); + // If this is a push promise frame, we want to grab the handle of + // the promised stream. int32_t id = (frame->hd.type == NGHTTP2_PUSH_PROMISE) ? - frame->push_promise.promised_stream_id : - frame->hd.stream_id; + frame->push_promise.promised_stream_id : + frame->hd.stream_id; Nghttp2Stream* stream = handle->FindStream(id); nghttp2_header_list* header = header_free_list.pop(); header->name = name; diff --git a/src/node_http2_core.h b/src/node_http2_core.h index 2cd669f118a403..69b9891d5871cb 100644 --- a/src/node_http2_core.h +++ b/src/node_http2_core.h @@ -141,9 +141,9 @@ class Nghttp2Session { inline ssize_t Write(const uv_buf_t* bufs, unsigned int nbufs); // Returns the nghttp2 library session - inline nghttp2_session* session() { return session_; } + inline nghttp2_session* session() const { return session_; } - nghttp2_session_type type() { + nghttp2_session_type type() const { return session_type_; } diff --git a/test/parallel/test-http2-client-promisify-connect.js b/test/parallel/test-http2-client-promisify-connect.js new file mode 100644 index 00000000000000..5b6dccad6a223e --- /dev/null +++ b/test/parallel/test-http2-client-promisify-connect.js @@ -0,0 +1,34 @@ +// Flags: --expose-http2 +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const assert = require('assert'); +const http2 = require('http2'); +const util = require('util'); + +const server = http2.createServer(); +server.on('stream', common.mustCall((stream) => { + stream.respond(); + stream.end('ok'); +})); +server.listen(0, common.mustCall(() => { + + const connect = util.promisify(http2.connect); + + connect(`http://localhost:${server.address().port}`) + .catch(common.mustNotCall()) + .then(common.mustCall((client) => { + assert(client); + const req = client.request(); + let data = ''; + req.setEncoding('utf8'); + req.on('data', (chunk) => data += chunk); + req.on('end', common.mustCall(() => { + assert.strictEqual(data, 'ok'); + client.destroy(); + server.close(); + })); + })); +})); From aa0917cd0a9d9f43771b59ebf479d9c85b26bae8 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Tue, 5 Sep 2017 15:02:48 -0700 Subject: [PATCH 047/145] http2: improve http2 coverage Improve http2 coverage through refactoring and tests PR-URL: https://github.com/nodejs/node/pull/15210 Reviewed-By: Matteo Collina --- lib/internal/http2/core.js | 106 +++++++----------- lib/internal/http2/util.js | 20 +++- src/node_http2.cc | 2 + ...test-http2-createsecureserver-nooptions.js | 45 ++++++++ test/parallel/test-http2-misc-util.js | 49 ++++++++ ...est-http2-server-settimeout-no-callback.js | 42 +++++++ 6 files changed, 196 insertions(+), 68 deletions(-) create mode 100644 test/parallel/test-http2-createsecureserver-nooptions.js create mode 100644 test/parallel/test-http2-misc-util.js create mode 100644 test/parallel/test-http2-server-settimeout-no-callback.js diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js index 8c3c6feea5d0a6..1fead9975b24f5 100644 --- a/lib/internal/http2/core.js +++ b/lib/internal/http2/core.js @@ -38,6 +38,7 @@ const { isPayloadMeaningless, mapToHeaders, NghttpError, + sessionName, toHeaderObject, updateOptionsBuffer, updateSettingsBuffer @@ -88,7 +89,6 @@ const { NGHTTP2_CANCEL, NGHTTP2_DEFAULT_WEIGHT, NGHTTP2_FLAG_END_STREAM, - NGHTTP2_HCAT_HEADERS, NGHTTP2_HCAT_PUSH_RESPONSE, NGHTTP2_HCAT_RESPONSE, NGHTTP2_INTERNAL_ERROR, @@ -129,17 +129,6 @@ const { HTTP_STATUS_SWITCHING_PROTOCOLS } = constants; -function sessionName(type) { - switch (type) { - case NGHTTP2_SESSION_CLIENT: - return 'client'; - case NGHTTP2_SESSION_SERVER: - return 'server'; - default: - return ''; - } -} - // Top level to avoid creating a closure function emit() { this.emit.apply(this, arguments); @@ -164,59 +153,43 @@ function onSessionHeaders(id, cat, flags, headers) { const obj = toHeaderObject(headers); if (stream === undefined) { - switch (owner[kType]) { - case NGHTTP2_SESSION_SERVER: - stream = new ServerHttp2Stream(owner, id, - { readable: !endOfStream }, - obj); - if (obj[HTTP2_HEADER_METHOD] === HTTP2_METHOD_HEAD) { - // For head requests, there must not be a body... - // end the writable side immediately. - stream.end(); - const state = stream[kState]; - state.headRequest = true; - } - break; - case NGHTTP2_SESSION_CLIENT: - stream = new ClientHttp2Stream(owner, id, { readable: !endOfStream }); - break; - default: - assert.fail(null, null, - 'Internal HTTP/2 Error. Invalid session type. Please ' + - 'report this as a bug in Node.js'); + // owner[kType] can be only one of two possible values + if (owner[kType] === NGHTTP2_SESSION_SERVER) { + stream = new ServerHttp2Stream(owner, id, + { readable: !endOfStream }, + obj); + if (obj[HTTP2_HEADER_METHOD] === HTTP2_METHOD_HEAD) { + // For head requests, there must not be a body... + // end the writable side immediately. + stream.end(); + const state = stream[kState]; + state.headRequest = true; + } + } else { + stream = new ClientHttp2Stream(owner, id, { readable: !endOfStream }); } streams.set(id, stream); process.nextTick(emit.bind(owner, 'stream', stream, obj, flags, headers)); } else { let event; - let status; - switch (cat) { - case NGHTTP2_HCAT_RESPONSE: - status = obj[HTTP2_HEADER_STATUS]; - if (!endOfStream && - status !== undefined && - status >= 100 && - status < 200) { - event = 'headers'; - } else { - event = 'response'; - } - break; - case NGHTTP2_HCAT_PUSH_RESPONSE: - event = 'push'; - break; - case NGHTTP2_HCAT_HEADERS: - status = obj[HTTP2_HEADER_STATUS]; - if (!endOfStream && status !== undefined && status >= 200) { - event = 'response'; - } else { - event = endOfStream ? 'trailers' : 'headers'; - } - break; - default: - assert.fail(null, null, - 'Internal HTTP/2 Error. Invalid headers category. Please ' + - 'report this as a bug in Node.js'); + const status = obj[HTTP2_HEADER_STATUS]; + if (cat === NGHTTP2_HCAT_RESPONSE) { + if (!endOfStream && + status !== undefined && + status >= 100 && + status < 200) { + event = 'headers'; + } else { + event = 'response'; + } + } else if (cat === NGHTTP2_HCAT_PUSH_RESPONSE) { + event = 'push'; + } else { // cat === NGHTTP2_HCAT_HEADERS: + if (!endOfStream && status !== undefined && status >= 200) { + event = 'response'; + } else { + event = endOfStream ? 'trailers' : 'headers'; + } } debug(`[${sessionName(owner[kType])}] emitting stream '${event}' event`); process.nextTick(emit.bind(stream, event, obj, flags, headers)); @@ -243,8 +216,10 @@ function onSessionTrailers(id) { 'Internal HTTP/2 Failure. Stream does not exist. Please ' + 'report this as a bug in Node.js'); const getTrailers = stream[kState].getTrailers; - if (typeof getTrailers !== 'function') - return []; + // We should not have been able to get here at all if getTrailers + // was not a function, and there's no code that could have changed + // it between there and here. + assert.strictEqual(typeof getTrailers, 'function'); const trailers = Object.create(null); getTrailers.call(stream, trailers); const headersList = mapToHeaders(trailers, assertValidPseudoHeaderTrailer); @@ -2492,9 +2467,10 @@ Object.defineProperty(connect, promisify.custom, { }); function createSecureServer(options, handler) { - if (typeof options === 'function') { - handler = options; - options = Object.create(null); + if (options == null || typeof options !== 'object') { + throw new errors.TypeError('ERR_INVALID_ARG_TYPE', + 'options', + 'object'); } debug('creating http2secureserver'); return new Http2SecureServer(options, handler); diff --git a/lib/internal/http2/util.js b/lib/internal/http2/util.js index d3fe5a4feae38c..baa233e5b0468c 100644 --- a/lib/internal/http2/util.js +++ b/lib/internal/http2/util.js @@ -4,6 +4,9 @@ const binding = process.binding('http2'); const errors = require('internal/errors'); const { + NGHTTP2_SESSION_CLIENT, + NGHTTP2_SESSION_SERVER, + HTTP2_HEADER_STATUS, HTTP2_HEADER_METHOD, HTTP2_HEADER_AUTHORITY, @@ -453,13 +456,12 @@ class NghttpError extends Error { } } -function assertIsObject(value, name, types) { +function assertIsObject(value, name, types = 'object') { if (value !== undefined && (value === null || typeof value !== 'object' || Array.isArray(value))) { - const err = new errors.TypeError('ERR_INVALID_ARG_TYPE', - name, types || 'object'); + const err = new errors.TypeError('ERR_INVALID_ARG_TYPE', name, types); Error.captureStackTrace(err, assertIsObject); throw err; } @@ -529,6 +531,17 @@ function isPayloadMeaningless(method) { return kNoPayloadMethods.has(method); } +function sessionName(type) { + switch (type) { + case NGHTTP2_SESSION_CLIENT: + return 'client'; + case NGHTTP2_SESSION_SERVER: + return 'server'; + default: + return ''; + } +} + module.exports = { assertIsObject, assertValidPseudoHeaderResponse, @@ -541,6 +554,7 @@ module.exports = { isPayloadMeaningless, mapToHeaders, NghttpError, + sessionName, toHeaderObject, updateOptionsBuffer, updateSettingsBuffer diff --git a/src/node_http2.cc b/src/node_http2.cc index 610c8e8f2351ba..85b7b0958ec97c 100644 --- a/src/node_http2.cc +++ b/src/node_http2.cc @@ -890,6 +890,8 @@ void Http2Session::OnHeaders(Nghttp2Stream* stream, Local fn = env()->push_values_to_array_function(); Local argv[NODE_PUSH_VAL_TO_ARRAY_MAX * 2]; + CHECK_LE(cat, NGHTTP2_HCAT_HEADERS); + // The headers are passed in above as a linked list of nghttp2_header_list // structs. The following converts that into a JS array with the structure: // [name1, value1, name2, value2, name3, value3, name3, value4] and so on. diff --git a/test/parallel/test-http2-createsecureserver-nooptions.js b/test/parallel/test-http2-createsecureserver-nooptions.js new file mode 100644 index 00000000000000..5a9849f9e11ab6 --- /dev/null +++ b/test/parallel/test-http2-createsecureserver-nooptions.js @@ -0,0 +1,45 @@ +// Flags: --expose-http2 +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const http2 = require('http2'); + +// Error if options are not passed to createSecureServer + +common.expectsError( + () => http2.createSecureServer(), + { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError + }); + +common.expectsError( + () => http2.createSecureServer(() => {}), + { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError + }); + +common.expectsError( + () => http2.createSecureServer(1), + { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError + }); + +common.expectsError( + () => http2.createSecureServer('test'), + { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError + }); + +common.expectsError( + () => http2.createSecureServer(null), + { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError + }); diff --git a/test/parallel/test-http2-misc-util.js b/test/parallel/test-http2-misc-util.js new file mode 100644 index 00000000000000..eaa297309b14a2 --- /dev/null +++ b/test/parallel/test-http2-misc-util.js @@ -0,0 +1,49 @@ +// Flags: --expose-internals +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const assert = require('assert'); + +const { + assertIsObject, + assertWithinRange, + sessionName +} = require('internal/http2/util'); + +// Code coverage for sessionName utility function +assert.strictEqual(sessionName(0), 'server'); +assert.strictEqual(sessionName(1), 'client'); +[2, '', 'test', {}, [], true].forEach((i) => { + assert.strictEqual(sessionName(2), ''); +}); + +// Code coverage for assertWithinRange function +common.expectsError( + () => assertWithinRange('test', -1), + { + code: 'ERR_HTTP2_INVALID_SETTING_VALUE', + type: RangeError, + message: 'Invalid value for setting "test": -1' + }); + +assertWithinRange('test', 1); + +common.expectsError( + () => assertIsObject('foo', 'test'), + { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError, + message: 'The "test" argument must be of type object' + }); + +common.expectsError( + () => assertIsObject('foo', 'test', ['Date']), + { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError, + message: 'The "test" argument must be of type Date' + }); + +assertIsObject({}, 'test'); diff --git a/test/parallel/test-http2-server-settimeout-no-callback.js b/test/parallel/test-http2-server-settimeout-no-callback.js new file mode 100644 index 00000000000000..eff0418fa7b6c2 --- /dev/null +++ b/test/parallel/test-http2-server-settimeout-no-callback.js @@ -0,0 +1,42 @@ +// Flags: --expose-http2 +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const http2 = require('http2'); + +// Verify that setTimeout callback verifications work correctly + +{ + const server = http2.createServer(); + common.expectsError( + () => server.setTimeout(10, 'test'), + { + code: 'ERR_INVALID_CALLBACK', + type: TypeError + }); + common.expectsError( + () => server.setTimeout(10, 1), + { + code: 'ERR_INVALID_CALLBACK', + type: TypeError + }); +} + +{ + const server = http2.createSecureServer({}); + common.expectsError( + () => server.setTimeout(10, 'test'), + { + code: 'ERR_INVALID_CALLBACK', + type: TypeError + }); + common.expectsError( + () => server.setTimeout(10, 1), + { + code: 'ERR_INVALID_CALLBACK', + type: TypeError + }); +} From 29e38ab2a27dafca720adec8309ec1adaabe43f9 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Tue, 12 Sep 2017 09:27:03 -0700 Subject: [PATCH 048/145] src: remove unused perf_hooks uv handles A couple of unused uv handles were accidentally left in env. PR-URL: https://github.com/nodejs/node/pull/15368 Reviewed-By: Colin Ihrig Reviewed-By: Anna Henningsen Reviewed-By: Brian White --- src/env-inl.h | 27 --------------------------- src/env.h | 11 ----------- 2 files changed, 38 deletions(-) diff --git a/src/env-inl.h b/src/env-inl.h index b27c5ec47b02bc..842ed4082843ac 100644 --- a/src/env-inl.h +++ b/src/env-inl.h @@ -503,33 +503,6 @@ inline std::map* Environment::performance_marks() { return &performance_marks_; } -inline Environment* Environment::from_performance_check_handle( - uv_check_t* handle) { - return ContainerOf(&Environment::performance_check_handle_, handle); -} - -inline Environment* Environment::from_performance_idle_handle( - uv_idle_t* handle) { - return ContainerOf(&Environment::performance_idle_handle_, handle); -} - -inline Environment* Environment::from_performance_prepare_handle( - uv_prepare_t* handle) { - return ContainerOf(&Environment::performance_prepare_handle_, handle); -} - -inline uv_check_t* Environment::performance_check_handle() { - return &performance_check_handle_; -} - -inline uv_idle_t* Environment::performance_idle_handle() { - return &performance_idle_handle_; -} - -inline uv_prepare_t* Environment::performance_prepare_handle() { - return &performance_prepare_handle_; -} - inline IsolateData* Environment::isolate_data() const { return isolate_data_; } diff --git a/src/env.h b/src/env.h index 96bbd3ce5c9db1..f9a2649115bfd7 100644 --- a/src/env.h +++ b/src/env.h @@ -597,14 +597,6 @@ class Environment { inline performance::performance_state* performance_state(); inline std::map* performance_marks(); - static inline Environment* from_performance_check_handle(uv_check_t* handle); - static inline Environment* from_performance_idle_handle(uv_idle_t* handle); - static inline Environment* from_performance_prepare_handle( - uv_prepare_t* handle); - inline uv_check_t* performance_check_handle(); - inline uv_idle_t* performance_idle_handle(); - inline uv_prepare_t* performance_prepare_handle(); - inline void ThrowError(const char* errmsg); inline void ThrowTypeError(const char* errmsg); inline void ThrowRangeError(const char* errmsg); @@ -684,9 +676,6 @@ class Environment { uv_timer_t destroy_ids_timer_handle_; uv_prepare_t idle_prepare_handle_; uv_check_t idle_check_handle_; - uv_prepare_t performance_prepare_handle_; - uv_check_t performance_check_handle_; - uv_idle_t performance_idle_handle_; AsyncHooks async_hooks_; DomainFlag domain_flag_; From b0f5b2a38c36c5634c6c07cb27958755300b055d Mon Sep 17 00:00:00 2001 From: Tuan Anh Tran Date: Mon, 11 Sep 2017 14:10:09 +0700 Subject: [PATCH 049/145] doc: fix "added in" for Buffer.allocUnsafeSlow() PR-URL: https://github.com/nodejs/node/pull/15330 Fixes: https://github.com/nodejs/node/issues/15279 Reviewed-By: James M Snell Reviewed-By: Richard Lau Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca --- doc/api/buffer.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/buffer.md b/doc/api/buffer.md index 363b10bc664b9f..0b01370f90f7ab 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -616,7 +616,7 @@ additional performance that [`Buffer.allocUnsafe()`] provides. ### Class Method: Buffer.allocUnsafeSlow(size) * `size` {integer} The desired length of the new `Buffer` From a32c8a566ef1996d786e49e9bb0e672f5864e5ba Mon Sep 17 00:00:00 2001 From: Mike Kaufman Date: Fri, 25 Aug 2017 12:45:00 -0700 Subject: [PATCH 050/145] http2,async-wrap: introduce AliasedBuffer class This change introduces an AliasedBuffer class and updates asytnc-wrap and http2 to use this class. A common technique to optimize performance is to create a native buffer and then map that native buffer to user space via JS array. The runtime can efficiently write to the native buffer without having to route though JS, and the values being written are accessible from user space. While efficient, this technique allows modifications to user space memory w/out going through JS type system APIs, effectively bypassing any monitoring the JS VM has in place to track program state modifications. The result is that monitors have an incorrect view of prorgram state. The AliasedBuffer class provides a future placeholder where this technique can be used, but writes can still be observed. To achieve this, the node-chakra-core fork will add in appropriate tracking logic in the AliasedBuffer's SetValue() method. Going forward, this class can evolve to support more sophisticated mechanisms if necessary. PR-URL: https://github.com/nodejs/node/pull/15077 Reviewed-By: Trevor Norris Reviewed-By: James M Snell Reviewed-By: Anna Henningsen --- node.gyp | 4 + src/aliased_buffer.h | 200 ++++++++++++++++++++++++++ src/async-wrap.cc | 16 +-- src/env-inl.h | 32 +++-- src/env.h | 24 ++-- src/node_http2.cc | 119 +++++----------- src/node_http2.h | 1 + src/node_http2_state.h | 116 ++++++++++++++++ test/cctest/node_test_fixture.cc | 3 + test/cctest/node_test_fixture.h | 2 +- test/cctest/test_aliased_buffer.cc | 216 +++++++++++++++++++++++++++++ 11 files changed, 610 insertions(+), 123 deletions(-) create mode 100644 src/aliased_buffer.h create mode 100755 src/node_http2_state.h create mode 100644 test/cctest/node_test_fixture.cc create mode 100644 test/cctest/test_aliased_buffer.cc diff --git a/node.gyp b/node.gyp index 79d9e0a68dcedf..17f23564147dd1 100644 --- a/node.gyp +++ b/node.gyp @@ -228,6 +228,7 @@ 'src/util.cc', 'src/uv.cc', # headers to make for a more pleasant IDE experience + 'src/aliased_buffer.h', 'src/async-wrap.h', 'src/async-wrap-inl.h', 'src/base-object.h', @@ -246,6 +247,7 @@ 'src/node_constants.h', 'src/node_debug_options.h', 'src/node_http2.h', + 'src/node_http2_state.h', 'src/node_internals.h', 'src/node_javascript.h', 'src/node_mutex.h', @@ -650,6 +652,8 @@ 'sources': [ 'src/node_platform.cc', 'src/node_platform.h', + 'test/cctest/node_test_fixture.cc', + 'test/cctest/test_aliased_buffer.cc', 'test/cctest/test_base64.cc', 'test/cctest/test_environment.cc', 'test/cctest/test_util.cc', diff --git a/src/aliased_buffer.h b/src/aliased_buffer.h new file mode 100644 index 00000000000000..2e5598b4757902 --- /dev/null +++ b/src/aliased_buffer.h @@ -0,0 +1,200 @@ + +#ifndef SRC_ALIASED_BUFFER_H_ +#define SRC_ALIASED_BUFFER_H_ + +#include "v8.h" +#include "util.h" +#include "util-inl.h" + +namespace node { + +/** + * This class encapsulates the technique of having a native buffer mapped to + * a JS object. Writes to the native buffer can happen efficiently without + * going through JS, and the data is then available to user's via the exposed + * JS object. + * + * While this technique is computationaly efficient, it is effectively a + * write to JS program state w/out going through the standard + * (monitored) API. Thus any VM capabilities to detect the modification are + * circumvented. + * + * The encapsulation herein provides a placeholder where such writes can be + * observed. Any notification APIs will be left as a future exercise. + */ +template +class AliasedBuffer { + public: + AliasedBuffer(v8::Isolate* isolate, const size_t count) + : isolate_(isolate), + count_(count), + byte_offset_(0), + free_buffer_(true) { + CHECK_GT(count, 0); + const v8::HandleScope handle_scope(isolate_); + + const size_t sizeInBytes = sizeof(NativeT) * count; + + // allocate native buffer + buffer_ = Calloc(count); + + // allocate v8 ArrayBuffer + v8::Local ab = v8::ArrayBuffer::New( + isolate_, buffer_, sizeInBytes); + + // allocate v8 TypedArray + v8::Local js_array = V8T::New(ab, byte_offset_, count); + js_array_ = v8::Global(isolate, js_array); + } + + /** + * Create an AliasedBuffer over a sub-region of another aliased buffer. + * The two will share a v8::ArrayBuffer instance & + * a native buffer, but will each read/write to different sections of the + * native buffer. + * + * Note that byte_offset must by aligned by sizeof(NativeT). + */ + AliasedBuffer(v8::Isolate* isolate, + const size_t byte_offset, + const size_t count, + const AliasedBuffer& backing_buffer) + : isolate_(isolate), + count_(count), + byte_offset_(byte_offset), + free_buffer_(false) { + const v8::HandleScope handle_scope(isolate_); + + v8::Local ab = backing_buffer.GetArrayBuffer(); + + // validate that the byte_offset is aligned with sizeof(NativeT) + CHECK_EQ(byte_offset & (sizeof(NativeT) - 1), 0); + // validate this fits inside the backing buffer + CHECK_LE(sizeof(NativeT) * count, ab->ByteLength() - byte_offset); + + buffer_ = reinterpret_cast( + const_cast(backing_buffer.GetNativeBuffer() + byte_offset)); + + v8::Local js_array = V8T::New(ab, byte_offset, count); + js_array_ = v8::Global(isolate, js_array); + } + + AliasedBuffer(const AliasedBuffer& that) + : isolate_(that.isolate_), + count_(that.count_), + byte_offset_(that.byte_offset_), + buffer_(that.buffer_), + free_buffer_(false) { + js_array_ = v8::Global(that.isolate_, that.GetJSArray()); + } + + ~AliasedBuffer() { + if (free_buffer_ && buffer_ != nullptr) { + free(buffer_); + } + js_array_.Reset(); + } + + /** + * Helper class that is returned from operator[] to support assignment into + * a specified location. + */ + class Reference { + public: + Reference(AliasedBuffer* aliased_buffer, size_t index) + : aliased_buffer_(aliased_buffer), + index_(index) { + } + + Reference(const Reference& that) + : aliased_buffer_(that.aliased_buffer_), + index_(that.index_) { + } + + inline Reference& operator=(const NativeT &val) { + aliased_buffer_->SetValue(index_, val); + return *this; + } + + operator NativeT() const { + return aliased_buffer_->GetValue(index_); + } + + private: + AliasedBuffer* aliased_buffer_; + size_t index_; + }; + + /** + * Get the underlying v8 TypedArray overlayed on top of the native buffer + */ + v8::Local GetJSArray() const { + return js_array_.Get(isolate_); + } + + /** + * Get the underlying v8::ArrayBuffer underlying the TypedArray and + * overlaying the native buffer + */ + v8::Local GetArrayBuffer() const { + return GetJSArray()->Buffer(); + } + + /** + * Get the underlying native buffer. Note that all reads/writes should occur + * through the GetValue/SetValue/operator[] methods + */ + inline const NativeT* GetNativeBuffer() const { + return buffer_; + } + + /** + * Synonym for GetBuffer() + */ + inline const NativeT* operator * () const { + return GetNativeBuffer(); + } + + /** + * Set position index to given value. + */ + inline void SetValue(const size_t index, NativeT value) { +#if defined(DEBUG) && DEBUG + CHECK_LT(index, count_); +#endif + buffer_[index] = value; + } + + /** + * Get value at position index + */ + inline const NativeT GetValue(const size_t index) const { +#if defined(DEBUG) && DEBUG + CHECK_LT(index, count_); +#endif + return buffer_[index]; + } + + /** + * Effectively, a synonym for GetValue/SetValue + */ + Reference operator[](size_t index) { + return Reference(this, index); + } + + NativeT operator[](size_t index) const { + return GetValue(index); + } + + private: + v8::Isolate* const isolate_; + size_t count_; + size_t byte_offset_; + NativeT* buffer_; + v8::Global js_array_; + bool free_buffer_; +}; +} // namespace node + +#endif // SRC_ALIASED_BUFFER_H_ diff --git a/src/async-wrap.cc b/src/async-wrap.cc index 646476a156f430..5b59ebb23fd9ec 100644 --- a/src/async-wrap.cc +++ b/src/async-wrap.cc @@ -31,7 +31,6 @@ #include "v8-profiler.h" using v8::Array; -using v8::ArrayBuffer; using v8::Context; using v8::Float64Array; using v8::Function; @@ -53,7 +52,6 @@ using v8::RetainedObjectInfo; using v8::String; using v8::Symbol; using v8::TryCatch; -using v8::Uint32Array; using v8::Undefined; using v8::Value; @@ -476,13 +474,9 @@ void AsyncWrap::Initialize(Local target, // callbacks waiting to be called on a particular event. It can then be // incremented/decremented from JS quickly to communicate to C++ if there are // any callbacks waiting to be called. - uint32_t* fields_ptr = env->async_hooks()->fields(); - int fields_count = env->async_hooks()->fields_count(); - Local fields_ab = - ArrayBuffer::New(isolate, fields_ptr, fields_count * sizeof(*fields_ptr)); FORCE_SET_TARGET_FIELD(target, "async_hook_fields", - Uint32Array::New(fields_ab, 0, fields_count)); + env->async_hooks()->fields().GetJSArray()); // The following v8::Float64Array has 5 fields. These fields are shared in // this way to allow JS and C++ to read/write each value as quickly as @@ -493,15 +487,9 @@ void AsyncWrap::Initialize(Local target, // kInitTriggerId: Write the id of the resource responsible for a handle's // creation just before calling the new handle's constructor. After the new // handle is constructed kInitTriggerId is set back to 0. - double* uid_fields_ptr = env->async_hooks()->uid_fields(); - int uid_fields_count = env->async_hooks()->uid_fields_count(); - Local uid_fields_ab = ArrayBuffer::New( - isolate, - uid_fields_ptr, - uid_fields_count * sizeof(*uid_fields_ptr)); FORCE_SET_TARGET_FIELD(target, "async_uid_fields", - Float64Array::New(uid_fields_ab, 0, uid_fields_count)); + env->async_hooks()->uid_fields().GetJSArray()); Local constants = Object::New(isolate); #define SET_HOOKS_CONSTANT(name) \ diff --git a/src/env-inl.h b/src/env-inl.h index 842ed4082843ac..229271ccff45a6 100644 --- a/src/env-inl.h +++ b/src/env-inl.h @@ -24,6 +24,7 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#include "aliased_buffer.h" #include "env.h" #include "node.h" #include "util.h" @@ -82,8 +83,8 @@ inline uint32_t* IsolateData::zero_fill_field() const { inline Environment::AsyncHooks::AsyncHooks(v8::Isolate* isolate) : isolate_(isolate), - fields_(), - uid_fields_() { + fields_(isolate, kFieldsCount), + uid_fields_(isolate, kUidFieldsCount) { v8::HandleScope handle_scope(isolate_); // kAsyncUidCntr should start at 1 because that'll be the id the execution @@ -105,7 +106,8 @@ inline Environment::AsyncHooks::AsyncHooks(v8::Isolate* isolate) #undef V } -inline uint32_t* Environment::AsyncHooks::fields() { +inline AliasedBuffer& +Environment::AsyncHooks::fields() { return fields_; } @@ -113,7 +115,8 @@ inline int Environment::AsyncHooks::fields_count() const { return kFieldsCount; } -inline double* Environment::AsyncHooks::uid_fields() { +inline AliasedBuffer& +Environment::AsyncHooks::uid_fields() { return uid_fields_; } @@ -147,7 +150,7 @@ inline bool Environment::AsyncHooks::pop_ids(double async_id) { fprintf(stderr, "Error: async hook stack has become corrupted (" "actual: %.f, expected: %.f)\n", - uid_fields_[kCurrentAsyncId], + uid_fields_.GetValue(kCurrentAsyncId), async_id); Environment* env = Environment::GetCurrent(isolate_); DumpBacktrace(stderr); @@ -326,7 +329,7 @@ inline Environment::~Environment() { delete[] heap_statistics_buffer_; delete[] heap_space_statistics_buffer_; delete[] http_parser_buffer_; - free(http2_state_buffer_); + delete http2_state_; free(performance_state_); } @@ -425,7 +428,9 @@ inline std::vector* Environment::destroy_ids_list() { } inline double Environment::new_async_id() { - return ++async_hooks()->uid_fields()[AsyncHooks::kAsyncUidCntr]; + async_hooks()->uid_fields()[AsyncHooks::kAsyncUidCntr] = + async_hooks()->uid_fields()[AsyncHooks::kAsyncUidCntr] + 1; + return async_hooks()->uid_fields()[AsyncHooks::kAsyncUidCntr]; } inline double Environment::current_async_id() { @@ -437,7 +442,8 @@ inline double Environment::trigger_id() { } inline double Environment::get_init_trigger_id() { - double* uid_fields = async_hooks()->uid_fields(); + AliasedBuffer& uid_fields = + async_hooks()->uid_fields(); double tid = uid_fields[AsyncHooks::kInitTriggerId]; uid_fields[AsyncHooks::kInitTriggerId] = 0; if (tid <= 0) tid = current_async_id(); @@ -477,13 +483,13 @@ inline void Environment::set_http_parser_buffer(char* buffer) { http_parser_buffer_ = buffer; } -inline http2::http2_state* Environment::http2_state_buffer() const { - return http2_state_buffer_; +inline http2::http2_state* Environment::http2_state() const { + return http2_state_; } -inline void Environment::set_http2_state_buffer(http2::http2_state* buffer) { - CHECK_EQ(http2_state_buffer_, nullptr); // Should be set only once. - http2_state_buffer_ = buffer; +inline void Environment::set_http2_state(http2::http2_state* buffer) { + CHECK_EQ(http2_state_, nullptr); // Should be set only once. + http2_state_ = buffer; } inline double* Environment::fs_stats_field_array() const { diff --git a/src/env.h b/src/env.h index f9a2649115bfd7..20495c4554b2d2 100644 --- a/src/env.h +++ b/src/env.h @@ -24,6 +24,7 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#include "aliased_buffer.h" #include "ares.h" #if HAVE_INSPECTOR #include "inspector_agent.h" @@ -34,6 +35,7 @@ #include "uv.h" #include "v8.h" #include "node.h" +#include "node_http2_state.h" #include #include @@ -46,10 +48,6 @@ struct nghttp2_rcbuf; namespace node { -namespace http2 { -struct http2_state; -} - // Pick an index that's hopefully out of the way when we're embedded inside // another application. Performance-wise or memory-wise it doesn't matter: // Context::SetAlignedPointerInEmbedderData() is backed by a FixedArray, @@ -389,10 +387,12 @@ class Environment { AsyncHooks() = delete; - inline uint32_t* fields(); + inline AliasedBuffer& fields(); inline int fields_count() const; - inline double* uid_fields(); + + inline AliasedBuffer& uid_fields(); inline int uid_fields_count() const; + inline v8::Local provider_string(int idx); inline void push_ids(double async_id, double trigger_id); @@ -411,7 +411,7 @@ class Environment { private: Environment* env_; - double* uid_fields_ref_; + AliasedBuffer uid_fields_ref_; DISALLOW_COPY_AND_ASSIGN(InitScope); }; @@ -427,9 +427,9 @@ class Environment { std::stack ids_stack_; // Attached to a Uint32Array that tracks the number of active hooks for // each type. - uint32_t fields_[kFieldsCount]; + AliasedBuffer fields_; // Attached to a Float64Array that tracks the state of async resources. - double uid_fields_[kUidFieldsCount]; + AliasedBuffer uid_fields_; DISALLOW_COPY_AND_ASSIGN(AsyncHooks); }; @@ -588,8 +588,8 @@ class Environment { inline char* http_parser_buffer() const; inline void set_http_parser_buffer(char* buffer); - inline http2::http2_state* http2_state_buffer() const; - inline void set_http2_state_buffer(http2::http2_state* buffer); + inline http2::http2_state* http2_state() const; + inline void set_http2_state(http2::http2_state * state); inline double* fs_stats_field_array() const; inline void set_fs_stats_field_array(double* fields); @@ -705,7 +705,7 @@ class Environment { double* heap_space_statistics_buffer_ = nullptr; char* http_parser_buffer_; - http2::http2_state* http2_state_buffer_ = nullptr; + http2::http2_state* http2_state_ = nullptr; double* fs_stats_field_array_; diff --git a/src/node_http2.cc b/src/node_http2.cc index 85b7b0958ec97c..c1e178f7175935 100644 --- a/src/node_http2.cc +++ b/src/node_http2.cc @@ -1,10 +1,11 @@ +#include "aliased_buffer.h" #include "node.h" #include "node_buffer.h" #include "node_http2.h" +#include "node_http2_state.h" namespace node { -using v8::ArrayBuffer; using v8::Boolean; using v8::Context; using v8::Float64Array; @@ -17,64 +18,6 @@ using v8::Undefined; namespace http2 { -enum Http2SettingsIndex { - IDX_SETTINGS_HEADER_TABLE_SIZE, - IDX_SETTINGS_ENABLE_PUSH, - IDX_SETTINGS_INITIAL_WINDOW_SIZE, - IDX_SETTINGS_MAX_FRAME_SIZE, - IDX_SETTINGS_MAX_CONCURRENT_STREAMS, - IDX_SETTINGS_MAX_HEADER_LIST_SIZE, - IDX_SETTINGS_COUNT -}; - -enum Http2SessionStateIndex { - IDX_SESSION_STATE_EFFECTIVE_LOCAL_WINDOW_SIZE, - IDX_SESSION_STATE_EFFECTIVE_RECV_DATA_LENGTH, - IDX_SESSION_STATE_NEXT_STREAM_ID, - IDX_SESSION_STATE_LOCAL_WINDOW_SIZE, - IDX_SESSION_STATE_LAST_PROC_STREAM_ID, - IDX_SESSION_STATE_REMOTE_WINDOW_SIZE, - IDX_SESSION_STATE_OUTBOUND_QUEUE_SIZE, - IDX_SESSION_STATE_HD_DEFLATE_DYNAMIC_TABLE_SIZE, - IDX_SESSION_STATE_HD_INFLATE_DYNAMIC_TABLE_SIZE, - IDX_SESSION_STATE_COUNT -}; - -enum Http2StreamStateIndex { - IDX_STREAM_STATE, - IDX_STREAM_STATE_WEIGHT, - IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT, - IDX_STREAM_STATE_LOCAL_CLOSE, - IDX_STREAM_STATE_REMOTE_CLOSE, - IDX_STREAM_STATE_LOCAL_WINDOW_SIZE, - IDX_STREAM_STATE_COUNT -}; - -enum Http2OptionsIndex { - IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE, - IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS, - IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH, - IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS, - IDX_OPTIONS_PADDING_STRATEGY, - IDX_OPTIONS_FLAGS -}; - -enum Http2PaddingBufferFields { - PADDING_BUF_FRAME_LENGTH, - PADDING_BUF_MAX_PAYLOAD_LENGTH, - PADDING_BUF_RETURN_VALUE, - PADDING_BUF_FIELD_COUNT -}; - -struct http2_state { - // doubles first so that they are always sizeof(double)-aligned - double session_state_buffer[IDX_SESSION_STATE_COUNT]; - double stream_state_buffer[IDX_STREAM_STATE_COUNT]; - uint32_t padding_buffer[PADDING_BUF_FIELD_COUNT]; - uint32_t options_buffer[IDX_OPTIONS_FLAGS + 1]; - uint32_t settings_buffer[IDX_SETTINGS_COUNT + 1]; -}; - Freelist data_chunk_free_list; @@ -92,7 +35,8 @@ Nghttp2Session::Callbacks Nghttp2Session::callback_struct_saved[2] = { Http2Options::Http2Options(Environment* env) { nghttp2_option_new(&options_); - uint32_t* buffer = env->http2_state_buffer()->options_buffer; + AliasedBuffer& buffer = + env->http2_state()->options_buffer; uint32_t flags = buffer[IDX_OPTIONS_FLAGS]; if (flags & (1 << IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE)) { @@ -124,7 +68,7 @@ Http2Options::Http2Options(Environment* env) { if (flags & (1 << IDX_OPTIONS_PADDING_STRATEGY)) { padding_strategy_type strategy = static_cast( - buffer[IDX_OPTIONS_PADDING_STRATEGY]); + buffer.GetValue(IDX_OPTIONS_PADDING_STRATEGY)); SetPaddingStrategy(strategy); } } @@ -149,7 +93,8 @@ ssize_t Http2Session::OnCallbackPadding(size_t frameLen, Context::Scope context_scope(context); if (object()->Has(context, env()->ongetpadding_string()).FromJust()) { - uint32_t* buffer = env()->http2_state_buffer()->padding_buffer; + AliasedBuffer& buffer = + env()->http2_state()->padding_buffer; buffer[PADDING_BUF_FRAME_LENGTH] = frameLen; buffer[PADDING_BUF_MAX_PAYLOAD_LENGTH] = maxPayloadLen; MakeCallback(env()->ongetpadding_string(), 0, nullptr); @@ -190,7 +135,8 @@ void PackSettings(const FunctionCallbackInfo& args) { std::vector entries; entries.reserve(6); - uint32_t* buffer = env->http2_state_buffer()->settings_buffer; + AliasedBuffer& buffer = + env->http2_state()->settings_buffer; uint32_t flags = buffer[IDX_SETTINGS_COUNT]; if (flags & (1 << IDX_SETTINGS_HEADER_TABLE_SIZE)) { @@ -250,7 +196,9 @@ void PackSettings(const FunctionCallbackInfo& args) { void RefreshDefaultSettings(const FunctionCallbackInfo& args) { DEBUG_HTTP2("Http2Session: refreshing default settings\n"); Environment* env = Environment::GetCurrent(args); - uint32_t* buffer = env->http2_state_buffer()->settings_buffer; + AliasedBuffer& buffer = + env->http2_state()->settings_buffer; + buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] = DEFAULT_SETTINGS_HEADER_TABLE_SIZE; buffer[IDX_SETTINGS_ENABLE_PUSH] = @@ -276,7 +224,8 @@ void RefreshSettings(const FunctionCallbackInfo& args) { ASSIGN_OR_RETURN_UNWRAP(&session, args[0].As()); nghttp2_session* s = session->session(); - uint32_t* buffer = env->http2_state_buffer()->settings_buffer; + AliasedBuffer& buffer = + env->http2_state()->settings_buffer; buffer[IDX_SETTINGS_HEADER_TABLE_SIZE] = fn(s, NGHTTP2_SETTINGS_HEADER_TABLE_SIZE); buffer[IDX_SETTINGS_MAX_CONCURRENT_STREAMS] = @@ -297,7 +246,8 @@ void RefreshSessionState(const FunctionCallbackInfo& args) { Environment* env = Environment::GetCurrent(args); CHECK_EQ(args.Length(), 1); CHECK(args[0]->IsObject()); - double* buffer = env->http2_state_buffer()->session_state_buffer; + AliasedBuffer& buffer = + env->http2_state()->session_state_buffer; Http2Session* session; ASSIGN_OR_RETURN_UNWRAP(&session, args[0].As()); nghttp2_session* s = session->session(); @@ -334,7 +284,8 @@ void RefreshStreamState(const FunctionCallbackInfo& args) { nghttp2_session* s = session->session(); Nghttp2Stream* stream; - double* buffer = env->http2_state_buffer()->stream_state_buffer; + AliasedBuffer& buffer = + env->http2_state()->stream_state_buffer; if ((stream = session->FindStream(id)) == nullptr) { buffer[IDX_STREAM_STATE] = NGHTTP2_STREAM_STATE_IDLE; @@ -446,7 +397,8 @@ void Http2Session::SubmitSettings(const FunctionCallbackInfo& args) { ASSIGN_OR_RETURN_UNWRAP(&session, args.Holder()); Environment* env = session->env(); - uint32_t* buffer = env->http2_state_buffer()->settings_buffer; + AliasedBuffer& buffer = + env->http2_state()->settings_buffer; uint32_t flags = buffer[IDX_SETTINGS_COUNT]; std::vector entries; @@ -1179,26 +1131,27 @@ void Initialize(Local target, Isolate* isolate = env->isolate(); HandleScope scope(isolate); - http2_state* state = Calloc(1); - env->set_http2_state_buffer(state); - auto state_ab = ArrayBuffer::New(isolate, state, sizeof(*state)); + http2_state* state = new http2_state(isolate); + env->set_http2_state(state); -#define SET_STATE_TYPEDARRAY(name, type, field) \ - target->Set(context, \ - FIXED_ONE_BYTE_STRING(isolate, (name)), \ - type::New(state_ab, \ - offsetof(http2_state, field), \ - arraysize(state->field))) \ - .FromJust() +#define SET_STATE_TYPEDARRAY(name, field) \ + target->Set(context, \ + FIXED_ONE_BYTE_STRING(isolate, (name)), \ + (field)).FromJust() // Initialize the buffer used for padding callbacks - SET_STATE_TYPEDARRAY("paddingBuffer", Uint32Array, padding_buffer); + SET_STATE_TYPEDARRAY( + "paddingBuffer", state->padding_buffer.GetJSArray()); // Initialize the buffer used to store the session state - SET_STATE_TYPEDARRAY("sessionState", Float64Array, session_state_buffer); + SET_STATE_TYPEDARRAY( + "sessionState", state->session_state_buffer.GetJSArray()); // Initialize the buffer used to store the stream state - SET_STATE_TYPEDARRAY("streamState", Float64Array, stream_state_buffer); - SET_STATE_TYPEDARRAY("settingsBuffer", Uint32Array, settings_buffer); - SET_STATE_TYPEDARRAY("optionsBuffer", Uint32Array, options_buffer); + SET_STATE_TYPEDARRAY( + "streamState", state->stream_state_buffer.GetJSArray()); + SET_STATE_TYPEDARRAY( + "settingsBuffer", state->settings_buffer.GetJSArray()); + SET_STATE_TYPEDARRAY( + "optionsBuffer", state->options_buffer.GetJSArray()); #undef SET_STATE_TYPEDARRAY NODE_DEFINE_CONSTANT(target, PADDING_BUF_FRAME_LENGTH); diff --git a/src/node_http2.h b/src/node_http2.h index 9e6931348d78b4..68801eeb54eb31 100644 --- a/src/node_http2.h +++ b/src/node_http2.h @@ -4,6 +4,7 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS #include "node_http2_core-inl.h" +#include "node_http2_state.h" #include "stream_base-inl.h" #include "string_bytes.h" diff --git a/src/node_http2_state.h b/src/node_http2_state.h new file mode 100755 index 00000000000000..a945f07b686b4a --- /dev/null +++ b/src/node_http2_state.h @@ -0,0 +1,116 @@ +#ifndef SRC_NODE_HTTP2_STATE_H_ +#define SRC_NODE_HTTP2_STATE_H_ + +#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#include "aliased_buffer.h" + +namespace node { +namespace http2 { + + enum Http2SettingsIndex { + IDX_SETTINGS_HEADER_TABLE_SIZE, + IDX_SETTINGS_ENABLE_PUSH, + IDX_SETTINGS_INITIAL_WINDOW_SIZE, + IDX_SETTINGS_MAX_FRAME_SIZE, + IDX_SETTINGS_MAX_CONCURRENT_STREAMS, + IDX_SETTINGS_MAX_HEADER_LIST_SIZE, + IDX_SETTINGS_COUNT + }; + + enum Http2SessionStateIndex { + IDX_SESSION_STATE_EFFECTIVE_LOCAL_WINDOW_SIZE, + IDX_SESSION_STATE_EFFECTIVE_RECV_DATA_LENGTH, + IDX_SESSION_STATE_NEXT_STREAM_ID, + IDX_SESSION_STATE_LOCAL_WINDOW_SIZE, + IDX_SESSION_STATE_LAST_PROC_STREAM_ID, + IDX_SESSION_STATE_REMOTE_WINDOW_SIZE, + IDX_SESSION_STATE_OUTBOUND_QUEUE_SIZE, + IDX_SESSION_STATE_HD_DEFLATE_DYNAMIC_TABLE_SIZE, + IDX_SESSION_STATE_HD_INFLATE_DYNAMIC_TABLE_SIZE, + IDX_SESSION_STATE_COUNT + }; + + enum Http2StreamStateIndex { + IDX_STREAM_STATE, + IDX_STREAM_STATE_WEIGHT, + IDX_STREAM_STATE_SUM_DEPENDENCY_WEIGHT, + IDX_STREAM_STATE_LOCAL_CLOSE, + IDX_STREAM_STATE_REMOTE_CLOSE, + IDX_STREAM_STATE_LOCAL_WINDOW_SIZE, + IDX_STREAM_STATE_COUNT + }; + + enum Http2OptionsIndex { + IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE, + IDX_OPTIONS_MAX_RESERVED_REMOTE_STREAMS, + IDX_OPTIONS_MAX_SEND_HEADER_BLOCK_LENGTH, + IDX_OPTIONS_PEER_MAX_CONCURRENT_STREAMS, + IDX_OPTIONS_PADDING_STRATEGY, + IDX_OPTIONS_FLAGS + }; + + enum Http2PaddingBufferFields { + PADDING_BUF_FRAME_LENGTH, + PADDING_BUF_MAX_PAYLOAD_LENGTH, + PADDING_BUF_RETURN_VALUE, + PADDING_BUF_FIELD_COUNT + }; + +class http2_state { + public: + explicit http2_state(v8::Isolate* isolate) : + root_buffer( + isolate, + sizeof(http2_state_internal)), + session_state_buffer( + isolate, + offsetof(http2_state_internal, session_state_buffer), + IDX_SESSION_STATE_COUNT, + root_buffer), + stream_state_buffer( + isolate, + offsetof(http2_state_internal, stream_state_buffer), + IDX_STREAM_STATE_COUNT, + root_buffer), + padding_buffer( + isolate, + offsetof(http2_state_internal, padding_buffer), + PADDING_BUF_FIELD_COUNT, + root_buffer), + options_buffer( + isolate, + offsetof(http2_state_internal, options_buffer), + IDX_OPTIONS_FLAGS + 1, + root_buffer), + settings_buffer( + isolate, + offsetof(http2_state_internal, settings_buffer), + IDX_SETTINGS_COUNT + 1, + root_buffer) { + } + + AliasedBuffer root_buffer; + AliasedBuffer session_state_buffer; + AliasedBuffer stream_state_buffer; + AliasedBuffer padding_buffer; + AliasedBuffer options_buffer; + AliasedBuffer settings_buffer; + + private: + struct http2_state_internal { + // doubles first so that they are always sizeof(double)-aligned + double session_state_buffer[IDX_SESSION_STATE_COUNT]; + double stream_state_buffer[IDX_STREAM_STATE_COUNT]; + uint32_t padding_buffer[PADDING_BUF_FIELD_COUNT]; + uint32_t options_buffer[IDX_OPTIONS_FLAGS + 1]; + uint32_t settings_buffer[IDX_SETTINGS_COUNT + 1]; + }; +}; + +} // namespace http2 +} // namespace node + +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +#endif // SRC_NODE_HTTP2_STATE_H_ diff --git a/test/cctest/node_test_fixture.cc b/test/cctest/node_test_fixture.cc new file mode 100644 index 00000000000000..477adb5711af38 --- /dev/null +++ b/test/cctest/node_test_fixture.cc @@ -0,0 +1,3 @@ +#include "node_test_fixture.h" + +uv_loop_t current_loop; diff --git a/test/cctest/node_test_fixture.h b/test/cctest/node_test_fixture.h index f30823a8fdb46a..79027d25ad8c8d 100644 --- a/test/cctest/node_test_fixture.h +++ b/test/cctest/node_test_fixture.h @@ -66,7 +66,7 @@ struct Argv { int nr_args_; }; -uv_loop_t current_loop; +extern uv_loop_t current_loop; class NodeTestFixture : public ::testing::Test { public: diff --git a/test/cctest/test_aliased_buffer.cc b/test/cctest/test_aliased_buffer.cc new file mode 100644 index 00000000000000..65b029f2a02d02 --- /dev/null +++ b/test/cctest/test_aliased_buffer.cc @@ -0,0 +1,216 @@ + +#include "v8.h" +#include "aliased_buffer.h" +#include "node_test_fixture.h" + +using node::AliasedBuffer; + +class AliasBufferTest : public NodeTestFixture { + protected: + void SetUp() override { + NodeTestFixture::SetUp(); + } + + void TearDown() override { + NodeTestFixture::TearDown(); + } +}; + +template +void CreateOracleValues(NativeT* buf, size_t count) { + for (size_t i = 0, j = count; i < count; i++, j--) { + buf[i] = static_cast(j); + } +} + +template +void WriteViaOperator(AliasedBuffer* aliasedBuffer, + size_t size, + NativeT* oracle) { + // write through the API + for (size_t i = 0; i < size; i++) { + (*aliasedBuffer)[i] = oracle[i]; + } +} + +template +void WriteViaSetValue(AliasedBuffer* aliasedBuffer, + size_t size, + NativeT* oracle) { + // write through the API + for (size_t i = 0; i < size; i++) { + aliasedBuffer->SetValue(i, oracle[i]); + } +} + +template +void ReadAndValidate(v8::Isolate* isolate, + v8::Local context, + AliasedBuffer* aliasedBuffer, + size_t size, + NativeT* oracle) { + // read through the API + for (size_t i = 0; i < size; i++) { + NativeT v1 = (*aliasedBuffer)[i]; + NativeT v2 = aliasedBuffer->GetValue(i); + EXPECT_TRUE(v1 == oracle[i]); + EXPECT_TRUE(v2 == oracle[i]); + } + + // validate size of JS Buffer + EXPECT_TRUE(aliasedBuffer->GetJSArray()->Length() == size); + EXPECT_TRUE( + aliasedBuffer->GetJSArray()->ByteLength() == + (size * sizeof(NativeT))); + + // validate operator * and GetBuffer are the same + EXPECT_TRUE(aliasedBuffer->GetNativeBuffer() == *(*aliasedBuffer)); + + // read through the JS API + for (size_t i = 0; i < size; i++) { + v8::Local v8TypedArray = aliasedBuffer->GetJSArray(); + v8::MaybeLocal v = v8TypedArray->Get(context, i); + EXPECT_TRUE(v.IsEmpty() == false); + v8::Local v2 = v.ToLocalChecked(); + EXPECT_TRUE(v2->IsNumber()); + v8::MaybeLocal v3 = v2->ToNumber(context); + v8::Local v4 = v3.ToLocalChecked(); + NativeT actualValue = static_cast(v4->Value()); + EXPECT_TRUE(actualValue == oracle[i]); + } +} + +template +void ReadWriteTest(v8::Isolate* isolate) { + v8::HandleScope handle_scope(isolate); + v8::Local context = v8::Context::New(isolate); + v8::Context::Scope context_scope(context); + + const size_t size = 100; + AliasedBuffer ab(isolate, size); + NativeT* oracle = new NativeT[size]; + CreateOracleValues(oracle, size); + WriteViaOperator(&ab, size, oracle); + ReadAndValidate(isolate, context, &ab, size, oracle); + + WriteViaSetValue(&ab, size, oracle); + + // validate copy constructor + { + AliasedBuffer ab2(ab); + ReadAndValidate(isolate, context, &ab2, size, oracle); + } + ReadAndValidate(isolate, context, &ab, size, oracle); + + delete[] oracle; +} + +template< + class NativeT_A, class V8T_A, + class NativeT_B, class V8T_B, + class NativeT_C, class V8T_C> +void SharedBufferTest( + v8::Isolate* isolate, + size_t count_A, + size_t count_B, + size_t count_C) { + v8::HandleScope handle_scope(isolate); + v8::Local context = v8::Context::New(isolate); + v8::Context::Scope context_scope(context); + + size_t sizeInBytes_A = count_A * sizeof(NativeT_A); + size_t sizeInBytes_B = count_B * sizeof(NativeT_B); + size_t sizeInBytes_C = count_C * sizeof(NativeT_C); + + AliasedBuffer rootBuffer( + isolate, sizeInBytes_A + sizeInBytes_B + sizeInBytes_C); + AliasedBuffer ab_A( + isolate, 0, count_A, rootBuffer); + AliasedBuffer ab_B( + isolate, sizeInBytes_A, count_B, rootBuffer); + AliasedBuffer ab_C( + isolate, sizeInBytes_A + sizeInBytes_B, count_C, rootBuffer); + + NativeT_A* oracle_A = new NativeT_A[count_A]; + NativeT_B* oracle_B = new NativeT_B[count_B]; + NativeT_C* oracle_C = new NativeT_C[count_C]; + CreateOracleValues(oracle_A, count_A); + CreateOracleValues(oracle_B, count_B); + CreateOracleValues(oracle_C, count_C); + + WriteViaOperator(&ab_A, count_A, oracle_A); + WriteViaOperator(&ab_B, count_B, oracle_B); + WriteViaOperator(&ab_C, count_C, oracle_C); + + ReadAndValidate(isolate, context, &ab_A, count_A, oracle_A); + ReadAndValidate(isolate, context, &ab_B, count_B, oracle_B); + ReadAndValidate(isolate, context, &ab_C, count_C, oracle_C); + + WriteViaSetValue(&ab_A, count_A, oracle_A); + WriteViaSetValue(&ab_B, count_B, oracle_B); + WriteViaSetValue(&ab_C, count_C, oracle_C); + + ReadAndValidate(isolate, context, &ab_A, count_A, oracle_A); + ReadAndValidate(isolate, context, &ab_B, count_B, oracle_B); + ReadAndValidate(isolate, context, &ab_C, count_C, oracle_C); +} + +TEST_F(AliasBufferTest, Uint8Array) { + ReadWriteTest(isolate_); +} + +TEST_F(AliasBufferTest, Int8Array) { + ReadWriteTest(isolate_); +} + +TEST_F(AliasBufferTest, Uint16Array) { + ReadWriteTest(isolate_); +} + +TEST_F(AliasBufferTest, Int16Array) { + ReadWriteTest(isolate_); +} + +TEST_F(AliasBufferTest, Uint32Array) { + ReadWriteTest(isolate_); +} + +TEST_F(AliasBufferTest, Int32Array) { + ReadWriteTest(isolate_); +} + +TEST_F(AliasBufferTest, Float32Array) { + ReadWriteTest(isolate_); +} + +TEST_F(AliasBufferTest, Float64Array) { + ReadWriteTest(isolate_); +} + +TEST_F(AliasBufferTest, SharedArrayBuffer1) { + SharedBufferTest< + uint32_t, v8::Uint32Array, + double, v8::Float64Array, + int8_t, v8::Int8Array>(isolate_, 100, 80, 8); +} + +TEST_F(AliasBufferTest, SharedArrayBuffer2) { + SharedBufferTest< + double, v8::Float64Array, + int8_t, v8::Int8Array, + double, v8::Float64Array>(isolate_, 100, 8, 8); +} + +TEST_F(AliasBufferTest, SharedArrayBuffer3) { + SharedBufferTest< + int8_t, v8::Int8Array, + int8_t, v8::Int8Array, + double, v8::Float64Array>(isolate_, 1, 7, 8); +} + +TEST_F(AliasBufferTest, SharedArrayBuffer4) { + SharedBufferTest< + int8_t, v8::Int8Array, + int8_t, v8::Int8Array, + int32_t, v8::Int32Array>(isolate_, 1, 3, 1); +} From 38422d59636f3a3bd0d311dcfc7586b7c949e705 Mon Sep 17 00:00:00 2001 From: Vse Mozhet Byt Date: Sun, 10 Sep 2017 15:13:47 +0300 Subject: [PATCH 051/145] doc: fix nits in esm.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix some abbreviated wording, a typo and a link. * Wrap long lines at 80 characters. PR-URL: https://github.com/nodejs/node/pull/15315 Reviewed-By: Michaël Zasso Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca Reviewed-By: Tobias Nießen Reviewed-By: James M Snell --- doc/api/esm.md | 37 +++++++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/doc/api/esm.md b/doc/api/esm.md index 108fd76336495d..7b684e99a27fc2 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -6,17 +6,21 @@ -Node contains support for ES Modules based upon the [the Node EP for ES Modules][]. +Node.js contains support for ES Modules based upon the +[Node.js EP for ES Modules][]. -Not all features of the EP are complete and will be landing as both VM support and implementation is ready. Error messages are still being polished. +Not all features of the EP are complete and will be landing as both VM support +and implementation is ready. Error messages are still being polished. ## Enabling -The `--experimental-modules` flag can be used to enable features for loading ESM modules. +The `--experimental-modules` flag can be used to enable features for loading +ESM modules. -Once this has been set, files ending with `.mjs` will be able to be loaded as ES Modules. +Once this has been set, files ending with `.mjs` will be able to be loaded +as ES Modules. ```sh node --experimental-modules my-app.mjs @@ -28,7 +32,9 @@ node --experimental-modules my-app.mjs ### Supported -Only the CLI argument for the main entry point to the program can be an entry point into an ESM graph. In the future `import()` can be used to create entry points into ESM graphs at run time. +Only the CLI argument for the main entry point to the program can be an entry +point into an ESM graph. In the future `import()` can be used to create entry +points into ESM graphs at run time. ### Unsupported @@ -43,11 +49,13 @@ Only the CLI argument for the main entry point to the program can be an entry po ### No NODE_PATH -`NODE_PATH` is not part of resolving `import` specifiers. Please use symlinks if this behavior is desired. +`NODE_PATH` is not part of resolving `import` specifiers. Please use symlinks +if this behavior is desired. ### No `require.extensions` -`require.extensions` is not used by `import`. The expectation is that loader hooks can provide this workflow in the future. +`require.extensions` is not used by `import`. The expectation is that loader +hooks can provide this workflow in the future. ### No `require.cache` @@ -55,9 +63,12 @@ Only the CLI argument for the main entry point to the program can be an entry po ### URL based paths -ESM are resolved and cached based upon [URL](url.spec.whatwg.org) semantics. This means that files containing special characters such as `#` and `?` need to be escaped. +ESM are resolved and cached based upon [URL](https://url.spec.whatwg.org/) +semantics. This means that files containing special characters such as `#` and +`?` need to be escaped. -Modules will be loaded multiple times if the `import` specifier used to resolve them have a different query or fragment. +Modules will be loaded multiple times if the `import` specifier used to resolve +them have a different query or fragment. ```js import './foo?query=1'; // loads ./foo with query of "?query=1" @@ -70,9 +81,11 @@ For now, only modules using the `file:` protocol can be loaded. All CommonJS, JSON, and C++ modules can be used with `import`. -Modules loaded this way will only be loaded once, even if their query or fragment string differs between `import` statements. +Modules loaded this way will only be loaded once, even if their query +or fragment string differs between `import` statements. -When loaded via `import` these modules will provide a single `default` export representing the value of `module.exports` at the time they finished evaluating. +When loaded via `import` these modules will provide a single `default` export +representing the value of `module.exports` at the time they finished evaluating. ```js import fs from 'fs'; @@ -85,4 +98,4 @@ fs.readFile('./foo.txt', (err, body) => { }); ``` -[the Node EP for ES Modules]: https://github.com/nodejs/node-eps/blob/master/002-es-modules.md +[Node.js EP for ES Modules]: https://github.com/nodejs/node-eps/blob/master/002-es-modules.md From d5b3002572edfc0e52a409d2e1cf52babc67d3b8 Mon Sep 17 00:00:00 2001 From: Gabriel Schulhof Date: Sat, 9 Sep 2017 12:15:14 +0300 Subject: [PATCH 052/145] n-api: stop creating references to primitives The binding testing napi_wrap() creates references to primitives passed into the binding in its second parameter. This is unnecessary and not at all the point of the test. Additionally, creating persistent references to primitive values may not be supported by all VMs, since primitives are best persisted in their native form. Instead, the point of the test is to make sure that the finalize callback gets called when it should get called, that it gets called with the correct pointer, and that it does not get called when it should not get called. Creating persistent references is not necessary for verifying this. PR-URL: https://github.com/nodejs/node/pull/15289 Reviewed-By: Jason Ginchereau Reviewed-By: Colin Ihrig Re: https://github.com/nodejs/node-chakracore/issues/380 --- doc/api/n-api.md | 2 +- src/node_api.cc | 10 ++++++++-- test/addons-napi/test_general/test.js | 10 +++++----- test/addons-napi/test_general/test_general.c | 17 +++++++---------- 4 files changed, 21 insertions(+), 18 deletions(-) diff --git a/doc/api/n-api.md b/doc/api/n-api.md index d56638463fd73f..70ee1cb70a320c 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -787,7 +787,7 @@ NODE_EXTERN napi_status napi_create_reference(napi_env env, - `[in] env`: The environment that the API is invoked under. - `[in] value`: `napi_value` representing the Object to which we want -a reference to. +a reference. - `[in] initial_refcount`: Initial reference count for the new reference. - `[out] result`: `napi_ref` pointing to the new reference. diff --git a/src/node_api.cc b/src/node_api.cc index e230b0b6a7a601..1ec30d3d80719e 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -2467,8 +2467,14 @@ napi_status napi_create_reference(napi_env env, CHECK_ARG(env, value); CHECK_ARG(env, result); - v8impl::Reference* reference = v8impl::Reference::New( - env, v8impl::V8LocalValueFromJsValue(value), initial_refcount, false); + v8::Local v8_value = v8impl::V8LocalValueFromJsValue(value); + + if (!(v8_value->IsObject() || v8_value->IsFunction())) { + return napi_set_last_error(env, napi_object_expected); + } + + v8impl::Reference* reference = + v8impl::Reference::New(env, v8_value, initial_refcount, false); *result = reinterpret_cast(reference); return napi_clear_last_error(env); diff --git a/test/addons-napi/test_general/test.js b/test/addons-napi/test_general/test.js index e9e2b9614ca34c..3ff57922c5372b 100644 --- a/test/addons-napi/test_general/test.js +++ b/test/addons-napi/test_general/test.js @@ -60,7 +60,7 @@ assert.strictEqual(test_general.testNapiTypeof(null), 'null'); // Ensure that garbage collecting an object with a wrapped native item results // in the finalize callback being called. let w = {}; -test_general.wrap(w, []); +test_general.wrap(w); w = null; global.gc(); assert.strictEqual(test_general.derefItemWasCalled(), true, @@ -69,17 +69,17 @@ assert.strictEqual(test_general.derefItemWasCalled(), true, // Assert that wrapping twice fails. const x = {}; -test_general.wrap(x, 25); +test_general.wrap(x); assert.throws(function() { - test_general.wrap(x, 'Blah'); + test_general.wrap(x); }, Error); // Ensure that wrapping, removing the wrap, and then wrapping again works. const y = {}; -test_general.wrap(y, -12); +test_general.wrap(y); test_general.removeWrap(y); assert.doesNotThrow(function() { - test_general.wrap(y, 're-wrap!'); + test_general.wrap(y); }, Error, 'Wrapping twice succeeds if a remove_wrap() separates the instances'); // Ensure that removing a wrap and garbage collecting does not fire the diff --git a/test/addons-napi/test_general/test_general.c b/test/addons-napi/test_general/test_general.c index 96623b475e5a96..099c1315c071fe 100644 --- a/test/addons-napi/test_general/test_general.c +++ b/test/addons-napi/test_general/test_general.c @@ -143,8 +143,10 @@ static bool deref_item_called = false; static void deref_item(napi_env env, void* data, void* hint) { (void) hint; + NAPI_ASSERT_RETURN_VOID(env, data == &deref_item_called, + "Finalize callback was called with the correct pointer"); + deref_item_called = true; - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, (napi_ref)data)); } napi_value deref_item_was_called(napi_env env, napi_callback_info info) { @@ -156,15 +158,13 @@ napi_value deref_item_was_called(napi_env env, napi_callback_info info) { } napi_value wrap(napi_env env, napi_callback_info info) { - size_t argc = 2; - napi_value argv[2]; - napi_ref payload; + size_t argc = 1; + napi_value to_wrap; deref_item_called = false; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); - NAPI_CALL(env, napi_create_reference(env, argv[1], 1, &payload)); - NAPI_CALL(env, napi_wrap(env, argv[0], payload, deref_item, NULL, NULL)); + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &to_wrap, NULL, NULL)); + NAPI_CALL(env, napi_wrap(env, to_wrap, &deref_item_called, deref_item, NULL, NULL)); return NULL; } @@ -176,9 +176,6 @@ napi_value remove_wrap(napi_env env, napi_callback_info info) { NAPI_CALL(env, napi_get_cb_info(env, info, &argc, &wrapped, NULL, NULL)); NAPI_CALL(env, napi_remove_wrap(env, wrapped, &data)); - if (data != NULL) { - NAPI_CALL(env, napi_delete_reference(env, (napi_ref)data)); - } return NULL; } From 950f7f5fe146a9c9cc27cc658b2501d73e41ddef Mon Sep 17 00:00:00 2001 From: Jon Moss Date: Wed, 30 Aug 2017 20:05:39 -0400 Subject: [PATCH 053/145] doc: update README with SHASUMS256.txt.sig info It is more secure to verify SHASUMS256.txt files via SHASUMS256.txt.sig than SHASUMS256.txt.asc. This comment does the best job at explaining the issue: https://github.com/nodejs/node/issues/6821#issuecomment-220033176 Refer: https://github.com/nodejs/node/issues/6821 Refer: https://github.com/nodejs/node/issues/9071 PR-URL: https://github.com/nodejs/node/pull/15107 Reviewed-By: Rod Vagg Reviewed-By: Ruben Bridgewater Reviewed-By: James Snell Reviewed-By: Luigi Pinca --- README.md | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index ec1488345adb7b..30b2f4c8fa6ede 100644 --- a/README.md +++ b/README.md @@ -134,12 +134,12 @@ $ grep node-vx.y.z.tar.gz SHASUMS256.txt | sha256sum -c - _(Where "node-vx.y.z.tar.gz" is the name of the file you have downloaded)_ -Additionally, Current and LTS releases (not Nightlies) have GPG signed -copies of SHASUMS256.txt files available as SHASUMS256.txt.asc. You can use -`gpg` to verify that the file has not been tampered with. +Additionally, Current and LTS releases (not Nightlies) have the GPG +detached signature of SHASUMS256.txt available as SHASUMS256.txt.sig. +You can use `gpg` to verify that SHASUMS256.txt has not been tampered with. -To verify a SHASUMS256.txt.asc, you will first need to import all of -the GPG keys of individuals authorized to create releases. They are +To verify SHASUMS256.txt has not been altered, you will first need to import +all of the GPG keys of individuals authorized to create releases. They are listed at the bottom of this README under [Release Team](#release-team). Use a command such as this to import the keys: @@ -150,10 +150,17 @@ $ gpg --keyserver pool.sks-keyservers.net --recv-keys DD8F2338BAE7501E3DD5AC78C2 _(See the bottom of this README for a full script to import active release keys)_ -You can then use `gpg --verify SHASUMS256.txt.asc` to verify that the -file has been signed by an authorized member of the Node.js team. +Next, download the SHASUMS256.txt.sig for the release: -Once verified, use the SHASUMS256.txt.asc file to get the checksum for +```console +$ curl -O https://nodejs.org/dist/vx.y.z/SHASUMS256.txt.sig +``` + +After downloading the appropriate SHASUMS256.txt and SHASUMS256.txt.sig files, +you can then use `gpg --verify SHASUMS256.txt.sig SHASUMS256.txt` to verify +that the file has been signed by an authorized member of the Node.js team. + +Once verified, use the SHASUMS256.txt file to get the checksum for the binary verification command above. ## Building Node.js From 9490be353ef5d5f0d790966c2c3c9bfcf9d8ac98 Mon Sep 17 00:00:00 2001 From: Anatoli Papirovski Date: Tue, 12 Sep 2017 07:39:53 -0400 Subject: [PATCH 054/145] http2: cleanup of h2 compat layer, add tests Remove unnecessary variable assignments, remove unreachable code pathways, remove path getter and setter, and other very minor cleanup. Only remove reference to stream on nextTick so that users and libraries can access it in the finish event. Fixes: https://github.com/nodejs/node/issues/15313 Refs: https://github.com/expressjs/express/pull/3390 PR-URL: https://github.com/nodejs/node/pull/15254 Reviewed-By: Matteo Collina Reviewed-By: James M Snell --- lib/internal/http2/compat.js | 238 ++++++++---------- ...test-http2-compat-serverrequest-headers.js | 7 +- .../test-http2-compat-serverrequest.js | 2 - ...est-http2-compat-serverresponse-destroy.js | 2 +- ...st-http2-compat-serverresponse-finished.js | 7 +- ...est-http2-compat-serverresponse-headers.js | 33 +++ ...t-http2-compat-serverresponse-writehead.js | 5 + test/parallel/test-http2-createwritereq.js | 2 +- 8 files changed, 158 insertions(+), 138 deletions(-) diff --git a/lib/internal/http2/compat.js b/lib/internal/http2/compat.js index 6a5fc40da18f95..c36b887f178c8d 100644 --- a/lib/internal/http2/compat.js +++ b/lib/internal/http2/compat.js @@ -17,6 +17,21 @@ const kRawHeaders = Symbol('rawHeaders'); const kTrailers = Symbol('trailers'); const kRawTrailers = Symbol('rawTrailers'); +const { + NGHTTP2_NO_ERROR, + + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_SCHEME, + HTTP2_HEADER_STATUS, + + HTTP_STATUS_CONTINUE, + HTTP_STATUS_EXPECTATION_FAILED, + HTTP_STATUS_METHOD_NOT_ALLOWED, + HTTP_STATUS_OK +} = constants; + let statusMessageWarned = false; // Defines and implements an API compatibility layer on top of the core @@ -24,6 +39,8 @@ let statusMessageWarned = false; // close as possible to the current require('http') API function assertValidHeader(name, value) { + if (name === '') + throw new errors.TypeError('ERR_INVALID_HTTP_TOKEN', 'Header name', name); if (isPseudoHeader(name)) throw new errors.Error('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED'); if (value === undefined || value === null) @@ -32,15 +49,11 @@ function assertValidHeader(name, value) { function isPseudoHeader(name) { switch (name) { - case ':status': - return true; - case ':method': - return true; - case ':path': - return true; - case ':authority': - return true; - case ':scheme': + case HTTP2_HEADER_STATUS: // :status + case HTTP2_HEADER_METHOD: // :method + case HTTP2_HEADER_PATH: // :path + case HTTP2_HEADER_AUTHORITY: // :authority + case HTTP2_HEADER_SCHEME: // :scheme return true; default: return false; @@ -58,8 +71,7 @@ function statusMessageWarn() { } function onStreamData(chunk) { - const request = this[kRequest]; - if (!request.push(chunk)) + if (!this[kRequest].push(chunk)) this.pause(); } @@ -71,8 +83,7 @@ function onStreamTrailers(trailers, flags, rawTrailers) { function onStreamEnd() { // Cause the request stream to end as well. - const request = this[kRequest]; - request.push(null); + this[kRequest].push(null); } function onStreamError(error) { @@ -86,13 +97,11 @@ function onStreamError(error) { } function onRequestPause() { - const stream = this[kStream]; - stream.pause(); + this[kStream].pause(); } function onRequestResume() { - const stream = this[kStream]; - stream.resume(); + this[kStream].resume(); } function onRequestDrain() { @@ -101,13 +110,11 @@ function onRequestDrain() { } function onStreamResponseDrain() { - const response = this[kResponse]; - response.emit('drain'); + this[kResponse].emit('drain'); } function onStreamClosedRequest() { - const req = this[kRequest]; - req.push(null); + this[kRequest].push(null); } function onStreamClosedResponse() { @@ -134,9 +141,8 @@ class Http2ServerRequest extends Readable { constructor(stream, headers, options, rawHeaders) { super(options); this[kState] = { - statusCode: null, closed: false, - closedCode: constants.NGHTTP2_NO_ERROR + closedCode: NGHTTP2_NO_ERROR }; this[kHeaders] = headers; this[kRawHeaders] = rawHeaders; @@ -162,23 +168,17 @@ class Http2ServerRequest extends Readable { } get closed() { - const state = this[kState]; - return Boolean(state.closed); + return this[kState].closed; } get code() { - const state = this[kState]; - return Number(state.closedCode); + return this[kState].closedCode; } get stream() { return this[kStream]; } - get statusCode() { - return this[kState].statusCode; - } - get headers() { return this[kHeaders]; } @@ -208,7 +208,10 @@ class Http2ServerRequest extends Readable { } get socket() { - return this.stream.session.socket; + const stream = this[kStream]; + if (stream === undefined) + return; + return stream.session.socket; } get connection() { @@ -217,7 +220,7 @@ class Http2ServerRequest extends Readable { _read(nread) { const stream = this[kStream]; - if (stream) { + if (stream !== undefined) { stream.resume(); } else { this.emit('error', new errors.Error('ERR_HTTP2_STREAM_CLOSED')); @@ -225,46 +228,23 @@ class Http2ServerRequest extends Readable { } get method() { - const headers = this[kHeaders]; - if (headers === undefined) - return; - return headers[constants.HTTP2_HEADER_METHOD]; + return this[kHeaders][HTTP2_HEADER_METHOD]; } get authority() { - const headers = this[kHeaders]; - if (headers === undefined) - return; - return headers[constants.HTTP2_HEADER_AUTHORITY]; + return this[kHeaders][HTTP2_HEADER_AUTHORITY]; } get scheme() { - const headers = this[kHeaders]; - if (headers === undefined) - return; - return headers[constants.HTTP2_HEADER_SCHEME]; + return this[kHeaders][HTTP2_HEADER_SCHEME]; } get url() { - return this.path; + return this[kHeaders][HTTP2_HEADER_PATH]; } set url(url) { - this.path = url; - } - - get path() { - const headers = this[kHeaders]; - if (headers === undefined) - return; - return headers[constants.HTTP2_HEADER_PATH]; - } - - set path(path) { - let headers = this[kHeaders]; - if (headers === undefined) - headers = this[kHeaders] = Object.create(null); - headers[constants.HTTP2_HEADER_PATH] = path; + this[kHeaders][HTTP2_HEADER_PATH] = url; } setTimeout(msecs, callback) { @@ -278,10 +258,10 @@ class Http2ServerRequest extends Readable { if (state.closed) return; if (code !== undefined) - state.closedCode = code; + state.closedCode = Number(code); state.closed = true; this.push(null); - this[kStream] = undefined; + process.nextTick(() => (this[kStream] = undefined)); } } @@ -290,12 +270,12 @@ class Http2ServerResponse extends Stream { super(options); this[kState] = { sendDate: true, - statusCode: constants.HTTP_STATUS_OK, - headerCount: 0, - trailerCount: 0, + statusCode: HTTP_STATUS_OK, closed: false, - closedCode: constants.NGHTTP2_NO_ERROR + closedCode: NGHTTP2_NO_ERROR }; + this[kHeaders] = Object.create(null); + this[kTrailers] = Object.create(null); this[kStream] = stream; stream[kResponse] = this; this.writable = true; @@ -313,13 +293,11 @@ class Http2ServerResponse extends Stream { } get closed() { - const state = this[kState]; - return Boolean(state.closed); + return this[kState].closed; } get code() { - const state = this[kState]; - return Number(state.closedCode); + return this[kState].closedCode; } get stream() { @@ -332,7 +310,7 @@ class Http2ServerResponse extends Stream { } get sendDate() { - return Boolean(this[kState].sendDate); + return this[kState].sendDate; } set sendDate(bool) { @@ -344,70 +322,71 @@ class Http2ServerResponse extends Stream { } set statusCode(code) { - const state = this[kState]; code |= 0; if (code >= 100 && code < 200) throw new errors.RangeError('ERR_HTTP2_INFO_STATUS_NOT_ALLOWED'); - if (code < 200 || code > 599) + if (code < 100 || code > 599) throw new errors.RangeError('ERR_HTTP2_STATUS_INVALID', code); - state.statusCode = code; + this[kState].statusCode = code; + } + + setTrailer(name, value) { + if (typeof name !== 'string') + throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'name', 'string'); + + name = name.trim().toLowerCase(); + assertValidHeader(name, value); + this[kTrailers][name] = String(value); } addTrailers(headers) { - let trailers = this[kTrailers]; const keys = Object.keys(headers); - if (keys.length === 0) - return; - if (trailers === undefined) - trailers = this[kTrailers] = Object.create(null); + let key = ''; for (var i = 0; i < keys.length; i++) { - trailers[keys[i]] = String(headers[keys[i]]); + key = keys[i]; + this.setTrailer(key, headers[key]); } } getHeader(name) { - const headers = this[kHeaders]; - if (headers === undefined) - return; - name = String(name).trim().toLowerCase(); - return headers[name]; + if (typeof name !== 'string') + throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'name', 'string'); + + name = name.trim().toLowerCase(); + return this[kHeaders][name]; } getHeaderNames() { - const headers = this[kHeaders]; - if (headers === undefined) - return []; - return Object.keys(headers); + return Object.keys(this[kHeaders]); } getHeaders() { - const headers = this[kHeaders]; - return Object.assign({}, headers); + return Object.assign({}, this[kHeaders]); } hasHeader(name) { - const headers = this[kHeaders]; - if (headers === undefined) - return false; - name = String(name).trim().toLowerCase(); - return Object.prototype.hasOwnProperty.call(headers, name); + if (typeof name !== 'string') + throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'name', 'string'); + + name = name.trim().toLowerCase(); + return Object.prototype.hasOwnProperty.call(this[kHeaders], name); } removeHeader(name) { - const headers = this[kHeaders]; - if (headers === undefined) - return; - name = String(name).trim().toLowerCase(); - delete headers[name]; + if (typeof name !== 'string') + throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'name', 'string'); + + name = name.trim().toLowerCase(); + delete this[kHeaders][name]; } setHeader(name, value) { - name = String(name).trim().toLowerCase(); + if (typeof name !== 'string') + throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'name', 'string'); + + name = name.trim().toLowerCase(); assertValidHeader(name, value); - let headers = this[kHeaders]; - if (headers === undefined) - headers = this[kHeaders] = Object.create(null); - headers[name] = String(value); + this[kHeaders][name] = String(value); } get statusMessage() { @@ -421,7 +400,8 @@ class Http2ServerResponse extends Stream { } flushHeaders() { - if (this[kStream].headersSent === false) + const stream = this[kStream]; + if (stream !== undefined && stream.headersSent === false) this[kBeginSend](); } @@ -435,11 +415,14 @@ class Http2ServerResponse extends Stream { } const stream = this[kStream]; + if (stream === undefined) { + throw new errors.Error('ERR_HTTP2_STREAM_CLOSED'); + } if (stream.headersSent === true) { throw new errors.Error('ERR_HTTP2_INFO_HEADERS_AFTER_RESPOND'); } - if (headers) { + if (typeof headers === 'object') { const keys = Object.keys(headers); let key = ''; for (var i = 0; i < keys.length; i++) { @@ -487,15 +470,16 @@ class Http2ServerResponse extends Stream { this.write(chunk, encoding); } - if (typeof cb === 'function' && stream !== undefined) { + if (stream === undefined) { + return; + } + + if (typeof cb === 'function') { stream.once('finish', cb); } this[kBeginSend]({ endStream: true }); - - if (stream !== undefined) { - stream.end(); - } + stream.end(); } destroy(err) { @@ -527,19 +511,19 @@ class Http2ServerResponse extends Stream { [kBeginSend](options) { const stream = this[kStream]; - options = options || Object.create(null); - if (stream !== undefined && stream.headersSent === false) { + if (stream !== undefined && + stream.destroyed === false && + stream.headersSent === false) { + options = options || Object.create(null); const state = this[kState]; - const headers = this[kHeaders] || Object.create(null); - headers[constants.HTTP2_HEADER_STATUS] = state.statusCode; + const headers = this[kHeaders]; + headers[HTTP2_HEADER_STATUS] = state.statusCode; if (stream.finished === true) options.endStream = true; options.getTrailers = (trailers) => { Object.assign(trailers, this[kTrailers]); }; - if (stream.destroyed === false) { - stream.respond(headers, options); - } + stream.respond(headers, options); } } @@ -548,11 +532,11 @@ class Http2ServerResponse extends Stream { if (state.closed) return; if (code !== undefined) - state.closedCode = code; + state.closedCode = Number(code); state.closed = true; state.headersSent = this[kStream].headersSent; this.end(); - this[kStream] = undefined; + process.nextTick(() => (this[kStream] = undefined)); this.emit('finish'); } @@ -561,7 +545,7 @@ class Http2ServerResponse extends Stream { const stream = this[kStream]; if (stream === undefined) return false; this[kStream].additionalHeaders({ - [constants.HTTP2_HEADER_STATUS]: constants.HTTP_STATUS_CONTINUE + [HTTP2_HEADER_STATUS]: HTTP_STATUS_CONTINUE }); return true; } @@ -574,10 +558,10 @@ function onServerStream(stream, headers, flags, rawHeaders) { const response = new Http2ServerResponse(stream); // Check for the CONNECT method - const method = headers[constants.HTTP2_HEADER_METHOD]; + const method = headers[HTTP2_HEADER_METHOD]; if (method === 'CONNECT') { if (!server.emit('connect', request, response)) { - response.statusCode = constants.HTTP_STATUS_METHOD_NOT_ALLOWED; + response.statusCode = HTTP_STATUS_METHOD_NOT_ALLOWED; response.end(); } return; @@ -595,7 +579,7 @@ function onServerStream(stream, headers, flags, rawHeaders) { } else if (server.listenerCount('checkExpectation')) { server.emit('checkExpectation', request, response); } else { - response.statusCode = constants.HTTP_STATUS_EXPECTATION_FAILED; + response.statusCode = HTTP_STATUS_EXPECTATION_FAILED; response.end(); } return; diff --git a/test/parallel/test-http2-compat-serverrequest-headers.js b/test/parallel/test-http2-compat-serverrequest-headers.js index d5a66391058708..286a0e19c87c11 100644 --- a/test/parallel/test-http2-compat-serverrequest-headers.js +++ b/test/parallel/test-http2-compat-serverrequest-headers.js @@ -21,9 +21,9 @@ server.listen(0, common.mustCall(function() { 'foo-bar': 'abc123' }; + assert.strictEqual(request.path, undefined); assert.strictEqual(request.method, expected[':method']); assert.strictEqual(request.scheme, expected[':scheme']); - assert.strictEqual(request.path, expected[':path']); assert.strictEqual(request.url, expected[':path']); assert.strictEqual(request.authority, expected[':authority']); @@ -41,11 +41,6 @@ server.listen(0, common.mustCall(function() { request.url = '/one'; assert.strictEqual(request.url, '/one'); - assert.strictEqual(request.path, '/one'); - - request.path = '/two'; - assert.strictEqual(request.url, '/two'); - assert.strictEqual(request.path, '/two'); response.on('finish', common.mustCall(function() { server.close(); diff --git a/test/parallel/test-http2-compat-serverrequest.js b/test/parallel/test-http2-compat-serverrequest.js index ebc91b7a9edabd..a6882c6a9bf1c4 100644 --- a/test/parallel/test-http2-compat-serverrequest.js +++ b/test/parallel/test-http2-compat-serverrequest.js @@ -15,7 +15,6 @@ server.listen(0, common.mustCall(function() { const port = server.address().port; server.once('request', common.mustCall(function(request, response) { const expected = { - statusCode: null, version: '2.0', httpVersionMajor: 2, httpVersionMinor: 0 @@ -24,7 +23,6 @@ server.listen(0, common.mustCall(function() { assert.strictEqual(request.closed, false); assert.strictEqual(request.code, h2.constants.NGHTTP2_NO_ERROR); - assert.strictEqual(request.statusCode, expected.statusCode); assert.strictEqual(request.httpVersion, expected.version); assert.strictEqual(request.httpVersionMajor, expected.httpVersionMajor); assert.strictEqual(request.httpVersionMinor, expected.httpVersionMinor); diff --git a/test/parallel/test-http2-compat-serverresponse-destroy.js b/test/parallel/test-http2-compat-serverresponse-destroy.js index 40c73b0887c32f..f2b3ae7cfefa49 100644 --- a/test/parallel/test-http2-compat-serverresponse-destroy.js +++ b/test/parallel/test-http2-compat-serverresponse-destroy.js @@ -26,7 +26,7 @@ const server = http2.createServer(common.mustCall((req, res) => { assert.strictEqual(res.closed, true); })); - if (req.path !== '/') { + if (req.url !== '/') { nextError = errors.shift(); } res.destroy(nextError); diff --git a/test/parallel/test-http2-compat-serverresponse-finished.js b/test/parallel/test-http2-compat-serverresponse-finished.js index c80bdc33f8615a..e54255f67cd2ee 100644 --- a/test/parallel/test-http2-compat-serverresponse-finished.js +++ b/test/parallel/test-http2-compat-serverresponse-finished.js @@ -8,13 +8,18 @@ const assert = require('assert'); const h2 = require('http2'); // Http2ServerResponse.finished - const server = h2.createServer(); server.listen(0, common.mustCall(function() { const port = server.address().port; server.once('request', common.mustCall(function(request, response) { response.on('finish', common.mustCall(function() { + assert.ok(request.stream !== undefined); + assert.ok(response.stream !== undefined); server.close(); + process.nextTick(common.mustCall(() => { + assert.strictEqual(request.stream, undefined); + assert.strictEqual(response.stream, undefined); + })); })); assert.strictEqual(response.finished, false); response.end(); diff --git a/test/parallel/test-http2-compat-serverresponse-headers.js b/test/parallel/test-http2-compat-serverresponse-headers.js index b2285f9d2aabfc..2cc82d4dd3c82f 100644 --- a/test/parallel/test-http2-compat-serverresponse-headers.js +++ b/test/parallel/test-http2-compat-serverresponse-headers.js @@ -42,6 +42,31 @@ server.listen(0, common.mustCall(function() { response.removeHeader(denormalised); assert.strictEqual(response.hasHeader(denormalised), false); + common.expectsError( + () => response.hasHeader(), + { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError, + message: 'The "name" argument must be of type string' + } + ); + common.expectsError( + () => response.getHeader(), + { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError, + message: 'The "name" argument must be of type string' + } + ); + common.expectsError( + () => response.removeHeader(), + { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError, + message: 'The "name" argument must be of type string' + } + ); + [ ':status', ':method', @@ -70,6 +95,14 @@ server.listen(0, common.mustCall(function() { type: TypeError, message: 'Value must not be undefined or null' })); + common.expectsError( + () => response.setHeader(), // header name undefined + { + code: 'ERR_INVALID_ARG_TYPE', + type: TypeError, + message: 'The "name" argument must be of type string' + } + ); response.setHeader(real, expectedValue); const expectedHeaderNames = [real]; diff --git a/test/parallel/test-http2-compat-serverresponse-writehead.js b/test/parallel/test-http2-compat-serverresponse-writehead.js index 04d7499083524f..12de2983468781 100644 --- a/test/parallel/test-http2-compat-serverresponse-writehead.js +++ b/test/parallel/test-http2-compat-serverresponse-writehead.js @@ -22,6 +22,11 @@ server.listen(0, common.mustCall(function() { response.on('finish', common.mustCall(function() { server.close(); + process.nextTick(common.mustCall(() => { + common.expectsError(() => { response.writeHead(300); }, { + code: 'ERR_HTTP2_STREAM_CLOSED' + }); + })); })); response.end(); })); diff --git a/test/parallel/test-http2-createwritereq.js b/test/parallel/test-http2-createwritereq.js index 7e4bd5cf112ee9..f4151d94e6aa10 100644 --- a/test/parallel/test-http2-createwritereq.js +++ b/test/parallel/test-http2-createwritereq.js @@ -30,7 +30,7 @@ const testsToRun = Object.keys(encodings).length; let testsFinished = 0; const server = http2.createServer(common.mustCall((req, res) => { - const testEncoding = encodings[req.path.slice(1)]; + const testEncoding = encodings[req.url.slice(1)]; req.on('data', common.mustCall((chunk) => assert.ok( Buffer.from(testString, testEncoding).equals(chunk) From ede09f29d0ba0f2f7c28ae4d39e39680e5d34a07 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Wed, 6 Sep 2017 15:47:58 -0700 Subject: [PATCH 055/145] meta: allow vague objections to be dismissed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Explicitly allow vague objections to change requests to be dismissed if requests for clarification go unanswered PR-URL: https://github.com/nodejs/node/pull/15233 Reviewed-By: Gibson Fahnestock Reviewed-By: Colin Ihrig Reviewed-By: Jan Krems Reviewed-By: Ryan Graham Reviewed-By: Ali Ijaz Sheikh Reviewed-By: Anna Henningsen Reviewed-By: Refael Ackermann Reviewed-By: Timothy Gu Reviewed-By: Michaël Zasso Reviewed-By: Yuta Hiroto Reviewed-By: Matteo Collina Reviewed-By: Ron Korving Reviewed-By: Tobias Nießen Reviewed-By: Michael Dawson Reviewed-By: Sakthipriyan Vairamani --- COLLABORATOR_GUIDE.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/COLLABORATOR_GUIDE.md b/COLLABORATOR_GUIDE.md index 5aa0fb49cd68a6..2a559af5bd57b4 100644 --- a/COLLABORATOR_GUIDE.md +++ b/COLLABORATOR_GUIDE.md @@ -88,6 +88,12 @@ All pull requests that modify executable code should be subjected to continuous integration tests on the [project CI server](https://ci.nodejs.org/). +If any Collaborator objects to a change *without giving any additional +explanation or context*, and the objecting Collaborator fails to respond to +explicit requests for explanation or context within a reasonable period of +time, the objection may be dismissed. Note that this does not apply to +objections that are explained. + #### Useful CI Jobs * [`node-test-pull-request`](https://ci.nodejs.org/job/node-test-pull-request/) From 3ce501c8ff8527c63f985d3d4412e62d482b6497 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Tue, 5 Sep 2017 16:08:11 -0700 Subject: [PATCH 056/145] test: improve process warning coverage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/15212 Reviewed-By: Refael Ackermann Reviewed-By: Daniel Bevenius Reviewed-By: Colin Ihrig Reviewed-By: Benjamin Gruenbaum Reviewed-By: Luigi Pinca Reviewed-By: Tobias Nießen --- test/parallel/test-process-warning.js | 59 +++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 test/parallel/test-process-warning.js diff --git a/test/parallel/test-process-warning.js b/test/parallel/test-process-warning.js new file mode 100644 index 00000000000000..da4521da790650 --- /dev/null +++ b/test/parallel/test-process-warning.js @@ -0,0 +1,59 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); + +function test1() { + // Output is skipped if the argument to the 'warning' event is + // not an Error object. + common.hijackStderr(common.mustNotCall('stderr.write must not be called')); + process.emit('warning', 'test'); + setImmediate(test2); +} + +function test2() { + // Output is skipped if it's a deprecation warning and + // process.noDeprecation = true + process.noDeprecation = true; + process.emitWarning('test', 'DeprecationWarning'); + process.noDeprecation = false; + setImmediate(test3); +} + +function test3() { + common.restoreStderr(); + // Type defaults to warning when the second argument is an object + process.emitWarning('test', {}); + process.once('warning', common.mustCall((warning) => { + assert.strictEqual(warning.name, 'Warning'); + })); + setImmediate(test4); +} + +function test4() { + // process.emitWarning will throw when process.throwDeprecation is true + // and type is `DeprecationWarning`. + process.throwDeprecation = true; + assert.throws( + () => process.emitWarning('test', 'DeprecationWarning'), + /^DeprecationWarning: test$/); + process.throwDeprecation = false; + setImmediate(test5); +} + +function test5() { + // Setting toString to a non-function should not cause an error + const err = new Error('test'); + err.toString = 1; + process.emitWarning(err); + setImmediate(test6); +} + +function test6() { + process.emitWarning('test', { detail: 'foo' }); + process.on('warning', (warning) => { + assert.strictEqual(warning.detail, 'foo'); + }); +} + +test1(); From d5d498b6dc42dd49ded2362569fb435c857a226d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Zasso?= Date: Mon, 4 Sep 2017 15:25:30 +0200 Subject: [PATCH 057/145] doc: update AUTHORS list Update AUTHORS list using tools/update-authors.sh. Update .mailmap to handle duplicates. PR-URL: https://github.com/nodejs/node/pull/15181 Reviewed-By: Luigi Pinca Reviewed-By: Timothy Gu Reviewed-By: Michael Dawson Reviewed-By: Khaidi Chu Reviewed-By: Gireesh Punathil Reviewed-By: Benjamin Gruenbaum Reviewed-By: Roman Reiss Reviewed-By: James M Snell Reviewed-By: Ruben Bridgewater --- .mailmap | 94 ++++++++++++++++-- AUTHORS | 298 ++++++++++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 361 insertions(+), 31 deletions(-) diff --git a/.mailmap b/.mailmap index a2b1fce896f284..842d610df87b94 100644 --- a/.mailmap +++ b/.mailmap @@ -3,26 +3,36 @@ Aaron Heckmann Abe Fettig Akito Ito Alejandro Oviedo Garcia Alejandro Oviedo -Alex Hultman +Alex Hultman +Alex Jordan AJ Jordan Alex Kocharin Alex Kocharin +Alexander Marchenko axvm Alexey Kupershtokh Alexis Campailla Alexis Sellier Alexis Sellier +Alfred Cepeda ALJCepeda +Amery 子丶言 Andreas Offenhaeuser anoff Andy Bettisworth Angel Stoyanov atstojanov -Anna Henningsen +Anna Henningsen +Anna Magdalena Kedzierska AnnaMag Aria Stewart Arlo Breault +Arnaud Lefebvre BlackYoup Artem Zaytsev +Artur G Vieira Artur Vieira Arnout Kazemier <3rd-Eden@users.noreply.github.com> Asaf David asafdav2 Atsuo Fukaya Ben Lugavere blugavere -Ben Noordhuis +Ben Noordhuis +Ben Noordhuis Ben Taber +Benjamin Fleischer Benjamin Fleischer +Benjamin Gruenbaum Benjamin Waters Bert Belder Bert Belder @@ -30,7 +40,9 @@ Bert Belder Beth Griggs Bethany Griggs Beth Griggs Bethany N Griggs Beth Griggs BethGriggs +Bidisha Pyne Brad Decker brad-decker +Bradley Meck Bradley Farias Brandon Benvie Brandon Kobel kobelb Brendan Ashworth @@ -45,67 +57,88 @@ Charles Rudolph Chris Johnson Claudio Rodriguez Colin Ihrig +Christophe Naud-Dulude Chris911 Christopher Lenz Dan Kaplun Dan Williams Dan.Williams +Daniel Bevenius daniel.bevenius Daniel Berger Daniel Chcouri <333222@gmail.com> Daniel Gröber Daniel Gröber Daniel Pihlström -Daniel Wang +Daniel Wang firedfox +Daniel Wang firedfox Danny Nemer +Danny Nemer Dave Pacheco +David Cai DavidCai +David Mark Clements davidmarkclements +David Mark Clements davidmarkclements David Siegel +DC dcposch@dcpos.ch Domenic Denicola Domenic Denicola +Doug Wade doug.wade Eduard Burtescu Einar Otto Stangvik Elliott Cable Eric Phetteplace +Eugene Obrezkov ghaiklor EungJun Yi Evan Larkin Evan Lucas Evan Lucas FangDun Cai Fangdun Cai (Fundon) +Fangshi He hefangshi Farid Neshat Fedor Indutny Felix Böhm Felix Geisendörfer Felix Geisendörfer +Flandre Scarlet Flandre +Florian Margaine Florian MARGAINE Forrest L Norvell Friedemann Altrock Fuji Goro Gabriel de Perthuis +Gareth Ellis Gibson Fahnestock Gil Pedersen +Graham Fairweather Xotic750 Greg Sabia Tucker Hitesh Kanwathirtha Henry Chin Herbert Vojčík Icer Liang +Igor Savin kibertoad Igor Soarez Igor Zinkovsky -Imran Iqbal +Imran Iqbal Ionică Bizău Isaac Z. Schlueter Isaac Z. Schlueter Italo A. Casas -Jackson Tian +Jackson Tian Jake Verbaten +Jamen Marzonie Jamen Marz James Hartig James M Snell Jan Krems Jenna Vuong +JeongHoon Byun Outsider Jered Schmidt Jeremiah Senkpiel Jerry Chin +Jessica Quynh Tran jessicaquynh Jesús Leganés-Combarro 'piranna Jesús Leganés Combarro "piranna Joe Shaw Johan Bergström Johan Dahlberg Johann Hofmann John Barboza jBarz +John Barboza jBarz +John Gardner Alhadis Johnny Ray Austin Johnny Ray Jon Tippens legalcodes Jonas Pfenniger @@ -114,9 +147,13 @@ Jonathan Persson Jonathan Rentzsch Josh Erickson Joshua S. Weinstein +Joyee Cheung joyeecheung Juan Soto +Julien Klepatch jklepatch +Julien Waechter julien.waechter Junliang Yan Junliang Yan +Junshu Okamoto jun-oka Jérémy Lal Jérémy Lal Kai Sasaki Lewuathe @@ -125,38 +162,56 @@ Kathy Truong k3kathy Kazuyuki Yamada Keith M Wesolowski Kelsey Breseman +Kiyoshi Nomo kysnm Koichi Kobayashi Kris Kowal Kyle Robinson Young +Lakshmi Swetha Gopireddy LAKSHMI SWETHA GOPIREDDY Luke Bayes +Lydia Kats Lydia Katsamberis Maciej Małecki Malte-Thorben Bruns +Malte-Thorben Bruns skenqbx +Marcelo Gobelli decareano Marcin Cieślak Marcin Cieślak Marcin Zielinski marzelin Marti Martz Martial James Jefferson +Matt Lang matt-in-a-hat +Matthias Bastian piepmatz Mathias Buus Mathias Pettersson Matthew Lye Michael Bernstein +Michael Dawson Michael Wilber -Michaël Zasso +Michaël Zasso +Michael-Rainabba Richardson rainabba Micheil Smith Micleusanu Nicu +Miguel Angel Asencio Hurtado maasencioh Mikael Bourges-Sevenier +Minqi Pan P.S.V.R +Minwoo Jung JungMinu Miroslav Bajtoš Mitar Milutinovic Myles Borins Myles Borins Nebu Pookins +Netto Farah nettofarah Nicholas Kinsey Nikolai Vavilov +Noah Rose Ledesma Noah Rose +Noah Rose Ledesma Onne Gorter Paul Querna +Pedro Lima Pedro Victor +Pedro Lima Pedro lima Peter Flannery Phillip Johnsen Ratikesh Misra +Ravindra Barthwal Ravindra barthwal Ray Morgan Ray Solomon Raymond Feng @@ -169,8 +224,12 @@ Rod Machen Roman Klauke Roman Reiss Ron Korving +Ron Korving ronkorving Ryan Dahl Ryan Emery +Ryan Scheel Ryan Scheel +Ryan Scheel Ryan Scheel (Havvy) +Saad Quadri saadq Sakthipriyan Vairamani Sam Mikes Sam P Gallagher-Bishop @@ -180,6 +239,8 @@ Sambasiva Suda Sam Roberts San-Tai Hsu Santiago Gimeno +Sarah Meyer sarahmeyer +Sartrey Lee sartrey Scott Blomquist Segu Riluvan Sergey Kryzhanovsky @@ -188,21 +249,32 @@ Shigeki Ohtsu Shigeki Ohtsu Siddharth Mahendraker Simon Willison +Siobhan O'Donovan justshiv +solebox solebox <5013box@gmail.com> +Sreepurna Jasti +Sreepurna Jasti sreepurnajasti +Sreepurna Jasti sreepurnajasti Stanislav Opichal -Stefan Budeanu +Stefan Budeanu Stefan Bühler Steve Mao Steven R. Loomis Stewart X Addison Stewart Addison Stewart X Addison sxa555 Suramya shah ss22ever +Surya Panikkal surya panikkal +Surya Panikkal suryagh +Taehee Kang hugnosis Tanuja-Sawant +Taylor Woll taylor.woll +Thomas Watson Steen Thomas Watson Toby Stableford toboid Todd Kennedy TJ Holowaychuk TJ Holowaychuk Tadashi SAWADA Takahiro ANDO +Tarun Batra Tarun Ted Young Thomas Lee Thomas Reggi @@ -220,15 +292,21 @@ Viktor Karpov vitkarpov Vincent Voyer Vladimir de Turckheim vsemozhetbyt Vse Mozhet Byt +Wang Xinyong +Weijia Wang <381152119@qq.com> starkwang <381152119@qq.com> Willi Eggeling +xiaoyu <306766053@qq.com> Poker <306766053@qq.com> Yazhong Liu Yazhong Liu Yazhong Liu Yorkie Yazhong Liu Yorkie Yoshihiro KIKUCHI Yosuke Furukawa Yuichiro MASUI +Yuta Hiroto abouthiroppy +Zach Bjornson Zachary Scott Zoran Tomicic +Сковорода Никита Андреевич ChALkeR # These people didn't contribute patches to node directly, # but we've landed their v8 patches in the node repository: diff --git a/AUTHORS b/AUTHORS index ee864d2d8ff8db..977f3b619f4b00 100644 --- a/AUTHORS +++ b/AUTHORS @@ -611,7 +611,7 @@ Patrick Mooney Jicheng Li James Ferguson Julien Fontanet -Steven R. Loomis +Steven R. Loomis gyson Steve Sharp Victor Widell @@ -624,7 +624,6 @@ Ray Donnelly dead-horse Luis Reis sudodoki -Steven Loomis haoxin Artur Cistov MK Safi @@ -707,7 +706,7 @@ Shinnosuke Watanabe Bruno Jouhier René Kooi Petka Antonov -Ryan Scheel +Ryan Scheel Benjamin Gruenbaum Pavel Medvedev Russell Dempsey @@ -785,7 +784,7 @@ Sven Slootweg Dmitry Vasilyev Malcolm Ahoy Imran Iqbal -Stewart Addison +Stewart X Addison Matt Harrison Christopher J. Brody Salman Aljammaz @@ -971,10 +970,9 @@ James Lal Josh Leder Surya Panikkal vsemozhetbyt -Eugene Obrezkov Alex Lamar Ian Kronquist -DavidCai +David Cai Patrick Mueller Ben Page Juan Soto @@ -1088,7 +1086,7 @@ Paul Kiddie scott stern Danny Guo lrlna -matt-in-a-hat +Matt Lang Thomas van Lankveld Tarjei Husøy Wietse Venema @@ -1104,16 +1102,14 @@ Michael-Rainabba Richardson oogz Rene Weber Lauren Spiegel -Lydia Katsamberis +Lydia Kats mpmckenna8 nohmapp -Matt Lang Marc-Aurèle DARCHE fen Christopher Fujino Richard Hong Akito Ito -Lydia Kats Madhav Gharmalkar Mike Woods Daniel Stenberg @@ -1130,7 +1126,7 @@ Alex Jordan Mariusz 'koder' Chwalba Juan Andres Andrango larissayvette -jessicaquynh +Jessica Quynh Tran Ilya Frolov Tanuja-Sawant Bradley T. Hughes @@ -1141,7 +1137,6 @@ Marcin Zielinski Benji Marinacci Indrek Ardel Parambir Singh -maasencioh Niels Nielsen Marc Udoff Oliver Salzburg @@ -1155,7 +1150,7 @@ Gerges Beshay Isobel Redelmeier Brandon Kobel coderaiser -Pedro Victor +Pedro Lima Reza Akhavan Yangyang Liu Zeke Sikelianos @@ -1183,10 +1178,8 @@ Aaron Petcoff Rahat Ahmed monkick Adam Brunner -子丶言 atrioom Dan Koster -Pedro Lima Francis Gulotta Yosuke Saito mkamakura @@ -1202,6 +1195,7 @@ Ashton Kinslow Kevin Zurawel Wes Tyler shiya +Joyee Cheung Greg Valdez Bidur Adhikari Kyle Carter @@ -1226,14 +1220,13 @@ Jonathan Darling JDHarmon bjdelro Hitesh Kanwathirtha -davidmarkclements +David Mark Clements Cesar Hernandez Konstantin Likhter Richard Karmazin Hutson Betts Kent.Fan Jay Brownlee -Outsider Sarah Meyer Andreas Offenhaeuser Sean Villars @@ -1247,7 +1240,6 @@ Ethan Arrowood Dan Villa CodeTheInternet Eric Gonzalez -sxa555 rgoodwin Nigel Kibodeaux fmizzell @@ -1297,7 +1289,6 @@ James Tenenbaum pallxk Amar Zavery Prieto, Marcos -Joyee Cheung hveldstra Siddhartha Sahai Andy Chen @@ -1332,13 +1323,11 @@ René Schünemann Jeremy Yallop malen Kailean Courtney -sarahmeyer Fumiya KARASAWA John Barboza Paul Graham Nate Chris Story -Stewart X Addison Matthew Garrett David Goussev George Adams @@ -1362,7 +1351,6 @@ Josh Hollandsworth Sumit Goel stefan judis Mark -Jessica Quynh Tran Travis Meisenheimer Vinícius do Carmo Birunthan Mohanathas @@ -1384,7 +1372,6 @@ Umair Ishaq Timo Tijhof Sebastian Van Sande Daiki Arai -ALJCepeda Sebastian Roeder Toby Stableford Shubheksha Jalan @@ -1415,5 +1402,270 @@ Bradley Curran chiaki-yokoo Benjamin Fleischer maurice_hayward +Ali BARIN +Nemanja Stojanovic +Jeroen Mandersloot +Michael Cox +Clarence Dimitri CHARLES +Lukas Möller +Juwan Yoo +Matej Krajčovič +Alexander +Gaara +mr-spd +Christian d'Heureuse +Shahar Or +detailyang +liusi +Noj Vek +Ruslan Bekenev +Jyotman Singh +Lucas Lago +TheBeastOfCaerbannog +Morgan Brenner +Nick Peleh +Sorin Baltateanu +Chris Burkhart +Rj Bernaldo +John F. Mercer +Dejon "DJ" Gill +Ahmad Nassri +Tom Atkinson +Tobias Nießen +Joseph Gentle +Zero King +Raphael Okon +JR McEntee +Lovell Fuller +Jason Marsh +Vinay Hiremath +Gabriel Schulhof +alejandro +dave-k +Steven +Uppinder Chugh +Karl Cheng +Taylor Woll +Tarun Batra +Nao YONASHIRO +Christopher Luke +Sampson Gao +John Paul Bamberg +Cody Deckard +Fabio Campinho +Gautam krishna.R +Mateusz Konieczny +Sebastian Plesciuc +MapleUncle +Ahmed Taj elsir +Ivo von Putzer Reibegg +Alex Autem +kumarrishav +morrme +vperezma +Muhsin Abdul-Musawwir +thelady +Neehar Venugopal +WORMSS +Zahidul Islam +RobotMermaid +coreybeaumont +alohaglenn +weewey +Zuzana Svetlikova +Cameron Little +gwer +Walter Huang +Leo +Tony Rice +Olivier Martin +jeyanthinath +Aditya Anand +Oscar Martinez +cool88 +Steven Lehn +Łukasz Szewczak +Madara Uchiha +Gil Tayar +Glenn Schlereth +Artur G Vieira +Flarna +Sreepurna Jasti +Rafael Fragoso +Andrei Cioromila +Frank Lanitz +XadillaX +Akshay Iyer +Rick Bullotta +Rajaram Gaunker +Shadowbeetle +Chris Young +Ebrahim Byagowi +Timur Shemsedinov +Jesus Seijas +mskec +Peter Dave Hello +JongChan Choi +Yihong Wang +Ryan Kelly +Alexander O'Mara +James, please +Josh Ferge +Bidisha Pyne +David D Lowe +rmdm +Dávid Szakállas +JiaLi.Passion +Paul Bininda +Gautam Mittal <200mittalgautam@gmail.com> +Jamen Marzonie +Jacob Jones +Vladimir Trifonov +aniketshukla +realwakka +Gergely Nemeth +Samuel Reed +Anshul Guleria +Justin Beckwith +Scott McKenzie +Julien Klepatch +Dan Homola +Chris Young +cornholio <0@mcornholio.ru> +Tamás Hódi +DuanPengfei <2459714173@qq.com> +Ruben Bridgewater +Lakshmi Swetha Gopireddy +Rob Wu +Steven Winston +sallen450 +OriLev +Zongmin Lei +lena +Azard <330815461@qq.com> +Ezequiel Garcia +Kyle Farnung +Weijia Wang <381152119@qq.com> +Nataly Shrits +Jaime Bernardo +Natanael Log +MoonBall +kuroljov +Matt Sergeant +Eduardo Leggiero +Moogen Tian +Jimmy Thomson +David Drysdale +Roman Shoryn +Peter Czibik +章礼平 +Fraser Xu +Song, Bintao Garfield +Flandre Scarlet +akira.xue +Bang Wu +kadoufall +jiangplus +tobewhatwewant +blade254353074 +weiyuanyue +xinglong.wangwxl +vercent deng +boydfd +Superwoods +shaman +Zhang Weijie +Gunar C. Gessner +SkyAo +Devin Boyer +Helianthus21 <740051540@qq.com> +Oleksandr Kushchak +Nathan Jiang +mac-haojin +jkzing +zzz +Henry +Gautam Arora +Marc Hernández Cabot +Vincent Xue +Bougarfaoui El houcine +ziyun +Lyall Sun +Marcelo Gobelli +Sebastiaan Deckers +nanaya +xeodou +Peter Marshall +笑斌 +atever +vixony +Ching Hsu +rockcoder23 +Anton Paras +Pratik Jain +Shivanth MP +Kunal Pathak +erdun <494251936@qq.com> +Jiajie Hu +Matt Woicik +Franziska Hinkelmann +alexbostock +Matthew Alsup +Greg Alexander +dcharbonnier +Jared Kantrowitz +Guy Margalit +Azard +nishijayaraj +Nick Stanish +Mandeep Singh +Prakash Palaniappan +Keita Akutsu +Michael Albert +Eugene Ostroukhov +Vishal Bisht +Griffith Tchenpan +Oky Antoro +icarter09 +Pini Houri +Runite618 +phisixersai +hsmtkk +Miroslav Bajtoš +Sebastian Murphy +陈刚 +Jon Moss +George Sapkin +Aleh Zasypkin +Anand Suresh +sharababy +Abhishek Raj +Daniel Taveras +RefinedSoftwareLLC +Ankit Parashar +James Kyle +Daniil Shakir +sevenryze +hafiz +Kyle Lamse +Michał Wadas +Mohd Maqbool Alam +Ian Perkins +Jimmy Cann +Dave Olszewski +Anatoli Papirovski +Simon Brewster +creeperyang +Roy Marples +Piotr Mionskowski +Cyril Lakech +Eduard Bondarenko +Adina Shanholtz +Miguel Martins +Yury Popov +George Bezerra +Benjamin Coe +Tim Costa +Rahul Mishra # Generated by tools/update-authors.sh From 5ea4b88a2972426b0f79daa079642b5a25c2333c Mon Sep 17 00:00:00 2001 From: Sebastiaan Deckers Date: Tue, 12 Sep 2017 13:09:02 +0800 Subject: [PATCH 058/145] doc: adding sebdeckers to collaborators PR-URL: https://github.com/nodejs/node/pull/15354 Reviewed-By: Rich Trott Reviewed-By: Gireesh Punathil --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 30b2f4c8fa6ede..0d03168c5452dc 100644 --- a/README.md +++ b/README.md @@ -468,6 +468,8 @@ For more information about the governance of the Node.js project, see **Sam Roberts** <vieuxtech@gmail.com> * [santigimeno](https://github.com/santigimeno) - **Santiago Gimeno** <santiago.gimeno@gmail.com> +* [sebdeckers](https://github.com/sebdeckers) - +**Sebastiaan Deckers** <sebdeckers83@gmail.com> * [seishun](https://github.com/seishun) - **Nikolai Vavilov** <vvnicholas@gmail.com> * [shigeki](https://github.com/shigeki) - From 354f32040d4683ffaebf9a123a749be9c1b9d4d5 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Fri, 8 Sep 2017 13:42:53 +0200 Subject: [PATCH 059/145] build: remove unused configuration variable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `want_separate_host_toolset_mkpeephole` was removed when V8 was upgraded to version 5.9 in commit 3dc8c3b from June. PR-URL: https://github.com/nodejs/node/pull/15266 Reviewed-By: Refael Ackermann Reviewed-By: Tobias Nießen Reviewed-By: Daniel Bevenius Reviewed-By: Colin Ihrig --- configure | 2 -- 1 file changed, 2 deletions(-) diff --git a/configure b/configure index cff6324a4d807c..4e3455056cfb98 100755 --- a/configure +++ b/configure @@ -843,8 +843,6 @@ def configure_node(o): want_snapshots = not options.without_snapshot o['variables']['want_separate_host_toolset'] = int( cross_compiling and want_snapshots) - o['variables']['want_separate_host_toolset_mkpeephole'] = int( - cross_compiling) if target_arch == 'arm': configure_arm(o) From cd238e2c0e75ee02d7bc0e42841854d0fd5e18d5 Mon Sep 17 00:00:00 2001 From: Rahul Mishra Date: Fri, 8 Sep 2017 11:08:37 +0530 Subject: [PATCH 060/145] test: check inspect array with empty string key MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/15258 Refs: https://github.com/nodejs/node/issues/15159 Reviewed-By: Luigi Pinca Reviewed-By: Tobias Nießen Reviewed-By: Colin Ihrig Reviewed-By: Ruben Bridgewater --- test/parallel/test-util-inspect.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 42717ee79dc84c..1ebd3c6dee2665 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -959,6 +959,12 @@ if (typeof Symbol !== 'undefined') { assert.strictEqual(util.inspect(x), '{}'); } +{ + const x = []; + x[''] = 1; + assert.strictEqual(util.inspect(x), '[ \'\': 1 ]'); +} + // The following maxArrayLength tests were introduced after v6.0.0 was released. // Do not backport to v5/v4 unless all of // https://github.com/nodejs/node/pull/6334 is backported. From b1a0bdcdafba1a9d632e3c84005430de7edc32c9 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Wed, 30 Aug 2017 23:38:49 -0300 Subject: [PATCH 061/145] test: remove faulty test case PR-URL: https://github.com/nodejs/node/pull/15110 Reviewed-By: James M Snell Reviewed-By: Claudio Rodriguez --- test/message/stack_overflow_async.js | 18 ------------------ test/message/stack_overflow_async.out | 4 ---- 2 files changed, 22 deletions(-) delete mode 100644 test/message/stack_overflow_async.js delete mode 100644 test/message/stack_overflow_async.out diff --git a/test/message/stack_overflow_async.js b/test/message/stack_overflow_async.js deleted file mode 100644 index 9aefbf9557ea03..00000000000000 --- a/test/message/stack_overflow_async.js +++ /dev/null @@ -1,18 +0,0 @@ -// Flags: --stack_trace_limit=3 - -'use strict'; -require('../common'); - -async function f() { - await f(); -} - -async function g() { - try { - await f(); - } catch (e) { - console.log(e); - } -} - -g(); diff --git a/test/message/stack_overflow_async.out b/test/message/stack_overflow_async.out deleted file mode 100644 index 4028c7642ac531..00000000000000 --- a/test/message/stack_overflow_async.out +++ /dev/null @@ -1,4 +0,0 @@ -RangeError: Maximum call stack size exceeded - at f (*test*message*stack_overflow_async.js:*) - at f (*test*message*stack_overflow_async.js:7:*) - at f (*test*message*stack_overflow_async.js:7:*) From c26e93b30965b5b746008350ee72f653cee8bb2f Mon Sep 17 00:00:00 2001 From: David Benjamin Date: Sat, 9 Sep 2017 18:41:56 -0400 Subject: [PATCH 062/145] crypto: fix Node_SignFinal PR #11705 switched Node away from using using OpenSSL's legacy EVP_Sign* and EVP_Verify* APIs. Instead, it computes a hash normally via EVP_Digest* and then uses EVP_PKEY_sign and EVP_PKEY_verify to verify the hash directly. This change corrects two problems: 1. The documentation still recommends the signature algorithm EVP_MD names of OpenSSL's legacy APIs. OpenSSL has since moved away from thosee, which is why ECDSA was strangely inconsistent. (This is why "ecdsa-with-SHA256" was missing.) 2. Node_SignFinal copied some code from EVP_SignFinal's internals. This is problematic for OpenSSL 1.1.0 and is missing a critical check that prevents pkey->pkey.ptr from being cast to the wrong type. To resolve this, remove the non-EVP_PKEY_sign codepath. This codepath is no longer necessary. PR #11705's verify half was already assuming all EVP_PKEYs supported EVP_PKEY_sign and EVP_PKEY_verify. Also, in the documentation, point users towards using hash function names which are more consisent. This avoids an ECDSA special-case and some strangeness around RSA-PSS ("RSA-SHA256" is the OpenSSL name of the sha256WithRSAEncryption OID which is not used for RSA-PSS). PR-URL: https://github.com/nodejs/node/pull/15024 Reviewed-By: Shigeki Ohtsu Reviewed-By: Ruben Bridgewater --- .../crypto/rsa-sign-verify-throughput.js | 2 +- doc/api/crypto.md | 40 ++++++++-------- src/node_crypto.cc | 47 ++++++++----------- test/fixtures/0-dns/create-cert.js | 4 +- test/parallel/test-crypto-binary-default.js | 24 +++++----- test/parallel/test-crypto-rsa-dsa.js | 46 +++++++++++++----- test/parallel/test-crypto-sign-verify.js | 36 +++++++------- test/parallel/test-crypto-verify-failure.js | 2 +- test/parallel/test-crypto.js | 6 +-- test/parallel/test-dsa-fips-invalid-key.js | 2 +- 10 files changed, 110 insertions(+), 99 deletions(-) diff --git a/benchmark/crypto/rsa-sign-verify-throughput.js b/benchmark/crypto/rsa-sign-verify-throughput.js index f13dc2585a7227..f912bf413387de 100644 --- a/benchmark/crypto/rsa-sign-verify-throughput.js +++ b/benchmark/crypto/rsa-sign-verify-throughput.js @@ -18,7 +18,7 @@ keylen_list.forEach(function(key) { var bench = common.createBenchmark(main, { writes: [500], - algo: ['RSA-SHA1', 'RSA-SHA224', 'RSA-SHA256', 'RSA-SHA384', 'RSA-SHA512'], + algo: ['SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512'], keylen: keylen_list, len: [1024, 102400, 2 * 102400, 3 * 102400, 1024 * 1024] }); diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 08d14e96975812..995009b2902236 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -918,28 +918,31 @@ of two ways: - Using the [`sign.update()`][] and [`sign.sign()`][] methods to produce the signature. -The [`crypto.createSign()`][] method is used to create `Sign` instances. `Sign` -objects are not to be created directly using the `new` keyword. +The [`crypto.createSign()`][] method is used to create `Sign` instances. The +argument is the string name of the hash function to use. `Sign` objects are not +to be created directly using the `new` keyword. Example: Using `Sign` objects as streams: ```js const crypto = require('crypto'); -const sign = crypto.createSign('RSA-SHA256'); +const sign = crypto.createSign('SHA256'); sign.write('some data to sign'); sign.end(); const privateKey = getPrivateKeySomehow(); console.log(sign.sign(privateKey, 'hex')); -// Prints: the calculated signature +// Prints: the calculated signature using the specified private key and +// SHA-256. For RSA keys, the algorithm is RSASSA-PKCS1-v1_5 (see padding +// parameter below for RSASSA-PSS). For EC keys, the algorithm is ECDSA. ``` Example: Using the [`sign.update()`][] and [`sign.sign()`][] methods: ```js const crypto = require('crypto'); -const sign = crypto.createSign('RSA-SHA256'); +const sign = crypto.createSign('SHA256'); sign.update('some data to sign'); @@ -948,27 +951,22 @@ console.log(sign.sign(privateKey, 'hex')); // Prints: the calculated signature ``` -A `Sign` instance can also be created by just passing in the digest -algorithm name, in which case OpenSSL will infer the full signature algorithm -from the type of the PEM-formatted private key, including algorithms that -do not have directly exposed name constants, e.g. 'ecdsa-with-SHA256'. +In some cases, a `Sign` instance can also be created by passing in a signature +algorithm name, such as 'RSA-SHA256'. This will use the corresponding digest +algorithm. This does not work for all signature algorithms, such as +'ecdsa-with-SHA256'. Use digest names instead. -Example: signing using ECDSA with SHA256 +Example: signing using legacy signature algorithm name ```js const crypto = require('crypto'); -const sign = crypto.createSign('sha256'); +const sign = crypto.createSign('RSA-SHA256'); sign.update('some data to sign'); -const privateKey = -`-----BEGIN EC PRIVATE KEY----- -MHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49 -AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2 -pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng== ------END EC PRIVATE KEY-----`; - -console.log(sign.sign(privateKey).toString('hex')); +const privateKey = getPrivateKeySomehow(); +console.log(sign.sign(privateKey, 'hex')); +// Prints: the calculated signature ``` ### sign.sign(privateKey[, outputFormat]) @@ -1051,7 +1049,7 @@ Example: Using `Verify` objects as streams: ```js const crypto = require('crypto'); -const verify = crypto.createVerify('RSA-SHA256'); +const verify = crypto.createVerify('SHA256'); verify.write('some data to sign'); verify.end(); @@ -1066,7 +1064,7 @@ Example: Using the [`verify.update()`][] and [`verify.verify()`][] methods: ```js const crypto = require('crypto'); -const verify = crypto.createVerify('RSA-SHA256'); +const verify = crypto.createVerify('SHA256'); verify.update('some data to sign'); diff --git a/src/node_crypto.cc b/src/node_crypto.cc index a3210b3ffb73e7..84ab819d54a47f 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -3974,7 +3974,8 @@ void SignBase::CheckThrow(SignBase::Error error) { static bool ApplyRSAOptions(EVP_PKEY* pkey, EVP_PKEY_CTX* pkctx, int padding, int salt_len) { - if (pkey->type == EVP_PKEY_RSA || pkey->type == EVP_PKEY_RSA2) { + if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA || + EVP_PKEY_id(pkey) == EVP_PKEY_RSA2) { if (EVP_PKEY_CTX_set_rsa_padding(pkctx, padding) <= 0) return false; if (padding == RSA_PKCS1_PSS_PADDING) { @@ -4083,33 +4084,23 @@ static int Node_SignFinal(EVP_MD_CTX* mdctx, unsigned char* md, if (!EVP_DigestFinal_ex(mdctx, m, &m_len)) return rv; - if (mdctx->digest->flags & EVP_MD_FLAG_PKEY_METHOD_SIGNATURE) { - size_t sltmp = static_cast(EVP_PKEY_size(pkey)); - pkctx = EVP_PKEY_CTX_new(pkey, nullptr); - if (pkctx == nullptr) - goto err; - if (EVP_PKEY_sign_init(pkctx) <= 0) - goto err; - if (!ApplyRSAOptions(pkey, pkctx, padding, pss_salt_len)) - goto err; - if (EVP_PKEY_CTX_set_signature_md(pkctx, mdctx->digest) <= 0) - goto err; - if (EVP_PKEY_sign(pkctx, md, &sltmp, m, m_len) <= 0) - goto err; - *sig_len = sltmp; - rv = 1; - err: - EVP_PKEY_CTX_free(pkctx); - return rv; - } - - if (mdctx->digest->sign == nullptr) { - EVPerr(EVP_F_EVP_SIGNFINAL, EVP_R_NO_SIGN_FUNCTION_CONFIGURED); - return 0; - } - - return mdctx->digest->sign(mdctx->digest->type, m, m_len, md, sig_len, - pkey->pkey.ptr); + size_t sltmp = static_cast(EVP_PKEY_size(pkey)); + pkctx = EVP_PKEY_CTX_new(pkey, nullptr); + if (pkctx == nullptr) + goto err; + if (EVP_PKEY_sign_init(pkctx) <= 0) + goto err; + if (!ApplyRSAOptions(pkey, pkctx, padding, pss_salt_len)) + goto err; + if (EVP_PKEY_CTX_set_signature_md(pkctx, EVP_MD_CTX_md(mdctx)) <= 0) + goto err; + if (EVP_PKEY_sign(pkctx, md, &sltmp, m, m_len) <= 0) + goto err; + *sig_len = sltmp; + rv = 1; + err: + EVP_PKEY_CTX_free(pkctx); + return rv; } SignBase::Error Sign::SignFinal(const char* key_pem, diff --git a/test/fixtures/0-dns/create-cert.js b/test/fixtures/0-dns/create-cert.js index 7a353906e4bbec..9a72104887a9d2 100644 --- a/test/fixtures/0-dns/create-cert.js +++ b/test/fixtures/0-dns/create-cert.js @@ -8,7 +8,7 @@ const BN = asn1.bignum; const id_at_commonName = [ 2, 5, 4, 3 ]; const rsaEncryption = [1, 2, 840, 113549, 1, 1, 1]; const sha256WithRSAEncryption = [1, 2, 840, 113549, 1, 1, 11]; -const sigalg = 'RSA-SHA256'; +const digest = 'SHA256'; const private_key = fs.readFileSync('./0-dns-key.pem'); // public key file can be generated from the private key with @@ -59,7 +59,7 @@ const tbs = { const tbs_der = rfc5280.TBSCertificate.encode(tbs, 'der'); -const sign = crypto.createSign(sigalg); +const sign = crypto.createSign(digest); sign.update(tbs_der); const signature = sign.sign(private_key); diff --git a/test/parallel/test-crypto-binary-default.js b/test/parallel/test-crypto-binary-default.js index 68dab386c42cfc..ab952fa89230bd 100644 --- a/test/parallel/test-crypto-binary-default.js +++ b/test/parallel/test-crypto-binary-default.js @@ -424,28 +424,28 @@ assert.throws(function() { }, /^Error: Digest method not supported$/); // Test signing and verifying -const s1 = crypto.createSign('RSA-SHA1') +const s1 = crypto.createSign('SHA1') .update('Test123') .sign(keyPem, 'base64'); -const s1Verified = crypto.createVerify('RSA-SHA1') +const s1Verified = crypto.createVerify('SHA1') .update('Test') .update('123') .verify(certPem, s1, 'base64'); assert.strictEqual(s1Verified, true, 'sign and verify (base 64)'); -const s2 = crypto.createSign('RSA-SHA256') +const s2 = crypto.createSign('SHA256') .update('Test123') .sign(keyPem); // binary -const s2Verified = crypto.createVerify('RSA-SHA256') +const s2Verified = crypto.createVerify('SHA256') .update('Test') .update('123') .verify(certPem, s2); // binary assert.strictEqual(s2Verified, true, 'sign and verify (binary)'); -const s3 = crypto.createSign('RSA-SHA1') +const s3 = crypto.createSign('SHA1') .update('Test123') .sign(keyPem, 'buffer'); -const s3Verified = crypto.createVerify('RSA-SHA1') +const s3Verified = crypto.createVerify('SHA1') .update('Test') .update('123') .verify(certPem, s3); @@ -610,8 +610,8 @@ const d = crypto.createDiffieHellman(p, 'hex'); assert.strictEqual(d.verifyError, DH_NOT_SUITABLE_GENERATOR); // Test RSA key signing/verification -const rsaSign = crypto.createSign('RSA-SHA1'); -const rsaVerify = crypto.createVerify('RSA-SHA1'); +const rsaSign = crypto.createSign('SHA1'); +const rsaVerify = crypto.createVerify('SHA1'); assert.ok(rsaSign instanceof crypto.Sign); assert.ok(rsaVerify instanceof crypto.Verify); @@ -646,13 +646,13 @@ assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); '8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' + '0ddfb299bedeb1ad'; - const sign = crypto.createSign('RSA-SHA256'); + const sign = crypto.createSign('SHA256'); sign.update(input); const output = sign.sign(privateKey, 'hex'); assert.strictEqual(output, signature); - const verify = crypto.createVerify('RSA-SHA256'); + const verify = crypto.createVerify('SHA256'); verify.update(input); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); @@ -670,11 +670,11 @@ assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); // DSA signatures vary across runs so there is no static string to verify // against - const sign = crypto.createSign('DSS1'); + const sign = crypto.createSign('SHA1'); sign.update(input); const signature = sign.sign(privateKey, 'hex'); - const verify = crypto.createVerify('DSS1'); + const verify = crypto.createVerify('SHA1'); verify.update(input); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index 94aa380e829d34..e0aa1ef872b89c 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -131,8 +131,8 @@ test_rsa('RSA_PKCS1_PADDING'); test_rsa('RSA_PKCS1_OAEP_PADDING'); // Test RSA key signing/verification -let rsaSign = crypto.createSign('RSA-SHA1'); -let rsaVerify = crypto.createVerify('RSA-SHA1'); +let rsaSign = crypto.createSign('SHA1'); +let rsaVerify = crypto.createVerify('SHA1'); assert.ok(rsaSign); assert.ok(rsaVerify); @@ -151,7 +151,7 @@ rsaVerify.update(rsaPubPem); assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); // Test RSA key signing/verification with encrypted key -rsaSign = crypto.createSign('RSA-SHA1'); +rsaSign = crypto.createSign('SHA1'); rsaSign.update(rsaPubPem); assert.doesNotThrow(() => { const signOptions = { key: rsaKeyPemEncrypted, passphrase: 'password' }; @@ -159,11 +159,11 @@ assert.doesNotThrow(() => { }); assert.strictEqual(rsaSignature, expectedSignature); -rsaVerify = crypto.createVerify('RSA-SHA1'); +rsaVerify = crypto.createVerify('SHA1'); rsaVerify.update(rsaPubPem); assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); -rsaSign = crypto.createSign('RSA-SHA1'); +rsaSign = crypto.createSign('SHA1'); rsaSign.update(rsaPubPem); assert.throws(() => { const signOptions = { key: rsaKeyPemEncrypted, passphrase: 'wrong' }; @@ -186,16 +186,28 @@ assert.throws(() => { '8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' + '0ddfb299bedeb1ad'; - const sign = crypto.createSign('RSA-SHA256'); + const sign = crypto.createSign('SHA256'); sign.update(input); const output = sign.sign(privateKey, 'hex'); assert.strictEqual(signature, output); - const verify = crypto.createVerify('RSA-SHA256'); + const verify = crypto.createVerify('SHA256'); verify.update(input); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); + + // Test the legacy signature algorithm name. + const sign2 = crypto.createSign('RSA-SHA256'); + sign2.update(input); + + const output2 = sign2.sign(privateKey, 'hex'); + assert.strictEqual(signature, output2); + + const verify2 = crypto.createVerify('SHA256'); + verify2.update(input); + + assert.strictEqual(verify2.verify(publicKey, signature, 'hex'), true); } @@ -207,14 +219,24 @@ assert.throws(() => { // DSA signatures vary across runs so there is no static string to verify // against - const sign = crypto.createSign('DSS1'); + const sign = crypto.createSign('SHA1'); sign.update(input); const signature = sign.sign(dsaKeyPem, 'hex'); - const verify = crypto.createVerify('DSS1'); + const verify = crypto.createVerify('SHA1'); verify.update(input); assert.strictEqual(verify.verify(dsaPubPem, signature, 'hex'), true); + + // Test the legacy 'DSS1' name. + const sign2 = crypto.createSign('DSS1'); + sign2.update(input); + const signature2 = sign2.sign(dsaKeyPem, 'hex'); + + const verify2 = crypto.createVerify('DSS1'); + verify2.update(input); + + assert.strictEqual(verify2.verify(dsaPubPem, signature2, 'hex'), true); } @@ -224,7 +246,7 @@ assert.throws(() => { const input = 'I AM THE WALRUS'; { - const sign = crypto.createSign('DSS1'); + const sign = crypto.createSign('SHA1'); sign.update(input); assert.throws(() => { sign.sign({ key: dsaKeyPemEncrypted, passphrase: 'wrong' }, 'hex'); @@ -234,7 +256,7 @@ const input = 'I AM THE WALRUS'; { // DSA signatures vary across runs so there is no static string to verify // against - const sign = crypto.createSign('DSS1'); + const sign = crypto.createSign('SHA1'); sign.update(input); let signature; @@ -243,7 +265,7 @@ const input = 'I AM THE WALRUS'; signature = sign.sign(signOptions, 'hex'); }); - const verify = crypto.createVerify('DSS1'); + const verify = crypto.createVerify('SHA1'); verify.update(input); assert.strictEqual(verify.verify(dsaPubPem, signature, 'hex'), true); diff --git a/test/parallel/test-crypto-sign-verify.js b/test/parallel/test-crypto-sign-verify.js index a24ce866624412..284261cd9e1771 100644 --- a/test/parallel/test-crypto-sign-verify.js +++ b/test/parallel/test-crypto-sign-verify.js @@ -17,15 +17,15 @@ const modSize = 1024; // Test signing and verifying { - const s1 = crypto.createSign('RSA-SHA1') + const s1 = crypto.createSign('SHA1') .update('Test123') .sign(keyPem, 'base64'); - let s1stream = crypto.createSign('RSA-SHA1'); + let s1stream = crypto.createSign('SHA1'); s1stream.end('Test123'); s1stream = s1stream.sign(keyPem, 'base64'); assert.strictEqual(s1, s1stream, 'Stream produces same output'); - const verified = crypto.createVerify('RSA-SHA1') + const verified = crypto.createVerify('SHA1') .update('Test') .update('123') .verify(certPem, s1, 'base64'); @@ -33,21 +33,21 @@ const modSize = 1024; } { - const s2 = crypto.createSign('RSA-SHA256') + const s2 = crypto.createSign('SHA256') .update('Test123') .sign(keyPem, 'latin1'); - let s2stream = crypto.createSign('RSA-SHA256'); + let s2stream = crypto.createSign('SHA256'); s2stream.end('Test123'); s2stream = s2stream.sign(keyPem, 'latin1'); assert.strictEqual(s2, s2stream, 'Stream produces same output'); - let verified = crypto.createVerify('RSA-SHA256') + let verified = crypto.createVerify('SHA256') .update('Test') .update('123') .verify(certPem, s2, 'latin1'); assert.strictEqual(verified, true, 'sign and verify (latin1)'); - const verStream = crypto.createVerify('RSA-SHA256'); + const verStream = crypto.createVerify('SHA256'); verStream.write('Tes'); verStream.write('t12'); verStream.end('3'); @@ -56,16 +56,16 @@ const modSize = 1024; } { - const s3 = crypto.createSign('RSA-SHA1') + const s3 = crypto.createSign('SHA1') .update('Test123') .sign(keyPem, 'buffer'); - let verified = crypto.createVerify('RSA-SHA1') + let verified = crypto.createVerify('SHA1') .update('Test') .update('123') .verify(certPem, s3); assert.strictEqual(verified, true, 'sign and verify (buffer)'); - const verStream = crypto.createVerify('RSA-SHA1'); + const verStream = crypto.createVerify('SHA1'); verStream.write('Tes'); verStream.write('t12'); verStream.end('3'); @@ -167,8 +167,8 @@ const modSize = 1024; }); } - testPSS('RSA-SHA1', 20); - testPSS('RSA-SHA256', 32); + testPSS('SHA1', 20); + testPSS('SHA256', 32); } // Test vectors for RSA_PKCS1_PSS_PADDING provided by the RSA Laboratories: @@ -176,7 +176,7 @@ const modSize = 1024; { // We only test verification as we cannot specify explicit salts when signing function testVerify(cert, vector) { - const verified = crypto.createVerify('RSA-SHA1') + const verified = crypto.createVerify('SHA1') .update(Buffer.from(vector.message, 'hex')) .verify({ key: cert, @@ -203,7 +203,7 @@ const modSize = 1024; [null, undefined, NaN, 'boom', {}, [], true, false] .forEach((invalidValue) => { assert.throws(() => { - crypto.createSign('RSA-SHA256') + crypto.createSign('SHA256') .update('Test123') .sign({ key: keyPem, @@ -212,7 +212,7 @@ const modSize = 1024; }, paddingNotInteger); assert.throws(() => { - crypto.createSign('RSA-SHA256') + crypto.createSign('SHA256') .update('Test123') .sign({ key: keyPem, @@ -223,7 +223,7 @@ const modSize = 1024; }); assert.throws(() => { - crypto.createSign('RSA-SHA1') + crypto.createSign('SHA1') .update('Test123') .sign({ key: keyPem, @@ -235,7 +235,7 @@ const modSize = 1024; // Test throws exception when key options is null { assert.throws(() => { - crypto.createSign('RSA-SHA1').update('Test123').sign(null, 'base64'); + crypto.createSign('SHA1').update('Test123').sign(null, 'base64'); }, /^Error: No key provided to sign$/); } @@ -248,7 +248,7 @@ const modSize = 1024; const privkey = fixtures.readKey('rsa_private_2048.pem'); const msg = 'Test123'; - const s5 = crypto.createSign('RSA-SHA256') + const s5 = crypto.createSign('SHA256') .update(msg) .sign({ key: privkey, diff --git a/test/parallel/test-crypto-verify-failure.js b/test/parallel/test-crypto-verify-failure.js index 0fbdb5b82608d9..72dfb926413d8b 100644 --- a/test/parallel/test-crypto-verify-failure.js +++ b/test/parallel/test-crypto-verify-failure.js @@ -48,7 +48,7 @@ const server = tls.Server(options, (socket) => { }); function verify() { - crypto.createVerify('RSA-SHA1') + crypto.createVerify('SHA1') .update('Test') .verify(certPem, 'asdfasdfas', 'base64'); } diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js index 7826d988704583..58c72127a479fc 100644 --- a/test/parallel/test-crypto.js +++ b/test/parallel/test-crypto.js @@ -146,11 +146,11 @@ assert.throws(function() { }, /^TypeError: Bad input string$/); assert.throws(function() { - crypto.createSign('RSA-SHA1').update('0', 'hex'); + crypto.createSign('SHA1').update('0', 'hex'); }, /^TypeError: Bad input string$/); assert.throws(function() { - crypto.createVerify('RSA-SHA1').update('0', 'hex'); + crypto.createVerify('SHA1').update('0', 'hex'); }, /^TypeError: Bad input string$/); assert.throws(function() { @@ -163,7 +163,7 @@ assert.throws(function() { '-----END RSA PRIVATE KEY-----', '' ].join('\n'); - crypto.createSign('RSA-SHA256').update('test').sign(priv); + crypto.createSign('SHA256').update('test').sign(priv); }, /digest too big for rsa key$/); assert.throws(function() { diff --git a/test/parallel/test-dsa-fips-invalid-key.js b/test/parallel/test-dsa-fips-invalid-key.js index b88c05a87cbf85..bb12e56ba5879a 100644 --- a/test/parallel/test-dsa-fips-invalid-key.js +++ b/test/parallel/test-dsa-fips-invalid-key.js @@ -11,7 +11,7 @@ const input = 'hello'; const dsapri = fs.readFileSync( `${common.fixturesDir}/keys/dsa_private_1025.pem`); -const sign = crypto.createSign('DSS1'); +const sign = crypto.createSign('SHA1'); sign.update(input); assert.throws(function() { From edece30930a31e3b4a0f9f246b5f6a15b7c21478 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 1 Sep 2017 13:02:50 -0700 Subject: [PATCH 063/145] test: remove random timer in test-tls-fast-writing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit test-tls-fast-writing can fail on a heavily-loaded system due to an arbitrary 1-second timeout. Remove the arbitrary timeout. PR-URL: https://github.com/nodejs/node/pull/15138 Reviewed-By: Anna Henningsen Reviewed-By: Refael Ackermann Reviewed-By: Colin Ihrig Reviewed-By: Ruben Bridgewater Reviewed-By: Luigi Pinca Reviewed-By: Michaël Zasso Reviewed-By: James M Snell --- test/parallel/test-tls-fast-writing.js | 5 ----- 1 file changed, 5 deletions(-) diff --git a/test/parallel/test-tls-fast-writing.js b/test/parallel/test-tls-fast-writing.js index b846f732d2fb0e..d80874eea6fc2f 100644 --- a/test/parallel/test-tls-fast-writing.js +++ b/test/parallel/test-tls-fast-writing.js @@ -37,11 +37,6 @@ const server = tls.createServer(options, onconnection); let gotChunk = false; let gotDrain = false; -setTimeout(function() { - console.log('not ok - timed out'); - process.exit(1); -}, common.platformTimeout(1000)); - function onconnection(conn) { conn.on('data', function(c) { if (!gotChunk) { From a92f3dfd8cb322ced1d28de75692d0a5cca647cb Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Mon, 4 Sep 2017 18:44:25 -0700 Subject: [PATCH 064/145] test: make test-http-agent-maxsockets robust MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a slow/busy machine, `test-http-agent-maxsockets` can fail if the test takes longer than 5 seconds because that is the default value for `server.keepAliveTimeout`. Disable `keepAliveTimeout` to make the test robust. PR-URL: https://github.com/nodejs/node/pull/15192 Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Ruben Bridgewater Reviewed-By: Tobias Nießen --- test/parallel/test-http-agent-maxsockets.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/parallel/test-http-agent-maxsockets.js b/test/parallel/test-http-agent-maxsockets.js index 66fffba250513f..4d422f4a90b4f9 100644 --- a/test/parallel/test-http-agent-maxsockets.js +++ b/test/parallel/test-http-agent-maxsockets.js @@ -15,6 +15,8 @@ const server = http.createServer(common.mustCall((req, res) => { res.end('hello world'); }, 2)); +server.keepAliveTimeout = 0; + function get(path, callback) { return http.get({ host: 'localhost', From 4d680644934841c70121fa868197b59221e16106 Mon Sep 17 00:00:00 2001 From: Jon Moss Date: Fri, 1 Sep 2017 12:37:41 -0400 Subject: [PATCH 065/145] test: move common.PORT tests to sequential Reasons: - `test-async-wrap-getasyncid` binds a handle, so move to sequential because port cannot be already in use. - `test-dgram-implicit-bind-failure` requires a hardcoded port number to properly send socket packet. - `test-http-agent-uninitialized-with-handle` requires a hardcoded port number to properly send http request. - `test-http-agent-uninitialized` requires a hardcoded port number to properly send http request. - `test-net-localport` requires a hardcoded port number for assertions. In addition this replaces two common.PORTs with a dynamic port. PR-URL: https://github.com/nodejs/node/pull/15151 Reviewed-By: Gibson Fahnestock Reviewed-By: Colin Ihrig Reviewed-By: Luigi Pinca --- test/parallel/test-http-agent-uninitialized-with-handle.js | 5 +++-- test/parallel/test-http-agent-uninitialized.js | 5 +++-- test/{parallel => sequential}/test-async-wrap-getasyncid.js | 0 .../test-dgram-implicit-bind-failure.js | 0 test/{parallel => sequential}/test-net-localport.js | 0 5 files changed, 6 insertions(+), 4 deletions(-) rename test/{parallel => sequential}/test-async-wrap-getasyncid.js (100%) rename test/{parallel => sequential}/test-dgram-implicit-bind-failure.js (100%) rename test/{parallel => sequential}/test-net-localport.js (100%) diff --git a/test/parallel/test-http-agent-uninitialized-with-handle.js b/test/parallel/test-http-agent-uninitialized-with-handle.js index fab32ade45efe4..77f01771734c87 100644 --- a/test/parallel/test-http-agent-uninitialized-with-handle.js +++ b/test/parallel/test-http-agent-uninitialized-with-handle.js @@ -13,11 +13,12 @@ socket._handle = { ref() { }, readStart() { }, }; -const req = new http.ClientRequest(`http://localhost:${common.PORT}/`); const server = http.createServer(common.mustCall((req, res) => { res.end(); -})).listen(common.PORT, common.mustCall(() => { +})).listen(0, common.mustCall(() => { + const req = new http.ClientRequest(`http://localhost:${server.address().port}/`); + // Manually add the socket without a _handle. agent.freeSockets[agent.getName(req)] = [socket]; // Now force the agent to use the socket and check that _handle exists before diff --git a/test/parallel/test-http-agent-uninitialized.js b/test/parallel/test-http-agent-uninitialized.js index c522b5fdbd43e9..dbb38e3b0f9847 100644 --- a/test/parallel/test-http-agent-uninitialized.js +++ b/test/parallel/test-http-agent-uninitialized.js @@ -8,11 +8,12 @@ const agent = new http.Agent({ keepAlive: true, }); const socket = new net.Socket(); -const req = new http.ClientRequest(`http://localhost:${common.PORT}/`); const server = http.createServer(common.mustCall((req, res) => { res.end(); -})).listen(common.PORT, common.mustCall(() => { +})).listen(0, common.mustCall(() => { + const req = new http.ClientRequest(`http://localhost:${server.address().port}/`); + // Manually add the socket without a _handle. agent.freeSockets[agent.getName(req)] = [socket]; // Now force the agent to use the socket and check that _handle exists before diff --git a/test/parallel/test-async-wrap-getasyncid.js b/test/sequential/test-async-wrap-getasyncid.js similarity index 100% rename from test/parallel/test-async-wrap-getasyncid.js rename to test/sequential/test-async-wrap-getasyncid.js diff --git a/test/parallel/test-dgram-implicit-bind-failure.js b/test/sequential/test-dgram-implicit-bind-failure.js similarity index 100% rename from test/parallel/test-dgram-implicit-bind-failure.js rename to test/sequential/test-dgram-implicit-bind-failure.js diff --git a/test/parallel/test-net-localport.js b/test/sequential/test-net-localport.js similarity index 100% rename from test/parallel/test-net-localport.js rename to test/sequential/test-net-localport.js From 2e421ff5c9f5b402c9a6bae7c214696fd29aedb3 Mon Sep 17 00:00:00 2001 From: Anatoli Papirovski Date: Thu, 7 Sep 2017 07:25:43 -0400 Subject: [PATCH 066/145] http2: correct behaviour for enablePush unpack The only valid values for enablePush are 0 and 1. If validation is requested, we should verify that it wasn't set to another value rather than casting to Boolean regardless of value. PR-URL: https://github.com/nodejs/node/pull/15167 Reviewed-By: Anna Henningsen Reviewed-By: Benjamin Gruenbaum Reviewed-By: Luigi Pinca Reviewed-By: James M Snell Reviewed-By: Ruben Bridgewater --- lib/internal/http2/core.js | 16 +++++++------- test/parallel/test-http2-getpackedsettings.js | 21 +++++++++++++++++++ 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js index 1fead9975b24f5..471fa5b1c5d5a9 100644 --- a/lib/internal/http2/core.js +++ b/lib/internal/http2/core.js @@ -2535,7 +2535,7 @@ function getUnpackedSettings(buf, options = {}) { settings.headerTableSize = value; break; case NGHTTP2_SETTINGS_ENABLE_PUSH: - settings.enablePush = Boolean(value); + settings.enablePush = value; break; case NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: settings.maxConcurrentStreams = value; @@ -2557,6 +2557,9 @@ function getUnpackedSettings(buf, options = {}) { assertWithinRange('headerTableSize', settings.headerTableSize, 0, 2 ** 32 - 1); + assertWithinRange('enablePush', + settings.enablePush, + 0, 1); assertWithinRange('initialWindowSize', settings.initialWindowSize, 0, 2 ** 32 - 1); @@ -2569,13 +2572,10 @@ function getUnpackedSettings(buf, options = {}) { assertWithinRange('maxHeaderListSize', settings.maxHeaderListSize, 0, 2 ** 32 - 1); - if (settings.enablePush !== undefined && - typeof settings.enablePush !== 'boolean') { - const err = new errors.TypeError('ERR_HTTP2_INVALID_SETTING_VALUE', - 'enablePush', settings.enablePush); - err.actual = settings.enablePush; - throw err; - } + } + + if (settings.enablePush !== undefined) { + settings.enablePush = !!settings.enablePush; } return settings; diff --git a/test/parallel/test-http2-getpackedsettings.js b/test/parallel/test-http2-getpackedsettings.js index e5e49571800797..8c46afcb57fd82 100644 --- a/test/parallel/test-http2-getpackedsettings.js +++ b/test/parallel/test-http2-getpackedsettings.js @@ -126,6 +126,27 @@ assert.doesNotThrow(() => http2.getPackedSettings({ enablePush: false })); assert.strictEqual(settings.enablePush, true); } +//should throw if enablePush is not 0 or 1 +{ + const packed = Buffer.from([ + 0x00, 0x02, 0x00, 0x00, 0x00, 0x00]); + + const settings = http2.getUnpackedSettings(packed, { validate: true }); + assert.strictEqual(settings.enablePush, false); +} +{ + const packed = Buffer.from([ + 0x00, 0x02, 0x00, 0x00, 0x00, 0x64]); + + assert.throws(() => { + http2.getUnpackedSettings(packed, { validate: true }); + }, common.expectsError({ + code: 'ERR_HTTP2_INVALID_SETTING_VALUE', + type: RangeError, + message: 'Invalid value for setting "enablePush": 100' + })); +} + //check for what happens if passing {validate: true} and no errors happen { const packed = Buffer.from([ From f0a741d17874bec7dbac4dcf0dedebda47dd7a7f Mon Sep 17 00:00:00 2001 From: Refael Ackermann Date: Mon, 4 Sep 2017 11:18:54 -0400 Subject: [PATCH 067/145] test: kill subprocess only after last ACK * Add multiple comments. * Switch to a persistent fixture for subprocess. * Assert that `send` queue is drained. PR-URL: https://github.com/nodejs/node/pull/15186 Fixes: https://github.com/nodejs/node/issues/15176 Reviewed-By: James M Snell --- ...test-child-process-send-returns-boolean.js | 64 ++++++++++++++----- 1 file changed, 47 insertions(+), 17 deletions(-) diff --git a/test/parallel/test-child-process-send-returns-boolean.js b/test/parallel/test-child-process-send-returns-boolean.js index e273d1c205c3ac..2fbba1a4544ced 100644 --- a/test/parallel/test-child-process-send-returns-boolean.js +++ b/test/parallel/test-child-process-send-returns-boolean.js @@ -1,28 +1,58 @@ 'use strict'; const common = require('../common'); + +// subprocess.send() will return false if the channel has closed or when the +// backlog of unsent messages exceeds a threshold that makes it unwise to send +// more. Otherwise, the method returns true. + const assert = require('assert'); const net = require('net'); const { fork, spawn } = require('child_process'); const fixtures = require('../common/fixtures'); -const emptyFile = fixtures.path('empty.js'); +// Just a script that stays alive (does not listen to `process.on('message')`). +const subScript = fixtures.path('child-process-persistent.js'); + +{ + // Test `send` return value on `fork` that opens and IPC by deafult. + const n = fork(subScript); + // `subprocess.send` should always return `true` for the first send. + const rv = n.send({ h: 'w' }, (err) => { if (err) assert.fail(err); }); + assert.strictEqual(rv, true); + n.kill(); +} -const n = fork(emptyFile); +{ + // Test `send` return value on `spawn` and saturate backlog with handles. + // Call `spawn` with options that open an IPC channel. + const spawnOptions = { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }; + const s = spawn(process.execPath, [subScript], spawnOptions); -const rv = n.send({ hello: 'world' }); -assert.strictEqual(rv, true); + const server = net.createServer(common.mustNotCall()).listen(0, () => { + const handle = server._handle; -const spawnOptions = { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] }; -const s = spawn(process.execPath, [emptyFile], spawnOptions); -let handle = null; -s.on('exit', function() { - handle.close(); -}); + // Sending a handle and not giving the tickQueue time to acknoladge should + // create the internal backlog, but leave it empty. + const rv1 = s.send('one', handle, (err) => { if (err) assert.fail(err); }); + assert.strictEqual(rv1, true); + // Since the first `send` included a handle (should be unackoladged), + // we can safly queue up only one more message. + const rv2 = s.send('two', (err) => { if (err) assert.fail(err); }); + assert.strictEqual(rv2, true); + // The backlog should now be indicate to backoff. + const rv3 = s.send('three', (err) => { if (err) assert.fail(err); }); + assert.strictEqual(rv3, false); + const rv4 = s.send('four', (err) => { + if (err) assert.fail(err); + // `send` queue should have been drained. + const rv5 = s.send('5', handle, (err) => { if (err) assert.fail(err); }); + assert.strictEqual(rv5, true); -net.createServer(common.mustNotCall()).listen(0, function() { - handle = this._handle; - assert.strictEqual(s.send('one', handle), true); - assert.strictEqual(s.send('two', handle), true); - assert.strictEqual(s.send('three'), false); - assert.strictEqual(s.send('four'), false); -}); + // End test and cleanup. + s.kill(); + handle.close(); + server.close(); + }); + assert.strictEqual(rv4, false); + }); +} From 7d95dc385cd05ad0ad7862a18cd32f1c254edf59 Mon Sep 17 00:00:00 2001 From: Timothy Gu Date: Mon, 17 Jul 2017 13:06:23 +0800 Subject: [PATCH 068/145] vm: support parsing a script in a specific context PR-URL: https://github.com/nodejs/node/pull/14888 Reviewed-By: James M Snell Reviewed-By: Ben Noordhuis Reviewed-By: Eugene Ostroukhov --- lib/vm.js | 41 ++++++-- src/env.h | 1 + src/node_contextify.cc | 49 ++++++++++ test/inspector/test-scriptparsed-context.js | 101 ++++++++++++++++++++ 4 files changed, 183 insertions(+), 9 deletions(-) create mode 100644 test/inspector/test-scriptparsed-context.js diff --git a/lib/vm.js b/lib/vm.js index 5bee450becec8b..e7fccc97493bcb 100644 --- a/lib/vm.js +++ b/lib/vm.js @@ -21,8 +21,14 @@ 'use strict'; -const binding = process.binding('contextify'); -const Script = binding.ContextifyScript; +const { + ContextifyScript: Script, + kParsingContext, + + makeContext, + isContext, + runInDebugContext +} = process.binding('contextify'); // The binding provides a few useful primitives: // - Script(code, { filename = "evalmachine.anonymous", @@ -62,11 +68,11 @@ Script.prototype.runInNewContext = function(sandbox, options) { function createContext(sandbox) { if (sandbox === undefined) { sandbox = {}; - } else if (binding.isContext(sandbox)) { + } else if (isContext(sandbox)) { return sandbox; } - binding.makeContext(sandbox); + makeContext(sandbox); return sandbox; } @@ -99,16 +105,33 @@ function sigintHandlersWrap(fn, thisArg, argsArray) { } } -function runInDebugContext(code) { - return binding.runInDebugContext(code); -} - function runInContext(code, contextifiedSandbox, options) { + if (typeof options === 'string') { + options = { + filename: options, + [kParsingContext]: contextifiedSandbox + }; + } else { + options = Object.assign({}, options, { + [kParsingContext]: contextifiedSandbox + }); + } return createScript(code, options) .runInContext(contextifiedSandbox, options); } function runInNewContext(code, sandbox, options) { + sandbox = createContext(sandbox); + if (typeof options === 'string') { + options = { + filename: options, + [kParsingContext]: sandbox + }; + } else { + options = Object.assign({}, options, { + [kParsingContext]: sandbox + }); + } return createScript(code, options).runInNewContext(sandbox, options); } @@ -124,5 +147,5 @@ module.exports = { runInContext, runInNewContext, runInThisContext, - isContext: binding.isContext + isContext }; diff --git a/src/env.h b/src/env.h index 20495c4554b2d2..023136bdcc795c 100644 --- a/src/env.h +++ b/src/env.h @@ -316,6 +316,7 @@ namespace node { V(tls_wrap_constructor_function, v8::Function) \ V(tty_constructor_template, v8::FunctionTemplate) \ V(udp_constructor_function, v8::Function) \ + V(vm_parsing_context_symbol, v8::Symbol) \ V(url_constructor_function, v8::Function) \ V(write_wrap_constructor_function, v8::Function) \ diff --git a/src/node_contextify.cc b/src/node_contextify.cc index 792b1c4f8009f9..c2037c4cbe7354 100644 --- a/src/node_contextify.cc +++ b/src/node_contextify.cc @@ -61,6 +61,7 @@ using v8::Script; using v8::ScriptCompiler; using v8::ScriptOrigin; using v8::String; +using v8::Symbol; using v8::TryCatch; using v8::Uint8Array; using v8::UnboundScript; @@ -531,6 +532,16 @@ class ContextifyScript : public BaseObject { target->Set(class_name, script_tmpl->GetFunction()); env->set_script_context_constructor_template(script_tmpl); + + Local parsing_context_symbol = + Symbol::New(env->isolate(), + FIXED_ONE_BYTE_STRING(env->isolate(), + "script parsing context")); + env->set_vm_parsing_context_symbol(parsing_context_symbol); + target->Set(env->context(), + FIXED_ONE_BYTE_STRING(env->isolate(), "kParsingContext"), + parsing_context_symbol) + .FromJust(); } @@ -555,6 +566,7 @@ class ContextifyScript : public BaseObject { Maybe maybe_display_errors = GetDisplayErrorsArg(env, options); MaybeLocal cached_data_buf = GetCachedData(env, options); Maybe maybe_produce_cached_data = GetProduceCachedData(env, options); + MaybeLocal maybe_context = GetContext(env, options); if (try_catch.HasCaught()) { try_catch.ReThrow(); return; @@ -583,6 +595,8 @@ class ContextifyScript : public BaseObject { else if (produce_cached_data) compile_options = ScriptCompiler::kProduceCodeCache; + Context::Scope scope(maybe_context.FromMaybe(env->context())); + MaybeLocal v8_script = ScriptCompiler::CompileUnboundScript( env->isolate(), &source, @@ -935,6 +949,41 @@ class ContextifyScript : public BaseObject { return value->ToInteger(env->context()); } + static MaybeLocal GetContext(Environment* env, + Local options) { + if (!options->IsObject()) + return MaybeLocal(); + + MaybeLocal maybe_value = + options.As()->Get(env->context(), + env->vm_parsing_context_symbol()); + Local value; + if (!maybe_value.ToLocal(&value)) + return MaybeLocal(); + + if (!value->IsObject()) { + if (!value->IsNullOrUndefined()) { + env->ThrowTypeError( + "contextifiedSandbox argument must be an object."); + } + return MaybeLocal(); + } + + ContextifyContext* sandbox = + ContextifyContext::ContextFromContextifiedSandbox( + env, value.As()); + if (!sandbox) { + env->ThrowTypeError( + "sandbox argument must have been converted to a context."); + return MaybeLocal(); + } + + Local context = sandbox->context(); + if (context.IsEmpty()) + return MaybeLocal(); + return context; + } + static bool EvalMachine(Environment* env, const int64_t timeout, diff --git a/test/inspector/test-scriptparsed-context.js b/test/inspector/test-scriptparsed-context.js new file mode 100644 index 00000000000000..f1258639f5d7ab --- /dev/null +++ b/test/inspector/test-scriptparsed-context.js @@ -0,0 +1,101 @@ +'use strict'; +const common = require('../common'); +common.skipIfInspectorDisabled(); +common.crashOnUnhandledRejection(); +const { NodeInstance } = require('./inspector-helper.js'); +const assert = require('assert'); + +const script = ` + 'use strict'; + const assert = require('assert'); + const vm = require('vm'); + const { kParsingContext } = process.binding('contextify'); + debugger; + + global.outer = true; + global.inner = false; + const context = vm.createContext({ + outer: false, + inner: true + }); + debugger; + + const scriptMain = new vm.Script("outer"); + debugger; + + const scriptContext = new vm.Script("inner", { + [kParsingContext]: context + }); + debugger; + + assert.strictEqual(scriptMain.runInThisContext(), true); + assert.strictEqual(scriptMain.runInContext(context), false); + assert.strictEqual(scriptContext.runInThisContext(), false); + assert.strictEqual(scriptContext.runInContext(context), true); + debugger; + + vm.runInContext('inner', context); + debugger; + + vm.runInNewContext('Array', {}); + debugger; +`; + +async function getContext(session) { + const created = + await session.waitForNotification('Runtime.executionContextCreated'); + return created.params.context; +} + +async function checkScriptContext(session, context) { + const scriptParsed = + await session.waitForNotification('Debugger.scriptParsed'); + assert.strictEqual(scriptParsed.params.executionContextId, context.id); +} + +async function runTests() { + const instance = new NodeInstance(['--inspect-brk=0', '--expose-internals'], + script); + const session = await instance.connectInspectorSession(); + await session.send([ + { 'method': 'Debugger.enable' }, + { 'method': 'Runtime.runIfWaitingForDebugger' } + ]); + await session.waitForBreakOnLine(5, '[eval]'); + + await session.send({ 'method': 'Runtime.enable' }); + const topContext = await getContext(session); + await session.send({ 'method': 'Debugger.resume' }); + const childContext = await getContext(session); + await session.waitForBreakOnLine(13, '[eval]'); + + console.error('[test]', 'Script associated with current context by default'); + await session.send({ 'method': 'Debugger.resume' }); + await checkScriptContext(session, topContext); + await session.waitForBreakOnLine(16, '[eval]'); + + console.error('[test]', 'Script associated with selected context'); + await session.send({ 'method': 'Debugger.resume' }); + await checkScriptContext(session, childContext); + await session.waitForBreakOnLine(21, '[eval]'); + + console.error('[test]', 'Script is unbound'); + await session.send({ 'method': 'Debugger.resume' }); + await session.waitForBreakOnLine(27, '[eval]'); + + console.error('[test]', 'vm.runInContext associates script with context'); + await session.send({ 'method': 'Debugger.resume' }); + await checkScriptContext(session, childContext); + await session.waitForBreakOnLine(30, '[eval]'); + + console.error('[test]', 'vm.runInNewContext associates script with context'); + await session.send({ 'method': 'Debugger.resume' }); + const thirdContext = await getContext(session); + await checkScriptContext(session, thirdContext); + await session.waitForBreakOnLine(33, '[eval]'); + + await session.runToCompletion(); + assert.strictEqual(0, (await instance.expectShutdown()).exitCode); +} + +runTests(); From 7fa175f6d3e243a4ff9f97bd5efc970856210d46 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Tue, 25 Jul 2017 21:36:12 -0300 Subject: [PATCH 069/145] assert: fix deepEqual inconsistencies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/14491 Fixes: https://github.com/nodejs/node/issues/14441 Reviewed-By: Matteo Collina Reviewed-By: Khaidi Chu Reviewed-By: Tobias Nießen --- lib/assert.js | 11 +++++++++-- test/parallel/test-assert-deep.js | 20 ++++++++++++++++++++ test/parallel/test-assert.js | 4 ++-- 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/lib/assert.js b/lib/assert.js index 6f340d8ef4e46b..73c4a1c444e2df 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -279,8 +279,15 @@ function innerDeepEqual(actual, expected, strict, memos) { position: 0 }; } else { - if (memos.actual.has(actual)) { - return memos.actual.get(actual) === memos.expected.get(expected); + // We prevent up to two map.has(x) calls by directly retrieving the value + // and checking for undefined. The map can only contain numbers, so it is + // safe to check for undefined only. + const expectedMemoA = memos.actual.get(actual); + if (expectedMemoA !== undefined) { + const expectedMemoB = memos.expected.get(expected); + if (expectedMemoB !== undefined) { + return expectedMemoA === expectedMemoB; + } } memos.position++; } diff --git a/test/parallel/test-assert-deep.js b/test/parallel/test-assert-deep.js index 74c4eb44ffc7b4..25e94b0f2fd187 100644 --- a/test/parallel/test-assert-deep.js +++ b/test/parallel/test-assert-deep.js @@ -303,6 +303,26 @@ assertOnlyDeepEqual( new Set([undefined]) ); +// Circular structures +{ + const a = {}; + const b = {}; + a.a = a; + b.a = {}; + b.a.a = a; + assertDeepAndStrictEqual(a, b); +} + +{ + const a = new Set(); + const b = new Set(); + const c = new Set(); + a.add(a); + b.add(b); + c.add(a); + assertDeepAndStrictEqual(b, c); +} + { const values = [ 123, diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index ab45aa6c4b63c4..98c0f9eef2994f 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -550,8 +550,8 @@ a.throws(makeBlock(thrower, TypeError), function(err) { const h = {ref: g}; - a.throws(makeBlock(a.deepEqual, f, h), /AssertionError/); - a.throws(makeBlock(a.deepStrictEqual, f, h), /AssertionError/); + a.doesNotThrow(makeBlock(a.deepEqual, f, h)); + a.doesNotThrow(makeBlock(a.deepStrictEqual, f, h)); } // GH-7178. Ensure reflexivity of deepEqual with `arguments` objects. const args = (function() { return arguments; })(); From 774e42b5755259a0e33be7b1558cdc33e3e5eff4 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Tue, 8 Aug 2017 19:56:02 +0200 Subject: [PATCH 070/145] src: refactor `#include` handling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `node_internals.h` already includes the most common headers, so double includes can be avoided in a lot of cases. Also don’t include `node_internals.h` from `node.h` implicitly anymore, as that is mostly unnecessary. PR-URL: https://github.com/nodejs/node/pull/14697 Reviewed-By: Tobias Nießen Reviewed-By: Refael Ackermann Reviewed-By: James M Snell --- src/async-wrap-inl.h | 5 ----- src/backtrace_posix.cc | 2 +- src/env-inl.h | 1 + src/env.cc | 4 +--- src/env.h | 4 ++++ src/inspector_agent.cc | 5 +---- src/node.cc | 1 - src/node.h | 4 ---- src/node_api.cc | 2 -- src/node_buffer.h | 3 +-- src/node_constants.cc | 4 +--- src/node_contextify.cc | 5 ----- src/node_counters.h | 2 +- src/node_dtrace.cc | 5 +---- src/node_dtrace.h | 4 +--- src/node_file.cc | 4 ---- src/node_i18n.h | 2 +- src/node_internals.h | 2 ++ src/node_javascript.h | 3 +-- src/node_main.cc | 2 ++ src/node_os.cc | 5 +---- src/node_perf.cc | 6 +----- src/node_url.cc | 6 ------ src/node_util.cc | 5 +---- src/node_watchdog.cc | 2 -- src/string_search.h | 2 +- src/tls_wrap.cc | 2 -- src/util.cc | 1 - test/cctest/node_test_fixture.h | 1 + test/cctest/test_environment.cc | 4 +--- 30 files changed, 25 insertions(+), 73 deletions(-) diff --git a/src/async-wrap-inl.h b/src/async-wrap-inl.h index 4f8b7c3f8dd914..ed5a0c0d279048 100644 --- a/src/async-wrap-inl.h +++ b/src/async-wrap-inl.h @@ -27,12 +27,7 @@ #include "async-wrap.h" #include "base-object.h" #include "base-object-inl.h" -#include "env.h" -#include "env-inl.h" #include "node_internals.h" -#include "util.h" -#include "util-inl.h" -#include "v8.h" namespace node { diff --git a/src/backtrace_posix.cc b/src/backtrace_posix.cc index 8fd798757a544a..0c69d820e7212a 100644 --- a/src/backtrace_posix.cc +++ b/src/backtrace_posix.cc @@ -1,4 +1,4 @@ -#include "node.h" +#include "node_internals.h" #if defined(__linux__) #include diff --git a/src/env-inl.h b/src/env-inl.h index 229271ccff45a6..eddec5ca54fb48 100644 --- a/src/env-inl.h +++ b/src/env-inl.h @@ -31,6 +31,7 @@ #include "util-inl.h" #include "uv.h" #include "v8.h" +#include "node_perf_common.h" #include #include diff --git a/src/env.cc b/src/env.cc index 076198cd626a81..ba5caa1ec3acca 100644 --- a/src/env.cc +++ b/src/env.cc @@ -1,7 +1,5 @@ -#include "env.h" -#include "env-inl.h" +#include "node_internals.h" #include "async-wrap.h" -#include "v8.h" #include "v8-profiler.h" #if defined(_MSC_VER) diff --git a/src/env.h b/src/env.h index 023136bdcc795c..315d4fdc1852a4 100644 --- a/src/env.h +++ b/src/env.h @@ -48,6 +48,10 @@ struct nghttp2_rcbuf; namespace node { +namespace performance { +struct performance_state; +} + // Pick an index that's hopefully out of the way when we're embedded inside // another application. Performance-wise or memory-wise it doesn't matter: // Context::SetAlignedPointerInEmbedderData() is backed by a FixedArray, diff --git a/src/inspector_agent.cc b/src/inspector_agent.cc index 828006ecf2fbb4..9f33b3d31e69e6 100644 --- a/src/inspector_agent.cc +++ b/src/inspector_agent.cc @@ -1,12 +1,9 @@ #include "inspector_agent.h" #include "inspector_io.h" -#include "env.h" -#include "env-inl.h" -#include "node.h" +#include "node_internals.h" #include "v8-inspector.h" #include "v8-platform.h" -#include "util.h" #include "zlib.h" #include "libplatform/libplatform.h" diff --git a/src/node.cc b/src/node.cc index e82f14cba9e9ed..1a8334a91e14cd 100644 --- a/src/node.cc +++ b/src/node.cc @@ -19,7 +19,6 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -#include "node.h" #include "node_buffer.h" #include "node_constants.h" #include "node_javascript.h" diff --git a/src/node.h b/src/node.h index efcf93a6776abb..29f07c39888a53 100644 --- a/src/node.h +++ b/src/node.h @@ -169,10 +169,6 @@ NODE_EXTERN v8::Local MakeCallback( } // namespace node -#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node_internals.h" -#endif - #include #include diff --git a/src/node_api.cc b/src/node_api.cc index 1ec30d3d80719e..996e9ab653b5ca 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -14,10 +14,8 @@ #include #include #include -#include "uv.h" #include "node_api.h" #include "node_internals.h" -#include "util.h" #define NAPI_VERSION 1 diff --git a/src/node_buffer.h b/src/node_buffer.h index acf9b23c3b3256..d680eb90eb1649 100644 --- a/src/node_buffer.h +++ b/src/node_buffer.h @@ -22,8 +22,7 @@ #ifndef SRC_NODE_BUFFER_H_ #define SRC_NODE_BUFFER_H_ -#include "node.h" -#include "v8.h" +#include "node_internals.h" namespace node { diff --git a/src/node_constants.cc b/src/node_constants.cc index 76e60d1e305e03..8b074050549ede 100644 --- a/src/node_constants.cc +++ b/src/node_constants.cc @@ -20,10 +20,8 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node_constants.h" -#include "env.h" -#include "env-inl.h" +#include "node_internals.h" -#include "uv.h" #include "zlib.h" #include diff --git a/src/node_contextify.cc b/src/node_contextify.cc index c2037c4cbe7354..dc939c6cf98fe3 100644 --- a/src/node_contextify.cc +++ b/src/node_contextify.cc @@ -19,15 +19,10 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -#include "node.h" #include "node_internals.h" #include "node_watchdog.h" #include "base-object.h" #include "base-object-inl.h" -#include "env.h" -#include "env-inl.h" -#include "util.h" -#include "util-inl.h" #include "v8-debug.h" namespace node { diff --git a/src/node_counters.h b/src/node_counters.h index 5d866aedb57677..c8a1a88f0b25e0 100644 --- a/src/node_counters.h +++ b/src/node_counters.h @@ -24,7 +24,7 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node.h" +#include "node_internals.h" #ifdef HAVE_PERFCTR #include "node_win32_perfctr_provider.h" diff --git a/src/node_dtrace.cc b/src/node_dtrace.cc index 94d06a7404ed33..4ff2f22d8e835a 100644 --- a/src/node_dtrace.cc +++ b/src/node_dtrace.cc @@ -43,10 +43,7 @@ #define NODE_GC_DONE(arg0, arg1, arg2) #endif -#include "env.h" -#include "env-inl.h" - -#include "util.h" +#include "node_internals.h" #include diff --git a/src/node_dtrace.h b/src/node_dtrace.h index c22bf4e7fc0f12..d16e23ddb384b7 100644 --- a/src/node_dtrace.h +++ b/src/node_dtrace.h @@ -24,9 +24,7 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node.h" -#include "v8.h" -#include "env.h" +#include "node_internals.h" extern "C" { /* diff --git a/src/node_file.cc b/src/node_file.cc index c4dcc9b287526e..887dff5a030e06 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -19,17 +19,13 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -#include "node.h" #include "node_buffer.h" #include "node_internals.h" #include "node_stat_watcher.h" -#include "env.h" -#include "env-inl.h" #include "req-wrap.h" #include "req-wrap-inl.h" #include "string_bytes.h" -#include "util.h" #include #include diff --git a/src/node_i18n.h b/src/node_i18n.h index adf9feb414df5c..70a0c79f76cf30 100644 --- a/src/node_i18n.h +++ b/src/node_i18n.h @@ -24,7 +24,7 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node.h" +#include "node_internals.h" #include #if defined(NODE_HAVE_I18N_SUPPORT) diff --git a/src/node_internals.h b/src/node_internals.h index d2fb875bd2e006..033634caf11dc1 100644 --- a/src/node_internals.h +++ b/src/node_internals.h @@ -27,6 +27,8 @@ #include "node.h" #include "util.h" #include "util-inl.h" +#include "env.h" +#include "env-inl.h" #include "uv.h" #include "v8.h" #include "tracing/trace_event.h" diff --git a/src/node_javascript.h b/src/node_javascript.h index 3e8528fd211fb6..664778091ff669 100644 --- a/src/node_javascript.h +++ b/src/node_javascript.h @@ -24,8 +24,7 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "v8.h" -#include "env.h" +#include "node_internals.h" namespace node { diff --git a/src/node_main.cc b/src/node_main.cc index 7d6d9b1a01bbd4..2a511b92996e86 100644 --- a/src/node_main.cc +++ b/src/node_main.cc @@ -20,8 +20,10 @@ // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "node.h" +#include #ifdef _WIN32 +#include #include #include diff --git a/src/node_os.cc b/src/node_os.cc index c1d1de971f4a09..dc2dd839963c2c 100644 --- a/src/node_os.cc +++ b/src/node_os.cc @@ -19,10 +19,7 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -#include "node.h" -#include "v8.h" -#include "env.h" -#include "env-inl.h" +#include "node_internals.h" #include "string_bytes.h" #include diff --git a/src/node_perf.cc b/src/node_perf.cc index 48917d5d4ea971..098cf35220a400 100644 --- a/src/node_perf.cc +++ b/src/node_perf.cc @@ -1,9 +1,5 @@ -#include "node.h" -#include "v8.h" -#include "env.h" -#include "env-inl.h" +#include "node_internals.h" #include "node_perf.h" -#include "uv.h" #include diff --git a/src/node_url.cc b/src/node_url.cc index f8adc7d7af5509..20a869ad7afc63 100644 --- a/src/node_url.cc +++ b/src/node_url.cc @@ -1,11 +1,5 @@ #include "node_url.h" -#include "node.h" #include "node_internals.h" -#include "env.h" -#include "env-inl.h" -#include "util.h" -#include "util-inl.h" -#include "v8.h" #include "base-object.h" #include "base-object-inl.h" #include "node_i18n.h" diff --git a/src/node_util.cc b/src/node_util.cc index bbbea9ea2254dd..ab1f3c9f91257d 100644 --- a/src/node_util.cc +++ b/src/node_util.cc @@ -1,8 +1,5 @@ -#include "node.h" +#include "node_internals.h" #include "node_watchdog.h" -#include "v8.h" -#include "env.h" -#include "env-inl.h" namespace node { namespace util { diff --git a/src/node_watchdog.cc b/src/node_watchdog.cc index f4020e56f7fb61..af4e9f6fcfe3c2 100644 --- a/src/node_watchdog.cc +++ b/src/node_watchdog.cc @@ -21,8 +21,6 @@ #include "node_watchdog.h" #include "node_internals.h" -#include "util.h" -#include "util-inl.h" #include namespace node { diff --git a/src/string_search.h b/src/string_search.h index dfdb8e9a160460..73e90f5873f767 100644 --- a/src/string_search.h +++ b/src/string_search.h @@ -7,7 +7,7 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS -#include "node.h" +#include "node_internals.h" #include namespace node { diff --git a/src/tls_wrap.cc b/src/tls_wrap.cc index b5829cf5b82f6c..dce05fabd62160 100644 --- a/src/tls_wrap.cc +++ b/src/tls_wrap.cc @@ -31,8 +31,6 @@ #include "node_internals.h" #include "stream_base.h" #include "stream_base-inl.h" -#include "util.h" -#include "util-inl.h" namespace node { diff --git a/src/util.cc b/src/util.cc index 4a89b3a42f24b0..ef93d16968e465 100644 --- a/src/util.cc +++ b/src/util.cc @@ -19,7 +19,6 @@ // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. -#include "util.h" #include "string_bytes.h" #include "node_buffer.h" #include "node_internals.h" diff --git a/test/cctest/node_test_fixture.h b/test/cctest/node_test_fixture.h index 79027d25ad8c8d..263f7b96f9daec 100644 --- a/test/cctest/node_test_fixture.h +++ b/test/cctest/node_test_fixture.h @@ -4,6 +4,7 @@ #include #include "gtest/gtest.h" #include "node.h" +#include "node_platform.h" #include "env.h" #include "v8.h" #include "libplatform/libplatform.h" diff --git a/test/cctest/test_environment.cc b/test/cctest/test_environment.cc index 4651e865a99e7d..8beacfa95ece7e 100644 --- a/test/cctest/test_environment.cc +++ b/test/cctest/test_environment.cc @@ -1,6 +1,4 @@ -#include "node.h" -#include "env.h" -#include "v8.h" +#include "node_internals.h" #include "libplatform/libplatform.h" #include From 50b6203a33c997953e3132fcfda4d39dfcd78eed Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Tue, 5 Sep 2017 19:06:37 +0200 Subject: [PATCH 071/145] test: add regression test for 5691 With `CallbackScope`, this has become possible to do properly. Fixes: https://github.com/nodejs/node/issues/5691 PR-URL: https://github.com/nodejs/node/pull/14697 Reviewed-By: James M Snell --- test/addons/callback-scope/binding.cc | 32 +++++++++++++++++++ .../callback-scope/test-resolve-async.js | 13 ++++++++ 2 files changed, 45 insertions(+) create mode 100644 test/addons/callback-scope/test-resolve-async.js diff --git a/test/addons/callback-scope/binding.cc b/test/addons/callback-scope/binding.cc index 31317e5dae236f..22105360fbfe5c 100644 --- a/test/addons/callback-scope/binding.cc +++ b/test/addons/callback-scope/binding.cc @@ -1,5 +1,6 @@ #include "node.h" #include "v8.h" +#include "uv.h" #include #include @@ -30,8 +31,39 @@ void RunInCallbackScope(const v8::FunctionCallbackInfo& args) { args.GetReturnValue().Set(ret.ToLocalChecked()); } +static v8::Persistent persistent; + +static void Callback(uv_work_t* req, int ignored) { + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + node::CallbackScope callback_scope(isolate, v8::Object::New(isolate), {0, 0}); + + v8::Local local = + v8::Local::New(isolate, persistent); + local->Resolve(v8::Undefined(isolate)); + delete req; +} + +static void TestResolveAsync(const v8::FunctionCallbackInfo& args) { + v8::Isolate* isolate = args.GetIsolate(); + + if (persistent.IsEmpty()) { + persistent.Reset(isolate, v8::Promise::Resolver::New(isolate)); + + uv_work_t* req = new uv_work_t; + + uv_queue_work(uv_default_loop(), req, [](uv_work_t*) {}, Callback); + } + + v8::Local local = + v8::Local::New(isolate, persistent); + + args.GetReturnValue().Set(local->GetPromise()); +} + void Initialize(v8::Local exports) { NODE_SET_METHOD(exports, "runInCallbackScope", RunInCallbackScope); + NODE_SET_METHOD(exports, "testResolveAsync", TestResolveAsync); } } // namespace diff --git a/test/addons/callback-scope/test-resolve-async.js b/test/addons/callback-scope/test-resolve-async.js new file mode 100644 index 00000000000000..e9f4b9044c0154 --- /dev/null +++ b/test/addons/callback-scope/test-resolve-async.js @@ -0,0 +1,13 @@ +'use strict'; + +const common = require('../../common'); +const assert = require('assert'); +const { testResolveAsync } = require(`./build/${common.buildType}/binding`); + +let called = false; +testResolveAsync().then(common.mustCall(() => { + called = true; +})); + +setTimeout(common.mustCall(() => { assert(called); }), + common.platformTimeout(20)); From 7b7c030adc2c6bc72f48c94d34dd602df05d5ce2 Mon Sep 17 00:00:00 2001 From: Jason Ginchereau Date: Sat, 9 Sep 2017 14:04:35 -0700 Subject: [PATCH 072/145] n-api: change async resource name to napi_value PR-URL: https://github.com/nodejs/node/pull/14697 Reviewed-By: Anna Henningsen --- doc/api/n-api.md | 2 +- src/async-wrap.cc | 15 +++++++++++---- src/node.h | 15 +++++++++++++++ src/node_api.cc | 17 ++++++++++------- src/node_api.h | 2 +- test/addons-napi/test_async/test_async.cc | 14 +++++++++++--- 6 files changed, 49 insertions(+), 16 deletions(-) diff --git a/doc/api/n-api.md b/doc/api/n-api.md index 70ee1cb70a320c..2ed9a8c709fef2 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -3273,7 +3273,7 @@ changes: NAPI_EXTERN napi_status napi_create_async_work(napi_env env, napi_value async_resource, - const char* async_resource_name, + napi_value async_resource_name, napi_async_execute_callback execute, napi_async_complete_callback complete, void* data, diff --git a/src/async-wrap.cc b/src/async-wrap.cc index 5b59ebb23fd9ec..025adff4d9911b 100644 --- a/src/async-wrap.cc +++ b/src/async-wrap.cc @@ -652,6 +652,16 @@ async_context EmitAsyncInit(Isolate* isolate, Local resource, const char* name, async_id trigger_async_id) { + Local type = + String::NewFromUtf8(isolate, name, v8::NewStringType::kInternalized) + .ToLocalChecked(); + return EmitAsyncInit(isolate, resource, type, trigger_async_id); +} + +async_context EmitAsyncInit(Isolate* isolate, + Local resource, + v8::Local name, + async_id trigger_async_id) { Environment* env = Environment::GetCurrent(isolate); // Initialize async context struct @@ -664,10 +674,7 @@ async_context EmitAsyncInit(Isolate* isolate, }; // Run init hooks - Local type = - String::NewFromUtf8(isolate, name, v8::NewStringType::kInternalized) - .ToLocalChecked(); - AsyncWrap::EmitAsyncInit(env, resource, type, context.async_id, + AsyncWrap::EmitAsyncInit(env, resource, name, context.async_id, context.trigger_async_id); return context; diff --git a/src/node.h b/src/node.h index 29f07c39888a53..e7a59b217da2a9 100644 --- a/src/node.h +++ b/src/node.h @@ -591,6 +591,11 @@ NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate, const char* name, async_id trigger_async_id = -1); +NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate, + v8::Local resource, + v8::Local name, + async_id trigger_async_id = -1); + /* Emit the destroy() callback. */ NODE_EXTERN void EmitAsyncDestroy(v8::Isolate* isolate, async_context asyncContext); @@ -702,6 +707,16 @@ class AsyncResource { trigger_async_id); } + AsyncResource(v8::Isolate* isolate, + v8::Local resource, + v8::Local name, + async_id trigger_async_id = -1) + : isolate_(isolate), + resource_(isolate, resource) { + async_context_ = EmitAsyncInit(isolate, resource, name, + trigger_async_id); + } + ~AsyncResource() { EmitAsyncDestroy(isolate_, async_context_); } diff --git a/src/node_api.cc b/src/node_api.cc index 996e9ab653b5ca..5934435c6cb26e 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -3259,7 +3259,7 @@ class Work : public node::AsyncResource { private: explicit Work(napi_env env, v8::Local async_resource, - const char* async_resource_name, + v8::Local async_resource_name, napi_async_execute_callback execute, napi_async_complete_callback complete = nullptr, void* data = nullptr) @@ -3279,7 +3279,7 @@ class Work : public node::AsyncResource { public: static Work* New(napi_env env, v8::Local async_resource, - const char* async_resource_name, + v8::Local async_resource_name, napi_async_execute_callback execute, napi_async_complete_callback complete, void* data) { @@ -3349,7 +3349,7 @@ class Work : public node::AsyncResource { napi_status napi_create_async_work(napi_env env, napi_value async_resource, - const char* async_resource_name, + napi_value async_resource_name, napi_async_execute_callback execute, napi_async_complete_callback complete, void* data, @@ -3358,17 +3358,20 @@ napi_status napi_create_async_work(napi_env env, CHECK_ARG(env, execute); CHECK_ARG(env, result); + v8::Local context = env->isolate->GetCurrentContext(); + v8::Local resource; if (async_resource != nullptr) { - auto value = v8impl::V8LocalValueFromJsValue(async_resource); - RETURN_STATUS_IF_FALSE(env, value->IsObject(), napi_invalid_arg); - resource = value.As(); + CHECK_TO_OBJECT(env, context, resource, async_resource); } else { resource = v8::Object::New(env->isolate); } + v8::Local resource_name; + CHECK_TO_STRING(env, context, resource_name, async_resource_name); + uvimpl::Work* work = - uvimpl::Work::New(env, resource, async_resource_name, + uvimpl::Work::New(env, resource, resource_name, execute, complete, data); *result = reinterpret_cast(work); diff --git a/src/node_api.h b/src/node_api.h index 3a71e4d1ea3f8e..a5044b4b35f149 100644 --- a/src/node_api.h +++ b/src/node_api.h @@ -523,7 +523,7 @@ NAPI_EXTERN napi_status napi_get_dataview_info(napi_env env, NAPI_EXTERN napi_status napi_create_async_work(napi_env env, napi_value async_resource, - const char* async_resource_name, + napi_value async_resource_name, napi_async_execute_callback execute, napi_async_complete_callback complete, void* data, diff --git a/test/addons-napi/test_async/test_async.cc b/test/addons-napi/test_async/test_async.cc index 53b361fbd1db28..251573828b9fe8 100644 --- a/test/addons-napi/test_async/test_async.cc +++ b/test/addons-napi/test_async/test_async.cc @@ -71,6 +71,7 @@ napi_value Test(napi_env env, napi_callback_info info) { size_t argc = 3; napi_value argv[3]; napi_value _this; + napi_value resource_name; void* data; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &_this, &data)); @@ -93,7 +94,10 @@ napi_value Test(napi_env env, napi_callback_info info) { napi_get_value_int32(env, argv[0], &the_carrier._input)); NAPI_CALL(env, napi_create_reference(env, argv[2], 1, &the_carrier._callback)); - NAPI_CALL(env, napi_create_async_work(env, argv[1], "TestResource", + + NAPI_CALL(env, + napi_create_string_utf8(env, "TestResource", -1, &resource_name)); + NAPI_CALL(env, napi_create_async_work(env, argv[1], resource_name, Execute, Complete, &the_carrier, &the_carrier._request)); NAPI_CALL(env, napi_queue_async_work(env, the_carrier._request)); @@ -138,12 +142,16 @@ napi_value TestCancel(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value argv[1]; napi_value _this; + napi_value resource_name; void* data; + NAPI_CALL(env, + napi_create_string_utf8(env, "TestResource", -1, &resource_name)); + // make sure the work we are going to cancel will not be // able to start by using all the threads in the pool for (int i = 1; i < MAX_CANCEL_THREADS; i++) { - NAPI_CALL(env, napi_create_async_work(env, nullptr, "TestCancelBusy", + NAPI_CALL(env, napi_create_async_work(env, nullptr, resource_name, CancelExecute, BusyCancelComplete, &async_carrier[i], &async_carrier[i]._request)); NAPI_CALL(env, napi_queue_async_work(env, async_carrier[i]._request)); @@ -155,7 +163,7 @@ napi_value TestCancel(napi_env env, napi_callback_info info) { // workers above. NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &_this, &data)); - NAPI_CALL(env, napi_create_async_work(env, nullptr, "TestCancelled", + NAPI_CALL(env, napi_create_async_work(env, nullptr, resource_name, CancelExecute, CancelComplete, &async_carrier[0], &async_carrier[0]._request)); NAPI_CALL(env, From 87a3162f85998de1e599cc6d386c73678df76a59 Mon Sep 17 00:00:00 2001 From: Jason Ginchereau Date: Sat, 26 Aug 2017 15:44:43 -0700 Subject: [PATCH 073/145] n-api: Context for custom async operations - Add napi_async_context opaque pointer type. (If needed, we could later add APIs for getting the async IDs out of this context.) - Add napi_async_init() and napi_async_destroy() APIs. - Add async_context parameter to napi_make_callback(). - Add code and checks to test_make_callback to validate async context APIs by checking async hooks are called with correct context. - Update API documentation. PR-URL: https://github.com/nodejs/node/pull/15189 Fixes: https://github.com/nodejs/node/issues/13254 Reviewed-By: Michael Dawson Reviewed-By: James M Snell --- doc/api/n-api.md | 214 +++++++++++------- src/node_api.cc | 61 ++++- src/node_api.h | 24 +- src/node_api_types.h | 1 + .../addons-napi/test_make_callback/binding.cc | 12 +- test/addons-napi/test_make_callback/test.js | 39 +++- .../test_make_callback_recurse/binding.cc | 4 +- 7 files changed, 259 insertions(+), 96 deletions(-) diff --git a/doc/api/n-api.md b/doc/api/n-api.md index 2ed9a8c709fef2..00bba55a4c9e3d 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -41,7 +41,8 @@ The documentation for N-API is structured as follows: * [Working with JavaScript Properties][] * [Working with JavaScript Functions][] * [Object Wrap][] -* [Asynchronous Operations][] +* [Simple Asynchronous Operations][] +* [Custom Asynchronous Operations][] * [Promises][] * [Script Execution][] @@ -264,7 +265,7 @@ It is intended only for logging purposes. added: v8.0.0 --> ```C -NAPI_EXTERN napi_status +napi_status napi_get_last_error_info(napi_env env, const napi_extended_error_info** result); ``` @@ -515,8 +516,8 @@ This API returns a JavaScript RangeError with the text provided. added: v8.0.0 --> ```C -NAPI_EXTERN napi_status napi_get_and_clear_last_exception(napi_env env, - napi_value* result); +napi_status napi_get_and_clear_last_exception(napi_env env, + napi_value* result); ``` - `[in] env`: The environment that the API is invoked under. @@ -531,7 +532,7 @@ This API returns true if an exception is pending. added: v8.0.0 --> ```C -NAPI_EXTERN napi_status napi_is_exception_pending(napi_env env, bool* result); +napi_status napi_is_exception_pending(napi_env env, bool* result); ``` - `[in] env`: The environment that the API is invoked under. @@ -551,7 +552,7 @@ thrown to immediately terminate the process. added: v8.2.0 --> ```C -NAPI_EXTERN NAPI_NO_RETURN void napi_fatal_error(const char* location, const char* message); +NAPI_NO_RETURN void napi_fatal_error(const char* location, const char* message); ``` - `[in] location`: Optional location at which the error occurred. @@ -718,10 +719,10 @@ reverse order from which they were created. added: v8.0.0 --> ```C -NAPI_EXTERN napi_status napi_escape_handle(napi_env env, - napi_escapable_handle_scope scope, - napi_value escapee, - napi_value* result); +napi_status napi_escape_handle(napi_env env, + napi_escapable_handle_scope scope, + napi_value escapee, + napi_value* result); ``` - `[in] env`: The environment that the API is invoked under. @@ -1478,10 +1479,10 @@ of the ECMAScript Language Specification. added: v8.0.0 --> ```C -NAPI_EXTERN napi_status napi_create_string_latin1(napi_env env, - const char* str, - size_t length, - napi_value* result); +napi_status napi_create_string_latin1(napi_env env, + const char* str, + size_t length, + napi_value* result); ``` - `[in] env`: The environment that the API is invoked under. @@ -1811,11 +1812,11 @@ JavaScript Number added: v8.0.0 --> ```C -NAPI_EXTERN napi_status napi_get_value_string_latin1(napi_env env, - napi_value value, - char* buf, - size_t bufsize, - size_t* result) +napi_status napi_get_value_string_latin1(napi_env env, + napi_value value, + char* buf, + size_t bufsize, + size_t* result) ``` - `[in] env`: The environment that the API is invoked under. @@ -2790,8 +2791,8 @@ in as arguments to the function. Returns `napi_ok` if the API succeeded. This method allows a JavaScript function object to be called from a native -add-on. This is an primary mechanism of calling back *from* the add-on's -native code *into* JavaScript. For special cases like calling into JavaScript +add-on. This is the primary mechanism of calling back *from* the add-on's +native code *into* JavaScript. For the special case of calling into JavaScript after an async operation, see [`napi_make_callback`][]. A sample use case might look as follows. Consider the following JavaScript @@ -3002,39 +3003,6 @@ status = napi_new_instance(env, constructor, argc, argv, &value); Returns `napi_ok` if the API succeeded. -### *napi_make_callback* - -```C -napi_status napi_make_callback(napi_env env, - napi_value recv, - napi_value func, - int argc, - const napi_value* argv, - napi_value* result) -``` - -- `[in] env`: The environment that the API is invoked under. -- `[in] recv`: The `this` object passed to the called function. -- `[in] func`: `napi_value` representing the JavaScript function -to be invoked. -- `[in] argc`: The count of elements in the `argv` array. -- `[in] argv`: Array of JavaScript values as `napi_value` -representing the arguments to the function. -- `[out] result`: `napi_value` representing the JavaScript object returned. - -Returns `napi_ok` if the API succeeded. - -This method allows a JavaScript function object to be called from a native -add-on. This API is similar to `napi_call_function`. However, it is used to call -*from* native code back *into* JavaScript *after* returning from an async -operation (when there is no other script on the stack). It is a fairly simple -wrapper around `node::MakeCallback`. - -For an example on how to use `napi_make_callback`, see the section on -[Asynchronous Operations][]. - ## Object Wrap N-API offers a way to "wrap" C++ classes and instances so that the class @@ -3213,7 +3181,7 @@ restoring the JavaScript object's prototype chain. If a finalize callback was associated with the wrapping, it will no longer be called when the JavaScript object becomes garbage-collected. -## Asynchronous Operations +## Simple Asynchronous Operations Addon modules often need to leverage async helpers from libuv as part of their implementation. This allows them to schedule work to be executed asynchronously @@ -3249,8 +3217,8 @@ Once created the async worker can be queued for execution using the [`napi_queue_async_work`][] function: ```C -NAPI_EXTERN napi_status napi_queue_async_work(napi_env env, - napi_async_work work); +napi_status napi_queue_async_work(napi_env env, + napi_async_work work); ``` [`napi_cancel_async_work`][] can be used if the work needs @@ -3270,7 +3238,6 @@ changes: description: Added `async_resource` and `async_resource_name` parameters. --> ```C -NAPI_EXTERN napi_status napi_create_async_work(napi_env env, napi_value async_resource, napi_value async_resource_name, @@ -3313,8 +3280,8 @@ for more information. added: v8.0.0 --> ```C -NAPI_EXTERN napi_status napi_delete_async_work(napi_env env, - napi_async_work work); +napi_status napi_delete_async_work(napi_env env, + napi_async_work work); ``` - `[in] env`: The environment that the API is invoked under. @@ -3329,8 +3296,8 @@ This API frees a previously allocated work object. added: v8.0.0 --> ```C -NAPI_EXTERN napi_status napi_queue_async_work(napi_env env, - napi_async_work work); +napi_status napi_queue_async_work(napi_env env, + napi_async_work work); ``` - `[in] env`: The environment that the API is invoked under. @@ -3346,8 +3313,8 @@ for execution. added: v8.0.0 --> ```C -NAPI_EXTERN napi_status napi_cancel_async_work(napi_env env, - napi_async_work work); +napi_status napi_cancel_async_work(napi_env env, + napi_async_work work); ``` - `[in] env`: The environment that the API is invoked under. @@ -3362,6 +3329,93 @@ the `complete` callback will be invoked with a status value of `napi_cancelled`. The work should not be deleted before the `complete` callback invocation, even if it has been successfully cancelled. +## Custom Asynchronous Operations +The simple asynchronous work APIs above may not be appropriate for every +scenario, because with those the async execution still happens on the main +event loop. When using any other async mechanism, the following APIs are +necessary to ensure an async operation is properly tracked by the runtime. + +### *napi_async_init** + +```C +napi_status napi_async_init(napi_env env, + napi_value async_resource, + napi_value async_resource_name, + napi_async_context* result) +``` + +- `[in] env`: The environment that the API is invoked under. +- `[in] async_resource`: An optional object associated with the async work + that will be passed to possible `async_hooks` [`init` hooks][]. +- `[in] async_resource_name`: Required identifier for the kind of resource + that is being provided for diagnostic information exposed by the + `async_hooks` API. +- `[out] result`: The initialized async context. + +Returns `napi_ok` if the API succeeded. + +### *napi_async_destroy** + +```C +napi_status napi_async_destroy(napi_env env, + napi_async_context async_context); +``` + +- `[in] env`: The environment that the API is invoked under. +- `[in] async_context`: The async context to be destroyed. + +Returns `napi_ok` if the API succeeded. + +### *napi_make_callback* + +```C +napi_status napi_make_callback(napi_env env, + napi_async_context async_context, + napi_value recv, + napi_value func, + int argc, + const napi_value* argv, + napi_value* result) +``` + +- `[in] env`: The environment that the API is invoked under. +- `[in] async_context`: Context for the async operation that is + invoking the callback. This should normally be a value previously + obtained from [`napi_async_init`][]. However `NULL` is also allowed, + which indicates the current async context (if any) is to be used + for the callback. +- `[in] recv`: The `this` object passed to the called function. +- `[in] func`: `napi_value` representing the JavaScript function +to be invoked. +- `[in] argc`: The count of elements in the `argv` array. +- `[in] argv`: Array of JavaScript values as `napi_value` +representing the arguments to the function. +- `[out] result`: `napi_value` representing the JavaScript object returned. + +Returns `napi_ok` if the API succeeded. + +This method allows a JavaScript function object to be called from a native +add-on. This API is similar to `napi_call_function`. However, it is used to call +*from* native code back *into* JavaScript *after* returning from an async +operation (when there is no other script on the stack). It is a fairly simple +wrapper around `node::MakeCallback`. + +Note it is *not* necessary to use `napi_make_callback` from within a +`napi_async_complete_callback`; in that situation the callback's async +context has already been set up, so a direct call to `napi_call_function` +is sufficient and appropriate. Use of the `napi_make_callback` function +may be required when implementing custom async behavior that does not use +`napi_create_async_work`. + ## Version Management ### napi_get_node_version @@ -3377,7 +3431,6 @@ typedef struct { const char* release; } napi_node_version; -NAPI_EXTERN napi_status napi_get_node_version(napi_env env, const napi_node_version** version); ``` @@ -3398,8 +3451,8 @@ The returned buffer is statically allocated and does not need to be freed. added: v8.0.0 --> ```C -NAPI_EXTERN napi_status napi_get_version(napi_env env, - uint32_t* result); +napi_status napi_get_version(napi_env env, + uint32_t* result); ``` - `[in] env`: The environment that the API is invoked under. @@ -3507,9 +3560,9 @@ deferred = NULL; added: v8.5.0 --> ```C -NAPI_EXTERN napi_status napi_create_promise(napi_env env, - napi_deferred* deferred, - napi_value* promise); +napi_status napi_create_promise(napi_env env, + napi_deferred* deferred, + napi_value* promise); ``` - `[in] env`: The environment that the API is invoked under. @@ -3527,9 +3580,9 @@ This API creates a deferred object and a JavaScript promise. added: v8.5.0 --> ```C -NAPI_EXTERN napi_status napi_resolve_deferred(napi_env env, - napi_deferred deferred, - napi_value resolution); +napi_status napi_resolve_deferred(napi_env env, + napi_deferred deferred, + napi_value resolution); ``` - `[in] env`: The environment that the API is invoked under. @@ -3550,9 +3603,9 @@ The deferred object is freed upon successful completion. added: v8.5.0 --> ```C -NAPI_EXTERN napi_status napi_reject_deferred(napi_env env, - napi_deferred deferred, - napi_value rejection); +napi_status napi_reject_deferred(napi_env env, + napi_deferred deferred, + napi_value rejection); ``` - `[in] env`: The environment that the API is invoked under. @@ -3573,9 +3626,9 @@ The deferred object is freed upon successful completion. added: v8.5.0 --> ```C -NAPI_EXTERN napi_status napi_is_promise(napi_env env, - napi_value promise, - bool* is_promise); +napi_status napi_is_promise(napi_env env, + napi_value promise, + bool* is_promise); ``` - `[in] env`: The environment that the API is invoked under. @@ -3603,7 +3656,8 @@ NAPI_EXTERN napi_status napi_run_script(napi_env env, - `[out] result`: The value resulting from having executed the script. [Promises]: #n_api_promises -[Asynchronous Operations]: #n_api_asynchronous_operations +[Simple Asynchronous Operations]: #n_api_asynchronous_operations +[Custom Asynchronous Operations]: #n_api_custom_asynchronous_operations [Basic N-API Data Types]: #n_api_basic_n_api_data_types [ECMAScript Language Specification]: https://tc39.github.io/ecma262/ [Error Handling]: #n_api_error_handling diff --git a/src/node_api.cc b/src/node_api.cc index 5934435c6cb26e..724d5c3ee96701 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -2768,7 +2768,52 @@ napi_status napi_instanceof(napi_env env, return GET_RETURN_STATUS(env); } +napi_status napi_async_init(napi_env env, + napi_value async_resource, + napi_value async_resource_name, + napi_async_context* result) { + CHECK_ENV(env); + CHECK_ARG(env, async_resource_name); + CHECK_ARG(env, result); + + v8::Isolate* isolate = env->isolate; + v8::Local context = isolate->GetCurrentContext(); + + v8::Local v8_resource; + if (async_resource != nullptr) { + CHECK_TO_OBJECT(env, context, v8_resource, async_resource); + } else { + v8_resource = v8::Object::New(isolate); + } + + v8::Local v8_resource_name; + CHECK_TO_STRING(env, context, v8_resource_name, async_resource_name); + + // TODO(jasongin): Consider avoiding allocation here by using + // a tagged pointer with 2×31 bit fields instead. + node::async_context* async_context = new node::async_context(); + + *async_context = node::EmitAsyncInit(isolate, v8_resource, v8_resource_name); + *result = reinterpret_cast(async_context); + + return napi_clear_last_error(env); +} + +napi_status napi_async_destroy(napi_env env, + napi_async_context async_context) { + CHECK_ENV(env); + CHECK_ARG(env, async_context); + + v8::Isolate* isolate = env->isolate; + node::async_context* node_async_context = + reinterpret_cast(async_context); + node::EmitAsyncDestroy(isolate, *node_async_context); + + return napi_clear_last_error(env); +} + napi_status napi_make_callback(napi_env env, + napi_async_context async_context, napi_value recv, napi_value func, size_t argc, @@ -2789,12 +2834,22 @@ napi_status napi_make_callback(napi_env env, v8::Local v8func; CHECK_TO_FUNCTION(env, v8func, func); - v8::Local callback_result = node::MakeCallback( + node::async_context* node_async_context = + reinterpret_cast(async_context); + if (node_async_context == nullptr) { + static node::async_context empty_context = { 0, 0 }; + node_async_context = &empty_context; + } + + v8::MaybeLocal callback_result = node::MakeCallback( isolate, v8recv, v8func, argc, - reinterpret_cast*>(const_cast(argv))); + reinterpret_cast*>(const_cast(argv)), + *node_async_context); + CHECK_MAYBE_EMPTY(env, callback_result, napi_generic_failure); if (result != nullptr) { - *result = v8impl::JsValueFromV8LocalValue(callback_result); + *result = v8impl::JsValueFromV8LocalValue( + callback_result.ToLocalChecked()); } return GET_RETURN_STATUS(env); diff --git a/src/node_api.h b/src/node_api.h index a5044b4b35f149..e1a40983a9907d 100644 --- a/src/node_api.h +++ b/src/node_api.h @@ -318,14 +318,6 @@ NAPI_EXTERN napi_status napi_instanceof(napi_env env, napi_value constructor, bool* result); -// Napi version of node::MakeCallback(...) -NAPI_EXTERN napi_status napi_make_callback(napi_env env, - napi_value recv, - napi_value func, - size_t argc, - const napi_value* argv, - napi_value* result); - // Methods to work with napi_callbacks // Gets all callback info in a single call. (Ugly, but faster.) @@ -535,6 +527,22 @@ NAPI_EXTERN napi_status napi_queue_async_work(napi_env env, NAPI_EXTERN napi_status napi_cancel_async_work(napi_env env, napi_async_work work); +// Methods for custom handling of async operations +NAPI_EXTERN napi_status napi_async_init(napi_env env, + napi_value async_resource, + napi_value async_resource_name, + napi_async_context* result); + +NAPI_EXTERN napi_status napi_async_destroy(napi_env env, + napi_async_context async_context); + +NAPI_EXTERN napi_status napi_make_callback(napi_env env, + napi_async_context async_context, + napi_value recv, + napi_value func, + size_t argc, + const napi_value* argv, + napi_value* result); // version management NAPI_EXTERN napi_status napi_get_version(napi_env env, uint32_t* result); diff --git a/src/node_api_types.h b/src/node_api_types.h index ac8482bf9dcf9d..574cb6ff984f16 100644 --- a/src/node_api_types.h +++ b/src/node_api_types.h @@ -16,6 +16,7 @@ typedef struct napi_ref__ *napi_ref; typedef struct napi_handle_scope__ *napi_handle_scope; typedef struct napi_escapable_handle_scope__ *napi_escapable_handle_scope; typedef struct napi_callback_info__ *napi_callback_info; +typedef struct napi_async_context__ *napi_async_context; typedef struct napi_async_work__ *napi_async_work; typedef struct napi_deferred__ *napi_deferred; diff --git a/test/addons-napi/test_make_callback/binding.cc b/test/addons-napi/test_make_callback/binding.cc index 2f52112e747fb8..df2c4dc672ea47 100644 --- a/test/addons-napi/test_make_callback/binding.cc +++ b/test/addons-napi/test_make_callback/binding.cc @@ -24,14 +24,22 @@ napi_value MakeCallback(napi_env env, napi_callback_info info) { NAPI_CALL(env, napi_typeof(env, func, &func_type)); + napi_value resource_name; + NAPI_CALL(env, napi_create_string_utf8(env, "test", -1, &resource_name)); + + napi_async_context context; + NAPI_CALL(env, napi_async_init(env, func, resource_name, &context)); + napi_value result; if (func_type == napi_function) { - NAPI_CALL(env, - napi_make_callback(env, recv, func, argv.size(), argv.data(), &result)); + NAPI_CALL(env, napi_make_callback( + env, context, recv, func, argv.size(), argv.data(), &result)); } else { NAPI_ASSERT(env, false, "Unexpected argument type"); } + NAPI_CALL(env, napi_async_destroy(env, context)); + return result; } diff --git a/test/addons-napi/test_make_callback/test.js b/test/addons-napi/test_make_callback/test.js index c4f24872bdb78e..0e94caf1d975f2 100644 --- a/test/addons-napi/test_make_callback/test.js +++ b/test/addons-napi/test_make_callback/test.js @@ -2,12 +2,12 @@ const common = require('../../common'); const assert = require('assert'); +const async_hooks = require('async_hooks'); const vm = require('vm'); const binding = require(`./build/${common.buildType}/binding`); const makeCallback = binding.makeCallback; function myMultiArgFunc(arg1, arg2, arg3) { - console.log(`MyFunc was called with ${arguments.length} arguments`); assert.strictEqual(arg1, 1); assert.strictEqual(arg2, 2); assert.strictEqual(arg3, 3); @@ -81,3 +81,40 @@ function endpoint($Object) { } assert.strictEqual(Object, makeCallback(process, forward, endpoint)); + +// Check async hooks integration using async context. +const hook_result = { + id: null, + init_called: false, + before_called: false, + after_called: false, + destroy_called: false, +}; +const test_hook = async_hooks.createHook({ + init: (id, type) => { + if (type === 'test') { + hook_result.id = id; + hook_result.init_called = true; + } + }, + before: (id) => { + if (id === hook_result.id) hook_result.before_called = true; + }, + after: (id) => { + if (id === hook_result.id) hook_result.after_called = true; + }, + destroy: (id) => { + if (id === hook_result.id) hook_result.destroy_called = true; + }, +}); + +test_hook.enable(); +makeCallback(process, function() {}); + +assert.strictEqual(hook_result.init_called, true); +assert.strictEqual(hook_result.before_called, true); +assert.strictEqual(hook_result.after_called, true); +setImmediate(() => { + assert.strictEqual(hook_result.destroy_called, true); + test_hook.disable(); +}); diff --git a/test/addons-napi/test_make_callback_recurse/binding.cc b/test/addons-napi/test_make_callback_recurse/binding.cc index ce75adc5b87b11..1e0c16c80ee664 100644 --- a/test/addons-napi/test_make_callback_recurse/binding.cc +++ b/test/addons-napi/test_make_callback_recurse/binding.cc @@ -12,8 +12,8 @@ napi_value MakeCallback(napi_env env, napi_callback_info info) { napi_value recv = args[0]; napi_value func = args[1]; - napi_make_callback(env, - recv, func, 0 /* argc */, nullptr /* argv */, nullptr /* result */); + napi_make_callback(env, nullptr /* async_context */, + recv, func, 0 /* argc */, nullptr /* argv */, nullptr /* result */); return recv; } From ba96c8f23e502edf4c31d92faf6c90603d4ef697 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Thu, 14 Sep 2017 19:30:01 -0400 Subject: [PATCH 074/145] test: don't skip when common.mustCall() is pending The test parallel/test-dgram-multicast-set-interface.js was calling common.skip() on hosts that do not support IPv6. However, by this point, there were several outstanding common.mustCall() invocations. The process.exit() in common.skip() triggered those common.mustCall()s as errors. Fixes: https://github.com/nodejs/node/issues/15419 PR-URL: https://github.com/nodejs/node/pull/15421 Reviewed-By: James M Snell Reviewed-By: Ruben Bridgewater Reviewed-By: Rich Trott Reviewed-By: Daniel Bevenius Reviewed-By: Luigi Pinca Reviewed-By: Brian White Reviewed-By: Sakthipriyan Vairamani --- test/parallel/test-dgram-multicast-set-interface.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/test/parallel/test-dgram-multicast-set-interface.js b/test/parallel/test-dgram-multicast-set-interface.js index 4be6b15dba1969..c065683f53c7fd 100644 --- a/test/parallel/test-dgram-multicast-set-interface.js +++ b/test/parallel/test-dgram-multicast-set-interface.js @@ -72,10 +72,11 @@ const dgram = require('dgram'); })); } -if (!common.hasIPv6) { - common.skip('Skipping udp6 tests, no IPv6 support.'); +// If IPv6 is not supported, skip the rest of the test. However, don't call +// common.skip(), which calls process.exit() while there is outstanding +// common.mustCall() activity. +if (!common.hasIPv6) return; -} { const socket = dgram.createSocket('udp6'); From b61220ed84a121fbc74811cf45633f5c9746faa8 Mon Sep 17 00:00:00 2001 From: Anatoli Papirovski Date: Thu, 14 Sep 2017 14:02:54 -0400 Subject: [PATCH 075/145] http2: fix subsequent end calls to not throw Calling Http2ServerResponse.end multiple times should never cause the code to throw an error, subsequent calls should instead return false. Fix behaviour to match http1. Fixes: https://github.com/nodejs/node/issues/15385 PR-URL: https://github.com/nodejs/node/pull/15414 Reviewed-By: James M Snell Reviewed-By: Matteo Collina --- lib/internal/http2/compat.js | 7 +++---- test/parallel/test-http2-compat-serverresponse-end.js | 5 ++++- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/lib/internal/http2/compat.js b/lib/internal/http2/compat.js index c36b887f178c8d..15e7358627dd8d 100644 --- a/lib/internal/http2/compat.js +++ b/lib/internal/http2/compat.js @@ -466,14 +466,13 @@ class Http2ServerResponse extends Stream { cb = encoding; encoding = 'utf8'; } + if (stream === undefined || stream.finished === true) { + return false; + } if (chunk !== null && chunk !== undefined) { this.write(chunk, encoding); } - if (stream === undefined) { - return; - } - if (typeof cb === 'function') { stream.once('finish', cb); } diff --git a/test/parallel/test-http2-compat-serverresponse-end.js b/test/parallel/test-http2-compat-serverresponse-end.js index 6c07f6d83e62e0..92a0fab4e0a49d 100644 --- a/test/parallel/test-http2-compat-serverresponse-end.js +++ b/test/parallel/test-http2-compat-serverresponse-end.js @@ -4,7 +4,7 @@ const { mustCall, mustNotCall, hasCrypto, skip } = require('../common'); if (!hasCrypto) skip('missing crypto'); -const { strictEqual } = require('assert'); +const { doesNotThrow, strictEqual } = require('assert'); const { createServer, connect, @@ -19,6 +19,9 @@ const { // but may be invoked repeatedly without throwing errors. const server = createServer(mustCall((request, response) => { strictEqual(response.closed, false); + response.on('finish', mustCall(() => process.nextTick( + mustCall(() => doesNotThrow(() => response.end('test', mustNotCall()))) + ))); response.end(mustCall(() => { server.close(); })); From 526e78f5cd47accd4d32b8be4dcb86a2ce367c04 Mon Sep 17 00:00:00 2001 From: Sampson Gao Date: Mon, 11 Sep 2017 09:57:38 -0400 Subject: [PATCH 076/145] n-api: add optional string length parameters PR-URL: https://github.com/nodejs/node/pull/15343 Reviewed-By: Michael Dawson Reviewed-By: James M Snell Reviewed-By: Franziska Hinkelmann --- doc/api/n-api.md | 15 ++++++++++- src/node_api.cc | 26 ++++++++++++++++--- src/node_api.h | 6 ++++- test/addons-napi/4_object_factory/binding.c | 2 +- test/addons-napi/5_function_factory/binding.c | 6 ++--- test/addons-napi/6_object_wrap/myobject.cc | 4 +-- test/addons-napi/7_factory_wrap/binding.cc | 2 +- test/addons-napi/7_factory_wrap/myobject.cc | 4 +-- .../addons-napi/8_passing_wrapped/myobject.cc | 3 ++- test/addons-napi/test_constructor/binding.gyp | 4 +++ test/addons-napi/test_constructor/test2.js | 8 ++++++ .../test_constructor/test_constructor.c | 2 +- .../test_constructor/test_constructor_name.c | 23 ++++++++++++++++ .../test_env_sharing/compare_env.c | 2 +- test/addons-napi/test_fatal/test2.js | 18 +++++++++++++ test/addons-napi/test_fatal/test_fatal.c | 8 +++++- test/addons-napi/test_function/test.js | 11 +++++--- .../addons-napi/test_function/test_function.c | 23 +++++++++++++--- .../addons-napi/test_make_callback/binding.cc | 2 +- .../test_make_callback_recurse/binding.cc | 2 +- 20 files changed, 141 insertions(+), 30 deletions(-) create mode 100644 test/addons-napi/test_constructor/test2.js create mode 100644 test/addons-napi/test_constructor/test_constructor_name.c create mode 100644 test/addons-napi/test_fatal/test2.js diff --git a/doc/api/n-api.md b/doc/api/n-api.md index 00bba55a4c9e3d..42db6e3a9e9535 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -552,11 +552,18 @@ thrown to immediately terminate the process. added: v8.2.0 --> ```C -NAPI_NO_RETURN void napi_fatal_error(const char* location, const char* message); +NAPI_NO_RETURN void napi_fatal_error(const char* location, + size_t location_len, + const char* message, + size_t message_len); ``` - `[in] location`: Optional location at which the error occurred. +- `[in] location_len`: The length of the location in bytes, or -1 if it is +null-terminated. - `[in] message`: The message associated with the error. +- `[in] message_len`: The length of the message in bytes, or -1 if it is +null-terminated. The function call does not return, the process will be terminated. @@ -1248,6 +1255,7 @@ added: v8.0.0 ```C napi_status napi_create_function(napi_env env, const char* utf8name, + size_t length, napi_callback cb, void* data, napi_value* result) @@ -1256,6 +1264,8 @@ napi_status napi_create_function(napi_env env, - `[in] env`: The environment that the API is invoked under. - `[in] utf8name`: A string representing the name of the function encoded as UTF8. +- `[in] length`: The length of the utf8name in bytes, or -1 if it is +null-terminated. - `[in] cb`: A function pointer to the native function to be invoked when the created function is invoked from JavaScript. - `[in] data`: Optional arbitrary context data to be passed into the native @@ -3026,6 +3036,7 @@ added: v8.0.0 ```C napi_status napi_define_class(napi_env env, const char* utf8name, + size_t length, napi_callback constructor, void* data, size_t property_count, @@ -3037,6 +3048,8 @@ napi_status napi_define_class(napi_env env, - `[in] utf8name`: Name of the JavaScript constructor function; this is not required to be the same as the C++ class name, though it is recommended for clarity. + - `[in] length`: The length of the utf8name in bytes, or -1 if it is +null-terminated. - `[in] constructor`: Callback function that handles constructing instances of the class. (This should be a static method on the class, not an actual C++ constructor function.) diff --git a/src/node_api.cc b/src/node_api.cc index 724d5c3ee96701..cedf5ad7a458eb 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -933,12 +933,29 @@ napi_status napi_get_last_error_info(napi_env env, } NAPI_NO_RETURN void napi_fatal_error(const char* location, - const char* message) { - node::FatalError(location, message); + size_t location_len, + const char* message, + size_t message_len) { + char* location_string = const_cast(location); + char* message_string = const_cast(message); + if (location_len != -1) { + location_string = reinterpret_cast( + malloc(location_len * sizeof(char) + 1)); + strncpy(location_string, location, location_len); + location_string[location_len] = '\0'; + } + if (message_len != -1) { + message_string = reinterpret_cast( + malloc(message_len * sizeof(char) + 1)); + strncpy(message_string, message, message_len); + message_string[message_len] = '\0'; + } + node::FatalError(location_string, message_string); } napi_status napi_create_function(napi_env env, const char* utf8name, + size_t length, napi_callback cb, void* callback_data, napi_value* result) { @@ -965,7 +982,7 @@ napi_status napi_create_function(napi_env env, if (utf8name != nullptr) { v8::Local name_string; - CHECK_NEW_FROM_UTF8(env, name_string, utf8name); + CHECK_NEW_FROM_UTF8_LEN(env, name_string, utf8name, length); return_value->SetName(name_string); } @@ -976,6 +993,7 @@ napi_status napi_create_function(napi_env env, napi_status napi_define_class(napi_env env, const char* utf8name, + size_t length, napi_callback constructor, void* callback_data, size_t property_count, @@ -997,7 +1015,7 @@ napi_status napi_define_class(napi_env env, isolate, v8impl::FunctionCallbackWrapper::Invoke, cbdata); v8::Local name_string; - CHECK_NEW_FROM_UTF8(env, name_string, utf8name); + CHECK_NEW_FROM_UTF8_LEN(env, name_string, utf8name, length); tpl->SetClassName(name_string); size_t static_property_count = 0; diff --git a/src/node_api.h b/src/node_api.h index e1a40983a9907d..82f2e1900e2fe4 100644 --- a/src/node_api.h +++ b/src/node_api.h @@ -109,7 +109,9 @@ napi_get_last_error_info(napi_env env, const napi_extended_error_info** result); NAPI_EXTERN NAPI_NO_RETURN void napi_fatal_error(const char* location, - const char* message); + size_t location_len, + const char* message, + size_t message_len); // Getters for defined singletons NAPI_EXTERN napi_status napi_get_undefined(napi_env env, napi_value* result); @@ -154,6 +156,7 @@ NAPI_EXTERN napi_status napi_create_symbol(napi_env env, napi_value* result); NAPI_EXTERN napi_status napi_create_function(napi_env env, const char* utf8name, + size_t length, napi_callback cb, void* data, napi_value* result); @@ -336,6 +339,7 @@ NAPI_EXTERN napi_status napi_get_new_target(napi_env env, NAPI_EXTERN napi_status napi_define_class(napi_env env, const char* utf8name, + size_t length, napi_callback constructor, void* data, size_t property_count, diff --git a/test/addons-napi/4_object_factory/binding.c b/test/addons-napi/4_object_factory/binding.c index dedfd288f7ec0f..38b8ec8e1cab48 100644 --- a/test/addons-napi/4_object_factory/binding.c +++ b/test/addons-napi/4_object_factory/binding.c @@ -16,7 +16,7 @@ napi_value CreateObject(napi_env env, napi_callback_info info) { napi_value Init(napi_env env, napi_value exports) { NAPI_CALL(env, - napi_create_function(env, "exports", CreateObject, NULL, &exports)); + 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 c8751f1fa918a7..8cc41f6aac5c3d 100644 --- a/test/addons-napi/5_function_factory/binding.c +++ b/test/addons-napi/5_function_factory/binding.c @@ -4,21 +4,19 @@ 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) { napi_value fn; NAPI_CALL(env, - napi_create_function(env, "theFunction", MyFunction, NULL, &fn)); - + napi_create_function(env, "theFunction", -1, MyFunction, NULL, &fn)); return fn; } napi_value Init(napi_env env, napi_value exports) { NAPI_CALL(env, - napi_create_function(env, "exports", CreateFunction, NULL, &exports)); + napi_create_function(env, "exports", -1, CreateFunction, NULL, &exports)); return exports; } diff --git a/test/addons-napi/6_object_wrap/myobject.cc b/test/addons-napi/6_object_wrap/myobject.cc index 90815253add651..aca91877d3a2ae 100644 --- a/test/addons-napi/6_object_wrap/myobject.cc +++ b/test/addons-napi/6_object_wrap/myobject.cc @@ -22,8 +22,8 @@ void MyObject::Init(napi_env env, napi_value exports) { }; napi_value cons; - NAPI_CALL_RETURN_VOID(env, - napi_define_class(env, "MyObject", New, nullptr, 3, properties, &cons)); + NAPI_CALL_RETURN_VOID(env, napi_define_class( + env, "MyObject", -1, New, nullptr, 3, properties, &cons)); NAPI_CALL_RETURN_VOID(env, napi_create_reference(env, cons, 1, &constructor)); diff --git a/test/addons-napi/7_factory_wrap/binding.cc b/test/addons-napi/7_factory_wrap/binding.cc index 551bfef15dbc87..c8fca4d536e74c 100644 --- a/test/addons-napi/7_factory_wrap/binding.cc +++ b/test/addons-napi/7_factory_wrap/binding.cc @@ -16,7 +16,7 @@ napi_value Init(napi_env env, napi_value exports) { NAPI_CALL(env, MyObject::Init(env)); NAPI_CALL(env, - napi_create_function(env, "exports", CreateObject, NULL, &exports)); + napi_create_function(env, "exports", -1, CreateObject, NULL, &exports)); return exports; } diff --git a/test/addons-napi/7_factory_wrap/myobject.cc b/test/addons-napi/7_factory_wrap/myobject.cc index c6d538a7cefbc6..4e1d79c1febc17 100644 --- a/test/addons-napi/7_factory_wrap/myobject.cc +++ b/test/addons-napi/7_factory_wrap/myobject.cc @@ -21,8 +21,8 @@ napi_status MyObject::Init(napi_env env) { }; napi_value cons; - status = - napi_define_class(env, "MyObject", New, nullptr, 1, properties, &cons); + status = napi_define_class( + env, "MyObject", -1, New, nullptr, 1, properties, &cons); if (status != napi_ok) return status; status = napi_create_reference(env, cons, 1, &constructor); diff --git a/test/addons-napi/8_passing_wrapped/myobject.cc b/test/addons-napi/8_passing_wrapped/myobject.cc index 0c24d7696e66ec..19cc7dd2a29493 100644 --- a/test/addons-napi/8_passing_wrapped/myobject.cc +++ b/test/addons-napi/8_passing_wrapped/myobject.cc @@ -17,7 +17,8 @@ napi_status MyObject::Init(napi_env env) { napi_status status; napi_value cons; - status = napi_define_class(env, "MyObject", New, nullptr, 0, nullptr, &cons); + status = napi_define_class( + env, "MyObject", -1, New, nullptr, 0, nullptr, &cons); if (status != napi_ok) return status; status = napi_create_reference(env, cons, 1, &constructor); diff --git a/test/addons-napi/test_constructor/binding.gyp b/test/addons-napi/test_constructor/binding.gyp index 55140e7c379f02..1945a9fd5a711e 100644 --- a/test/addons-napi/test_constructor/binding.gyp +++ b/test/addons-napi/test_constructor/binding.gyp @@ -3,6 +3,10 @@ { "target_name": "test_constructor", "sources": [ "test_constructor.c" ] + }, + { + "target_name": "test_constructor_name", + "sources": [ "test_constructor_name.c" ] } ] } diff --git a/test/addons-napi/test_constructor/test2.js b/test/addons-napi/test_constructor/test2.js new file mode 100644 index 00000000000000..64c03cbc684ac3 --- /dev/null +++ b/test/addons-napi/test_constructor/test2.js @@ -0,0 +1,8 @@ +'use strict'; +const common = require('../../common'); +const assert = require('assert'); + +// Testing api calls for a constructor that defines properties +const TestConstructor = + require(`./build/${common.buildType}/test_constructor_name`); +assert.strictEqual(TestConstructor.name, 'MyObject'); diff --git a/test/addons-napi/test_constructor/test_constructor.c b/test/addons-napi/test_constructor/test_constructor.c index 73de5ad2877740..d742f2bcd1707b 100644 --- a/test/addons-napi/test_constructor/test_constructor.c +++ b/test/addons-napi/test_constructor/test_constructor.c @@ -77,7 +77,7 @@ napi_value Init(napi_env env, napi_value exports) { }; napi_value cons; - NAPI_CALL(env, napi_define_class(env, "MyObject", New, + NAPI_CALL(env, napi_define_class(env, "MyObject", -1, New, NULL, sizeof(properties)/sizeof(*properties), properties, &cons)); NAPI_CALL(env, napi_create_reference(env, cons, 1, &constructor_)); diff --git a/test/addons-napi/test_constructor/test_constructor_name.c b/test/addons-napi/test_constructor/test_constructor_name.c new file mode 100644 index 00000000000000..b178e80f49f489 --- /dev/null +++ b/test/addons-napi/test_constructor/test_constructor_name.c @@ -0,0 +1,23 @@ +#include +#include "../common.h" + +napi_ref constructor_; + +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) { + 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; +} + +NAPI_MODULE(addon, Init) diff --git a/test/addons-napi/test_env_sharing/compare_env.c b/test/addons-napi/test_env_sharing/compare_env.c index b7e789ac499317..da984b68f53f3e 100644 --- a/test/addons-napi/test_env_sharing/compare_env.c +++ b/test/addons-napi/test_env_sharing/compare_env.c @@ -15,7 +15,7 @@ napi_value compare(napi_env env, napi_callback_info info) { } napi_value Init(napi_env env, napi_value exports) { - NAPI_CALL(env, napi_create_function(env, "exports", compare, NULL, &exports)); + NAPI_CALL(env, napi_create_function(env, "exports", -1, compare, NULL, &exports)); return exports; } diff --git a/test/addons-napi/test_fatal/test2.js b/test/addons-napi/test_fatal/test2.js new file mode 100644 index 00000000000000..b9bde8f13016cc --- /dev/null +++ b/test/addons-napi/test_fatal/test2.js @@ -0,0 +1,18 @@ +'use strict'; +const common = require('../../common'); +const assert = require('assert'); +const child_process = require('child_process'); +const test_fatal = require(`./build/${common.buildType}/test_fatal`); + +// Test in a child process because the test code will trigger a fatal error +// that crashes the process. +if (process.argv[2] === 'child') { + test_fatal.TestStringLength(); + return; +} + +const p = child_process.spawnSync( + process.execPath, [ '--napi-modules', __filename, 'child' ]); +assert.ifError(p.error); +assert.ok(p.stderr.toString().includes( + 'FATAL ERROR: test_fatal::Test fatal message')); diff --git a/test/addons-napi/test_fatal/test_fatal.c b/test/addons-napi/test_fatal/test_fatal.c index 78d791cc91f0a3..6d8fa6ff8613f2 100644 --- a/test/addons-napi/test_fatal/test_fatal.c +++ b/test/addons-napi/test_fatal/test_fatal.c @@ -2,13 +2,19 @@ #include "../common.h" napi_value Test(napi_env env, napi_callback_info info) { - napi_fatal_error("test_fatal::Test", "fatal message"); + napi_fatal_error("test_fatal::Test", -1, "fatal message", -1); + return NULL; +} + +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) { napi_property_descriptor properties[] = { DECLARE_NAPI_PROPERTY("Test", Test), + DECLARE_NAPI_PROPERTY("TestStringLength", TestStringLength), }; NAPI_CALL(env, napi_define_properties( diff --git a/test/addons-napi/test_function/test.js b/test/addons-napi/test_function/test.js index bdb9133adf9346..752e9965b23039 100644 --- a/test/addons-napi/test_function/test.js +++ b/test/addons-napi/test_function/test.js @@ -9,20 +9,23 @@ const test_function = require(`./build/${common.buildType}/test_function`); function func1() { return 1; } -assert.strictEqual(test_function.Test(func1), 1); +assert.strictEqual(test_function.TestCall(func1), 1); function func2() { console.log('hello world!'); return null; } -assert.strictEqual(test_function.Test(func2), null); +assert.strictEqual(test_function.TestCall(func2), null); function func3(input) { return input + 1; } -assert.strictEqual(test_function.Test(func3, 1), 2); +assert.strictEqual(test_function.TestCall(func3, 1), 2); function func4(input) { return func3(input); } -assert.strictEqual(test_function.Test(func4, 1), 2); +assert.strictEqual(test_function.TestCall(func4, 1), 2); + +assert.strictEqual(test_function.TestName.name, 'Name'); +assert.strictEqual(test_function.TestNameShort.name, 'Name_'); diff --git a/test/addons-napi/test_function/test_function.c b/test/addons-napi/test_function/test_function.c index 76a8b05e036f32..99a699bfea0c87 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 Test(napi_env env, napi_callback_info info) { +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,10 +26,25 @@ napi_value Test(napi_env env, napi_callback_info info) { return result; } +void TestFunctionName(napi_env env, napi_callback_info info) {} + napi_value Init(napi_env env, napi_value exports) { - napi_value fn; - NAPI_CALL(env, napi_create_function(env, NULL, Test, NULL, &fn)); - NAPI_CALL(env, napi_set_named_property(env, exports, "Test", fn)); + napi_value fn1; + NAPI_CALL(env, napi_create_function( + env, NULL, -1, TestCallFunction, NULL, &fn1)); + + napi_value fn2; + NAPI_CALL(env, napi_create_function( + env, "Name", -1, TestFunctionName, NULL, &fn2)); + + napi_value fn3; + NAPI_CALL(env, napi_create_function( + env, "Name_extra", 5, TestFunctionName, NULL, &fn3)); + + NAPI_CALL(env, napi_set_named_property(env, exports, "TestCall", fn1)); + NAPI_CALL(env, napi_set_named_property(env, exports, "TestName", fn2)); + NAPI_CALL(env, napi_set_named_property(env, exports, "TestNameShort", fn3)); + return exports; } diff --git a/test/addons-napi/test_make_callback/binding.cc b/test/addons-napi/test_make_callback/binding.cc index df2c4dc672ea47..8a6d94985c1962 100644 --- a/test/addons-napi/test_make_callback/binding.cc +++ b/test/addons-napi/test_make_callback/binding.cc @@ -45,7 +45,7 @@ napi_value MakeCallback(napi_env env, napi_callback_info info) { napi_value Init(napi_env env, napi_value exports) { napi_value fn; - NAPI_CALL(env, napi_create_function(env, NULL, MakeCallback, NULL, &fn)); + NAPI_CALL(env, napi_create_function(env, NULL, -1, MakeCallback, NULL, &fn)); NAPI_CALL(env, napi_set_named_property(env, exports, "makeCallback", fn)); return exports; } diff --git a/test/addons-napi/test_make_callback_recurse/binding.cc b/test/addons-napi/test_make_callback_recurse/binding.cc index 1e0c16c80ee664..212c9ec4022fa3 100644 --- a/test/addons-napi/test_make_callback_recurse/binding.cc +++ b/test/addons-napi/test_make_callback_recurse/binding.cc @@ -20,7 +20,7 @@ napi_value MakeCallback(napi_env env, napi_callback_info info) { napi_value Init(napi_env env, napi_value exports) { napi_value fn; - NAPI_CALL(env, napi_create_function(env, NULL, MakeCallback, NULL, &fn)); + NAPI_CALL(env, napi_create_function(env, NULL, -1, MakeCallback, NULL, &fn)); NAPI_CALL(env, napi_set_named_property(env, exports, "makeCallback", fn)); return exports; } From cd3a8e8832b3fd1a122bf177ef9308d1502ef48b Mon Sep 17 00:00:00 2001 From: Gabriel Schulhof Date: Fri, 18 Aug 2017 13:30:05 +0300 Subject: [PATCH 077/145] n-api: remove n-api module loading flag Remove the command line flag that was needed for N-API module loading. Re: https://github.com/nodejs/vm/issues/9 PR-URL: https://github.com/nodejs/node/pull/14902 Reviewed-By: Refael Ackermann Reviewed-By: Colin Ihrig Reviewed-By: Anna Henningsen Reviewed-By: Matteo Collina Reviewed-By: Michael Dawson Reviewed-By: James M Snell Reviewed-By: Hitesh Kanwathirtha --- doc/api/cli.md | 9 ---- doc/api/n-api.md | 8 ---- src/env-inl.h | 1 + src/env.cc | 6 +++ src/env.h | 2 + src/node.cc | 48 +++++++------------ src/node_api.cc | 20 +------- test/addons-napi/test_async/test.js | 2 +- test/addons-napi/test_fatal/test.js | 2 +- .../addons-napi/test_function/test_function.c | 4 +- test/addons-napi/test_warning/binding.gyp | 12 +++++ test/addons-napi/test_warning/test.js | 18 +++++++ test/addons-napi/test_warning/test_warning.c | 11 +++++ test/addons-napi/test_warning/test_warning2.c | 11 +++++ test/addons-napi/testcfg.py | 2 +- 15 files changed, 86 insertions(+), 70 deletions(-) create mode 100644 test/addons-napi/test_warning/binding.gyp create mode 100644 test/addons-napi/test_warning/test.js create mode 100644 test/addons-napi/test_warning/test_warning.c create mode 100644 test/addons-napi/test_warning/test_warning2.c diff --git a/doc/api/cli.md b/doc/api/cli.md index e3727c0b248fb7..db56a45861a578 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -178,14 +178,6 @@ added: v8.4.0 Enable the experimental `'http2'` module. -### `--napi-modules` - - -Enable loading native modules compiled with the ABI-stable Node.js API (N-API) -(experimental). - ### `--abort-on-uncaught-exception` Node.js includes an out-of-process debugging utility accessible via a -[TCP-based protocol][] and built-in debugging client. To use it, start Node.js +[V8 Inspector][] and built-in debugging client. To use it, start Node.js with the `inspect` argument followed by the path to the script to debug; a prompt will be displayed indicating successful launch of the debugger: @@ -194,4 +194,4 @@ at the end of the URL is generated on the fly, it varies in different debugging sessions.) [Chrome Debugging Protocol]: https://chromedevtools.github.io/debugger-protocol-viewer/ -[TCP-based protocol]: #debugger_tcp_based_protocol +[V8 Inspector]: #debugger_v8_inspector_integration_for_node_js diff --git a/doc/api/deprecations.md b/doc/api/deprecations.md index 5e0b63b13ee13e..96b8930834a2cb 100644 --- a/doc/api/deprecations.md +++ b/doc/api/deprecations.md @@ -660,7 +660,7 @@ Type: Runtime [`os.networkInterfaces`]: os.html#os_os_networkinterfaces [`os.tmpdir()`]: os.html#os_os_tmpdir [`punycode`]: punycode.html -[`require.extensions`]: globals.html#globals_require_extensions +[`require.extensions`]: modules.html#modules_require_extensions [`tls.CryptoStream`]: tls.html#tls_class_cryptostream [`tls.SecureContext`]: tls.html#tls_tls_createsecurecontext_options [`tls.SecurePair`]: tls.html#tls_class_securepair diff --git a/doc/api/http2.md b/doc/api/http2.md index 43813feffdfb80..6f0f0b41bafa1e 100644 --- a/doc/api/http2.md +++ b/doc/api/http2.md @@ -1505,8 +1505,7 @@ added: v8.4.0 * `options` {Object} * `allowHTTP1` {boolean} Incoming client connections that do not support HTTP/2 will be downgraded to HTTP/1.x when set to `true`. The default value - is `false`. See the [`'unknownProtocol'`][] event. See [ALPN - negotiation](#alpn-negotiation). + is `false`. See the [`'unknownProtocol'`][] event. See [ALPN negotiation][]. * `maxDeflateDynamicTableSize` {number} Sets the maximum dynamic table size for deflating header fields. Defaults to 4Kib. * `maxSendHeaderBlockLength` {number} Sets the maximum allowed size for a @@ -2019,9 +2018,9 @@ added: v8.4.0 * `error` {Error} -Calls `destroy()` on the [`Http2Stream`][] that received the [`ServerRequest`][]. If -`error` is provided, an `'error'` event is emitted and `error` is passed as an -argument to any listeners on the event. +Calls `destroy()` on the [`Http2Stream`][] that received +the [`Http2ServerRequest`][]. If `error` is provided, an `'error'` event +is emitted and `error` is passed as an argument to any listeners on the event. It does nothing if the stream was already destroyed. @@ -2655,7 +2654,7 @@ will result in a [`TypeError`][] being thrown. added: v8.4.0 --> -Call [`stream.pushStream()`][] with the given headers, and wraps the +Call [`http2stream.pushStream()`][] with the given headers, and wraps the given newly created [`Http2Stream`] on `Http2ServerRespose`. The callback will be called with an error with code `ERR_HTTP2_STREAM_CLOSED` @@ -2667,7 +2666,7 @@ if the stream is closed. [HTTP/2]: https://tools.ietf.org/html/rfc7540 [HTTPS]: https.html [Headers Object]: #http2_headers_object -[Http2Session and Sockets]: #http2_http2sesion_and_sockets +[Http2Session and Sockets]: #http2_http2session_and_sockets [Readable Stream]: stream.html#stream_class_stream_readable [Settings Object]: #http2_settings_object [Using options.selectPadding]: #http2_using_options_selectpadding @@ -2678,14 +2677,15 @@ if the stream is closed. [`ClientHttp2Stream`]: #http2_class_clienthttp2stream [`Duplex`]: stream.html#stream_class_stream_duplex [`EventEmitter`]: events.html#events_class_eventemitter +[`Http2ServerRequest`]: #http2_class_http2_http2serverrequest [`Http2Stream`]: #http2_class_http2stream [`ServerHttp2Stream`]: #http2_class_serverhttp2stream -[`ServerRequest`]: #http2_class_server_request [`TypeError`]: errors.html#errors_class_typeerror [`http2.SecureServer`]: #http2_class_http2secureserver [`http2.createSecureServer()`]: #http2_createsecureserver_options_onrequesthandler [`http2.Server`]: #http2_class_http2server [`http2.createServer()`]: #http2_createserver_options_onrequesthandler +[`http2stream.pushStream()`]: #http2_http2stream_pushstream_headers_options_callback [`net.Socket`]: net.html#net_class_net_socket [`request.socket.getPeerCertificate()`]: tls.html#tls_tlssocket_getpeercertificate_detailed [`response.end()`]: #http2_response_end_data_encoding_callback @@ -2695,7 +2695,6 @@ if the stream is closed. [`response.write(data, encoding)`]: http.html#http_response_write_chunk_encoding_callback [`response.writeContinue()`]: #http2_response_writecontinue [`response.writeHead()`]: #http2_response_writehead_statuscode_statusmessage_headers -[`stream.pushStream()`]: #http2_stream-pushstream [`tls.TLSSocket`]: tls.html#tls_class_tls_tlssocket [`tls.createServer()`]: tls.html#tls_tls_createserver_options_secureconnectionlistener [error code]: #error_codes diff --git a/doc/api/process.md b/doc/api/process.md index dd731bf96b49a1..ea474cf30bf576 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -399,7 +399,7 @@ It is important to take note of the following: called asynchronously and therefore unable to correct the underlying problem. *Note*: Windows does not support sending signals, but Node.js offers some -emulation with [`process.kill()`][], and [`ChildProcess.kill()`][]. Sending +emulation with [`process.kill()`][], and [`subprocess.kill()`][]. Sending signal `0` can be used to test for the existence of a process. Sending `SIGINT`, `SIGTERM`, and `SIGKILL` cause the unconditional termination of the target process. @@ -1827,9 +1827,9 @@ cases: [`'message'`]: child_process.html#child_process_event_message [`'rejectionHandled'`]: #process_event_rejectionhandled [`'uncaughtException'`]: #process_event_uncaughtexception -[`ChildProcess.disconnect()`]: child_process.html#child_process_child_disconnect -[`ChildProcess.kill()`]: child_process.html#child_process_child_kill_signal -[`ChildProcess.send()`]: child_process.html#child_process_child_send_message_sendhandle_options_callback +[`ChildProcess.disconnect()`]: child_process.html#child_process_subprocess_disconnect +[`subprocess.kill()`]: child_process.html#child_process_subprocess_kill_signal +[`ChildProcess.send()`]: child_process.html#child_process_subprocess_send_message_sendhandle_options_callback [`ChildProcess`]: child_process.html#child_process_class_childprocess [`Error`]: errors.html#errors_class_error [`EventEmitter`]: events.html#events_class_eventemitter diff --git a/doc/api/stream.md b/doc/api/stream.md index 17678aba28b6f5..8aaa4ff2e65478 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -2210,14 +2210,14 @@ contain multi-byte characters. [TCP sockets]: net.html#net_class_net_socket [Transform]: #stream_class_stream_transform [Writable]: #stream_class_stream_writable -[child process stdin]: child_process.html#child_process_child_stdin -[child process stdout and stderr]: child_process.html#child_process_child_stdout +[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 [fs read streams]: fs.html#fs_class_fs_readstream [fs write streams]: fs.html#fs_class_fs_writestream [http-incoming-message]: http.html#http_class_http_incomingmessage [zlib]: zlib.html -[hwm-gotcha]: #stream_highWaterMark_discrepency_after_calling_readable_setencoding +[hwm-gotcha]: #stream_highwatermark_discrepency_after_calling_readable_setencoding [Readable]: #stream_class_stream_readable [stream-_flush]: #stream_transform_flush_callback [stream-_read]: #stream_readable_read_size_1 From 9049f09e0f53cb40d4cd03f2a4f95056a19ebae4 Mon Sep 17 00:00:00 2001 From: Sebastiaan Deckers Date: Mon, 10 Jul 2017 20:54:06 -0400 Subject: [PATCH 079/145] tools: enforce consistent spacing inside braces PR-URL: https://github.com/nodejs/node/pull/14162 Reviewed-By: Vse Mozhet Byt Reviewed-By: Refael Ackermann Reviewed-By: Timothy Gu Reviewed-By: James M Snell --- .eslintignore | 1 + .eslintrc.yaml | 7 ++++--- doc/.eslintrc.yaml | 2 -- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.eslintignore b/.eslintignore index 38d3367e9d1779..a681716c667576 100644 --- a/.eslintignore +++ b/.eslintignore @@ -4,6 +4,7 @@ test/addons/??_*/ test/fixtures test/tmp*/ tools/eslint +tools/icu node_modules benchmark/tmp/ doc/**/*.js diff --git a/.eslintrc.yaml b/.eslintrc.yaml index 6643b4649d0da5..b68d26574658c5 100644 --- a/.eslintrc.yaml +++ b/.eslintrc.yaml @@ -141,6 +141,7 @@ rules: }] no-tabs: error no-trailing-spaces: error + object-curly-spacing: [error, always] one-var-declaration-per-line: error operator-linebreak: [error, after] quotes: [error, single, avoid-escape] @@ -148,9 +149,9 @@ rules: semi-spacing: error space-before-blocks: [error, always] space-before-function-paren: [error, { - "anonymous": "never", - "named": "never", - "asyncArrow": "always" + anonymous: never, + named: never, + asyncArrow: always }] space-in-parens: [error, never] space-infix-ops: error diff --git a/doc/.eslintrc.yaml b/doc/.eslintrc.yaml index 1c5177d90642ad..b269eb14e625f4 100644 --- a/doc/.eslintrc.yaml +++ b/doc/.eslintrc.yaml @@ -1,8 +1,6 @@ ## Docs-specific linter rules rules: - object-curly-spacing: [error, always] - # ease some restrictions in doc examples no-restricted-properties: off no-undef: off From 91e96d8f08d3a3d65679ad0cbcea86a94510ec4b Mon Sep 17 00:00:00 2001 From: James M Snell Date: Wed, 20 Sep 2017 10:36:14 -0700 Subject: [PATCH 080/145] lib,src: fix consistent spacing inside braces PR-URL: #14162 Reviewed-By: Vse Mozhet Byt Reviewed-By: Refael Ackermann Reviewed-By: Timothy Gu Reviewed-By: James M Snell --- benchmark/_test-double-benchmarker.js | 2 +- benchmark/crypto/aes-gcm-throughput.js | 2 +- benchmark/events/ee-add-remove.js | 2 +- benchmark/events/ee-emit-multi-args.js | 2 +- benchmark/events/ee-emit.js | 2 +- .../events/ee-listener-count-on-prototype.js | 2 +- benchmark/events/ee-listeners-many.js | 2 +- benchmark/events/ee-listeners.js | 2 +- benchmark/events/ee-once.js | 2 +- benchmark/url/url-format.js | 4 +- benchmark/util/format.js | 2 +- benchmark/util/inspect-proxy.js | 10 +- benchmark/util/inspect.js | 4 +- benchmark/vm/run-in-context.js | 2 +- benchmark/vm/run-in-this-context.js | 2 +- lib/console.js | 2 +- lib/dgram.js | 2 +- lib/dns.js | 2 +- lib/fs.js | 8 +- lib/inspector.js | 2 +- lib/internal/bootstrap_node.js | 2 +- lib/internal/child_process.js | 8 +- lib/internal/cluster/master.js | 2 +- lib/internal/socket_list.js | 2 +- lib/internal/util.js | 4 +- lib/readline.js | 4 +- lib/repl.js | 2 +- .../test_make_callback_recurse/test.js | 14 +- test/addons-napi/test_object/test.js | 8 +- test/addons/make-callback-recurse/test.js | 14 +- .../test-promise.promise-before-init-hooks.js | 2 +- test/debugger/helper-debugger-repl.js | 2 +- test/gc/test-http-client-onerror.js | 2 +- test/gc/test-http-client.js | 2 +- test/inspector/test-port-cluster.js | 70 +++--- .../test-dgram-broadcast-multi-process.js | 4 +- test/internet/test-dns-ipv4.js | 4 +- test/internet/test-dns-ipv6.js | 2 +- test/internet/test-dns.js | 23 +- .../test-tls-reuse-host-from-socket.js | 2 +- .../test-stdin-is-always-net.socket.js | 3 +- .../test-vm-inherited_properties.js | 2 +- test/known_issues/test-vm-proxy-failure-CP.js | 2 +- test/message/vm_display_runtime_error.js | 2 +- test/parallel/test-assert-deep.js | 28 +-- test/parallel/test-assert.js | 46 ++-- test/parallel/test-async-hooks-http-agent.js | 2 +- test/parallel/test-async-hooks-promise.js | 2 +- test/parallel/test-buffer-alloc.js | 8 +- test/parallel/test-buffer-compare-offset.js | 2 +- test/parallel/test-buffer-from.js | 2 +- .../parallel/test-buffer-sharedarraybuffer.js | 2 +- test/parallel/test-buffer-tostring-range.js | 4 +- test/parallel/test-child-process-cwd.js | 19 +- test/parallel/test-child-process-exec-cwd.js | 2 +- .../test-child-process-exec-maxBuffer.js | 4 +- .../test-child-process-fork-exec-path.js | 2 +- test/parallel/test-child-process-fork-net.js | 14 +- test/parallel/test-child-process-fork-ref.js | 2 +- ...child-process-fork-stdio-string-variant.js | 8 +- .../parallel/test-child-process-fork-stdio.js | 2 +- test/parallel/test-child-process-internal.js | 4 +- .../test-child-process-send-keep-open.js | 2 +- .../test-child-process-send-type-error.js | 2 +- test/parallel/test-child-process-silent.js | 8 +- .../test-child-process-spawn-argv0.js | 2 +- .../test-child-process-spawn-shell.js | 4 +- ...est-child-process-spawnsync-kill-signal.js | 2 +- .../test-child-process-spawnsync-shell.js | 8 +- .../test-child-process-spawnsync-timeout.js | 2 +- test/parallel/test-child-process-spawnsync.js | 6 +- test/parallel/test-child-process-stdio.js | 12 +- test/parallel/test-child-process-uid-gid.js | 4 +- test/parallel/test-cli-bad-options.js | 2 +- test/parallel/test-cli-syntax.js | 4 +- test/parallel/test-cluster-bind-twice.js | 4 +- test/parallel/test-cluster-dgram-1.js | 2 +- .../test-cluster-disconnect-unshared-tcp.js | 2 +- .../test-cluster-disconnect-unshared-udp.js | 2 +- test/parallel/test-cluster-eaccess.js | 2 +- test/parallel/test-cluster-ipc-throw.js | 4 +- test/parallel/test-cluster-master-error.js | 2 +- test/parallel/test-cluster-send-deadlock.js | 2 +- .../test-cluster-shared-handle-bind-error.js | 2 +- .../test-cluster-worker-constructor.js | 2 +- ...test-cluster-worker-disconnect-on-error.js | 2 +- test/parallel/test-cluster-worker-no-exit.js | 2 +- test/parallel/test-common.js | 4 +- test/parallel/test-console.js | 8 +- test/parallel/test-crypto-binary-default.js | 10 +- test/parallel/test-crypto.js | 12 +- .../test-dgram-exclusive-implicit-bind.js | 10 +- test/parallel/test-dgram-membership.js | 2 +- test/parallel/test-dns.js | 4 +- test/parallel/test-domain-http-server.js | 2 +- ...st-domain-top-level-error-handler-throw.js | 2 +- test/parallel/test-event-emitter-errors.js | 2 +- test/parallel/test-fs-read-stream-inherit.js | 18 +- .../test-fs-read-stream-throw-type-error.js | 2 +- test/parallel/test-fs-read-stream.js | 16 +- .../test-fs-realpath-buffer-encoding.js | 30 +-- test/parallel/test-fs-watch-encoding.js | 4 +- test/parallel/test-fs-watch-recursive.js | 2 +- test/parallel/test-fs-watchfile.js | 2 +- test/parallel/test-fs-write-file-sync.js | 10 +- .../test-fs-write-stream-autoclose-option.js | 6 +- .../test-fs-write-stream-throw-type-error.js | 2 +- test/parallel/test-http-1.0-keep-alive.js | 12 +- test/parallel/test-http-1.0.js | 6 +- test/parallel/test-http-abort-queued-2.js | 6 +- test/parallel/test-http-abort-stream-end.js | 2 +- test/parallel/test-http-client-get-url.js | 2 +- test/parallel/test-http-client-pipe-end.js | 2 +- test/parallel/test-http-client-race-2.js | 5 +- test/parallel/test-http-client-race.js | 5 +- ...ient-reject-chunked-with-content-length.js | 2 +- .../test-http-client-reject-cr-no-lf.js | 2 +- ...est-http-client-reject-unexpected-agent.js | 2 +- .../test-http-client-response-domain.js | 2 +- .../test-http-client-timeout-agent.js | 2 +- .../test-http-client-timeout-with-data.js | 2 +- test/parallel/test-http-client-upload-buf.js | 2 +- test/parallel/test-http-client-upload.js | 2 +- test/parallel/test-http-contentLength0.js | 2 +- test/parallel/test-http-dns-error.js | 8 +- .../test-http-double-content-length.js | 2 +- test/parallel/test-http-exceptions.js | 2 +- .../test-http-flush-response-headers.js | 2 +- test/parallel/test-http-header-obstext.js | 2 +- .../test-http-hostname-typechecking.js | 8 +- .../test-http-incoming-matchKnownFields.js | 154 +++++++------- test/parallel/test-http-invalidheaderfield.js | 6 +- .../test-http-keep-alive-close-on-header.js | 4 +- test/parallel/test-http-keep-alive.js | 6 +- test/parallel/test-http-malformed-request.js | 2 +- test/parallel/test-http-no-content-length.js | 2 +- test/parallel/test-http-outgoing-proto.js | 12 +- test/parallel/test-http-parser-free.js | 2 +- .../test-http-pause-resume-one-end.js | 2 +- test/parallel/test-http-proxy.js | 6 +- test/parallel/test-http-request-end-twice.js | 4 +- .../test-http-request-invalid-method-error.js | 2 +- test/parallel/test-http-request-methods.js | 2 +- .../parallel/test-http-res-write-after-end.js | 2 +- ...test-http-res-write-end-dont-take-array.js | 6 +- ...est-http-response-add-header-after-sent.js | 2 +- ...test-http-response-multi-content-length.js | 4 +- .../test-http-response-multiheaders.js | 2 +- ...-http-response-remove-header-after-sent.js | 2 +- test/parallel/test-http-response-splitting.js | 8 +- .../parallel/test-http-server-multiheaders.js | 2 +- .../test-http-server-multiheaders2.js | 2 +- ...rver-reject-chunked-with-content-length.js | 2 +- .../test-http-server-reject-cr-no-lf.js | 2 +- test/parallel/test-http-server-stale-close.js | 4 +- test/parallel/test-http-server.js | 2 +- test/parallel/test-http-set-timeout.js | 2 +- test/parallel/test-http-set-trailers.js | 2 +- test/parallel/test-http-should-keep-alive.js | 2 +- test/parallel/test-http-status-code.js | 2 +- test/parallel/test-http-timeout-overflow.js | 2 +- test/parallel/test-http-timeout.js | 6 +- test/parallel/test-http-upgrade-server.js | 2 +- test/parallel/test-http-wget.js | 2 +- test/parallel/test-http-write-empty-string.js | 2 +- test/parallel/test-http.js | 2 +- .../parallel/test-https-agent-sockets-leak.js | 2 +- test/parallel/test-https-client-get-url.js | 2 +- .../test-https-connect-address-family.js | 2 +- test/parallel/test-icu-stringwidth.js | 4 +- test/parallel/test-inspector-open.js | 14 +- test/parallel/test-intl.js | 8 +- test/parallel/test-listen-fd-ebadf.js | 4 +- .../test-module-symlinked-peer-modules.js | 4 +- .../test-net-connect-call-socket-connect.js | 2 +- .../test-net-connect-immediate-finish.js | 2 +- test/parallel/test-net-connect-options-fd.js | 2 +- .../parallel/test-net-connect-options-ipv6.js | 2 +- .../parallel/test-net-connect-options-path.js | 12 +- .../parallel/test-net-connect-options-port.js | 14 +- test/parallel/test-net-listen-fd0.js | 2 +- .../test-net-server-connections-child-null.js | 2 +- .../parallel/test-net-server-listen-handle.js | 26 +-- .../test-net-server-listen-options.js | 4 +- test/parallel/test-net-server-listen-path.js | 4 +- .../test-net-server-pause-on-connect.js | 8 +- .../parallel/test-net-socket-timeout-unref.js | 2 +- .../test-net-socket-write-after-close.js | 4 +- test/parallel/test-openssl-ca-options.js | 2 +- test/parallel/test-path-parse-format.js | 68 +++--- test/parallel/test-pipe-file-to-http.js | 2 +- test/parallel/test-preload.js | 4 +- .../test-process-external-stdio-close.js | 2 +- .../test-process-redirect-warnings.js | 2 +- test/parallel/test-querystring-escape.js | 6 +- .../test-querystring-maxKeys-non-finite.js | 7 +- .../test-querystring-multichar-separator.js | 10 +- test/parallel/test-querystring.js | 122 +++++------ test/parallel/test-readline-interface.js | 2 +- test/parallel/test-readline.js | 50 ++--- test/parallel/test-regress-GH-2245.js | 2 +- test/parallel/test-regress-GH-4948.js | 4 +- test/parallel/test-repl-editor.js | 14 +- test/parallel/test-repl-eval-scope.js | 4 +- test/parallel/test-repl-eval.js | 2 +- test/parallel/test-repl-history-perm.js | 2 +- test/parallel/test-repl-save-load.js | 2 +- test/parallel/test-repl.js | 2 +- test/parallel/test-require-cache.js | 4 +- test/parallel/test-stream-big-packet.js | 2 +- ...t-stream-pipe-await-drain-manual-resume.js | 2 +- .../test-stream-pipe-unpipe-streams.js | 6 +- test/parallel/test-stream-unpipe-event.js | 8 +- test/parallel/test-stream-writable-null.js | 8 +- test/parallel/test-stream-writev.js | 2 +- ...est-stream2-base64-single-char-read-end.js | 2 +- .../test-stream2-httpclient-response-end.js | 4 +- test/parallel/test-stream2-objects.js | 10 +- test/parallel/test-stream2-transform.js | 8 +- test/parallel/test-timers-active.js | 2 +- .../test-timers-throw-when-cb-not-function.js | 6 +- test/parallel/test-tls-alpn-server-client.js | 200 +++++++++--------- test/parallel/test-tls-basic-validations.js | 18 +- test/parallel/test-tls-client-abort.js | 2 +- .../test-tls-connect-address-family.js | 2 +- test/parallel/test-tls-connect.js | 2 +- .../parallel/test-tls-delayed-attach-error.js | 2 +- test/parallel/test-tls-env-extra-ca.js | 2 +- test/parallel/test-tls-passphrase.js | 26 +-- test/parallel/test-tls-peer-certificate.js | 2 +- test/parallel/test-tls-securepair-server.js | 2 +- .../test-tls-socket-default-options.js | 15 +- ...tls-socket-failed-handshake-emits-error.js | 2 +- test/parallel/test-url-parse-query.js | 2 +- test/parallel/test-util-format.js | 2 +- test/parallel/test-util-inspect-proxy.js | 2 +- test/parallel/test-util-inspect.js | 88 ++++---- test/parallel/test-util-log.js | 18 +- test/parallel/test-util-promisify.js | 2 +- test/parallel/test-util.js | 14 +- .../test-vm-property-not-on-sandbox.js | 4 +- .../test-whatwg-url-searchparams-inspect.js | 2 +- .../test-whatwg-url-searchparams-sort.js | 2 +- test/parallel/test-zerolengthbufferbug.js | 4 +- test/parallel/test-zlib-const.js | 2 +- .../test-zlib-deflate-constructors.js | 28 +-- .../test-zlib-not-string-or-buffer.js | 2 +- test/pummel/test-exec.js | 5 +- test/pummel/test-fs-watch-file-slow.js | 2 +- test/pummel/test-http-client-reconnect-bug.js | 2 +- test/pummel/test-keep-alive.js | 2 +- test/pummel/test-regress-GH-892.js | 2 +- test/pummel/test-tls-securepair-client.js | 2 +- test/sequential/test-benchmark-http.js | 2 +- .../sequential/test-child-process-execsync.js | 10 +- .../test-child-process-fork-getconnections.js | 2 +- test/sequential/test-init.js | 2 +- .../test-net-listen-shared-ports.js | 2 +- test/sequential/test-stream2-stderr-sync.js | 2 +- tools/doc/json.js | 4 +- tools/eslint-rules/prefer-assert-iferror.js | 2 +- 261 files changed, 1000 insertions(+), 964 deletions(-) diff --git a/benchmark/_test-double-benchmarker.js b/benchmark/_test-double-benchmarker.js index a95ad9c8613db8..0a8c5f9264efc8 100644 --- a/benchmark/_test-double-benchmarker.js +++ b/benchmark/_test-double-benchmarker.js @@ -3,5 +3,5 @@ const http = require('http'); http.get(process.env.path, function() { - console.log(JSON.stringify({throughput: 1})); + console.log(JSON.stringify({ throughput: 1 })); }); diff --git a/benchmark/crypto/aes-gcm-throughput.js b/benchmark/crypto/aes-gcm-throughput.js index 0cb32689510dd3..8264f53547e8f2 100644 --- a/benchmark/crypto/aes-gcm-throughput.js +++ b/benchmark/crypto/aes-gcm-throughput.js @@ -1,7 +1,7 @@ 'use strict'; var common = require('../common.js'); var crypto = require('crypto'); -var keylen = {'aes-128-gcm': 16, 'aes-192-gcm': 24, 'aes-256-gcm': 32}; +var keylen = { 'aes-128-gcm': 16, 'aes-192-gcm': 24, 'aes-256-gcm': 32 }; var bench = common.createBenchmark(main, { n: [500], cipher: ['aes-128-gcm', 'aes-192-gcm', 'aes-256-gcm'], diff --git a/benchmark/events/ee-add-remove.js b/benchmark/events/ee-add-remove.js index 1140a81649f9a6..bc53cc727047dc 100644 --- a/benchmark/events/ee-add-remove.js +++ b/benchmark/events/ee-add-remove.js @@ -2,7 +2,7 @@ var common = require('../common.js'); var events = require('events'); -var bench = common.createBenchmark(main, {n: [25e4]}); +var bench = common.createBenchmark(main, { n: [25e4] }); function main(conf) { var n = conf.n | 0; diff --git a/benchmark/events/ee-emit-multi-args.js b/benchmark/events/ee-emit-multi-args.js index b423c216b1ed73..8c05b15962e424 100644 --- a/benchmark/events/ee-emit-multi-args.js +++ b/benchmark/events/ee-emit-multi-args.js @@ -2,7 +2,7 @@ var common = require('../common.js'); var EventEmitter = require('events').EventEmitter; -var bench = common.createBenchmark(main, {n: [2e6]}); +var bench = common.createBenchmark(main, { n: [2e6] }); function main(conf) { var n = conf.n | 0; diff --git a/benchmark/events/ee-emit.js b/benchmark/events/ee-emit.js index 87772222f0a467..fdd4978a1a7a04 100644 --- a/benchmark/events/ee-emit.js +++ b/benchmark/events/ee-emit.js @@ -2,7 +2,7 @@ var common = require('../common.js'); var EventEmitter = require('events').EventEmitter; -var bench = common.createBenchmark(main, {n: [2e6]}); +var bench = common.createBenchmark(main, { n: [2e6] }); function main(conf) { var n = conf.n | 0; diff --git a/benchmark/events/ee-listener-count-on-prototype.js b/benchmark/events/ee-listener-count-on-prototype.js index 269fd5a493ee34..407564835598d9 100644 --- a/benchmark/events/ee-listener-count-on-prototype.js +++ b/benchmark/events/ee-listener-count-on-prototype.js @@ -2,7 +2,7 @@ var common = require('../common.js'); var EventEmitter = require('events').EventEmitter; -var bench = common.createBenchmark(main, {n: [5e7]}); +var bench = common.createBenchmark(main, { n: [5e7] }); function main(conf) { var n = conf.n | 0; diff --git a/benchmark/events/ee-listeners-many.js b/benchmark/events/ee-listeners-many.js index 09e533de32bf9a..fd04be127bf878 100644 --- a/benchmark/events/ee-listeners-many.js +++ b/benchmark/events/ee-listeners-many.js @@ -2,7 +2,7 @@ var common = require('../common.js'); var EventEmitter = require('events').EventEmitter; -var bench = common.createBenchmark(main, {n: [5e6]}); +var bench = common.createBenchmark(main, { n: [5e6] }); function main(conf) { var n = conf.n | 0; diff --git a/benchmark/events/ee-listeners.js b/benchmark/events/ee-listeners.js index 56c0e85dad41a4..36bda66a4e857e 100644 --- a/benchmark/events/ee-listeners.js +++ b/benchmark/events/ee-listeners.js @@ -2,7 +2,7 @@ var common = require('../common.js'); var EventEmitter = require('events').EventEmitter; -var bench = common.createBenchmark(main, {n: [5e6]}); +var bench = common.createBenchmark(main, { n: [5e6] }); function main(conf) { var n = conf.n | 0; diff --git a/benchmark/events/ee-once.js b/benchmark/events/ee-once.js index 56f7fb9e7c3a9e..5be5dc9837b867 100644 --- a/benchmark/events/ee-once.js +++ b/benchmark/events/ee-once.js @@ -2,7 +2,7 @@ var common = require('../common.js'); var EventEmitter = require('events').EventEmitter; -var bench = common.createBenchmark(main, {n: [2e7]}); +var bench = common.createBenchmark(main, { n: [2e7] }); function main(conf) { var n = conf.n | 0; diff --git a/benchmark/url/url-format.js b/benchmark/url/url-format.js index 771786d3350513..dc8e020879e400 100644 --- a/benchmark/url/url-format.js +++ b/benchmark/url/url-format.js @@ -3,8 +3,8 @@ const common = require('../common.js'); const url = require('url'); const inputs = { - slashes: {slashes: true, host: 'localhost'}, - file: {protocol: 'file:', pathname: '/foo'}, + slashes: { slashes: true, host: 'localhost' }, + file: { protocol: 'file:', pathname: '/foo' }, }; const bench = common.createBenchmark(main, { diff --git a/benchmark/util/format.js b/benchmark/util/format.js index 82e25b4c4c8127..55ce76e1db5924 100644 --- a/benchmark/util/format.js +++ b/benchmark/util/format.js @@ -17,7 +17,7 @@ const bench = common.createBenchmark(main, { const inputs = { 'string': ['Hello, my name is %s', 'fred'], 'number': ['Hi, I was born in %d', 1942], - 'object': ['An error occurred %j', {msg: 'This is an error', code: 'ERR'}], + 'object': ['An error occurred %j', { msg: 'This is an error', code: 'ERR' }], 'unknown': ['hello %a', 'test'], 'no-replace': [1, 2] }; diff --git a/benchmark/util/inspect-proxy.js b/benchmark/util/inspect-proxy.js index 805c520e28745c..c220462ce7f163 100644 --- a/benchmark/util/inspect-proxy.js +++ b/benchmark/util/inspect-proxy.js @@ -10,20 +10,20 @@ const bench = common.createBenchmark(main, { function twoDifferentProxies(n) { // This one should be slower because we're looking up multiple proxies. - const proxyA = new Proxy({}, {get: () => {}}); - const proxyB = new Proxy({}, {get: () => {}}); + const proxyA = new Proxy({}, { get: () => {} }); + const proxyB = new Proxy({}, { get: () => {} }); bench.start(); for (var i = 0; i < n; i += 1) - util.inspect({a: proxyA, b: proxyB}, {showProxy: true}); + util.inspect({ a: proxyA, b: proxyB }, { showProxy: true }); bench.end(n); } function oneProxy(n) { // This one should be a bit faster because of the internal caching. - const proxy = new Proxy({}, {get: () => {}}); + const proxy = new Proxy({}, { get: () => {} }); bench.start(); for (var i = 0; i < n; i += 1) - util.inspect({a: proxy, b: proxy}, {showProxy: true}); + util.inspect({ a: proxy, b: proxy }, { showProxy: true }); bench.end(n); } diff --git a/benchmark/util/inspect.js b/benchmark/util/inspect.js index 3312bd683ba81b..115a3b64a730f5 100644 --- a/benchmark/util/inspect.js +++ b/benchmark/util/inspect.js @@ -3,14 +3,14 @@ var util = require('util'); var common = require('../common.js'); -var bench = common.createBenchmark(main, {n: [5e6]}); +var bench = common.createBenchmark(main, { n: [5e6] }); function main(conf) { var n = conf.n | 0; bench.start(); for (var i = 0; i < n; i += 1) { - util.inspect({a: 'a', b: 'b', c: 'c', d: 'd'}); + util.inspect({ a: 'a', b: 'b', c: 'c', d: 'd' }); } bench.end(n); } diff --git a/benchmark/vm/run-in-context.js b/benchmark/vm/run-in-context.js index d1d4b5a7abbf20..6e26a6d0ebeb38 100644 --- a/benchmark/vm/run-in-context.js +++ b/benchmark/vm/run-in-context.js @@ -12,7 +12,7 @@ const vm = require('vm'); function main(conf) { const n = +conf.n; - const options = conf.breakOnSigint ? {breakOnSigint: true} : {}; + const options = conf.breakOnSigint ? { breakOnSigint: true } : {}; const withSigintListener = !!conf.withSigintListener; process.removeAllListeners('SIGINT'); diff --git a/benchmark/vm/run-in-this-context.js b/benchmark/vm/run-in-this-context.js index f3a7e969287d50..a0c737f46954f1 100644 --- a/benchmark/vm/run-in-this-context.js +++ b/benchmark/vm/run-in-this-context.js @@ -12,7 +12,7 @@ const vm = require('vm'); function main(conf) { const n = +conf.n; - const options = conf.breakOnSigint ? {breakOnSigint: true} : {}; + const options = conf.breakOnSigint ? { breakOnSigint: true } : {}; const withSigintListener = !!conf.withSigintListener; process.removeAllListeners('SIGINT'); diff --git a/lib/console.js b/lib/console.js index 8783047bbbc0a2..b5ff18fcc1911e 100644 --- a/lib/console.js +++ b/lib/console.js @@ -146,7 +146,7 @@ Console.prototype.error = Console.prototype.warn; Console.prototype.dir = function dir(object, options) { - options = Object.assign({customInspect: false}, options); + options = Object.assign({ customInspect: false }, options); write(this._ignoreErrors, this._stdout, util.inspect(object, options), diff --git a/lib/dgram.js b/lib/dgram.js index a19f4d8b5b3ae9..486f269345cacf 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -411,7 +411,7 @@ Socket.prototype.send = function(buffer, this._healthCheck(); if (this._bindState === BIND_STATE_UNBOUND) - this.bind({port: 0, exclusive: true}, null); + this.bind({ port: 0, exclusive: true }, null); if (list.length === 0) list.push(Buffer.alloc(0)); diff --git a/lib/dns.js b/lib/dns.js index 7a3d3336e3aa1d..6d60c783b3f0fc 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -169,7 +169,7 @@ function lookup(hostname, options, callback) { if (matchedFamily) { if (all) { process.nextTick( - callback, null, [{address: hostname, family: matchedFamily}]); + callback, null, [{ address: hostname, family: matchedFamily }]); } else { process.nextTick(callback, null, hostname, matchedFamily); } diff --git a/lib/fs.js b/lib/fs.js index 17e92f6ee1bba4..ab5af78ccb78e9 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -254,10 +254,10 @@ function statsFromValues() { // Don't allow mode to accidentally be overwritten. Object.defineProperties(fs, { - F_OK: {enumerable: true, value: constants.F_OK || 0}, - R_OK: {enumerable: true, value: constants.R_OK || 0}, - W_OK: {enumerable: true, value: constants.W_OK || 0}, - X_OK: {enumerable: true, value: constants.X_OK || 0}, + F_OK: { enumerable: true, value: constants.F_OK || 0 }, + R_OK: { enumerable: true, value: constants.R_OK || 0 }, + W_OK: { enumerable: true, value: constants.W_OK || 0 }, + X_OK: { enumerable: true, value: constants.X_OK || 0 }, }); function handleError(val, callback) { diff --git a/lib/inspector.js b/lib/inspector.js index abde3b38cbca41..adbb0afaa55674 100644 --- a/lib/inspector.js +++ b/lib/inspector.js @@ -66,7 +66,7 @@ class Session extends EventEmitter { throw new Error('Session is not connected'); } const id = this[nextIdSymbol]++; - const message = {id, method}; + const message = { id, method }; if (params) { message['params'] = params; } diff --git a/lib/internal/bootstrap_node.js b/lib/internal/bootstrap_node.js index 5a323035b1e7df..3f83c08354e58f 100644 --- a/lib/internal/bootstrap_node.js +++ b/lib/internal/bootstrap_node.js @@ -476,7 +476,7 @@ // wrap it source = Module.wrap(source); // compile the script, this will throw if it fails - new vm.Script(source, {displayErrors: true, filename}); + new vm.Script(source, { displayErrors: true, filename }); } // Below you find a minimal module system, which is used to load the node diff --git a/lib/internal/child_process.js b/lib/internal/child_process.js index 62150fe86da1b9..e9eedeb867d545 100644 --- a/lib/internal/child_process.js +++ b/lib/internal/child_process.js @@ -109,7 +109,7 @@ const handleConversion = { }, got: function(message, handle, emit) { - var socket = new net.Socket({handle: handle}); + var socket = new net.Socket({ handle: handle }); socket.readable = socket.writable = true; // if the socket was created by net.Server we will track the socket @@ -582,7 +582,7 @@ function setupChannel(target, channel) { throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object'); } - options = Object.assign({swallowErrors: false}, options); + options = Object.assign({ swallowErrors: false }, options); if (this.connected) { return this._send(message, handle, options, callback); @@ -604,7 +604,7 @@ function setupChannel(target, channel) { // Support legacy function signature if (typeof options === 'boolean') { - options = {swallowErrors: options}; + options = { swallowErrors: options }; } // package messages with a handle object @@ -838,7 +838,7 @@ function _validateStdio(stdio, sync) { } if (stdio === 'ignore') { - acc.push({type: 'ignore'}); + acc.push({ type: 'ignore' }); } else if (stdio === 'pipe' || typeof stdio === 'number' && stdio < 0) { var a = { type: 'pipe', diff --git a/lib/internal/cluster/master.js b/lib/internal/cluster/master.js index 05663e792b3ba6..4ccf0393223a23 100644 --- a/lib/internal/cluster/master.js +++ b/lib/internal/cluster/master.js @@ -12,7 +12,7 @@ const cluster = new EventEmitter(); const intercom = new EventEmitter(); const SCHED_NONE = 1; const SCHED_RR = 2; -const {isLegalPort} = require('internal/net'); +const { isLegalPort } = require('internal/net'); module.exports = cluster; diff --git a/lib/internal/socket_list.js b/lib/internal/socket_list.js index 15e880ba8c13d4..961289efebc3c9 100644 --- a/lib/internal/socket_list.js +++ b/lib/internal/socket_list.js @@ -102,4 +102,4 @@ class SocketListReceive extends EventEmitter { } } -module.exports = {SocketListSend, SocketListReceive}; +module.exports = { SocketListSend, SocketListReceive }; diff --git a/lib/internal/util.js b/lib/internal/util.js index 091706d4fdb289..113c0c66c0fe47 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -150,8 +150,8 @@ function createClassWrapper(type) { } // Mask the wrapper function name and length values Object.defineProperties(fn, { - name: {value: type.name}, - length: {value: type.length} + name: { value: type.name }, + length: { value: type.length } }); Object.setPrototypeOf(fn, type); fn.prototype = type.prototype; diff --git a/lib/readline.js b/lib/readline.js index 85333d4a6c095f..60d67083274532 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -683,7 +683,7 @@ Interface.prototype._getDisplayPos = function(str) { } var cols = offset % col; var rows = row + (offset - cols) / col; - return {cols: cols, rows: rows}; + return { cols: cols, rows: rows }; }; @@ -702,7 +702,7 @@ Interface.prototype._getCursorPos = function() { rows++; cols = 0; } - return {cols: cols, rows: rows}; + return { cols: cols, rows: rows }; }; diff --git a/lib/repl.js b/lib/repl.js index 2a5077f390b54d..0d2be97714d77b 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -1069,7 +1069,7 @@ REPLServer.prototype.parseREPLKeyword = function(keyword, rest) { REPLServer.prototype.defineCommand = function(keyword, cmd) { if (typeof cmd === 'function') { - cmd = {action: cmd}; + cmd = { action: cmd }; } else if (typeof cmd.action !== 'function') { throw new Error('Bad argument, "action" command must be a function'); } diff --git a/test/addons-napi/test_make_callback_recurse/test.js b/test/addons-napi/test_make_callback_recurse/test.js index 895769bc33029a..77815e052ab1f9 100644 --- a/test/addons-napi/test_make_callback_recurse/test.js +++ b/test/addons-napi/test_make_callback_recurse/test.js @@ -101,11 +101,11 @@ function checkDomains() { const d2 = domain.create(); const d3 = domain.create(); - makeCallback({domain: d1}, common.mustCall(function() { + makeCallback({ domain: d1 }, common.mustCall(function() { assert.strictEqual(d1, process.domain); - makeCallback({domain: d2}, common.mustCall(function() { + makeCallback({ domain: d2 }, common.mustCall(function() { assert.strictEqual(d2, process.domain); - makeCallback({domain: d3}, common.mustCall(function() { + makeCallback({ domain: d3 }, common.mustCall(function() { assert.strictEqual(d3, process.domain); })); assert.strictEqual(d2, process.domain); @@ -119,11 +119,11 @@ function checkDomains() { const d2 = domain.create(); const d3 = domain.create(); - makeCallback({domain: d1}, common.mustCall(function() { + makeCallback({ domain: d1 }, common.mustCall(function() { assert.strictEqual(d1, process.domain); - makeCallback({domain: d2}, common.mustCall(function() { + makeCallback({ domain: d2 }, common.mustCall(function() { assert.strictEqual(d2, process.domain); - makeCallback({domain: d3}, common.mustCall(function() { + makeCallback({ domain: d3 }, common.mustCall(function() { assert.strictEqual(d3, process.domain); })); assert.strictEqual(d2, process.domain); @@ -139,7 +139,7 @@ function checkDomains() { d.on('error', common.mustCall(function(e) { assert.strictEqual(e.message, `throw from domain ${id}`); })); - makeCallback({domain: d}, function() { + makeCallback({ domain: d }, function() { throw new Error(`throw from domain ${id}`); }); throw new Error('UNREACHABLE'); diff --git a/test/addons-napi/test_object/test.js b/test/addons-napi/test_object/test.js index 9e8f17de28287c..8e44a1b5ed647f 100644 --- a/test/addons-napi/test_object/test.js +++ b/test/addons-napi/test_object/test.js @@ -92,12 +92,12 @@ assert.strictEqual(newObject.test_string, 'test string'); z: 10 }; - assert.deepStrictEqual(test_object.Inflate(cube), {x: 11, y: 11, z: 11}); - assert.deepStrictEqual(test_object.Inflate(cube), {x: 12, y: 12, z: 12}); - assert.deepStrictEqual(test_object.Inflate(cube), {x: 13, y: 13, z: 13}); + assert.deepStrictEqual(test_object.Inflate(cube), { x: 11, y: 11, z: 11 }); + assert.deepStrictEqual(test_object.Inflate(cube), { x: 12, y: 12, z: 12 }); + assert.deepStrictEqual(test_object.Inflate(cube), { x: 13, y: 13, z: 13 }); cube.t = 13; assert.deepStrictEqual( - test_object.Inflate(cube), {x: 14, y: 14, z: 14, t: 14}); + test_object.Inflate(cube), { x: 14, y: 14, z: 14, t: 14 }); const sym1 = Symbol('1'); const sym2 = Symbol('2'); diff --git a/test/addons/make-callback-recurse/test.js b/test/addons/make-callback-recurse/test.js index 895769bc33029a..77815e052ab1f9 100644 --- a/test/addons/make-callback-recurse/test.js +++ b/test/addons/make-callback-recurse/test.js @@ -101,11 +101,11 @@ function checkDomains() { const d2 = domain.create(); const d3 = domain.create(); - makeCallback({domain: d1}, common.mustCall(function() { + makeCallback({ domain: d1 }, common.mustCall(function() { assert.strictEqual(d1, process.domain); - makeCallback({domain: d2}, common.mustCall(function() { + makeCallback({ domain: d2 }, common.mustCall(function() { assert.strictEqual(d2, process.domain); - makeCallback({domain: d3}, common.mustCall(function() { + makeCallback({ domain: d3 }, common.mustCall(function() { assert.strictEqual(d3, process.domain); })); assert.strictEqual(d2, process.domain); @@ -119,11 +119,11 @@ function checkDomains() { const d2 = domain.create(); const d3 = domain.create(); - makeCallback({domain: d1}, common.mustCall(function() { + makeCallback({ domain: d1 }, common.mustCall(function() { assert.strictEqual(d1, process.domain); - makeCallback({domain: d2}, common.mustCall(function() { + makeCallback({ domain: d2 }, common.mustCall(function() { assert.strictEqual(d2, process.domain); - makeCallback({domain: d3}, common.mustCall(function() { + makeCallback({ domain: d3 }, common.mustCall(function() { assert.strictEqual(d3, process.domain); })); assert.strictEqual(d2, process.domain); @@ -139,7 +139,7 @@ function checkDomains() { d.on('error', common.mustCall(function(e) { assert.strictEqual(e.message, `throw from domain ${id}`); })); - makeCallback({domain: d}, function() { + makeCallback({ domain: d }, function() { throw new Error(`throw from domain ${id}`); }); throw new Error('UNREACHABLE'); diff --git a/test/async-hooks/test-promise.promise-before-init-hooks.js b/test/async-hooks/test-promise.promise-before-init-hooks.js index 27536b727d232f..79bbd1751d83fd 100644 --- a/test/async-hooks/test-promise.promise-before-init-hooks.js +++ b/test/async-hooks/test-promise.promise-before-init-hooks.js @@ -10,7 +10,7 @@ const p = new Promise(common.mustCall(function executor(resolve, reject) { })); // init hooks after promise was created -const hooks = initHooks({allowNoInit: true}); +const hooks = initHooks({ allowNoInit: true }); hooks.enable(); p.then(function afterresolution(val) { diff --git a/test/debugger/helper-debugger-repl.js b/test/debugger/helper-debugger-repl.js index f11d4d94981e0e..365b29e50d6556 100644 --- a/test/debugger/helper-debugger-repl.js +++ b/test/debugger/helper-debugger-repl.js @@ -125,7 +125,7 @@ function addTest(input, output) { quit(); } } - expected.push({input: input, lines: output, callback: next}); + expected.push({ input: input, lines: output, callback: next }); } const handshakeLines = [ diff --git a/test/gc/test-http-client-onerror.js b/test/gc/test-http-client-onerror.js index 0baa310a042522..8b05e941749c63 100644 --- a/test/gc/test-http-client-onerror.js +++ b/test/gc/test-http-client-onerror.js @@ -6,7 +6,7 @@ const common = require('../common'); function serverHandler(req, res) { req.resume(); - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World\n'); } diff --git a/test/gc/test-http-client.js b/test/gc/test-http-client.js index 569dc574912884..8b50ad5ea4ffce 100644 --- a/test/gc/test-http-client.js +++ b/test/gc/test-http-client.js @@ -4,7 +4,7 @@ const common = require('../common'); function serverHandler(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World\n'); } diff --git a/test/inspector/test-port-cluster.js b/test/inspector/test-port-cluster.js index 166f5a8d108664..3b2464d81268b4 100644 --- a/test/inspector/test-port-cluster.js +++ b/test/inspector/test-port-cluster.js @@ -20,7 +20,7 @@ let offset = 0; function testRunnerMain() { let defaultPortCase = spawnMaster({ execArgv: ['--inspect'], - workers: [{expectedPort: 9230}] + workers: [{ expectedPort: 9230 }] }); let port = debuggerPort + offset++ * 5; @@ -28,9 +28,9 @@ function testRunnerMain() { spawnMaster({ execArgv: [`--inspect=${port}`], workers: [ - {expectedPort: port + 1}, - {expectedPort: port + 2}, - {expectedPort: port + 3} + { expectedPort: port + 1 }, + { expectedPort: port + 2 }, + { expectedPort: port + 3 } ] }); @@ -38,28 +38,28 @@ function testRunnerMain() { spawnMaster({ execArgv: ['--inspect', `--inspect-port=${port}`], - workers: [{expectedPort: port + 1}] + workers: [{ expectedPort: port + 1 }] }); port = debuggerPort + offset++ * 5; spawnMaster({ execArgv: ['--inspect', `--debug-port=${port}`], - workers: [{expectedPort: port + 1}] + workers: [{ expectedPort: port + 1 }] }); port = debuggerPort + offset++ * 5; spawnMaster({ execArgv: [`--inspect=0.0.0.0:${port}`], - workers: [{expectedPort: port + 1, expectedHost: '0.0.0.0'}] + workers: [{ expectedPort: port + 1, expectedHost: '0.0.0.0' }] }); port = debuggerPort + offset++ * 5; spawnMaster({ execArgv: [`--inspect=127.0.0.1:${port}`], - workers: [{expectedPort: port + 1, expectedHost: '127.0.0.1'}] + workers: [{ expectedPort: port + 1, expectedHost: '127.0.0.1' }] }); if (common.hasIPv6) { @@ -67,14 +67,14 @@ function testRunnerMain() { spawnMaster({ execArgv: [`--inspect=[::]:${port}`], - workers: [{expectedPort: port + 1, expectedHost: '::'}] + workers: [{ expectedPort: port + 1, expectedHost: '::' }] }); port = debuggerPort + offset++ * 5; spawnMaster({ execArgv: [`--inspect=[::1]:${port}`], - workers: [{expectedPort: port + 1, expectedHost: '::1'}] + workers: [{ expectedPort: port + 1, expectedHost: '::1' }] }); } @@ -85,18 +85,18 @@ function testRunnerMain() { spawnMaster({ execArgv: [`--inspect=${port}`], - clusterSettings: {inspectPort: port + 2}, - workers: [{expectedPort: port + 2}] + clusterSettings: { inspectPort: port + 2 }, + workers: [{ expectedPort: port + 2 }] }); port = debuggerPort + offset++ * 5; spawnMaster({ execArgv: [`--inspect=${port}`], - clusterSettings: {inspectPort: 'addTwo'}, + clusterSettings: { inspectPort: 'addTwo' }, workers: [ - {expectedPort: port + 2}, - {expectedPort: port + 4} + { expectedPort: port + 2 }, + { expectedPort: port + 4 } ] }); @@ -104,7 +104,7 @@ function testRunnerMain() { spawnMaster({ execArgv: [`--inspect=${port}`], - clusterSettings: {inspectPort: 'string'}, + clusterSettings: { inspectPort: 'string' }, workers: [{}] }); @@ -112,7 +112,7 @@ function testRunnerMain() { spawnMaster({ execArgv: [`--inspect=${port}`], - clusterSettings: {inspectPort: 'null'}, + clusterSettings: { inspectPort: 'null' }, workers: [{}] }); @@ -120,7 +120,7 @@ function testRunnerMain() { spawnMaster({ execArgv: [`--inspect=${port}`], - clusterSettings: {inspectPort: 'bignumber'}, + clusterSettings: { inspectPort: 'bignumber' }, workers: [{}] }); @@ -128,7 +128,7 @@ function testRunnerMain() { spawnMaster({ execArgv: [`--inspect=${port}`], - clusterSettings: {inspectPort: 'negativenumber'}, + clusterSettings: { inspectPort: 'negativenumber' }, workers: [{}] }); @@ -136,7 +136,7 @@ function testRunnerMain() { spawnMaster({ execArgv: [`--inspect=${port}`], - clusterSettings: {inspectPort: 'bignumberfunc'}, + clusterSettings: { inspectPort: 'bignumberfunc' }, workers: [{}] }); @@ -144,7 +144,7 @@ function testRunnerMain() { spawnMaster({ execArgv: [`--inspect=${port}`], - clusterSettings: {inspectPort: 'strfunc'}, + clusterSettings: { inspectPort: 'strfunc' }, workers: [{}] }); @@ -152,9 +152,9 @@ function testRunnerMain() { spawnMaster({ execArgv: [], - clusterSettings: {inspectPort: port, execArgv: ['--inspect']}, + clusterSettings: { inspectPort: port, execArgv: ['--inspect'] }, workers: [ - {expectedPort: port} + { expectedPort: port } ] }); @@ -162,11 +162,11 @@ function testRunnerMain() { spawnMaster({ execArgv: [`--inspect=${port}`], - clusterSettings: {inspectPort: 0}, + clusterSettings: { inspectPort: 0 }, workers: [ - {expectedInitialPort: 0}, - {expectedInitialPort: 0}, - {expectedInitialPort: 0} + { expectedInitialPort: 0 }, + { expectedInitialPort: 0 }, + { expectedInitialPort: 0 } ] }); @@ -174,11 +174,11 @@ function testRunnerMain() { spawnMaster({ execArgv: [], - clusterSettings: {inspectPort: 0}, + clusterSettings: { inspectPort: 0 }, workers: [ - {expectedInitialPort: 0}, - {expectedInitialPort: 0}, - {expectedInitialPort: 0} + { expectedInitialPort: 0 }, + { expectedInitialPort: 0 }, + { expectedInitialPort: 0 } ] }); @@ -186,9 +186,9 @@ function testRunnerMain() { port = debuggerPort + offset++ * 5; defaultPortCase = spawnMaster({ execArgv: ['--inspect'], - clusterSettings: {inspectPort: port + 2}, + clusterSettings: { inspectPort: port + 2 }, workers: [ - {expectedInitialPort: port + 2} + { expectedInitialPort: port + 2 } ] }); }); @@ -290,7 +290,7 @@ function masterProcessMain() { } function workerProcessMain() { - const {expectedPort, expectedInitialPort, expectedHost} = process.env; + const { expectedPort, expectedInitialPort, expectedHost } = process.env; const debugOptions = process.binding('config').debugOptions; if ('expectedPort' in process.env) { @@ -308,7 +308,7 @@ function workerProcessMain() { process.exit(); } -function spawnMaster({execArgv, workers, clusterSettings = {}}) { +function spawnMaster({ execArgv, workers, clusterSettings = {} }) { return new Promise((resolve) => { childProcess.fork(__filename, { env: { diff --git a/test/internet/test-dgram-broadcast-multi-process.js b/test/internet/test-dgram-broadcast-multi-process.js index 0ec4bbd9ce5aa7..82ddd7743f64de 100644 --- a/test/internet/test-dgram-broadcast-multi-process.js +++ b/test/internet/test-dgram-broadcast-multi-process.js @@ -233,7 +233,7 @@ if (process.argv[2] === 'child') { receivedMessages.push(buf); - process.send({message: buf.toString()}); + process.send({ message: buf.toString() }); if (receivedMessages.length === messages.length) { process.nextTick(function() { @@ -252,7 +252,7 @@ if (process.argv[2] === 'child') { }); listenSocket.on('listening', function() { - process.send({listening: true}); + process.send({ listening: true }); }); listenSocket.bind(common.PORT); diff --git a/test/internet/test-dns-ipv4.js b/test/internet/test-dns-ipv4.js index 4d4c7da6a7026d..d3d5ba22009675 100644 --- a/test/internet/test-dns-ipv4.js +++ b/test/internet/test-dns-ipv4.js @@ -155,7 +155,7 @@ TEST(function test_lookup_localhost_ipv4(done) { TEST(function test_lookup_all_ipv4(done) { const req = dns.lookup( 'www.google.com', - {all: true, family: 4}, + { all: true, family: 4 }, common.mustCall((err, ips) => { assert.ifError(err); assert.ok(Array.isArray(ips)); @@ -190,7 +190,7 @@ TEST(function test_lookupservice_ip_ipv4(done) { TEST(function test_lookupservice_ip_ipv4_promise(done) { util.promisify(dns.lookupService)('127.0.0.1', 80) - .then(common.mustCall(({hostname, service}) => { + .then(common.mustCall(({ hostname, service }) => { assert.strictEqual(typeof hostname, 'string'); assert(hostname.length > 0); assert(['http', 'www', '80'].includes(service)); diff --git a/test/internet/test-dns-ipv6.js b/test/internet/test-dns-ipv6.js index 9b9360c2a1628c..a91b108456c027 100644 --- a/test/internet/test-dns-ipv6.js +++ b/test/internet/test-dns-ipv6.js @@ -154,7 +154,7 @@ TEST(function test_lookup_ip_ipv6(done) { TEST(function test_lookup_all_ipv6(done) { const req = dns.lookup( 'www.google.com', - {all: true, family: 6}, + { all: true, family: 6 }, common.mustCall((err, ips) => { assert.ifError(err); assert.ok(Array.isArray(ips)); diff --git a/test/internet/test-dns.js b/test/internet/test-dns.js index 75e8815f8823d8..e2214433c51436 100644 --- a/test/internet/test-dns.js +++ b/test/internet/test-dns.js @@ -403,22 +403,23 @@ TEST(function test_lookup_failure(done) { TEST(function test_lookup_ip_all(done) { - const req = dns.lookup('127.0.0.1', {all: true}, function(err, ips, family) { - assert.ifError(err); - assert.ok(Array.isArray(ips)); - assert.ok(ips.length > 0); - assert.strictEqual(ips[0].address, '127.0.0.1'); - assert.strictEqual(ips[0].family, 4); + const req = + dns.lookup('127.0.0.1', { all: true }, function(err, ips, family) { + assert.ifError(err); + assert.ok(Array.isArray(ips)); + assert.ok(ips.length > 0); + assert.strictEqual(ips[0].address, '127.0.0.1'); + assert.strictEqual(ips[0].family, 4); - done(); - }); + done(); + }); checkWrap(req); }); TEST(function test_lookup_ip_all_promise(done) { - const req = util.promisify(dns.lookup)('127.0.0.1', {all: true}) + const req = util.promisify(dns.lookup)('127.0.0.1', { all: true }) .then(function(ips) { assert.ok(Array.isArray(ips)); assert.ok(ips.length > 0); @@ -444,7 +445,7 @@ TEST(function test_lookup_ip_promise(done) { TEST(function test_lookup_null_all(done) { - const req = dns.lookup(null, {all: true}, function(err, ips, family) { + const req = dns.lookup(null, { all: true }, function(err, ips, family) { assert.ifError(err); assert.ok(Array.isArray(ips)); assert.strictEqual(ips.length, 0); @@ -457,7 +458,7 @@ TEST(function test_lookup_null_all(done) { TEST(function test_lookup_all_mixed(done) { - const req = dns.lookup('www.google.com', {all: true}, function(err, ips) { + const req = dns.lookup('www.google.com', { all: true }, function(err, ips) { assert.ifError(err); assert.ok(Array.isArray(ips)); assert.ok(ips.length > 0); diff --git a/test/internet/test-tls-reuse-host-from-socket.js b/test/internet/test-tls-reuse-host-from-socket.js index 73ee91d3b2ea0d..8501efd74e619f 100644 --- a/test/internet/test-tls-reuse-host-from-socket.js +++ b/test/internet/test-tls-reuse-host-from-socket.js @@ -30,7 +30,7 @@ const tls = require('tls'); const net = require('net'); const socket = net.connect(443, 'www.example.org', common.mustCall(() => { - const secureSocket = tls.connect({socket: socket}, common.mustCall(() => { + const secureSocket = tls.connect({ socket: socket }, common.mustCall(() => { secureSocket.destroy(); console.log('ok'); })); diff --git a/test/known_issues/test-stdin-is-always-net.socket.js b/test/known_issues/test-stdin-is-always-net.socket.js index 78c1a7d2eac20e..35e36a014e93e6 100644 --- a/test/known_issues/test-stdin-is-always-net.socket.js +++ b/test/known_issues/test-stdin-is-always-net.socket.js @@ -11,7 +11,8 @@ if (process.argv[2] === 'child') { return; } -const proc = spawn(process.execPath, [__filename, 'child'], {stdio: 'ignore'}); +const proc = spawn(process.execPath, [__filename, 'child'], + { stdio: 'ignore' }); // To double-check this test, set stdio to 'pipe' and uncomment the line below. // proc.stderr.pipe(process.stderr); proc.on('exit', common.mustCall(function(exitCode) { diff --git a/test/known_issues/test-vm-inherited_properties.js b/test/known_issues/test-vm-inherited_properties.js index f90cf3568ed9c5..3df9c57219d8be 100644 --- a/test/known_issues/test-vm-inherited_properties.js +++ b/test/known_issues/test-vm-inherited_properties.js @@ -10,7 +10,7 @@ const base = { }; const sandbox = Object.create(base, { - propSandbox: {value: 3} + propSandbox: { value: 3 } }); const context = vm.createContext(sandbox); diff --git a/test/known_issues/test-vm-proxy-failure-CP.js b/test/known_issues/test-vm-proxy-failure-CP.js index ac73a1475bb449..cb636f2ae2bb80 100644 --- a/test/known_issues/test-vm-proxy-failure-CP.js +++ b/test/known_issues/test-vm-proxy-failure-CP.js @@ -13,7 +13,7 @@ const handler = { throw new Error('whoops'); } }; -const sandbox = new Proxy({foo: 'bar'}, handler); +const sandbox = new Proxy({ foo: 'bar' }, handler); const context = vm.createContext(sandbox); diff --git a/test/message/vm_display_runtime_error.js b/test/message/vm_display_runtime_error.js index 8a40a03a03962a..230c45feab19a7 100644 --- a/test/message/vm_display_runtime_error.js +++ b/test/message/vm_display_runtime_error.js @@ -26,7 +26,7 @@ const vm = require('vm'); console.error('beginning'); try { - vm.runInThisContext('throw new Error("boo!")', { filename: 'test.vm'}); + vm.runInThisContext('throw new Error("boo!")', { filename: 'test.vm' }); } catch (err) { console.error(err.stack); } diff --git a/test/parallel/test-assert-deep.js b/test/parallel/test-assert-deep.js index 25e94b0f2fd187..d075f91b5954d0 100644 --- a/test/parallel/test-assert-deep.js +++ b/test/parallel/test-assert-deep.js @@ -86,8 +86,8 @@ assert.throws(() => assert.deepStrictEqual(re1, re2), // For these weird cases, deepEqual should pass (at least for now), // but deepStrictEqual should throw. const similar = new Set([ - {0: '1'}, // Object - {0: 1}, // Object + { 0: '1' }, // Object + { 0: 1 }, // Object new String('1'), // Object ['1'], // Array [1], // Array @@ -115,7 +115,7 @@ for (const a of similar) { } assert.throws( - () => { assert.deepEqual(new Set([{a: 0}]), new Set([{a: 1}])); }, + () => { assert.deepEqual(new Set([{ a: 0 }]), new Set([{ a: 1 }])); }, common.expectsError({ code: 'ERR_ASSERTION', message: /^Set { { a: 0 } } deepEqual Set { { a: 1 } }$/ @@ -181,7 +181,7 @@ assertNotDeepOrStrict(new Set([1]), [1]); assertNotDeepOrStrict(new Set(), []); assertNotDeepOrStrict(new Set(), {}); -assertNotDeepOrStrict(new Map([['a', 1]]), {a: 1}); +assertNotDeepOrStrict(new Map([['a', 1]]), { a: 1 }); assertNotDeepOrStrict(new Map(), []); assertNotDeepOrStrict(new Map(), {}); @@ -195,24 +195,24 @@ assertDeepAndStrictEqual(new Set([{}]), new Set([{}])); // Ref: https://github.com/nodejs/node/issues/13347 assertNotDeepOrStrict( - new Set([{a: 1}, {a: 1}]), - new Set([{a: 1}, {a: 2}]) + new Set([{ a: 1 }, { a: 1 }]), + new Set([{ a: 1 }, { a: 2 }]) ); assertNotDeepOrStrict( - new Set([{a: 1}, {a: 1}, {a: 2}]), - new Set([{a: 1}, {a: 2}, {a: 2}]) + new Set([{ a: 1 }, { a: 1 }, { a: 2 }]), + new Set([{ a: 1 }, { a: 2 }, { a: 2 }]) ); assertNotDeepOrStrict( - new Map([[{x: 1}, 5], [{x: 1}, 5]]), - new Map([[{x: 1}, 5], [{x: 2}, 5]]) + new Map([[{ x: 1 }, 5], [{ x: 1 }, 5]]), + new Map([[{ x: 1 }, 5], [{ x: 2 }, 5]]) ); assertNotDeepOrStrict(new Set([3, '3']), new Set([3, 4])); assertNotDeepOrStrict(new Map([[3, 0], ['3', 0]]), new Map([[3, 0], [4, 0]])); assertNotDeepOrStrict( - new Set([{a: 1}, {a: 1}, {a: 2}]), - new Set([{a: 1}, {a: 2}, {a: 2}]) + new Set([{ a: 1 }, { a: 1 }, { a: 2 }]), + new Set([{ a: 1 }, { a: 2 }, { a: 2 }]) ); // Mixed primitive and object keys @@ -339,7 +339,7 @@ assertOnlyDeepEqual( assertDeepAndStrictEqual(new Set(values), new Set(values)); assertDeepAndStrictEqual(new Set(values), new Set(values.reverse())); - const mapValues = values.map((v) => [v, {a: 5}]); + const mapValues = values.map((v) => [v, { a: 5 }]); assertDeepAndStrictEqual(new Map(mapValues), new Map(mapValues)); assertDeepAndStrictEqual(new Map(mapValues), new Map(mapValues.reverse())); } @@ -357,7 +357,7 @@ assertOnlyDeepEqual( { const m1 = new Map(); const m2 = new Map(); - const obj = {a: 5, b: 6}; + const obj = { a: 5, b: 6 }; m1.set(1, obj); m1.set(2, 'hi'); m1.set(3, [1, 2, 3]); diff --git a/test/parallel/test-assert.js b/test/parallel/test-assert.js index 98c0f9eef2994f..703097b26051c7 100644 --- a/test/parallel/test-assert.js +++ b/test/parallel/test-assert.js @@ -163,14 +163,14 @@ assert.throws(makeBlock(a.deepEqual, 4, '5'), 'deepEqual( 4, \'5\')'); // having the same number of owned properties && the same set of keys -assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4}, {a: 4})); -assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '2'}, {a: 4, b: '2'})); +assert.doesNotThrow(makeBlock(a.deepEqual, { a: 4 }, { a: 4 })); +assert.doesNotThrow(makeBlock(a.deepEqual, { a: 4, b: '2' }, { a: 4, b: '2' })); assert.doesNotThrow(makeBlock(a.deepEqual, [4], ['4'])); -assert.throws(makeBlock(a.deepEqual, {a: 4}, {a: 4, b: true}), +assert.throws(makeBlock(a.deepEqual, { a: 4 }, { a: 4, b: true }), a.AssertionError); -assert.doesNotThrow(makeBlock(a.deepEqual, ['a'], {0: 'a'})); +assert.doesNotThrow(makeBlock(a.deepEqual, ['a'], { 0: 'a' })); //(although not necessarily the same order), -assert.doesNotThrow(makeBlock(a.deepEqual, {a: 4, b: '1'}, {b: '1', a: 4})); +assert.doesNotThrow(makeBlock(a.deepEqual, { a: 4, b: '1' }, { b: '1', a: 4 })); const a1 = [1, 2, 3]; const a2 = [1, 2, 3]; a1.a = 'test'; @@ -213,7 +213,7 @@ assert.doesNotThrow(makeBlock(a.deepEqual, nb1, nb2)); assert.throws(makeBlock(a.deepEqual, null, {}), a.AssertionError); assert.throws(makeBlock(a.deepEqual, undefined, {}), a.AssertionError); assert.throws(makeBlock(a.deepEqual, 'a', ['a']), a.AssertionError); -assert.throws(makeBlock(a.deepEqual, 'a', {0: 'a'}), a.AssertionError); +assert.throws(makeBlock(a.deepEqual, 'a', { 0: 'a' }), a.AssertionError); assert.throws(makeBlock(a.deepEqual, 1, {}), a.AssertionError); assert.throws(makeBlock(a.deepEqual, true, {}), a.AssertionError); assert.throws(makeBlock(a.deepEqual, Symbol(), {}), a.AssertionError); @@ -221,7 +221,7 @@ assert.throws(makeBlock(a.deepEqual, Symbol(), {}), a.AssertionError); // primitive wrappers and object assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), ['a']), a.AssertionError); -assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), {0: 'a'}), +assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), { 0: 'a' }), a.AssertionError); assert.doesNotThrow(makeBlock(a.deepEqual, new Number(1), {}), a.AssertionError); @@ -229,7 +229,7 @@ assert.doesNotThrow(makeBlock(a.deepEqual, new Boolean(true), {}), a.AssertionError); // same number of keys but different key names -assert.throws(makeBlock(a.deepEqual, {a: 1}, {b: 1}), a.AssertionError); +assert.throws(makeBlock(a.deepEqual, { a: 1 }, { b: 1 }), a.AssertionError); //deepStrictEqual assert.doesNotThrow( @@ -314,23 +314,23 @@ assert.throws(makeBlock(a.deepStrictEqual, 4, '5'), 'deepStrictEqual(4, \'5\')'); // having the same number of owned properties && the same set of keys -assert.doesNotThrow(makeBlock(a.deepStrictEqual, {a: 4}, {a: 4})); +assert.doesNotThrow(makeBlock(a.deepStrictEqual, { a: 4 }, { a: 4 })); assert.doesNotThrow(makeBlock(a.deepStrictEqual, - {a: 4, b: '2'}, - {a: 4, b: '2'})); + { a: 4, b: '2' }, + { a: 4, b: '2' })); assert.throws(makeBlock(a.deepStrictEqual, [4], ['4']), common.expectsError({ code: 'ERR_ASSERTION', type: a.AssertionError, message: /^\[ 4 ] deepStrictEqual \[ '4' ]$/ })); -assert.throws(makeBlock(a.deepStrictEqual, {a: 4}, {a: 4, b: true}), +assert.throws(makeBlock(a.deepStrictEqual, { a: 4 }, { a: 4, b: true }), common.expectsError({ code: 'ERR_ASSERTION', type: a.AssertionError, message: /^{ a: 4 } deepStrictEqual { a: 4, b: true }$/ })); -assert.throws(makeBlock(a.deepStrictEqual, ['a'], {0: 'a'}), +assert.throws(makeBlock(a.deepStrictEqual, ['a'], { 0: 'a' }), common.expectsError({ code: 'ERR_ASSERTION', type: a.AssertionError, @@ -338,8 +338,8 @@ assert.throws(makeBlock(a.deepStrictEqual, ['a'], {0: 'a'}), })); //(although not necessarily the same order), assert.doesNotThrow(makeBlock(a.deepStrictEqual, - {a: 4, b: '1'}, - {b: '1', a: 4})); + { a: 4, b: '1' }, + { b: '1', a: 4 })); assert.throws(makeBlock(a.deepStrictEqual, [0, 1, 2, 'a', 'b'], @@ -385,7 +385,7 @@ assert.doesNotThrow(makeBlock(assert.deepStrictEqual, s, s)); assert.throws(makeBlock(a.deepStrictEqual, null, {}), a.AssertionError); assert.throws(makeBlock(a.deepStrictEqual, undefined, {}), a.AssertionError); assert.throws(makeBlock(a.deepStrictEqual, 'a', ['a']), a.AssertionError); -assert.throws(makeBlock(a.deepStrictEqual, 'a', {0: 'a'}), a.AssertionError); +assert.throws(makeBlock(a.deepStrictEqual, 'a', { 0: 'a' }), a.AssertionError); assert.throws(makeBlock(a.deepStrictEqual, 1, {}), a.AssertionError); assert.throws(makeBlock(a.deepStrictEqual, true, {}), a.AssertionError); assert.throws(makeBlock(assert.deepStrictEqual, Symbol(), {}), @@ -395,7 +395,7 @@ assert.throws(makeBlock(assert.deepStrictEqual, Symbol(), {}), // primitive wrappers and object assert.throws(makeBlock(a.deepStrictEqual, new String('a'), ['a']), a.AssertionError); -assert.throws(makeBlock(a.deepStrictEqual, new String('a'), {0: 'a'}), +assert.throws(makeBlock(a.deepStrictEqual, new String('a'), { 0: 'a' }), a.AssertionError); assert.throws(makeBlock(a.deepStrictEqual, new Number(1), {}), a.AssertionError); @@ -548,7 +548,7 @@ a.throws(makeBlock(thrower, TypeError), function(err) { const g = {}; g.ref = g; - const h = {ref: g}; + const h = { ref: g }; a.doesNotThrow(makeBlock(a.deepEqual, f, h)); a.doesNotThrow(makeBlock(a.deepStrictEqual, f, h)); @@ -569,7 +569,7 @@ a.throws(makeBlock(a.deepEqual, args, [])); a.throws(makeBlock(a.deepEqual, someArgs, ['a'])); a.throws(makeBlock(a.deepEqual, ['a'], someArgs)); - a.throws(makeBlock(a.deepEqual, someArgs, {'0': 'a'})); + a.throws(makeBlock(a.deepEqual, someArgs, { '0': 'a' })); a.throws(makeBlock(a.deepEqual, someArgs, diffArgs)); a.doesNotThrow(makeBlock(a.deepEqual, someArgs, sameArgs)); } @@ -606,7 +606,7 @@ a.throws(makeBlock(a.deepEqual, args, [])); })); } -const circular = {y: 1}; +const circular = { y: 1 }; circular.x = circular; function testAssertionMessage(actual, expected) { @@ -638,8 +638,8 @@ testAssertionMessage(function f() {}, '[Function: f]'); testAssertionMessage(function() {}, '[Function]'); testAssertionMessage({}, '{}'); testAssertionMessage(circular, '{ y: 1, x: [Circular] }'); -testAssertionMessage({a: undefined, b: null}, '{ a: undefined, b: null }'); -testAssertionMessage({a: NaN, b: Infinity, c: -Infinity}, +testAssertionMessage({ a: undefined, b: null }, '{ a: undefined, b: null }'); +testAssertionMessage({ a: NaN, b: Infinity, c: -Infinity }, '{ a: NaN, b: Infinity, c: -Infinity }'); // #2893 @@ -727,7 +727,7 @@ assert.throws(() => { assert.strictEqual('A'.repeat(1000), ''); }, common.expectsError({ code: 'ERR_ASSERTION', - message: new RegExp(`^'${'A'.repeat(127)} === ''$`)})); + message: new RegExp(`^'${'A'.repeat(127)} === ''$`) })); { // bad args to AssertionError constructor should throw TypeError diff --git a/test/parallel/test-async-hooks-http-agent.js b/test/parallel/test-async-hooks-http-agent.js index 348b97b111658a..ff19d089a02099 100644 --- a/test/parallel/test-async-hooks-http-agent.js +++ b/test/parallel/test-async-hooks-http-agent.js @@ -17,7 +17,7 @@ const agent = new http.Agent({ const server = http.createServer(common.mustCall((req, res) => { req.once('data', common.mustCallAtLeast(() => { - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('foo'); })); req.on('end', common.mustCall(() => { diff --git a/test/parallel/test-async-hooks-promise.js b/test/parallel/test-async-hooks-promise.js index ea5e59d319db53..c2d7bc76da64fb 100644 --- a/test/parallel/test-async-hooks-promise.js +++ b/test/parallel/test-async-hooks-promise.js @@ -8,7 +8,7 @@ const initCalls = []; async_hooks.createHook({ init: common.mustCall((id, type, triggerId, resource) => { assert.strictEqual(type, 'PROMISE'); - initCalls.push({id, triggerId, resource}); + initCalls.push({ id, triggerId, resource }); }, 2) }).enable(); diff --git a/test/parallel/test-buffer-alloc.js b/test/parallel/test-buffer-alloc.js index f86f31ec68811f..9e26c7aee6416e 100644 --- a/test/parallel/test-buffer-alloc.js +++ b/test/parallel/test-buffer-alloc.js @@ -266,10 +266,10 @@ assert.doesNotThrow(() => Buffer.alloc(1).write('', 1, 0)); // Test construction from arrayish object { - const arrayIsh = {0: 0, 1: 1, 2: 2, 3: 3, length: 4}; + const arrayIsh = { 0: 0, 1: 1, 2: 2, 3: 3, length: 4 }; let g = Buffer.from(arrayIsh); assert.deepStrictEqual(g, Buffer.from([0, 1, 2, 3])); - const strArrayIsh = {0: '0', 1: '1', 2: '2', 3: '3', length: 4}; + const strArrayIsh = { 0: '0', 1: '1', 2: '2', 3: '3', length: 4 }; g = Buffer.from(strArrayIsh); assert.deepStrictEqual(g, Buffer.from([0, 1, 2, 3])); } @@ -754,8 +754,8 @@ Buffer.allocUnsafe(3.3).fill().toString(); Buffer.alloc(3.3).fill().toString(); assert.strictEqual(Buffer.allocUnsafe(NaN).length, 0); assert.strictEqual(Buffer.allocUnsafe(3.3).length, 3); -assert.strictEqual(Buffer.from({length: 3.3}).length, 3); -assert.strictEqual(Buffer.from({length: 'BAM'}).length, 0); +assert.strictEqual(Buffer.from({ length: 3.3 }).length, 3); +assert.strictEqual(Buffer.from({ length: 'BAM' }).length, 0); // Make sure that strings are not coerced to numbers. assert.strictEqual(Buffer.from('99').length, 2); diff --git a/test/parallel/test-buffer-compare-offset.js b/test/parallel/test-buffer-compare-offset.js index 037e82e055cb91..ae7d81df3aaecc 100644 --- a/test/parallel/test-buffer-compare-offset.js +++ b/test/parallel/test-buffer-compare-offset.js @@ -49,7 +49,7 @@ assert.strictEqual(-1, a.compare(b, 0, 7, 4, 6)); assert.strictEqual(1, a.compare(b, 0, null)); // coerces to targetEnd == 5 -assert.strictEqual(-1, a.compare(b, 0, {valueOf: () => 5})); +assert.strictEqual(-1, a.compare(b, 0, { valueOf: () => 5 })); // zero length target assert.strictEqual(1, a.compare(b, Infinity, -Infinity)); diff --git a/test/parallel/test-buffer-from.js b/test/parallel/test-buffer-from.js index 214d8c67d2fc7d..ce20ff30bb3165 100644 --- a/test/parallel/test-buffer-from.js +++ b/test/parallel/test-buffer-from.js @@ -31,7 +31,7 @@ deepStrictEqual(Buffer.from(new String(checkString)), check); deepStrictEqual(Buffer.from(new MyString()), check); deepStrictEqual(Buffer.from(new MyPrimitive()), check); deepStrictEqual(Buffer.from( - runInNewContext('new String(checkString)', {checkString})), + runInNewContext('new String(checkString)', { checkString })), check); const err = new RegExp('^TypeError: First argument must be a string, Buffer, ' + diff --git a/test/parallel/test-buffer-sharedarraybuffer.js b/test/parallel/test-buffer-sharedarraybuffer.js index 582841d679c8d1..6c526bd6942734 100644 --- a/test/parallel/test-buffer-sharedarraybuffer.js +++ b/test/parallel/test-buffer-sharedarraybuffer.js @@ -27,4 +27,4 @@ assert.deepStrictEqual(arr_buf, ar_buf, 0); assert.strictEqual(Buffer.byteLength(sab), sab.byteLength, 0); -assert.doesNotThrow(() => Buffer.from({buffer: sab})); +assert.doesNotThrow(() => Buffer.from({ buffer: sab })); diff --git a/test/parallel/test-buffer-tostring-range.js b/test/parallel/test-buffer-tostring-range.js index a550906912a480..a1b39c88cec926 100644 --- a/test/parallel/test-buffer-tostring-range.js +++ b/test/parallel/test-buffer-tostring-range.js @@ -79,9 +79,9 @@ assert.strictEqual(rangeBuffer.toString('ascii', 0, 1.99), 'a'); assert.strictEqual(rangeBuffer.toString('ascii', 0, true), 'a'); // try toString() with a object as a encoding -assert.strictEqual(rangeBuffer.toString({toString: function() { +assert.strictEqual(rangeBuffer.toString({ toString: function() { return 'ascii'; -}}), 'abc'); +} }), 'abc'); // try toString() with 0 and null as the encoding assert.throws(() => { diff --git a/test/parallel/test-child-process-cwd.js b/test/parallel/test-child-process-cwd.js index 087a85243446d8..e1dcf85b0937b2 100644 --- a/test/parallel/test-child-process-cwd.js +++ b/test/parallel/test-child-process-cwd.js @@ -57,26 +57,27 @@ function testCwd(options, forCode, forData) { } // Assume these exist, and 'pwd' gives us the right directory back -testCwd({cwd: common.rootDir}, 0, common.rootDir); +testCwd({ cwd: common.rootDir }, 0, common.rootDir); if (common.isWindows) { - testCwd({cwd: process.env.windir}, 0, process.env.windir); + testCwd({ cwd: process.env.windir }, 0, process.env.windir); } else { - testCwd({cwd: '/dev'}, 0, '/dev'); + testCwd({ cwd: '/dev' }, 0, '/dev'); } // Assume does-not-exist doesn't exist, expect exitCode=-1 and errno=ENOENT { - testCwd({cwd: 'does-not-exist'}, -1).on('error', common.mustCall(function(e) { - assert.strictEqual(e.code, 'ENOENT'); - })); + testCwd({ cwd: 'does-not-exist' }, -1) + .on('error', common.mustCall(function(e) { + assert.strictEqual(e.code, 'ENOENT'); + })); } // Spawn() shouldn't try to chdir() so this should just work testCwd(undefined, 0); testCwd({}, 0); -testCwd({cwd: ''}, 0); -testCwd({cwd: undefined}, 0); -testCwd({cwd: null}, 0); +testCwd({ cwd: '' }, 0); +testCwd({ cwd: undefined }, 0); +testCwd({ cwd: null }, 0); // Check whether all tests actually returned assert.notStrictEqual(returns, 0); diff --git a/test/parallel/test-child-process-exec-cwd.js b/test/parallel/test-child-process-exec-cwd.js index f6719830c33538..c16f77f4c52906 100644 --- a/test/parallel/test-child-process-exec-cwd.js +++ b/test/parallel/test-child-process-exec-cwd.js @@ -34,7 +34,7 @@ if (common.isWindows) { dir = '/dev'; } -exec(pwdcommand, {cwd: dir}, common.mustCall(function(err, stdout, stderr) { +exec(pwdcommand, { cwd: dir }, common.mustCall(function(err, stdout, stderr) { assert.ifError(err); assert(stdout.startsWith(dir)); })); diff --git a/test/parallel/test-child-process-exec-maxBuffer.js b/test/parallel/test-child-process-exec-maxBuffer.js index 2c585abcdf82a8..6418f91765028a 100644 --- a/test/parallel/test-child-process-exec-maxBuffer.js +++ b/test/parallel/test-child-process-exec-maxBuffer.js @@ -32,11 +32,11 @@ const unicode = '中文测试'; // length = 4, byte length = 12 { const cmd = `"${process.execPath}" -e "console.log('${unicode}');"`; - cp.exec(cmd, {maxBuffer: 10}, checkFactory('stdout')); + cp.exec(cmd, { maxBuffer: 10 }, checkFactory('stdout')); } { const cmd = `"${process.execPath}" -e "console.error('${unicode}');"`; - cp.exec(cmd, {maxBuffer: 10}, checkFactory('stderr')); + cp.exec(cmd, { maxBuffer: 10 }, checkFactory('stderr')); } diff --git a/test/parallel/test-child-process-fork-exec-path.js b/test/parallel/test-child-process-fork-exec-path.js index aee99fbc7f3c59..06c6244eddaac4 100644 --- a/test/parallel/test-child-process-fork-exec-path.js +++ b/test/parallel/test-child-process-fork-exec-path.js @@ -24,7 +24,7 @@ const common = require('../common'); const assert = require('assert'); const fs = require('fs'); const path = require('path'); -const msg = {test: 'this'}; +const msg = { test: 'this' }; const nodePath = process.execPath; const copyPath = path.join(common.tmpDir, 'node-copy.exe'); diff --git a/test/parallel/test-child-process-fork-net.js b/test/parallel/test-child-process-fork-net.js index de0ec6ca003045..1da92592ffc3ba 100644 --- a/test/parallel/test-child-process-fork-net.js +++ b/test/parallel/test-child-process-fork-net.js @@ -50,13 +50,13 @@ if (process.argv[2] === 'child') { server.on('connection', function(socket) { console.log('CHILD: got connection'); - process.send({what: 'connection'}); + process.send({ what: 'connection' }); socket.destroy(); }); // start making connection from parent console.log('CHILD: server listening'); - process.send({what: 'listening'}); + process.send({ what: 'listening' }); }); process.on('message', function onClose(msg) { @@ -64,7 +64,7 @@ if (process.argv[2] === 'child') { process.removeListener('message', onClose); serverScope.on('close', function() { - process.send({what: 'close'}); + process.send({ what: 'close' }); }); serverScope.close(); }); @@ -76,7 +76,7 @@ if (process.argv[2] === 'child') { console.log('CHILD: got socket'); }); - process.send({what: 'ready'}); + process.send({ what: 'ready' }); } else { const child = fork(process.argv[1], ['child']); @@ -93,7 +93,7 @@ if (process.argv[2] === 'child') { const progress = new ProgressTracker(2, function() { server.on('close', function() { console.log('PARENT: server closed'); - child.send({what: 'close'}); + child.send({ what: 'close' }); }); server.close(); }); @@ -111,7 +111,7 @@ if (process.argv[2] === 'child') { }); server.on('listening', function() { console.log('PARENT: server listening'); - child.send({what: 'server'}, server); + child.send({ what: 'server' }, server); }); server.listen(0); @@ -153,7 +153,7 @@ if (process.argv[2] === 'child') { socket.on('close', function() { console.log('CLIENT: socket closed'); }); - child.send({what: 'socket'}, socket); + child.send({ what: 'socket' }, socket); }); server.on('close', function() { console.log('PARENT: server closed'); diff --git a/test/parallel/test-child-process-fork-ref.js b/test/parallel/test-child-process-fork-ref.js index a88408674afd74..3eae2b242e9ce2 100644 --- a/test/parallel/test-child-process-fork-ref.js +++ b/test/parallel/test-child-process-fork-ref.js @@ -37,7 +37,7 @@ if (process.argv[2] === 'child') { }); } else { - const child = fork(__filename, ['child'], {silent: true}); + const child = fork(__filename, ['child'], { silent: true }); const ipc = []; let stdout = ''; diff --git a/test/parallel/test-child-process-fork-stdio-string-variant.js b/test/parallel/test-child-process-fork-stdio-string-variant.js index cb20ed8f70ca72..cdeb15975a7b5a 100644 --- a/test/parallel/test-child-process-fork-stdio-string-variant.js +++ b/test/parallel/test-child-process-fork-stdio-string-variant.js @@ -11,16 +11,16 @@ const fixtures = require('../common/fixtures'); const childScript = fixtures.path('child-process-spawn-node'); const errorRegexp = /^TypeError: Incorrect value of stdio option:/; -const malFormedOpts = {stdio: '33'}; -const payload = {hello: 'world'}; +const malFormedOpts = { stdio: '33' }; +const payload = { hello: 'world' }; assert.throws(() => fork(childScript, malFormedOpts), errorRegexp); function test(stringVariant) { - const child = fork(childScript, {stdio: stringVariant}); + const child = fork(childScript, { stdio: stringVariant }); child.on('message', common.mustCall((message) => { - assert.deepStrictEqual(message, {foo: 'bar'}); + assert.deepStrictEqual(message, { foo: 'bar' }); })); child.send(payload); diff --git a/test/parallel/test-child-process-fork-stdio.js b/test/parallel/test-child-process-fork-stdio.js index 89a5ff98e5f8a8..be0bdf19c35832 100644 --- a/test/parallel/test-child-process-fork-stdio.js +++ b/test/parallel/test-child-process-fork-stdio.js @@ -20,7 +20,7 @@ if (process.argv[2] === 'child') { }); } else { assert.throws(() => { - cp.fork(__filename, {stdio: ['pipe', 'pipe', 'pipe', 'pipe']}); + cp.fork(__filename, { stdio: ['pipe', 'pipe', 'pipe', 'pipe'] }); }, /Forked processes must have an IPC channel/); let ipc = ''; diff --git a/test/parallel/test-child-process-internal.js b/test/parallel/test-child-process-internal.js index 0056d4215b65b6..4b22b4060307ed 100644 --- a/test/parallel/test-child-process-internal.js +++ b/test/parallel/test-child-process-internal.js @@ -25,8 +25,8 @@ const assert = require('assert'); //messages const PREFIX = 'NODE_'; -const normal = {cmd: `foo${PREFIX}`}; -const internal = {cmd: `${PREFIX}bar`}; +const normal = { cmd: `foo${PREFIX}` }; +const internal = { cmd: `${PREFIX}bar` }; if (process.argv[2] === 'child') { //send non-internal message containing PREFIX at a non prefix position diff --git a/test/parallel/test-child-process-send-keep-open.js b/test/parallel/test-child-process-send-keep-open.js index 1ce7d3828275c5..2d8a28121ac1fb 100644 --- a/test/parallel/test-child-process-send-keep-open.js +++ b/test/parallel/test-child-process-send-keep-open.js @@ -32,7 +32,7 @@ if (process.argv[2] !== 'child') { }); })); - child.send('socket', socket, {keepOpen: true}, common.mustCall((err) => { + child.send('socket', socket, { keepOpen: true }, common.mustCall((err) => { assert.ifError(err); })); }); diff --git a/test/parallel/test-child-process-send-type-error.js b/test/parallel/test-child-process-send-type-error.js index 00263a5d21550f..29dd45f6bdd7ee 100644 --- a/test/parallel/test-child-process-send-type-error.js +++ b/test/parallel/test-child-process-send-type-error.js @@ -7,7 +7,7 @@ const cp = require('child_process'); function fail(proc, args) { assert.throws(() => { proc.send.apply(proc, args); - }, common.expectsError({code: 'ERR_INVALID_ARG_TYPE', type: TypeError})); + }, common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', type: TypeError })); } let target = process; diff --git a/test/parallel/test-child-process-silent.js b/test/parallel/test-child-process-silent.js index bd61770cde4e34..b280e101810c54 100644 --- a/test/parallel/test-child-process-silent.js +++ b/test/parallel/test-child-process-silent.js @@ -39,7 +39,7 @@ if (process.argv[2] === 'pipe') { } else if (process.argv[2] === 'parent') { // Parent | start child pipe test - const child = childProcess.fork(process.argv[1], ['pipe'], {silent: true}); + const child = childProcess.fork(process.argv[1], ['pipe'], { silent: true }); // Allow child process to self terminate child.channel.close(); @@ -67,11 +67,11 @@ if (process.argv[2] === 'pipe') { }); // testing: do message system work when using silent - const child = childProcess.fork(process.argv[1], ['ipc'], {silent: true}); + const child = childProcess.fork(process.argv[1], ['ipc'], { silent: true }); // Manual pipe so we will get errors - child.stderr.pipe(process.stderr, {end: false}); - child.stdout.pipe(process.stdout, {end: false}); + child.stderr.pipe(process.stderr, { end: false }); + child.stdout.pipe(process.stdout, { end: false }); let childSending = false; let childReciveing = false; diff --git a/test/parallel/test-child-process-spawn-argv0.js b/test/parallel/test-child-process-spawn-argv0.js index b556c8bcf6ba32..a426fe8053bbd8 100644 --- a/test/parallel/test-child-process-spawn-argv0.js +++ b/test/parallel/test-child-process-spawn-argv0.js @@ -14,5 +14,5 @@ const noArgv0 = cp.spawnSync(process.execPath, [__filename, 'child']); assert.strictEqual(noArgv0.stdout.toString().trim(), process.execPath); const withArgv0 = cp.spawnSync(process.execPath, [__filename, 'child'], - {argv0: 'withArgv0'}); + { argv0: 'withArgv0' }); assert.strictEqual(withArgv0.stdout.toString().trim(), 'withArgv0'); diff --git a/test/parallel/test-child-process-spawn-shell.js b/test/parallel/test-child-process-spawn-shell.js index e9dd0e07efaa0c..e9a753e91a4e48 100644 --- a/test/parallel/test-child-process-spawn-shell.js +++ b/test/parallel/test-child-process-spawn-shell.js @@ -4,7 +4,7 @@ const assert = require('assert'); const cp = require('child_process'); // Verify that a shell is, in fact, executed -const doesNotExist = cp.spawn('does-not-exist', {shell: true}); +const doesNotExist = cp.spawn('does-not-exist', { shell: true }); assert.notStrictEqual(doesNotExist.spawnfile, 'does-not-exist'); doesNotExist.on('error', common.mustNotCall()); @@ -50,7 +50,7 @@ command.on('close', common.mustCall((code, signal) => { // Verify that the environment is properly inherited const env = cp.spawn(`"${process.execPath}" -pe process.env.BAZ`, { - env: Object.assign({}, process.env, {BAZ: 'buzz'}), + env: Object.assign({}, process.env, { BAZ: 'buzz' }), encoding: 'utf8', shell: true }); diff --git a/test/parallel/test-child-process-spawnsync-kill-signal.js b/test/parallel/test-child-process-spawnsync-kill-signal.js index ff0b36150f15a2..6a03f185a43f52 100644 --- a/test/parallel/test-child-process-spawnsync-kill-signal.js +++ b/test/parallel/test-child-process-spawnsync-kill-signal.js @@ -11,7 +11,7 @@ if (process.argv[2] === 'child') { function spawn(killSignal) { const child = cp.spawnSync(process.execPath, [__filename, 'child'], - {killSignal, timeout: 100}); + { killSignal, timeout: 100 }); assert.strictEqual(child.status, null); assert.strictEqual(child.error.code, 'ETIMEDOUT'); diff --git a/test/parallel/test-child-process-spawnsync-shell.js b/test/parallel/test-child-process-spawnsync-shell.js index 9e03ee126f087b..12cd8486ca9286 100644 --- a/test/parallel/test-child-process-spawnsync-shell.js +++ b/test/parallel/test-child-process-spawnsync-shell.js @@ -4,7 +4,7 @@ const assert = require('assert'); const cp = require('child_process'); // Verify that a shell is, in fact, executed -const doesNotExist = cp.spawnSync('does-not-exist', {shell: true}); +const doesNotExist = cp.spawnSync('does-not-exist', { shell: true }); assert.notStrictEqual(doesNotExist.file, 'does-not-exist'); assert.strictEqual(doesNotExist.error, undefined); @@ -16,7 +16,7 @@ else assert.strictEqual(doesNotExist.status, 127); // Exit code of /bin/sh // Verify that passing arguments works -const echo = cp.spawnSync('echo', ['foo'], {shell: true}); +const echo = cp.spawnSync('echo', ['foo'], { shell: true }); assert.strictEqual(echo.args[echo.args.length - 1].replace(/"/g, ''), 'echo foo'); @@ -24,13 +24,13 @@ assert.strictEqual(echo.stdout.toString().trim(), 'foo'); // Verify that shell features can be used const cmd = 'echo bar | cat'; -const command = cp.spawnSync(cmd, {shell: true}); +const command = cp.spawnSync(cmd, { shell: true }); assert.strictEqual(command.stdout.toString().trim(), 'bar'); // Verify that the environment is properly inherited const env = cp.spawnSync(`"${process.execPath}" -pe process.env.BAZ`, { - env: Object.assign({}, process.env, {BAZ: 'buzz'}), + env: Object.assign({}, process.env, { BAZ: 'buzz' }), shell: true }); diff --git a/test/parallel/test-child-process-spawnsync-timeout.js b/test/parallel/test-child-process-spawnsync-timeout.js index 07d89059be33d5..35df6cee22f5f2 100644 --- a/test/parallel/test-child-process-spawnsync-timeout.js +++ b/test/parallel/test-child-process-spawnsync-timeout.js @@ -38,7 +38,7 @@ switch (process.argv[2]) { default: const start = Date.now(); const ret = spawnSync(process.execPath, [__filename, 'child'], - {timeout: TIMER}); + { timeout: TIMER }); assert.strictEqual(ret.error.errno, 'ETIMEDOUT'); const end = Date.now() - start; assert(end < SLEEP); diff --git a/test/parallel/test-child-process-spawnsync.js b/test/parallel/test-child-process-spawnsync.js index 0d0a3dba566ad9..7b768d8403ac07 100644 --- a/test/parallel/test-child-process-spawnsync.js +++ b/test/parallel/test-child-process-spawnsync.js @@ -42,7 +42,7 @@ assert.deepStrictEqual(ret_err.spawnargs, ['bar']); { // Test the cwd option const cwd = common.rootDir; - const response = common.spawnSyncPwd({cwd}); + const response = common.spawnSyncPwd({ cwd }); assert.strictEqual(response.stdout.toString().trim(), cwd); } @@ -50,8 +50,8 @@ assert.deepStrictEqual(ret_err.spawnargs, ['bar']); { // Test the encoding option const noEncoding = common.spawnSyncPwd(); - const bufferEncoding = common.spawnSyncPwd({encoding: 'buffer'}); - const utf8Encoding = common.spawnSyncPwd({encoding: 'utf8'}); + const bufferEncoding = common.spawnSyncPwd({ encoding: 'buffer' }); + const utf8Encoding = common.spawnSyncPwd({ encoding: 'utf8' }); assert.deepStrictEqual(noEncoding.output, bufferEncoding.output); assert.deepStrictEqual([ diff --git a/test/parallel/test-child-process-stdio.js b/test/parallel/test-child-process-stdio.js index eda2d8841a8f5c..f1d18d437fd458 100644 --- a/test/parallel/test-child-process-stdio.js +++ b/test/parallel/test-child-process-stdio.js @@ -24,22 +24,22 @@ const common = require('../common'); const assert = require('assert'); const spawnSync = require('child_process').spawnSync; -let options = {stdio: ['pipe']}; +let options = { stdio: ['pipe'] }; let child = common.spawnPwd(options); assert.notStrictEqual(child.stdout, null); assert.notStrictEqual(child.stderr, null); -options = {stdio: 'ignore'}; +options = { stdio: 'ignore' }; child = common.spawnPwd(options); assert.strictEqual(child.stdout, null); assert.strictEqual(child.stderr, null); -options = {stdio: 'ignore'}; +options = { stdio: 'ignore' }; child = spawnSync('cat', [], options); -assert.deepStrictEqual(options, {stdio: 'ignore'}); +assert.deepStrictEqual(options, { stdio: 'ignore' }); assert.throws(() => { - common.spawnPwd({stdio: ['pipe', 'pipe', 'pipe', 'ipc', 'ipc']}); -}, common.expectsError({code: 'ERR_IPC_ONE_PIPE', type: Error})); + common.spawnPwd({ stdio: ['pipe', 'pipe', 'pipe', 'ipc', 'ipc'] }); +}, common.expectsError({ code: 'ERR_IPC_ONE_PIPE', type: Error })); diff --git a/test/parallel/test-child-process-uid-gid.js b/test/parallel/test-child-process-uid-gid.js index ec2cb9a31956c1..621884cea627ea 100644 --- a/test/parallel/test-child-process-uid-gid.js +++ b/test/parallel/test-child-process-uid-gid.js @@ -6,12 +6,12 @@ const expectedError = common.isWindows ? /\bENOTSUP\b/ : /\bEPERM\b/; if (common.isWindows || process.getuid() !== 0) { assert.throws(() => { - spawn('echo', ['fhqwhgads'], {uid: 0}); + spawn('echo', ['fhqwhgads'], { uid: 0 }); }, expectedError); } if (common.isWindows || !process.getgroups().some((gid) => gid === 0)) { assert.throws(() => { - spawn('echo', ['fhqwhgads'], {gid: 0}); + spawn('echo', ['fhqwhgads'], { gid: 0 }); }, expectedError); } diff --git a/test/parallel/test-cli-bad-options.js b/test/parallel/test-cli-bad-options.js index 15a385b99f66d9..ebc434670ed4a7 100644 --- a/test/parallel/test-cli-bad-options.js +++ b/test/parallel/test-cli-bad-options.js @@ -13,7 +13,7 @@ requiresArgument('--debug-port='); requiresArgument('--eval'); function requiresArgument(option) { - const r = spawn(process.execPath, [option], {encoding: 'utf8'}); + const r = spawn(process.execPath, [option], { encoding: 'utf8' }); assert.strictEqual(r.status, 9); diff --git a/test/parallel/test-cli-syntax.js b/test/parallel/test-cli-syntax.js index 256334f21fd75c..1171a153e3ec25 100644 --- a/test/parallel/test-cli-syntax.js +++ b/test/parallel/test-cli-syntax.js @@ -95,7 +95,7 @@ const notFoundRE = /^Error: Cannot find module/m; // loop each possible option, `-c` or `--check` syntaxArgs.forEach(function(args) { const stdin = 'throw new Error("should not get run");'; - const c = spawnSync(node, args, {encoding: 'utf8', input: stdin}); + const c = spawnSync(node, args, { encoding: 'utf8', input: stdin }); // no stdout or stderr should be produced assert.strictEqual(c.stdout, '', 'stdout produced'); @@ -108,7 +108,7 @@ syntaxArgs.forEach(function(args) { // loop each possible option, `-c` or `--check` syntaxArgs.forEach(function(args) { const stdin = 'var foo bar;'; - const c = spawnSync(node, args, {encoding: 'utf8', input: stdin}); + const c = spawnSync(node, args, { encoding: 'utf8', input: stdin }); // stderr should include '[stdin]' as the filename assert(c.stderr.startsWith('[stdin]'), "stderr doesn't start with [stdin]"); diff --git a/test/parallel/test-cluster-bind-twice.js b/test/parallel/test-cluster-bind-twice.js index 1fde246525eae1..4ef319ae80d409 100644 --- a/test/parallel/test-cluster-bind-twice.js +++ b/test/parallel/test-cluster-bind-twice.js @@ -68,7 +68,7 @@ if (!id) { a.on('message', common.mustCall((m) => { assert.strictEqual(m.msg, 'READY'); - b.send({msg: 'START', port: m.port}); + b.send({ msg: 'START', port: m.port }); })); b.on('message', common.mustCall((m) => { @@ -82,7 +82,7 @@ if (!id) { const server = http.createServer(common.mustNotCall()); server.listen(0, common.mustCall(() => { - process.send({msg: 'READY', port: server.address().port}); + process.send({ msg: 'READY', port: server.address().port }); })); process.on('message', common.mustCall((m) => { diff --git a/test/parallel/test-cluster-dgram-1.js b/test/parallel/test-cluster-dgram-1.js index 3688c67f6c68c8..5de04b3b7cb2d3 100644 --- a/test/parallel/test-cluster-dgram-1.js +++ b/test/parallel/test-cluster-dgram-1.js @@ -102,7 +102,7 @@ function worker() { // Every 10 messages, notify the master. if (received === PACKETS_PER_WORKER) { - process.send({received: received}); + process.send({ received: received }); socket.close(); } }, PACKETS_PER_WORKER)); diff --git a/test/parallel/test-cluster-disconnect-unshared-tcp.js b/test/parallel/test-cluster-disconnect-unshared-tcp.js index 584881f05f63fe..59df0c54795ec2 100644 --- a/test/parallel/test-cluster-disconnect-unshared-tcp.js +++ b/test/parallel/test-cluster-disconnect-unshared-tcp.js @@ -30,7 +30,7 @@ if (cluster.isMaster) { const unbound = cluster.fork().on('online', bind); function bind() { - cluster.fork({BOUND: 'y'}).on('listening', disconnect); + cluster.fork({ BOUND: 'y' }).on('listening', disconnect); } function disconnect() { diff --git a/test/parallel/test-cluster-disconnect-unshared-udp.js b/test/parallel/test-cluster-disconnect-unshared-udp.js index d34ce11b0285ab..b0670f3e323671 100644 --- a/test/parallel/test-cluster-disconnect-unshared-udp.js +++ b/test/parallel/test-cluster-disconnect-unshared-udp.js @@ -33,7 +33,7 @@ if (cluster.isMaster) { const unbound = cluster.fork().on('online', bind); function bind() { - cluster.fork({BOUND: 'y'}).on('listening', disconnect); + cluster.fork({ BOUND: 'y' }).on('listening', disconnect); } function disconnect() { diff --git a/test/parallel/test-cluster-eaccess.js b/test/parallel/test-cluster-eaccess.js index c7bb46b2844add..ecf0862fa3bab5 100644 --- a/test/parallel/test-cluster-eaccess.js +++ b/test/parallel/test-cluster-eaccess.js @@ -35,7 +35,7 @@ if (cluster.isMaster && process.argv.length !== 3) { // cluster.isMaster common.refreshTmpDir(); const PIPE_NAME = common.PIPE; - const worker = cluster.fork({PIPE_NAME}); + const worker = cluster.fork({ PIPE_NAME }); // makes sure master is able to fork the worker cluster.on('fork', common.mustCall()); diff --git a/test/parallel/test-cluster-ipc-throw.js b/test/parallel/test-cluster-ipc-throw.js index 95c5d84ea6dbb0..d19cf0c3811aa5 100644 --- a/test/parallel/test-cluster-ipc-throw.js +++ b/test/parallel/test-cluster-ipc-throw.js @@ -9,8 +9,8 @@ cluster.schedulingPolicy = cluster.SCHED_RR; const server = http.createServer(); if (cluster.isMaster) { - server.listen({port: 0}, common.mustCall(() => { - const worker = cluster.fork({PORT: server.address().port}); + server.listen({ port: 0 }, common.mustCall(() => { + const worker = cluster.fork({ PORT: server.address().port }); worker.on('exit', common.mustCall(() => { server.close(); })); diff --git a/test/parallel/test-cluster-master-error.js b/test/parallel/test-cluster-master-error.js index cc104ec44139f6..9abb42e4225567 100644 --- a/test/parallel/test-cluster-master-error.js +++ b/test/parallel/test-cluster-master-error.js @@ -84,7 +84,7 @@ if (cluster.isWorker) { const workers = []; // Spawn a cluster process - const master = fork(process.argv[1], ['cluster'], {silent: true}); + const master = fork(process.argv[1], ['cluster'], { silent: true }); // Handle messages from the cluster master.on('message', common.mustCall((data) => { diff --git a/test/parallel/test-cluster-send-deadlock.js b/test/parallel/test-cluster-send-deadlock.js index 9ae0f4a1192ac7..da503f67aa3a86 100644 --- a/test/parallel/test-cluster-send-deadlock.js +++ b/test/parallel/test-cluster-send-deadlock.js @@ -41,7 +41,7 @@ if (cluster.isMaster) { }); server.listen(0, function() { - worker.send({message: 'listen', port: server.address().port}); + worker.send({ message: 'listen', port: server.address().port }); }); } else { process.on('message', function(msg, handle) { diff --git a/test/parallel/test-cluster-shared-handle-bind-error.js b/test/parallel/test-cluster-shared-handle-bind-error.js index c58b6ed7d95001..1ce7a573cf6477 100644 --- a/test/parallel/test-cluster-shared-handle-bind-error.js +++ b/test/parallel/test-cluster-shared-handle-bind-error.js @@ -32,7 +32,7 @@ if (cluster.isMaster) { const server = net.createServer(common.mustNotCall()); server.listen(0, common.mustCall(() => { - const worker = cluster.fork({PORT: server.address().port}); + const worker = cluster.fork({ PORT: server.address().port }); worker.on('exit', common.mustCall((exitCode) => { assert.strictEqual(exitCode, 0); server.close(); diff --git a/test/parallel/test-cluster-worker-constructor.js b/test/parallel/test-cluster-worker-constructor.js index a8094e34df9c72..717969983d11ef 100644 --- a/test/parallel/test-cluster-worker-constructor.js +++ b/test/parallel/test-cluster-worker-constructor.js @@ -44,6 +44,6 @@ assert.strictEqual(worker.state, 'online'); assert.strictEqual(worker.id, 3); assert.strictEqual(worker.process, process); -worker = cluster.Worker.call({}, {id: 5}); +worker = cluster.Worker.call({}, { id: 5 }); assert(worker instanceof cluster.Worker); assert.strictEqual(worker.id, 5); diff --git a/test/parallel/test-cluster-worker-disconnect-on-error.js b/test/parallel/test-cluster-worker-disconnect-on-error.js index 70d6a4df2a950c..c55e69e256950f 100644 --- a/test/parallel/test-cluster-worker-disconnect-on-error.js +++ b/test/parallel/test-cluster-worker-disconnect-on-error.js @@ -14,7 +14,7 @@ if (cluster.isMaster) { assert.ifError(error); assert(worker); - worker.send({port: server.address().port}); + worker.send({ port: server.address().port }); })); worker = cluster.fork(); diff --git a/test/parallel/test-cluster-worker-no-exit.js b/test/parallel/test-cluster-worker-no-exit.js index 7dbe9fcb375caf..490000aeb6c42d 100644 --- a/test/parallel/test-cluster-worker-no-exit.js +++ b/test/parallel/test-cluster-worker-no-exit.js @@ -60,7 +60,7 @@ if (cluster.isMaster) { worker = cluster.fork() .on('online', function() { - this.send({port: port}); + this.send({ port: port }); }); }); process.on('exit', function() { diff --git a/test/parallel/test-common.js b/test/parallel/test-common.js index 50832b3343cf86..647c39d939f2aa 100644 --- a/test/parallel/test-common.js +++ b/test/parallel/test-common.js @@ -22,8 +22,8 @@ 'use strict'; const common = require('../common'); const assert = require('assert'); -const {join} = require('path'); -const {execFile} = require('child_process'); +const { join } = require('path'); +const { execFile } = require('child_process'); // test for leaked global detection global.gc = 42; // Not a valid global unless --expose_gc is set. diff --git a/test/parallel/test-console.js b/test/parallel/test-console.js index 0fcb765f207fb9..bca70467c0caac 100644 --- a/test/parallel/test-console.js +++ b/test/parallel/test-console.js @@ -58,28 +58,28 @@ common.hijackStderr(function(data) { console.log('foo'); console.log('foo', 'bar'); console.log('%s %s', 'foo', 'bar', 'hop'); -console.log({slashes: '\\\\'}); +console.log({ slashes: '\\\\' }); console.log(custom_inspect); // test console.info() goes to stdout console.info('foo'); console.info('foo', 'bar'); console.info('%s %s', 'foo', 'bar', 'hop'); -console.info({slashes: '\\\\'}); +console.info({ slashes: '\\\\' }); console.info(custom_inspect); // test console.error() goes to stderr console.error('foo'); console.error('foo', 'bar'); console.error('%s %s', 'foo', 'bar', 'hop'); -console.error({slashes: '\\\\'}); +console.error({ slashes: '\\\\' }); console.error(custom_inspect); // test console.warn() goes to stderr console.warn('foo'); console.warn('foo', 'bar'); console.warn('%s %s', 'foo', 'bar', 'hop'); -console.warn({slashes: '\\\\'}); +console.warn({ slashes: '\\\\' }); console.warn(custom_inspect); // test console.dir() diff --git a/test/parallel/test-crypto-binary-default.js b/test/parallel/test-crypto-binary-default.js index ab952fa89230bd..0350015dc64003 100644 --- a/test/parallel/test-crypto-binary-default.js +++ b/test/parallel/test-crypto-binary-default.js @@ -47,19 +47,19 @@ const rsaKeyPem = fixtures.readSync('test_rsa_privkey.pem', 'ascii'); // PFX tests assert.doesNotThrow(function() { - tls.createSecureContext({pfx: certPfx, passphrase: 'sample'}); + tls.createSecureContext({ pfx: certPfx, passphrase: 'sample' }); }); assert.throws(function() { - tls.createSecureContext({pfx: certPfx}); + tls.createSecureContext({ pfx: certPfx }); }, /^Error: mac verify failure$/); assert.throws(function() { - tls.createSecureContext({pfx: certPfx, passphrase: 'test'}); + tls.createSecureContext({ pfx: certPfx, passphrase: 'test' }); }, /^Error: mac verify failure$/); assert.throws(function() { - tls.createSecureContext({pfx: 'sample', passphrase: 'test'}); + tls.createSecureContext({ pfx: 'sample', passphrase: 'test' }); }, /^Error: not enough data$/); // Test HMAC @@ -569,7 +569,7 @@ testCipher4(Buffer.from('0123456789abcd0123456789'), Buffer.from('12345678')); // update() should only take buffers / strings assert.throws(function() { - crypto.createHash('sha1').update({foo: 'bar'}); + crypto.createHash('sha1').update({ foo: 'bar' }); }, /^TypeError: Data must be a string or a buffer$/); diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js index 58c72127a479fc..6262e083841617 100644 --- a/test/parallel/test-crypto.js +++ b/test/parallel/test-crypto.js @@ -41,7 +41,7 @@ const keyPem = fixtures.readSync('test_key.pem', 'ascii'); // 'this' safety // https://github.com/joyent/node/issues/6690 assert.throws(function() { - const options = {key: keyPem, cert: certPem, ca: caPem}; + const options = { key: keyPem, cert: certPem, ca: caPem }; const credentials = tls.createSecureContext(options); const context = credentials.context; const notcontext = { setOptions: context.setOptions, setKey: context.setKey }; @@ -50,25 +50,25 @@ assert.throws(function() { // PFX tests assert.doesNotThrow(function() { - tls.createSecureContext({pfx: certPfx, passphrase: 'sample'}); + tls.createSecureContext({ pfx: certPfx, passphrase: 'sample' }); }); assert.throws(function() { - tls.createSecureContext({pfx: certPfx}); + tls.createSecureContext({ pfx: certPfx }); }, /^Error: mac verify failure$/); assert.throws(function() { - tls.createSecureContext({pfx: certPfx, passphrase: 'test'}); + tls.createSecureContext({ pfx: certPfx, passphrase: 'test' }); }, /^Error: mac verify failure$/); assert.throws(function() { - tls.createSecureContext({pfx: 'sample', passphrase: 'test'}); + tls.createSecureContext({ pfx: 'sample', passphrase: 'test' }); }, /^Error: not enough data$/); // update() should only take buffers / strings assert.throws(function() { - crypto.createHash('sha1').update({foo: 'bar'}); + crypto.createHash('sha1').update({ foo: 'bar' }); }, /^TypeError: Data must be a string or a buffer$/); diff --git a/test/parallel/test-dgram-exclusive-implicit-bind.js b/test/parallel/test-dgram-exclusive-implicit-bind.js index de7137d964d932..171b221ee2982c 100644 --- a/test/parallel/test-dgram-exclusive-implicit-bind.js +++ b/test/parallel/test-dgram-exclusive-implicit-bind.js @@ -70,15 +70,15 @@ if (cluster.isMaster) { }); target.on('listening', function() { - cluster.fork({PORT: target.address().port}); - cluster.fork({PORT: target.address().port}); + cluster.fork({ PORT: target.address().port }); + cluster.fork({ PORT: target.address().port }); if (!common.isWindows) { - cluster.fork({BOUND: 'y', PORT: target.address().port}); - cluster.fork({BOUND: 'y', PORT: target.address().port}); + cluster.fork({ BOUND: 'y', PORT: target.address().port }); + cluster.fork({ BOUND: 'y', PORT: target.address().port }); } }); - target.bind({port: 0, exclusive: true}); + target.bind({ port: 0, exclusive: true }); return; } diff --git a/test/parallel/test-dgram-membership.js b/test/parallel/test-dgram-membership.js index 586db5f3cfeb70..183faca1a43b6f 100644 --- a/test/parallel/test-dgram-membership.js +++ b/test/parallel/test-dgram-membership.js @@ -5,7 +5,7 @@ const assert = require('assert'); const dgram = require('dgram'); const multicastAddress = '224.0.0.114'; -const setup = dgram.createSocket.bind(dgram, {type: 'udp4', reuseAddr: true}); +const setup = dgram.createSocket.bind(dgram, { type: 'udp4', reuseAddr: true }); // addMembership() on closed socket should throw { diff --git a/test/parallel/test-dns.js b/test/parallel/test-dns.js index abbfb9d16b19e8..8142489a235869 100644 --- a/test/parallel/test-dns.js +++ b/test/parallel/test-dns.js @@ -166,7 +166,7 @@ assert.throws(() => dns.lookup('nodejs.org'), assert.throws(() => dns.lookup('nodejs.org', 4), /^TypeError: Invalid arguments: callback must be passed$/); -assert.doesNotThrow(() => dns.lookup('', {family: 4, hints: 0}, +assert.doesNotThrow(() => dns.lookup('', { family: 4, hints: 0 }, common.mustCall())); assert.doesNotThrow(() => { @@ -176,7 +176,7 @@ assert.doesNotThrow(() => { }, common.mustCall()); }); -assert.doesNotThrow(() => dns.lookup('', {hints: dns.V4MAPPED}, +assert.doesNotThrow(() => dns.lookup('', { hints: dns.V4MAPPED }, common.mustCall())); assert.doesNotThrow(() => { diff --git a/test/parallel/test-domain-http-server.js b/test/parallel/test-domain-http-server.js index 98e15a8437774b..99000563eba8c8 100644 --- a/test/parallel/test-domain-http-server.js +++ b/test/parallel/test-domain-http-server.js @@ -41,7 +41,7 @@ const server = http.createServer(function(req, res) { serverCaught++; console.log('horray! got a server error', er); // try to send a 500. If that fails, oh well. - res.writeHead(500, {'content-type': 'text/plain'}); + res.writeHead(500, { 'content-type': 'text/plain' }); res.end(er.stack || er.message || 'Unknown error'); }); diff --git a/test/parallel/test-domain-top-level-error-handler-throw.js b/test/parallel/test-domain-top-level-error-handler-throw.js index 86df8db5b7423f..3a0768327383da 100644 --- a/test/parallel/test-domain-top-level-error-handler-throw.js +++ b/test/parallel/test-domain-top-level-error-handler-throw.js @@ -29,7 +29,7 @@ if (process.argv[2] === 'child') { const fork = require('child_process').fork; const assert = require('assert'); - const child = fork(process.argv[1], ['child'], {silent: true}); + const child = fork(process.argv[1], ['child'], { silent: true }); let stderrOutput = ''; if (child) { child.stderr.on('data', function onStderrData(data) { diff --git a/test/parallel/test-event-emitter-errors.js b/test/parallel/test-event-emitter-errors.js index be4f4007f096df..d52d3b4f4e74ef 100644 --- a/test/parallel/test-event-emitter-errors.js +++ b/test/parallel/test-event-emitter-errors.js @@ -10,5 +10,5 @@ assert.throws(() => { }, /^Error: Unhandled "error" event\. \(Accepts a string\)$/); assert.throws(() => { - EE.emit('error', {message: 'Error!'}); + EE.emit('error', { message: 'Error!' }); }, /^Error: Unhandled "error" event\. \(\[object Object\]\)$/); diff --git a/test/parallel/test-fs-read-stream-inherit.js b/test/parallel/test-fs-read-stream-inherit.js index 8b1ca06950a98a..ddb07274d1f887 100644 --- a/test/parallel/test-fs-read-stream-inherit.js +++ b/test/parallel/test-fs-read-stream-inherit.js @@ -49,7 +49,7 @@ const rangeFile = path.join(common.fixturesDir, 'x.txt'); } { - const file = fs.createReadStream(fn, Object.create({encoding: 'utf8'})); + const file = fs.createReadStream(fn, Object.create({ encoding: 'utf8' })); file.length = 0; file.on('data', function(data) { assert.strictEqual(typeof data, 'string'); @@ -67,7 +67,7 @@ const rangeFile = path.join(common.fixturesDir, 'x.txt'); } { - const options = Object.create({bufferSize: 1, start: 1, end: 2}); + const options = Object.create({ bufferSize: 1, start: 1, end: 2 }); const file = fs.createReadStream(rangeFile, options); assert.strictEqual(file.start, 1); assert.strictEqual(file.end, 2); @@ -81,7 +81,7 @@ const rangeFile = path.join(common.fixturesDir, 'x.txt'); } { - const options = Object.create({bufferSize: 1, start: 1}); + const options = Object.create({ bufferSize: 1, start: 1 }); const file = fs.createReadStream(rangeFile, options); assert.strictEqual(file.start, 1); file.data = ''; @@ -95,7 +95,7 @@ const rangeFile = path.join(common.fixturesDir, 'x.txt'); // https://github.com/joyent/node/issues/2320 { - const options = Object.create({bufferSize: 1.23, start: 1}); + const options = Object.create({ bufferSize: 1.23, start: 1 }); const file = fs.createReadStream(rangeFile, options); assert.strictEqual(file.start, 1); file.data = ''; @@ -109,12 +109,12 @@ const rangeFile = path.join(common.fixturesDir, 'x.txt'); { assert.throws(function() { - fs.createReadStream(rangeFile, Object.create({start: 10, end: 2})); + fs.createReadStream(rangeFile, Object.create({ start: 10, end: 2 })); }, /"start" option must be <= "end" option/); } { - const options = Object.create({start: 0, end: 0}); + const options = Object.create({ start: 0, end: 0 }); const stream = fs.createReadStream(rangeFile, options); assert.strictEqual(stream.start, 0); assert.strictEqual(stream.end, 0); @@ -139,7 +139,7 @@ const rangeFile = path.join(common.fixturesDir, 'x.txt'); { let data = ''; let file = - fs.createReadStream(rangeFile, Object.create({autoClose: false })); + fs.createReadStream(rangeFile, Object.create({ autoClose: false })); assert.strictEqual(file.autoClose, false); file.on('data', (chunk) => { data += chunk; }); file.on('end', common.mustCall(function() { @@ -153,7 +153,7 @@ const rangeFile = path.join(common.fixturesDir, 'x.txt'); function fileNext() { // This will tell us if the fd is usable again or not. - file = fs.createReadStream(null, Object.create({fd: file.fd, start: 0 })); + file = fs.createReadStream(null, Object.create({ fd: file.fd, start: 0 })); file.data = ''; file.on('data', function(data) { file.data += data; @@ -170,7 +170,7 @@ const rangeFile = path.join(common.fixturesDir, 'x.txt'); // Just to make sure autoClose won't close the stream because of error. { - const options = Object.create({fd: 13337, autoClose: false}); + const options = Object.create({ fd: 13337, autoClose: false }); const file = fs.createReadStream(null, options); file.on('data', common.mustNotCall()); file.on('error', common.mustCall()); diff --git a/test/parallel/test-fs-read-stream-throw-type-error.js b/test/parallel/test-fs-read-stream-throw-type-error.js index 6e4f405daa8ff6..b6e1869fdc2cc9 100644 --- a/test/parallel/test-fs-read-stream-throw-type-error.js +++ b/test/parallel/test-fs-read-stream-throw-type-error.js @@ -16,7 +16,7 @@ assert.doesNotThrow(function() { fs.createReadStream(example, 'utf8'); }); assert.doesNotThrow(function() { - fs.createReadStream(example, {encoding: 'utf8'}); + fs.createReadStream(example, { encoding: 'utf8' }); }); const errMessage = /"options" must be a string or an object/; diff --git a/test/parallel/test-fs-read-stream.js b/test/parallel/test-fs-read-stream.js index eb216d2a4daaf7..04c10b5a4415c1 100644 --- a/test/parallel/test-fs-read-stream.js +++ b/test/parallel/test-fs-read-stream.js @@ -86,7 +86,7 @@ const rangeFile = fixtures.path('x.txt'); } { - const file = fs.createReadStream(fn, {encoding: 'utf8'}); + const file = fs.createReadStream(fn, { encoding: 'utf8' }); file.length = 0; file.on('data', function(data) { assert.strictEqual('string', typeof data); @@ -107,7 +107,7 @@ const rangeFile = fixtures.path('x.txt'); { const file = - fs.createReadStream(rangeFile, {bufferSize: 1, start: 1, end: 2}); + fs.createReadStream(rangeFile, { bufferSize: 1, start: 1, end: 2 }); let contentRead = ''; file.on('data', function(data) { contentRead += data.toString('utf-8'); @@ -118,7 +118,7 @@ const rangeFile = fixtures.path('x.txt'); } { - const file = fs.createReadStream(rangeFile, {bufferSize: 1, start: 1}); + const file = fs.createReadStream(rangeFile, { bufferSize: 1, start: 1 }); file.data = ''; file.on('data', function(data) { file.data += data.toString('utf-8'); @@ -130,7 +130,7 @@ const rangeFile = fixtures.path('x.txt'); { // Ref: https://github.com/nodejs/node-v0.x-archive/issues/2320 - const file = fs.createReadStream(rangeFile, {bufferSize: 1.23, start: 1}); + const file = fs.createReadStream(rangeFile, { bufferSize: 1.23, start: 1 }); file.data = ''; file.on('data', function(data) { file.data += data.toString('utf-8'); @@ -141,7 +141,7 @@ const rangeFile = fixtures.path('x.txt'); } assert.throws(function() { - fs.createReadStream(rangeFile, {start: 10, end: 2}); + fs.createReadStream(rangeFile, { start: 10, end: 2 }); }, /"start" option must be <= "end" option/); { @@ -165,7 +165,7 @@ assert.throws(function() { } { - let file = fs.createReadStream(rangeFile, {autoClose: false }); + let file = fs.createReadStream(rangeFile, { autoClose: false }); let data = ''; file.on('data', function(chunk) { data += chunk; }); file.on('end', common.mustCall(function() { @@ -179,7 +179,7 @@ assert.throws(function() { function fileNext() { // This will tell us if the fd is usable again or not. - file = fs.createReadStream(null, {fd: file.fd, start: 0 }); + file = fs.createReadStream(null, { fd: file.fd, start: 0 }); file.data = ''; file.on('data', function(data) { file.data += data; @@ -196,7 +196,7 @@ assert.throws(function() { { // Just to make sure autoClose won't close the stream because of error. - const file = fs.createReadStream(null, {fd: 13337, autoClose: false }); + const file = fs.createReadStream(null, { fd: 13337, autoClose: false }); file.on('data', common.mustNotCall()); file.on('error', common.mustCall()); process.on('exit', function() { diff --git a/test/parallel/test-fs-realpath-buffer-encoding.js b/test/parallel/test-fs-realpath-buffer-encoding.js index 0ce6ec576dac69..84fd3dca24a329 100644 --- a/test/parallel/test-fs-realpath-buffer-encoding.js +++ b/test/parallel/test-fs-realpath-buffer-encoding.js @@ -20,13 +20,13 @@ for (encoding in expected) { const expected_value = expected[encoding]; let result; - result = fs.realpathSync(string_dir, {encoding: encoding}); + result = fs.realpathSync(string_dir, { encoding: encoding }); assert.strictEqual(result, expected_value); result = fs.realpathSync(string_dir, encoding); assert.strictEqual(result, expected_value); - result = fs.realpathSync(buffer_dir, {encoding: encoding}); + result = fs.realpathSync(buffer_dir, { encoding: encoding }); assert.strictEqual(result, expected_value); result = fs.realpathSync(buffer_dir, encoding); @@ -34,13 +34,13 @@ for (encoding in expected) { } let buffer_result; -buffer_result = fs.realpathSync(string_dir, {encoding: 'buffer'}); +buffer_result = fs.realpathSync(string_dir, { encoding: 'buffer' }); assert.deepStrictEqual(buffer_result, buffer_dir); buffer_result = fs.realpathSync(string_dir, 'buffer'); assert.deepStrictEqual(buffer_result, buffer_dir); -buffer_result = fs.realpathSync(buffer_dir, {encoding: 'buffer'}); +buffer_result = fs.realpathSync(buffer_dir, { encoding: 'buffer' }); assert.deepStrictEqual(buffer_result, buffer_dir); buffer_result = fs.realpathSync(buffer_dir, 'buffer'); @@ -50,25 +50,27 @@ assert.deepStrictEqual(buffer_result, buffer_dir); for (encoding in expected) { const expected_value = expected[encoding]; - fs.realpath(string_dir, {encoding: encoding}, common.mustCall((err, res) => { - assert.ifError(err); - assert.strictEqual(res, expected_value); - })); + fs.realpath(string_dir, { encoding: encoding }, + common.mustCall((err, res) => { + assert.ifError(err); + assert.strictEqual(res, expected_value); + })); fs.realpath(string_dir, encoding, common.mustCall((err, res) => { assert.ifError(err); assert.strictEqual(res, expected_value); })); - fs.realpath(buffer_dir, {encoding: encoding}, common.mustCall((err, res) => { - assert.ifError(err); - assert.strictEqual(res, expected_value); - })); + fs.realpath(buffer_dir, { encoding: encoding }, + common.mustCall((err, res) => { + assert.ifError(err); + assert.strictEqual(res, expected_value); + })); fs.realpath(buffer_dir, encoding, common.mustCall((err, res) => { assert.ifError(err); assert.strictEqual(res, expected_value); })); } -fs.realpath(string_dir, {encoding: 'buffer'}, common.mustCall((err, res) => { +fs.realpath(string_dir, { encoding: 'buffer' }, common.mustCall((err, res) => { assert.ifError(err); assert.deepStrictEqual(res, buffer_dir); })); @@ -78,7 +80,7 @@ fs.realpath(string_dir, 'buffer', common.mustCall((err, res) => { assert.deepStrictEqual(res, buffer_dir); })); -fs.realpath(buffer_dir, {encoding: 'buffer'}, common.mustCall((err, res) => { +fs.realpath(buffer_dir, { encoding: 'buffer' }, common.mustCall((err, res) => { assert.ifError(err); assert.deepStrictEqual(res, buffer_dir); })); diff --git a/test/parallel/test-fs-watch-encoding.js b/test/parallel/test-fs-watch-encoding.js index 18b6f2ecf6a16b..5226899d2f33a8 100644 --- a/test/parallel/test-fs-watch-encoding.js +++ b/test/parallel/test-fs-watch-encoding.js @@ -43,7 +43,7 @@ function unregisterWatcher(watcher) { const watcher1 = fs.watch( common.tmpDir, - {encoding: 'hex'}, + { encoding: 'hex' }, (event, filename) => { if (['e696b0e5bbbae69687e5a4b9e4bbb62e747874', null].includes(filename)) done(watcher1); @@ -62,7 +62,7 @@ registerWatcher(watcher2); const watcher3 = fs.watch( common.tmpDir, - {encoding: 'buffer'}, + { encoding: 'buffer' }, (event, filename) => { if (filename instanceof Buffer && filename.toString('utf8') === fn) done(watcher3); diff --git a/test/parallel/test-fs-watch-recursive.js b/test/parallel/test-fs-watch-recursive.js index 8e27abb2517692..3e3746df1ef336 100644 --- a/test/parallel/test-fs-watch-recursive.js +++ b/test/parallel/test-fs-watch-recursive.js @@ -18,7 +18,7 @@ const testsubdir = fs.mkdtempSync(testDir + path.sep); const relativePathOne = path.join(path.basename(testsubdir), filenameOne); const filepathOne = path.join(testsubdir, filenameOne); -const watcher = fs.watch(testDir, {recursive: true}); +const watcher = fs.watch(testDir, { recursive: true }); let watcherClosed = false; watcher.on('change', function(event, filename) { diff --git a/test/parallel/test-fs-watchfile.js b/test/parallel/test-fs-watchfile.js index 2c0e35719c40c6..d99de562bb2a8e 100644 --- a/test/parallel/test-fs-watchfile.js +++ b/test/parallel/test-fs-watchfile.js @@ -42,7 +42,7 @@ common.refreshTmpDir(); // time, the callback should be invoked again with proper values in stat object let fileExists = false; -fs.watchFile(enoentFile, {interval: 0}, common.mustCall(function(curr, prev) { +fs.watchFile(enoentFile, { interval: 0 }, common.mustCall(function(curr, prev) { if (!fileExists) { // If the file does not exist, all the fields should be zero and the date // fields should be UNIX EPOCH time diff --git a/test/parallel/test-fs-write-file-sync.js b/test/parallel/test-fs-write-file-sync.js index d888fcd3a3b7c1..570fe743fd1318 100644 --- a/test/parallel/test-fs-write-file-sync.js +++ b/test/parallel/test-fs-write-file-sync.js @@ -51,9 +51,9 @@ common.refreshTmpDir(); // Test writeFileSync const file1 = path.join(common.tmpDir, 'testWriteFileSync.txt'); -fs.writeFileSync(file1, '123', {mode: mode}); +fs.writeFileSync(file1, '123', { mode: mode }); -content = fs.readFileSync(file1, {encoding: 'utf8'}); +content = fs.readFileSync(file1, { encoding: 'utf8' }); assert.strictEqual(content, '123'); assert.strictEqual(fs.statSync(file1).mode & 0o777, mode); @@ -61,9 +61,9 @@ assert.strictEqual(fs.statSync(file1).mode & 0o777, mode); // Test appendFileSync const file2 = path.join(common.tmpDir, 'testAppendFileSync.txt'); -fs.appendFileSync(file2, 'abc', {mode: mode}); +fs.appendFileSync(file2, 'abc', { mode: mode }); -content = fs.readFileSync(file2, {encoding: 'utf8'}); +content = fs.readFileSync(file2, { encoding: 'utf8' }); assert.strictEqual(content, 'abc'); assert.strictEqual(fs.statSync(file2).mode & mode, mode); @@ -75,7 +75,7 @@ const fd = fs.openSync(file3, 'w+', mode); fs.writeFileSync(fd, '123'); fs.closeSync(fd); -content = fs.readFileSync(file3, {encoding: 'utf8'}); +content = fs.readFileSync(file3, { encoding: 'utf8' }); assert.strictEqual(content, '123'); assert.strictEqual(fs.statSync(file3).mode & 0o777, mode); diff --git a/test/parallel/test-fs-write-stream-autoclose-option.js b/test/parallel/test-fs-write-stream-autoclose-option.js index 4bfa4ba5341e1e..df73d18b44210d 100644 --- a/test/parallel/test-fs-write-stream-autoclose-option.js +++ b/test/parallel/test-fs-write-stream-autoclose-option.js @@ -6,7 +6,7 @@ const fs = require('fs'); const file = path.join(common.tmpDir, 'write-autoclose-opt1.txt'); common.refreshTmpDir(); -let stream = fs.createWriteStream(file, {flags: 'w+', autoClose: false}); +let stream = fs.createWriteStream(file, { flags: 'w+', autoClose: false }); stream.write('Test1'); stream.end(); stream.on('finish', common.mustCall(function() { @@ -19,7 +19,7 @@ stream.on('finish', common.mustCall(function() { function next() { // This will tell us if the fd is usable again or not - stream = fs.createWriteStream(null, {fd: stream.fd, start: 0}); + stream = fs.createWriteStream(null, { fd: stream.fd, start: 0 }); stream.write('Test2'); stream.end(); stream.on('finish', common.mustCall(function() { @@ -40,7 +40,7 @@ function next2() { function next3() { // This is to test success scenario where autoClose is true - const stream = fs.createWriteStream(file, {autoClose: true}); + const stream = fs.createWriteStream(file, { autoClose: true }); stream.write('Test3'); stream.end(); stream.on('finish', common.mustCall(function() { diff --git a/test/parallel/test-fs-write-stream-throw-type-error.js b/test/parallel/test-fs-write-stream-throw-type-error.js index 62627e1e32e192..5652e9e5e697cc 100644 --- a/test/parallel/test-fs-write-stream-throw-type-error.js +++ b/test/parallel/test-fs-write-stream-throw-type-error.js @@ -27,7 +27,7 @@ assert.doesNotThrow(() => { }); assert.doesNotThrow(() => { - fs.createWriteStream(example, {encoding: 'utf8'}); + fs.createWriteStream(example, { encoding: 'utf8' }); }); assert.throws(() => { diff --git a/test/parallel/test-http-1.0-keep-alive.js b/test/parallel/test-http-1.0-keep-alive.js index f3b69a4cd059dd..6d117035a5c727 100644 --- a/test/parallel/test-http-1.0-keep-alive.js +++ b/test/parallel/test-http-1.0-keep-alive.js @@ -39,7 +39,7 @@ check([{ '\r\n' }], responses: [{ - headers: {'Connection': 'keep-alive'}, + headers: { 'Connection': 'keep-alive' }, chunks: ['OK'] }, { chunks: [] @@ -58,7 +58,7 @@ check([{ '\r\n' }], responses: [{ - headers: {'Connection': 'keep-alive'}, + headers: { 'Connection': 'keep-alive' }, chunks: ['OK'] }, { chunks: [] @@ -76,8 +76,8 @@ check([{ '\r\n' }], responses: [{ - headers: {'Connection': 'keep-alive', - 'Transfer-Encoding': 'chunked'}, + headers: { 'Connection': 'keep-alive', + 'Transfer-Encoding': 'chunked' }, chunks: ['OK'] }, { chunks: [] @@ -95,8 +95,8 @@ check([{ '\r\n' }], responses: [{ - headers: {'Connection': 'keep-alive', - 'Content-Length': '2'}, + headers: { 'Connection': 'keep-alive', + 'Content-Length': '2' }, chunks: ['OK'] }, { chunks: [] diff --git a/test/parallel/test-http-1.0.js b/test/parallel/test-http-1.0.js index f67d949bc8f5f6..47df50e2897b79 100644 --- a/test/parallel/test-http-1.0.js +++ b/test/parallel/test-http-1.0.js @@ -61,7 +61,7 @@ function test(handler, request_generator, response_validator) { assert.strictEqual('1.0', req.httpVersion); assert.strictEqual(1, req.httpVersionMajor); assert.strictEqual(0, req.httpVersionMinor); - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(body); } @@ -90,7 +90,7 @@ function test(handler, request_generator, response_validator) { assert.strictEqual(1, req.httpVersionMajor); assert.strictEqual(0, req.httpVersionMinor); res.sendDate = false; - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('Hello, '); res._send(''); res.write('world!'); res._send(''); res.end(); @@ -126,7 +126,7 @@ function test(handler, request_generator, response_validator) { assert.strictEqual(1, req.httpVersionMajor); assert.strictEqual(1, req.httpVersionMinor); res.sendDate = false; - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('Hello, '); res._send(''); res.write('world!'); res._send(''); res.end(); diff --git a/test/parallel/test-http-abort-queued-2.js b/test/parallel/test-http-abort-queued-2.js index ecb76c1f5ed6db..6282aa3da7caf2 100644 --- a/test/parallel/test-http-abort-queued-2.js +++ b/test/parallel/test-http-abort-queued-2.js @@ -22,12 +22,12 @@ server.listen(0, common.mustCall(() => { maxSockets: 1 }); - http.get({agent, port}, (res) => res.resume()); + http.get({ agent, port }, (res) => res.resume()); - const req = http.get({agent, port}, common.mustNotCall()); + const req = http.get({ agent, port }, common.mustNotCall()); req.abort(); - http.get({agent, port}, common.mustCall((res) => { + http.get({ agent, port }, common.mustCall((res) => { res.resume(); assert.strictEqual(socketsCreated, 1); agent.destroy(); diff --git a/test/parallel/test-http-abort-stream-end.js b/test/parallel/test-http-abort-stream-end.js index 1610c5ae6d44ad..8d2704a1ee7d17 100644 --- a/test/parallel/test-http-abort-stream-end.js +++ b/test/parallel/test-http-abort-stream-end.js @@ -31,7 +31,7 @@ let size = 0; const server = http.createServer(common.mustCall((req, res) => { server.close(); - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); for (let i = 0; i < maxSize; i++) { res.write(`x${i}`); } diff --git a/test/parallel/test-http-client-get-url.js b/test/parallel/test-http-client-get-url.js index 53ccd66182a663..7f6bfb8ecaa17b 100644 --- a/test/parallel/test-http-client-get-url.js +++ b/test/parallel/test-http-client-get-url.js @@ -30,7 +30,7 @@ const testPath = '/foo?bar'; const server = http.createServer(common.mustCall((req, res) => { assert.strictEqual('GET', req.method); assert.strictEqual(testPath, req.url); - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('hello\n'); res.end(); }, 3)); diff --git a/test/parallel/test-http-client-pipe-end.js b/test/parallel/test-http-client-pipe-end.js index 81955996528e8f..4b9f168e9907f2 100644 --- a/test/parallel/test-http-client-pipe-end.js +++ b/test/parallel/test-http-client-pipe-end.js @@ -39,7 +39,7 @@ common.refreshTmpDir(); server.listen(common.PIPE, function() { const req = http.request({ socketPath: common.PIPE, - headers: {'Content-Length': '1'}, + headers: { 'Content-Length': '1' }, method: 'POST', path: '/' }); diff --git a/test/parallel/test-http-client-race-2.js b/test/parallel/test-http-client-race-2.js index e1f8409a8cbd50..acd848c26532c1 100644 --- a/test/parallel/test-http-client-race-2.js +++ b/test/parallel/test-http-client-race-2.js @@ -45,7 +45,10 @@ const server = http.createServer(function(req, res) { } res.writeHead(200, - {'Content-Type': 'text/plain', 'Content-Length': body.length}); + { + 'Content-Type': 'text/plain', + 'Content-Length': body.length + }); res.end(body); }); server.listen(0); diff --git a/test/parallel/test-http-client-race.js b/test/parallel/test-http-client-race.js index 33c74ce370866a..d7ba5ed566e674 100644 --- a/test/parallel/test-http-client-race.js +++ b/test/parallel/test-http-client-race.js @@ -31,7 +31,10 @@ const body2_s = '22222'; const server = http.createServer(function(req, res) { const body = url.parse(req.url).pathname === '/1' ? body1_s : body2_s; res.writeHead(200, - {'Content-Type': 'text/plain', 'Content-Length': body.length}); + { + 'Content-Type': 'text/plain', + 'Content-Length': body.length + }); res.end(body); }); server.listen(0); diff --git a/test/parallel/test-http-client-reject-chunked-with-content-length.js b/test/parallel/test-http-client-reject-chunked-with-content-length.js index d29e37291dffde..8683b5726e2758 100644 --- a/test/parallel/test-http-client-reject-chunked-with-content-length.js +++ b/test/parallel/test-http-client-reject-chunked-with-content-length.js @@ -17,7 +17,7 @@ server.listen(0, () => { // The callback should not be called because the server is sending // both a Content-Length header and a Transfer-Encoding: chunked // header, which is a violation of the HTTP spec. - const req = http.get({port: server.address().port}, common.mustNotCall()); + const req = http.get({ port: server.address().port }, common.mustNotCall()); req.on('error', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); assert.strictEqual(err.code, 'HPE_UNEXPECTED_CONTENT_LENGTH'); diff --git a/test/parallel/test-http-client-reject-cr-no-lf.js b/test/parallel/test-http-client-reject-cr-no-lf.js index 03dfabf0d7f0f8..bd303888bb63f9 100644 --- a/test/parallel/test-http-client-reject-cr-no-lf.js +++ b/test/parallel/test-http-client-reject-cr-no-lf.js @@ -16,7 +16,7 @@ const server = net.createServer((socket) => { server.listen(0, () => { // The callback should not be called because the server is sending a // header field that ends only in \r with no following \n - const req = http.get({port: server.address().port}, common.mustNotCall()); + const req = http.get({ port: server.address().port }, common.mustNotCall()); req.on('error', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); assert.strictEqual(err.code, 'HPE_LF_EXPECTED'); diff --git a/test/parallel/test-http-client-reject-unexpected-agent.js b/test/parallel/test-http-client-reject-unexpected-agent.js index e89bcfad5b5995..f1798b483f44fa 100644 --- a/test/parallel/test-http-client-reject-unexpected-agent.js +++ b/test/parallel/test-http-client-reject-unexpected-agent.js @@ -32,7 +32,7 @@ const server = http.createServer((req, res) => { let numberOfResponses = 0; function createRequest(agent) { - const options = Object.assign(baseOptions, {agent}); + const options = Object.assign(baseOptions, { agent }); const request = http.request(options); request.end(); request.on('response', common.mustCall(() => { diff --git a/test/parallel/test-http-client-response-domain.js b/test/parallel/test-http-client-response-domain.js index dab5711eb17833..ff73fd51cc5d73 100644 --- a/test/parallel/test-http-client-response-domain.js +++ b/test/parallel/test-http-client-response-domain.js @@ -49,7 +49,7 @@ function test() { const req = http.get({ socketPath: common.PIPE, - headers: {'Content-Length': '1'}, + headers: { 'Content-Length': '1' }, method: 'POST', path: '/' }); diff --git a/test/parallel/test-http-client-timeout-agent.js b/test/parallel/test-http-client-timeout-agent.js index b041f21ca8c196..641de122d57abd 100644 --- a/test/parallel/test-http-client-timeout-agent.js +++ b/test/parallel/test-http-client-timeout-agent.js @@ -40,7 +40,7 @@ const server = http.createServer(function(req, res) { if (reqid % 2) { // do not reply the request } else { - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write(reqid.toString()); res.end(); } diff --git a/test/parallel/test-http-client-timeout-with-data.js b/test/parallel/test-http-client-timeout-with-data.js index a35611bb083d3d..bc5670b6939e39 100644 --- a/test/parallel/test-http-client-timeout-with-data.js +++ b/test/parallel/test-http-client-timeout-with-data.js @@ -34,7 +34,7 @@ const options = { }; const server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Length': '2'}); + res.writeHead(200, { 'Content-Length': '2' }); res.write('*'); server.once('timeout', common.mustCall(function() { res.end('*'); })); }); diff --git a/test/parallel/test-http-client-upload-buf.js b/test/parallel/test-http-client-upload-buf.js index b56c1302c2ad00..b778d07a826b1d 100644 --- a/test/parallel/test-http-client-upload-buf.js +++ b/test/parallel/test-http-client-upload-buf.js @@ -38,7 +38,7 @@ const server = http.createServer(common.mustCall(function(req, res) { req.on('end', common.mustCall(function() { assert.strictEqual(N, bytesReceived); console.log('request complete from server'); - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('hello\n'); res.end(); })); diff --git a/test/parallel/test-http-client-upload.js b/test/parallel/test-http-client-upload.js index 1e1f540cf01e04..000bf1d58424a3 100644 --- a/test/parallel/test-http-client-upload.js +++ b/test/parallel/test-http-client-upload.js @@ -38,7 +38,7 @@ const server = http.createServer(common.mustCall(function(req, res) { req.on('end', common.mustCall(function() { assert.strictEqual('1\n2\n3\n', sent_body); console.log('request complete from server'); - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('hello\n'); res.end(); })); diff --git a/test/parallel/test-http-contentLength0.js b/test/parallel/test-http-contentLength0.js index 565de21c7285ff..975e2abe881ac5 100644 --- a/test/parallel/test-http-contentLength0.js +++ b/test/parallel/test-http-contentLength0.js @@ -29,7 +29,7 @@ const http = require('http'); const s = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Length': '0 '}); + res.writeHead(200, { 'Content-Length': '0 ' }); res.end(); }); s.listen(0, function() { diff --git a/test/parallel/test-http-dns-error.js b/test/parallel/test-http-dns-error.js index 76634c5a830a72..723b710647682b 100644 --- a/test/parallel/test-http-dns-error.js +++ b/test/parallel/test-http-dns-error.js @@ -39,13 +39,17 @@ function test(mod) { // Bad host name should not throw an uncatchable exception. // Ensure that there is time to attach an error listener. - const req1 = mod.get({host: host, port: 42}, do_not_call); + const req1 = mod.get({ host: host, port: 42 }, do_not_call); req1.on('error', common.mustCall(function(err) { assert.strictEqual(err.code, 'ENOTFOUND'); })); // http.get() called req1.end() for us - const req2 = mod.request({method: 'GET', host: host, port: 42}, do_not_call); + const req2 = mod.request({ + method: 'GET', + host: host, + port: 42 + }, do_not_call); req2.on('error', common.mustCall(function(err) { assert.strictEqual(err.code, 'ENOTFOUND'); })); diff --git a/test/parallel/test-http-double-content-length.js b/test/parallel/test-http-double-content-length.js index 7dd9e1527c5d80..53f924d652dd75 100644 --- a/test/parallel/test-http-double-content-length.js +++ b/test/parallel/test-http-double-content-length.js @@ -18,7 +18,7 @@ server.listen(0, () => { const req = http.get({ port: server.address().port, // Send two content-length header values. - headers: {'Content-Length': [1, 2]} + headers: { 'Content-Length': [1, 2] } }, common.mustNotCall('an error should have occurred')); req.on('error', common.mustCall(() => { server.close(); diff --git a/test/parallel/test-http-exceptions.js b/test/parallel/test-http-exceptions.js index 6b02a98242f3d7..0b6ac5bdc1f7d0 100644 --- a/test/parallel/test-http-exceptions.js +++ b/test/parallel/test-http-exceptions.js @@ -25,7 +25,7 @@ const http = require('http'); const server = http.createServer(function(req, res) { intentionally_not_defined(); // eslint-disable-line no-undef - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('Thank you, come again.'); res.end(); }); diff --git a/test/parallel/test-http-flush-response-headers.js b/test/parallel/test-http-flush-response-headers.js index bfc43a602b7018..b8045568d49ac7 100644 --- a/test/parallel/test-http-flush-response-headers.js +++ b/test/parallel/test-http-flush-response-headers.js @@ -6,7 +6,7 @@ const http = require('http'); const server = http.createServer(); server.on('request', function(req, res) { - res.writeHead(200, {'foo': 'bar'}); + res.writeHead(200, { 'foo': 'bar' }); res.flushHeaders(); res.flushHeaders(); // Should be idempotent. }); diff --git a/test/parallel/test-http-header-obstext.js b/test/parallel/test-http-header-obstext.js index 8762c753206a80..23aea246d782f7 100644 --- a/test/parallel/test-http-header-obstext.js +++ b/test/parallel/test-http-header-obstext.js @@ -13,7 +13,7 @@ const server = http.createServer(common.mustCall((req, res) => { server.listen(0, () => { http.get({ port: server.address().port, - headers: {'Test': 'Düsseldorf'} + headers: { 'Test': 'Düsseldorf' } }, common.mustCall((res) => { assert.strictEqual(res.statusCode, 200); server.close(); diff --git a/test/parallel/test-http-hostname-typechecking.js b/test/parallel/test-http-hostname-typechecking.js index e63af7d3f09ecc..91d4d99b9a524e 100644 --- a/test/parallel/test-http-hostname-typechecking.js +++ b/test/parallel/test-http-hostname-typechecking.js @@ -14,8 +14,8 @@ const errHost = /^TypeError: "options\.host" must either be a string, undefined or null$/; vals.forEach((v) => { - assert.throws(() => http.request({hostname: v}), errHostname); - assert.throws(() => http.request({host: v}), errHost); + assert.throws(() => http.request({ hostname: v }), errHostname); + assert.throws(() => http.request({ host: v }), errHost); }); // These values are OK and should not throw synchronously. @@ -23,7 +23,7 @@ vals.forEach((v) => { const dontCare = () => {}; ['', undefined, null].forEach((v) => { assert.doesNotThrow(() => { - http.request({hostname: v}).on('error', dontCare).end(); - http.request({host: v}).on('error', dontCare).end(); + http.request({ hostname: v }).on('error', dontCare).end(); + http.request({ host: v }).on('error', dontCare).end(); }); }); diff --git a/test/parallel/test-http-incoming-matchKnownFields.js b/test/parallel/test-http-incoming-matchKnownFields.js index f301b9169fcd2b..14ba8acd021f68 100644 --- a/test/parallel/test-http-incoming-matchKnownFields.js +++ b/test/parallel/test-http-incoming-matchKnownFields.js @@ -14,80 +14,80 @@ function checkDest(field, result, value) { assert.deepStrictEqual(dest, result); } -checkDest('', {'': undefined}); -checkDest('Content-Type', {'content-type': undefined}); -checkDest('content-type', {'content-type': 'test'}, 'value'); -checkDest('User-Agent', {'user-agent': undefined}); -checkDest('user-agent', {'user-agent': 'test'}, 'value'); -checkDest('Referer', {referer: undefined}); -checkDest('referer', {referer: 'test'}, 'value'); -checkDest('Host', {host: undefined}); -checkDest('host', {host: 'test'}, 'value'); -checkDest('Authorization', {authorization: undefined}, undefined); -checkDest('authorization', {authorization: 'test'}, 'value'); -checkDest('Proxy-Authorization', {'proxy-authorization': undefined}); -checkDest('proxy-authorization', {'proxy-authorization': 'test'}, 'value'); -checkDest('If-Modified-Since', {'if-modified-since': undefined}); -checkDest('if-modified-since', {'if-modified-since': 'test'}, 'value'); -checkDest('If-Unmodified-Since', {'if-unmodified-since': undefined}); -checkDest('if-unmodified-since', {'if-unmodified-since': 'test'}, 'value'); -checkDest('Form', {form: undefined}); -checkDest('form', {form: 'test, value'}, 'value'); -checkDest('Location', {location: undefined}); -checkDest('location', {location: 'test'}, 'value'); -checkDest('Max-Forwards', {'max-forwards': undefined}); -checkDest('max-forwards', {'max-forwards': 'test'}, 'value'); -checkDest('Retry-After', {'retry-after': undefined}); -checkDest('retry-after', {'retry-after': 'test'}, 'value'); -checkDest('Etag', {etag: undefined}); -checkDest('etag', {etag: 'test'}, 'value'); -checkDest('Last-Modified', {'last-modified': undefined}); -checkDest('last-modified', {'last-modified': 'test'}, 'value'); -checkDest('Server', {server: undefined}); -checkDest('server', {server: 'test'}, 'value'); -checkDest('Age', {age: undefined}); -checkDest('age', {age: 'test'}, 'value'); -checkDest('Expires', {expires: undefined}); -checkDest('expires', {expires: 'test'}, 'value'); -checkDest('Set-Cookie', {'set-cookie': [undefined]}); -checkDest('set-cookie', {'set-cookie': ['test', 'value']}, 'value'); -checkDest('Transfer-Encoding', {'transfer-encoding': undefined}); -checkDest('transfer-encoding', {'transfer-encoding': 'test, value'}, 'value'); -checkDest('Date', {date: undefined}); -checkDest('date', {date: 'test, value'}, 'value'); -checkDest('Connection', {connection: undefined}); -checkDest('connection', {connection: 'test, value'}, 'value'); -checkDest('Cache-Control', {'cache-control': undefined}); -checkDest('cache-control', {'cache-control': 'test, value'}, 'value'); -checkDest('Transfer-Encoding', {'transfer-encoding': undefined}); -checkDest('transfer-encoding', {'transfer-encoding': 'test, value'}, 'value'); -checkDest('Vary', {vary: undefined}); -checkDest('vary', {vary: 'test, value'}, 'value'); -checkDest('Content-Encoding', {'content-encoding': undefined}, undefined); -checkDest('content-encoding', {'content-encoding': 'test, value'}, 'value'); -checkDest('Cookie', {cookie: undefined}); -checkDest('cookie', {cookie: 'test; value'}, 'value'); -checkDest('Origin', {origin: undefined}); -checkDest('origin', {origin: 'test, value'}, 'value'); -checkDest('Upgrade', {upgrade: undefined}); -checkDest('upgrade', {upgrade: 'test, value'}, 'value'); -checkDest('Expect', {expect: undefined}); -checkDest('expect', {expect: 'test, value'}, 'value'); -checkDest('If-Match', {'if-match': undefined}); -checkDest('if-match', {'if-match': 'test, value'}, 'value'); -checkDest('If-None-Match', {'if-none-match': undefined}); -checkDest('if-none-match', {'if-none-match': 'test, value'}, 'value'); -checkDest('Accept', {accept: undefined}); -checkDest('accept', {accept: 'test, value'}, 'value'); -checkDest('Accept-Encoding', {'accept-encoding': undefined}); -checkDest('accept-encoding', {'accept-encoding': 'test, value'}, 'value'); -checkDest('Accept-Language', {'accept-language': undefined}); -checkDest('accept-language', {'accept-language': 'test, value'}, 'value'); -checkDest('X-Forwarded-For', {'x-forwarded-for': undefined}); -checkDest('x-forwarded-for', {'x-forwarded-for': 'test, value'}, 'value'); -checkDest('X-Forwarded-Host', {'x-forwarded-host': undefined}); -checkDest('x-forwarded-host', {'x-forwarded-host': 'test, value'}, 'value'); -checkDest('X-Forwarded-Proto', {'x-forwarded-proto': undefined}); -checkDest('x-forwarded-proto', {'x-forwarded-proto': 'test, value'}, 'value'); -checkDest('X-Foo', {'x-foo': undefined}); -checkDest('x-foo', {'x-foo': 'test, value'}, 'value'); +checkDest('', { '': undefined }); +checkDest('Content-Type', { 'content-type': undefined }); +checkDest('content-type', { 'content-type': 'test' }, 'value'); +checkDest('User-Agent', { 'user-agent': undefined }); +checkDest('user-agent', { 'user-agent': 'test' }, 'value'); +checkDest('Referer', { referer: undefined }); +checkDest('referer', { referer: 'test' }, 'value'); +checkDest('Host', { host: undefined }); +checkDest('host', { host: 'test' }, 'value'); +checkDest('Authorization', { authorization: undefined }, undefined); +checkDest('authorization', { authorization: 'test' }, 'value'); +checkDest('Proxy-Authorization', { 'proxy-authorization': undefined }); +checkDest('proxy-authorization', { 'proxy-authorization': 'test' }, 'value'); +checkDest('If-Modified-Since', { 'if-modified-since': undefined }); +checkDest('if-modified-since', { 'if-modified-since': 'test' }, 'value'); +checkDest('If-Unmodified-Since', { 'if-unmodified-since': undefined }); +checkDest('if-unmodified-since', { 'if-unmodified-since': 'test' }, 'value'); +checkDest('Form', { form: undefined }); +checkDest('form', { form: 'test, value' }, 'value'); +checkDest('Location', { location: undefined }); +checkDest('location', { location: 'test' }, 'value'); +checkDest('Max-Forwards', { 'max-forwards': undefined }); +checkDest('max-forwards', { 'max-forwards': 'test' }, 'value'); +checkDest('Retry-After', { 'retry-after': undefined }); +checkDest('retry-after', { 'retry-after': 'test' }, 'value'); +checkDest('Etag', { etag: undefined }); +checkDest('etag', { etag: 'test' }, 'value'); +checkDest('Last-Modified', { 'last-modified': undefined }); +checkDest('last-modified', { 'last-modified': 'test' }, 'value'); +checkDest('Server', { server: undefined }); +checkDest('server', { server: 'test' }, 'value'); +checkDest('Age', { age: undefined }); +checkDest('age', { age: 'test' }, 'value'); +checkDest('Expires', { expires: undefined }); +checkDest('expires', { expires: 'test' }, 'value'); +checkDest('Set-Cookie', { 'set-cookie': [undefined] }); +checkDest('set-cookie', { 'set-cookie': ['test', 'value'] }, 'value'); +checkDest('Transfer-Encoding', { 'transfer-encoding': undefined }); +checkDest('transfer-encoding', { 'transfer-encoding': 'test, value' }, 'value'); +checkDest('Date', { date: undefined }); +checkDest('date', { date: 'test, value' }, 'value'); +checkDest('Connection', { connection: undefined }); +checkDest('connection', { connection: 'test, value' }, 'value'); +checkDest('Cache-Control', { 'cache-control': undefined }); +checkDest('cache-control', { 'cache-control': 'test, value' }, 'value'); +checkDest('Transfer-Encoding', { 'transfer-encoding': undefined }); +checkDest('transfer-encoding', { 'transfer-encoding': 'test, value' }, 'value'); +checkDest('Vary', { vary: undefined }); +checkDest('vary', { vary: 'test, value' }, 'value'); +checkDest('Content-Encoding', { 'content-encoding': undefined }, undefined); +checkDest('content-encoding', { 'content-encoding': 'test, value' }, 'value'); +checkDest('Cookie', { cookie: undefined }); +checkDest('cookie', { cookie: 'test; value' }, 'value'); +checkDest('Origin', { origin: undefined }); +checkDest('origin', { origin: 'test, value' }, 'value'); +checkDest('Upgrade', { upgrade: undefined }); +checkDest('upgrade', { upgrade: 'test, value' }, 'value'); +checkDest('Expect', { expect: undefined }); +checkDest('expect', { expect: 'test, value' }, 'value'); +checkDest('If-Match', { 'if-match': undefined }); +checkDest('if-match', { 'if-match': 'test, value' }, 'value'); +checkDest('If-None-Match', { 'if-none-match': undefined }); +checkDest('if-none-match', { 'if-none-match': 'test, value' }, 'value'); +checkDest('Accept', { accept: undefined }); +checkDest('accept', { accept: 'test, value' }, 'value'); +checkDest('Accept-Encoding', { 'accept-encoding': undefined }); +checkDest('accept-encoding', { 'accept-encoding': 'test, value' }, 'value'); +checkDest('Accept-Language', { 'accept-language': undefined }); +checkDest('accept-language', { 'accept-language': 'test, value' }, 'value'); +checkDest('X-Forwarded-For', { 'x-forwarded-for': undefined }); +checkDest('x-forwarded-for', { 'x-forwarded-for': 'test, value' }, 'value'); +checkDest('X-Forwarded-Host', { 'x-forwarded-host': undefined }); +checkDest('x-forwarded-host', { 'x-forwarded-host': 'test, value' }, 'value'); +checkDest('X-Forwarded-Proto', { 'x-forwarded-proto': undefined }); +checkDest('x-forwarded-proto', { 'x-forwarded-proto': 'test, value' }, 'value'); +checkDest('X-Foo', { 'x-foo': undefined }); +checkDest('x-foo', { 'x-foo': 'test, value' }, 'value'); diff --git a/test/parallel/test-http-invalidheaderfield.js b/test/parallel/test-http-invalidheaderfield.js index 21be4c4d6d95e0..9e844e8a425af0 100644 --- a/test/parallel/test-http-invalidheaderfield.js +++ b/test/parallel/test-http-invalidheaderfield.js @@ -19,7 +19,7 @@ const server = http.createServer(function(req, res) { }); server.listen(0, function() { - http.get({port: this.address().port}, function() { + http.get({ port: this.address().port }, function() { ee.emit('done'); }); @@ -27,7 +27,7 @@ server.listen(0, function() { function() { const options = { port: server.address().port, - headers: {'testing 123': 123} + headers: { 'testing 123': 123 } }; http.get(options, common.mustNotCall()); }, @@ -41,7 +41,7 @@ server.listen(0, function() { function() { const options = { port: server.address().port, - headers: {'testing_123': 123} + headers: { 'testing_123': 123 } }; http.get(options, function() { ee.emit('done'); diff --git a/test/parallel/test-http-keep-alive-close-on-header.js b/test/parallel/test-http-keep-alive-close-on-header.js index fa459a00e671a9..f5fb9466db1fa7 100644 --- a/test/parallel/test-http-keep-alive-close-on-header.js +++ b/test/parallel/test-http-keep-alive-close-on-header.js @@ -25,10 +25,10 @@ const assert = require('assert'); const http = require('http'); const body = 'hello world\n'; -const headers = {'connection': 'keep-alive'}; +const headers = { 'connection': 'keep-alive' }; const server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Length': body.length, 'Connection': 'close'}); + res.writeHead(200, { 'Content-Length': body.length, 'Connection': 'close' }); res.write(body); res.end(); }); diff --git a/test/parallel/test-http-keep-alive.js b/test/parallel/test-http-keep-alive.js index 1dc65f72120e55..42d534e8e6b459 100644 --- a/test/parallel/test-http-keep-alive.js +++ b/test/parallel/test-http-keep-alive.js @@ -27,13 +27,13 @@ const http = require('http'); const server = http.createServer(common.mustCall((req, res) => { const body = 'hello world\n'; - res.writeHead(200, {'Content-Length': body.length}); + res.writeHead(200, { 'Content-Length': body.length }); res.write(body); res.end(); }, 3)); -const agent = new http.Agent({maxSockets: 1}); -const headers = {'connection': 'keep-alive'}; +const agent = new http.Agent({ maxSockets: 1 }); +const headers = { 'connection': 'keep-alive' }; let name; server.listen(0, common.mustCall(function() { diff --git a/test/parallel/test-http-malformed-request.js b/test/parallel/test-http-malformed-request.js index e0f719614edf48..59816b513b3af7 100644 --- a/test/parallel/test-http-malformed-request.js +++ b/test/parallel/test-http-malformed-request.js @@ -35,7 +35,7 @@ const nrequests_expected = 1; const server = http.createServer(function(req, res) { console.log(`req: ${JSON.stringify(url.parse(req.url))}`); - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('Hello World'); res.end(); diff --git a/test/parallel/test-http-no-content-length.js b/test/parallel/test-http-no-content-length.js index f43d4da42ef8a3..a3a51c015ec86f 100644 --- a/test/parallel/test-http-no-content-length.js +++ b/test/parallel/test-http-no-content-length.js @@ -29,7 +29,7 @@ const server = net.createServer(function(socket) { // Neither Content-Length nor Connection socket.end('HTTP/1.1 200 ok\r\n\r\nHello'); }).listen(0, common.mustCall(function() { - http.get({port: this.address().port}, common.mustCall(function(res) { + http.get({ port: this.address().port }, common.mustCall(function(res) { let body = ''; res.setEncoding('utf8'); diff --git a/test/parallel/test-http-outgoing-proto.js b/test/parallel/test-http-outgoing-proto.js index 80240c24ec8a59..202a185c7843e3 100644 --- a/test/parallel/test-http-outgoing-proto.js +++ b/test/parallel/test-http-outgoing-proto.js @@ -32,7 +32,7 @@ assert.throws(() => { assert.throws(() => { const outgoingMessage = new OutgoingMessage(); - outgoingMessage.setHeader.call({_header: 'test'}, 'test', 'value'); + outgoingMessage.setHeader.call({ _header: 'test' }, 'test', 'value'); }, /^Error: Can't set headers after they are sent\.$/); assert.throws(() => { @@ -46,16 +46,16 @@ assert.throws(() => { outgoingMessage.write(); }, /^Error: _implicitHeader\(\) method is not implemented$/); -assert(OutgoingMessage.prototype.write.call({_header: 'test'})); +assert(OutgoingMessage.prototype.write.call({ _header: 'test' })); assert.throws(() => { const outgoingMessage = new OutgoingMessage(); - outgoingMessage.write.call({_header: 'test', _hasBody: 'test'}); + outgoingMessage.write.call({ _header: 'test', _hasBody: 'test' }); }, /^TypeError: First argument must be a string or Buffer$/); assert.throws(() => { const outgoingMessage = new OutgoingMessage(); - outgoingMessage.write.call({_header: 'test', _hasBody: 'test'}, 1); + outgoingMessage.write.call({ _header: 'test', _hasBody: 'test' }, 1); }, /^TypeError: First argument must be a string or Buffer$/); // addTrailers @@ -66,10 +66,10 @@ assert.throws(() => { assert.throws(() => { const outgoingMessage = new OutgoingMessage(); - outgoingMessage.addTrailers({'あ': 'value'}); + outgoingMessage.addTrailers({ 'あ': 'value' }); }, /^TypeError: Trailer name must be a valid HTTP Token \["あ"\]$/); assert.throws(() => { const outgoingMessage = new OutgoingMessage(); - outgoingMessage.addTrailers({404: 'あ'}); + outgoingMessage.addTrailers({ 404: 'あ' }); }, /^TypeError: The trailer content contains invalid characters$/); diff --git a/test/parallel/test-http-parser-free.js b/test/parallel/test-http-parser-free.js index 53a9a8e5f7841e..1ead3c14928d88 100644 --- a/test/parallel/test-http-parser-free.js +++ b/test/parallel/test-http-parser-free.js @@ -35,7 +35,7 @@ server.listen(0, function() { let parser; for (let i = 0; i < N; ++i) { (function makeRequest(i) { - const req = http.get({port: server.address().port}, function(res) { + const req = http.get({ port: server.address().port }, function(res) { if (!parser) { parser = req.parser; } else { diff --git a/test/parallel/test-http-pause-resume-one-end.js b/test/parallel/test-http-pause-resume-one-end.js index c6c414cccb15cc..4886a7d490e413 100644 --- a/test/parallel/test-http-pause-resume-one-end.js +++ b/test/parallel/test-http-pause-resume-one-end.js @@ -24,7 +24,7 @@ const common = require('../common'); const http = require('http'); const server = http.Server(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World\n'); server.close(); }); diff --git a/test/parallel/test-http-proxy.js b/test/parallel/test-http-proxy.js index dfe3218a48fe7e..a6267faaa6715c 100644 --- a/test/parallel/test-http-proxy.js +++ b/test/parallel/test-http-proxy.js @@ -30,9 +30,9 @@ const cookies = [ 'prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT' ]; -const headers = {'content-type': 'text/plain', - 'set-cookie': cookies, - 'hello': 'world' }; +const headers = { 'content-type': 'text/plain', + 'set-cookie': cookies, + 'hello': 'world' }; const backend = http.createServer(function(req, res) { console.error('backend request'); diff --git a/test/parallel/test-http-request-end-twice.js b/test/parallel/test-http-request-end-twice.js index 27db0a6a5ee568..525377d2e1ccbf 100644 --- a/test/parallel/test-http-request-end-twice.js +++ b/test/parallel/test-http-request-end-twice.js @@ -25,11 +25,11 @@ const assert = require('assert'); const http = require('http'); const server = http.Server(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('hello world\n'); }); server.listen(0, function() { - const req = http.get({port: this.address().port}, function(res) { + const req = http.get({ port: this.address().port }, function(res) { res.on('end', function() { assert.ok(!req.end()); server.close(); diff --git a/test/parallel/test-http-request-invalid-method-error.js b/test/parallel/test-http-request-invalid-method-error.js index 470f51a08fbc4e..d5dffdd2212da9 100644 --- a/test/parallel/test-http-request-invalid-method-error.js +++ b/test/parallel/test-http-request-invalid-method-error.js @@ -4,7 +4,7 @@ const assert = require('assert'); const http = require('http'); assert.throws( - () => { http.request({method: '\0'}); }, + () => { http.request({ method: '\0' }); }, common.expectsError({ type: TypeError, message: 'Method must be a valid HTTP token' }) ); diff --git a/test/parallel/test-http-request-methods.js b/test/parallel/test-http-request-methods.js index 9be64e91a73fa7..3532d45c637c0d 100644 --- a/test/parallel/test-http-request-methods.js +++ b/test/parallel/test-http-request-methods.js @@ -30,7 +30,7 @@ const http = require('http'); ['DELETE', 'PATCH', 'PURGE'].forEach(function(method, index) { const server = http.createServer(common.mustCall(function(req, res) { assert.strictEqual(req.method, method); - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('hello '); res.write('world\n'); res.end(); diff --git a/test/parallel/test-http-res-write-after-end.js b/test/parallel/test-http-res-write-after-end.js index 7133e32429e7b1..32c6cf2e082668 100644 --- a/test/parallel/test-http-res-write-after-end.js +++ b/test/parallel/test-http-res-write-after-end.js @@ -37,7 +37,7 @@ const server = http.Server(common.mustCall(function(req, res) { })); server.listen(0, function() { - http.get({port: this.address().port}, function(res) { + http.get({ port: this.address().port }, function(res) { server.close(); }); }); diff --git a/test/parallel/test-http-res-write-end-dont-take-array.js b/test/parallel/test-http-res-write-end-dont-take-array.js index 0d519d60592922..fcf9da8c12b0e3 100644 --- a/test/parallel/test-http-res-write-end-dont-take-array.js +++ b/test/parallel/test-http-res-write-end-dont-take-array.js @@ -27,7 +27,7 @@ const http = require('http'); let test = 1; const server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); if (test === 1) { // write should accept string res.write('string'); @@ -54,12 +54,12 @@ const server = http.createServer(function(req, res) { server.listen(0, function() { // just make a request, other tests handle responses - http.get({port: this.address().port}, function(res) { + http.get({ port: this.address().port }, function(res) { res.resume(); // lazy serial test, because we can only call end once per request test += 1; // do it again to test .end(Buffer); - http.get({port: server.address().port}, function(res) { + http.get({ port: server.address().port }, function(res) { res.resume(); server.close(); }); diff --git a/test/parallel/test-http-response-add-header-after-sent.js b/test/parallel/test-http-response-add-header-after-sent.js index 4261bb61ec2957..19b71fc31d7528 100644 --- a/test/parallel/test-http-response-add-header-after-sent.js +++ b/test/parallel/test-http-response-add-header-after-sent.js @@ -15,7 +15,7 @@ const server = http.createServer((req, res) => { }); server.listen(0, () => { - http.get({port: server.address().port}, () => { + http.get({ port: server.address().port }, () => { server.close(); }); }); diff --git a/test/parallel/test-http-response-multi-content-length.js b/test/parallel/test-http-response-multi-content-length.js index c915cb1d531808..14015475ca702d 100644 --- a/test/parallel/test-http-response-multi-content-length.js +++ b/test/parallel/test-http-response-multi-content-length.js @@ -16,7 +16,7 @@ const server = http.createServer((req, res) => { res.setHeader('content-length', [2, 1]); break; case '2': - res.writeHead(200, {'content-length': [1, 2]}); + res.writeHead(200, { 'content-length': [1, 2] }); break; default: assert.fail('should never get here'); @@ -33,7 +33,7 @@ server.listen(0, common.mustCall(() => { // case, the error handler must be called because the client // is not allowed to accept multiple content-length headers. http.get( - {port: server.address().port, headers: {'x-num': n}}, + { port: server.address().port, headers: { 'x-num': n } }, (res) => { assert.fail('client allowed multiple content-length headers.'); } diff --git a/test/parallel/test-http-response-multiheaders.js b/test/parallel/test-http-response-multiheaders.js index 5739dac31d690b..ccfc31192d3770 100644 --- a/test/parallel/test-http-response-multiheaders.js +++ b/test/parallel/test-http-response-multiheaders.js @@ -56,7 +56,7 @@ server.listen(0, common.mustCall(function() { // value should be reported for the header fields listed // in the norepeat array. http.get( - {port: this.address().port, headers: {'x-num': n}}, + { port: this.address().port, headers: { 'x-num': n } }, common.mustCall(function(res) { if (++count === 2) server.close(); for (const name of norepeat) { diff --git a/test/parallel/test-http-response-remove-header-after-sent.js b/test/parallel/test-http-response-remove-header-after-sent.js index 972ccfeb8c70cc..4e35b7e9d0c9a2 100644 --- a/test/parallel/test-http-response-remove-header-after-sent.js +++ b/test/parallel/test-http-response-remove-header-after-sent.js @@ -15,7 +15,7 @@ const server = http.createServer((req, res) => { }); server.listen(0, () => { - http.get({port: server.address().port}, () => { + http.get({ port: server.address().port }, () => { server.close(); }); }); diff --git a/test/parallel/test-http-response-splitting.js b/test/parallel/test-http-response-splitting.js index aebb6b813be35e..b14d59e59ce8f9 100644 --- a/test/parallel/test-http-response-splitting.js +++ b/test/parallel/test-http-response-splitting.js @@ -29,13 +29,13 @@ const server = http.createServer((req, res) => { switch (count++) { case 0: const loc = url.parse(req.url, true).query.lang; - test(res, 302, {Location: `/foo?lang=${loc}`}); + test(res, 302, { Location: `/foo?lang=${loc}` }); break; case 1: - test(res, 200, {'foo': x}); + test(res, 200, { 'foo': x }); break; case 2: - test(res, 200, {'foo': y}); + test(res, 200, { 'foo': y }); break; default: assert.fail('should not get to here.'); @@ -46,7 +46,7 @@ const server = http.createServer((req, res) => { }); server.listen(0, () => { const end = 'HTTP/1.1\r\n\r\n'; - const client = net.connect({port: server.address().port}, () => { + const client = net.connect({ port: server.address().port }, () => { client.write(`GET ${str} ${end}`); client.write(`GET / ${end}`); client.write(`GET / ${end}`); diff --git a/test/parallel/test-http-server-multiheaders.js b/test/parallel/test-http-server-multiheaders.js index 89d17d0f50774d..201a95c346ae65 100644 --- a/test/parallel/test-http-server-multiheaders.js +++ b/test/parallel/test-http-server-multiheaders.js @@ -40,7 +40,7 @@ const srv = http.createServer(function(req, res) { 'foo; 1, bar; 2, baz'); assert.strictEqual(req.headers['constructor'], 'foo, bar, baz'); - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('EOF'); srv.close(); diff --git a/test/parallel/test-http-server-multiheaders2.js b/test/parallel/test-http-server-multiheaders2.js index 265867abc6978e..c4a9151862ee6b 100644 --- a/test/parallel/test-http-server-multiheaders2.js +++ b/test/parallel/test-http-server-multiheaders2.js @@ -80,7 +80,7 @@ const srv = http.createServer(function(req, res) { `header parsed incorrectly: ${header}`); }); - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('EOF'); srv.close(); diff --git a/test/parallel/test-http-server-reject-chunked-with-content-length.js b/test/parallel/test-http-server-reject-chunked-with-content-length.js index f316d86a7019dc..b3bc4295a84c0b 100644 --- a/test/parallel/test-http-server-reject-chunked-with-content-length.js +++ b/test/parallel/test-http-server-reject-chunked-with-content-length.js @@ -16,7 +16,7 @@ server.on('clientError', common.mustCall((err) => { server.close(); })); server.listen(0, () => { - const client = net.connect({port: server.address().port}, () => { + const client = net.connect({ port: server.address().port }, () => { client.write(reqstr); client.end(); }); diff --git a/test/parallel/test-http-server-reject-cr-no-lf.js b/test/parallel/test-http-server-reject-cr-no-lf.js index 98217150376403..5dace4f7bfd706 100644 --- a/test/parallel/test-http-server-reject-cr-no-lf.js +++ b/test/parallel/test-http-server-reject-cr-no-lf.js @@ -18,7 +18,7 @@ server.on('clientError', common.mustCall((err) => { server.close(); })); server.listen(0, () => { - const client = net.connect({port: server.address().port}, () => { + const client = net.connect({ port: server.address().port }, () => { client.on('data', common.mustNotCall()); client.on('end', common.mustCall(() => { server.close(); diff --git a/test/parallel/test-http-server-stale-close.js b/test/parallel/test-http-server-stale-close.js index 77c0e4aa7e2849..b72c2b55a02f25 100644 --- a/test/parallel/test-http-server-stale-close.js +++ b/test/parallel/test-http-server-stale-close.js @@ -26,7 +26,7 @@ const fork = require('child_process').fork; if (process.env.NODE_TEST_FORK_PORT) { const req = http.request({ - headers: {'Content-Length': '42'}, + headers: { 'Content-Length': '42' }, method: 'POST', host: '127.0.0.1', port: +process.env.NODE_TEST_FORK_PORT, @@ -35,7 +35,7 @@ if (process.env.NODE_TEST_FORK_PORT) { req.end(); } else { const server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Length': '42'}); + res.writeHead(200, { 'Content-Length': '42' }); req.pipe(res); req.on('close', function() { server.close(); diff --git a/test/parallel/test-http-server.js b/test/parallel/test-http-server.js index 85b2be52fef212..567f2b3b31b83b 100644 --- a/test/parallel/test-http-server.js +++ b/test/parallel/test-http-server.js @@ -58,7 +58,7 @@ const server = http.createServer(function(req, res) { } setTimeout(function() { - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write(url.parse(req.url).pathname); res.end(); }, 1); diff --git a/test/parallel/test-http-set-timeout.js b/test/parallel/test-http-set-timeout.js index 6253a4cc8c0a4c..5440c23c215521 100644 --- a/test/parallel/test-http-set-timeout.js +++ b/test/parallel/test-http-set-timeout.js @@ -39,7 +39,7 @@ const server = http.createServer(function(req, res) { server.listen(0, function() { console.log(`Server running at http://127.0.0.1:${this.address().port}/`); - const request = http.get({port: this.address().port, path: '/'}); + const request = http.get({ port: this.address().port, path: '/' }); request.on('error', common.mustCall(function() { console.log('HTTP REQUEST COMPLETE (this is good)'); })); diff --git a/test/parallel/test-http-set-trailers.js b/test/parallel/test-http-set-trailers.js index c267e5c82ee914..204207dfa8dcb6 100644 --- a/test/parallel/test-http-set-trailers.js +++ b/test/parallel/test-http-set-trailers.js @@ -29,7 +29,7 @@ let outstanding_reqs = 0; const server = http.createServer(function(req, res) { res.writeHead(200, [['content-type', 'text/plain']]); - res.addTrailers({'x-foo': 'bar'}); + res.addTrailers({ 'x-foo': 'bar' }); res.end('stuff\n'); }); server.listen(0); diff --git a/test/parallel/test-http-should-keep-alive.js b/test/parallel/test-http-should-keep-alive.js index 6a100fdd624894..dd4709d6946a84 100644 --- a/test/parallel/test-http-should-keep-alive.js +++ b/test/parallel/test-http-should-keep-alive.js @@ -50,7 +50,7 @@ const server = net.createServer(function(socket) { ++requests; }).listen(0, function() { function makeRequest() { - const req = http.get({port: server.address().port}, function(res) { + const req = http.get({ port: server.address().port }, function(res) { assert.strictEqual( req.shouldKeepAlive, SHOULD_KEEP_ALIVE[responses], `${SERVER_RESPONSES[responses]} should ${ diff --git a/test/parallel/test-http-status-code.js b/test/parallel/test-http-status-code.js index d48b71eb840738..802565f26bb697 100644 --- a/test/parallel/test-http-status-code.js +++ b/test/parallel/test-http-status-code.js @@ -33,7 +33,7 @@ let testIdx = 0; const s = http.createServer(function(req, res) { const t = tests[testIdx]; - res.writeHead(t, {'Content-Type': 'text/plain'}); + res.writeHead(t, { 'Content-Type': 'text/plain' }); console.log(`--\nserver: statusCode after writeHead: ${res.statusCode}`); assert.strictEqual(res.statusCode, t); res.end('hello world\n'); diff --git a/test/parallel/test-http-timeout-overflow.js b/test/parallel/test-http-timeout-overflow.js index d880309a5d3dd7..dc93b3da7ae20d 100644 --- a/test/parallel/test-http-timeout-overflow.js +++ b/test/parallel/test-http-timeout-overflow.js @@ -30,7 +30,7 @@ let clientRequests = 0; const server = http.createServer(function(req, res) { serverRequests++; - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('OK'); }); diff --git a/test/parallel/test-http-timeout.js b/test/parallel/test-http-timeout.js index 8c24f6e16b96b2..817bfe7a3c3be7 100644 --- a/test/parallel/test-http-timeout.js +++ b/test/parallel/test-http-timeout.js @@ -25,11 +25,11 @@ require('../common'); const http = require('http'); const server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('OK'); }); -const agent = new http.Agent({maxSockets: 1}); +const agent = new http.Agent({ maxSockets: 1 }); server.listen(0, function() { @@ -43,7 +43,7 @@ server.listen(0, function() { function createRequest() { const req = http.request( - {port: server.address().port, path: '/', agent: agent}, + { port: server.address().port, path: '/', agent: agent }, function(res) { req.clearTimeout(callback); diff --git a/test/parallel/test-http-upgrade-server.js b/test/parallel/test-http-upgrade-server.js index 3b91afc03fbf7f..71a075831603da 100644 --- a/test/parallel/test-http-upgrade-server.js +++ b/test/parallel/test-http-upgrade-server.js @@ -45,7 +45,7 @@ function testServer() { }); this.on('request', function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('okay'); res.end(); }); diff --git a/test/parallel/test-http-wget.js b/test/parallel/test-http-wget.js index 5f38997872c500..ef06deefdf8afa 100644 --- a/test/parallel/test-http-wget.js +++ b/test/parallel/test-http-wget.js @@ -41,7 +41,7 @@ const http = require('http'); // closed. const server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('hello '); res.write('world\n'); res.end(); diff --git a/test/parallel/test-http-write-empty-string.js b/test/parallel/test-http-write-empty-string.js index a20602e39d994c..35a7aca61b4030 100644 --- a/test/parallel/test-http-write-empty-string.js +++ b/test/parallel/test-http-write-empty-string.js @@ -28,7 +28,7 @@ const http = require('http'); const server = http.createServer(function(request, response) { console.log(`responding to ${request.url}`); - response.writeHead(200, {'Content-Type': 'text/plain'}); + response.writeHead(200, { 'Content-Type': 'text/plain' }); response.write('1\n'); response.write(''); response.write('2\n'); diff --git a/test/parallel/test-http.js b/test/parallel/test-http.js index e9d4950a4650df..d9fa581f3b55ce 100644 --- a/test/parallel/test-http.js +++ b/test/parallel/test-http.js @@ -53,7 +53,7 @@ const server = http.Server(common.mustCall(function(req, res) { this.close(); req.on('end', function() { - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write(`The path was ${url.parse(req.url).pathname}`); res.end(); }); diff --git a/test/parallel/test-https-agent-sockets-leak.js b/test/parallel/test-https-agent-sockets-leak.js index 2fc477c0b33c7b..3772fd3a10689f 100644 --- a/test/parallel/test-https-agent-sockets-leak.js +++ b/test/parallel/test-https-agent-sockets-leak.js @@ -27,7 +27,7 @@ server.listen(0, common.mustCall(() => { https.get({ host: server.address().host, port: server.address().port, - headers: {host: 'agent1'}, + headers: { host: 'agent1' }, rejectUnauthorized: true, ca: options.ca, agent: agent diff --git a/test/parallel/test-https-client-get-url.js b/test/parallel/test-https-client-get-url.js index f0e919ca648b05..705e779aacb762 100644 --- a/test/parallel/test-https-client-get-url.js +++ b/test/parallel/test-https-client-get-url.js @@ -42,7 +42,7 @@ const options = { const server = https.createServer(options, common.mustCall((req, res) => { assert.strictEqual('GET', req.method); assert.strictEqual('/foo?bar', req.url); - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('hello\n'); res.end(); }, 3)); diff --git a/test/parallel/test-https-connect-address-family.js b/test/parallel/test-https-connect-address-family.js index 76a12ef5d5dc0e..fa9baa528efa00 100644 --- a/test/parallel/test-https-connect-address-family.js +++ b/test/parallel/test-https-connect-address-family.js @@ -31,7 +31,7 @@ function runTest() { })); } -dns.lookup('localhost', {family: 6, all: true}, (err, addresses) => { +dns.lookup('localhost', { family: 6, all: true }, (err, addresses) => { if (err) { if (err.code === 'ENOTFOUND') common.skip('localhost does not resolve to ::1'); diff --git a/test/parallel/test-icu-stringwidth.js b/test/parallel/test-icu-stringwidth.js index d1b95c779241b6..a66ab0ce8b1e8c 100644 --- a/test/parallel/test-icu-stringwidth.js +++ b/test/parallel/test-icu-stringwidth.js @@ -55,7 +55,7 @@ assert.strictEqual(readline.getStringWidth(0x20DD), 0); // individually. assert.strictEqual(readline.getStringWidth('👩‍👩‍👧‍👧'), 2); assert.strictEqual( - readline.getStringWidth('👩‍👩‍👧‍👧', {expandEmojiSequence: true}), 8); + readline.getStringWidth('👩‍👩‍👧‍👧', { expandEmojiSequence: true }), 8); // By default, unicode characters whose width is considered ambiguous will // be considered half-width. For these characters, getStringWidth will return @@ -65,7 +65,7 @@ assert.strictEqual( // as 2 columns. assert.strictEqual(readline.getStringWidth('\u01d4'), 1); assert.strictEqual( - readline.getStringWidth('\u01d4', {ambiguousAsFullWidth: true}), 2); + readline.getStringWidth('\u01d4', { ambiguousAsFullWidth: true }), 2); // Control chars and combining chars are zero assert.strictEqual(readline.getStringWidth('\u200E\n\u220A\u20D2'), 1); diff --git a/test/parallel/test-inspector-open.js b/test/parallel/test-inspector-open.js index 0bbf168471a72e..a0d2eaf1f3415a 100644 --- a/test/parallel/test-inspector-open.js +++ b/test/parallel/test-inspector-open.js @@ -19,7 +19,7 @@ const child = fork(__filename, child.once('message', common.mustCall((msg) => { assert.strictEqual(msg.cmd, 'started'); - child.send({cmd: 'open', args: [0]}); + child.send({ cmd: 'open', args: [0] }); child.once('message', common.mustCall(firstOpen)); })); @@ -31,7 +31,7 @@ function firstOpen(msg) { ping(port, (err) => { assert.ifError(err); // Inspector is already open, and won't be reopened, so args don't matter. - child.send({cmd: 'open', args: []}); + child.send({ cmd: 'open', args: [] }); child.once('message', common.mustCall(tryToOpenWhenOpen)); firstPort = port; }); @@ -44,7 +44,7 @@ function tryToOpenWhenOpen(msg) { assert.strictEqual(port, firstPort); ping(port, (err) => { assert.ifError(err); - child.send({cmd: 'close'}); + child.send({ cmd: 'close' }); child.once('message', common.mustCall(closeWhenOpen)); }); } @@ -54,7 +54,7 @@ function closeWhenOpen(msg) { assert.strictEqual(msg.url, undefined); ping(firstPort, (err) => { assert(err); - child.send({cmd: 'close'}); + child.send({ cmd: 'close' }); child.once('message', common.mustCall(tryToCloseWhenClosed)); }); } @@ -62,7 +62,7 @@ function closeWhenOpen(msg) { function tryToCloseWhenClosed(msg) { assert.strictEqual(msg.cmd, 'url'); assert.strictEqual(msg.url, undefined); - child.send({cmd: 'open', args: []}); + child.send({ cmd: 'open', args: [] }); child.once('message', common.mustCall(reopenAfterClose)); } @@ -89,7 +89,7 @@ function ping(port, callback) { function beChild() { const inspector = require('inspector'); - process.send({cmd: 'started'}); + process.send({ cmd: 'started' }); process.on('message', (msg) => { if (msg.cmd === 'open') { @@ -98,6 +98,6 @@ function beChild() { if (msg.cmd === 'close') { inspector.close(); } - process.send({cmd: 'url', url: inspector.url()}); + process.send({ cmd: 'url', url: inspector.url() }); }); } diff --git a/test/parallel/test-intl.js b/test/parallel/test-intl.js index 5ce8cbc43c6c4e..983685c32cff04 100644 --- a/test/parallel/test-intl.js +++ b/test/parallel/test-intl.js @@ -67,7 +67,11 @@ if (!common.hasIntl) { // Construct an English formatter. Should format to "Jan 70" const dtf = new Intl.DateTimeFormat(['en'], - {timeZone: GMT, month: 'short', year: '2-digit'}); + { + timeZone: GMT, + month: 'short', + year: '2-digit' + }); // If list is specified and doesn't contain 'en' then return. if (process.config.variables.icu_locales && !haveLocale('en')) { @@ -89,7 +93,7 @@ if (!common.hasIntl) { assert.strictEqual(localeString, 'Jan 70'); } // Options to request GMT - const optsGMT = {timeZone: GMT}; + const optsGMT = { timeZone: GMT }; // Test format { diff --git a/test/parallel/test-listen-fd-ebadf.js b/test/parallel/test-listen-fd-ebadf.js index 82340c8bea13e1..0f09d386d5fa7c 100644 --- a/test/parallel/test-listen-fd-ebadf.js +++ b/test/parallel/test-listen-fd-ebadf.js @@ -24,9 +24,9 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -net.createServer(common.mustNotCall()).listen({fd: 2}) +net.createServer(common.mustNotCall()).listen({ fd: 2 }) .on('error', common.mustCall(onError)); -net.createServer(common.mustNotCall()).listen({fd: 42}) +net.createServer(common.mustNotCall()).listen({ fd: 42 }) .on('error', common.mustCall(onError)); function onError(ex) { diff --git a/test/parallel/test-module-symlinked-peer-modules.js b/test/parallel/test-module-symlinked-peer-modules.js index 5fe3169ee87382..e3d538c42b0bf6 100644 --- a/test/parallel/test-module-symlinked-peer-modules.js +++ b/test/parallel/test-module-symlinked-peer-modules.js @@ -49,13 +49,13 @@ try { } fs.writeFileSync(path.join(moduleA, 'package.json'), - JSON.stringify({name: 'moduleA', main: 'index.js'}), 'utf8'); + JSON.stringify({ name: 'moduleA', main: 'index.js' }), 'utf8'); fs.writeFileSync(path.join(moduleA, 'index.js'), 'module.exports = require(\'moduleB\');', 'utf8'); fs.writeFileSync(path.join(app, 'index.js'), '\'use strict\'; require(\'moduleA\');', 'utf8'); fs.writeFileSync(path.join(moduleB, 'package.json'), - JSON.stringify({name: 'moduleB', main: 'index.js'}), 'utf8'); + JSON.stringify({ name: 'moduleB', main: 'index.js' }), 'utf8'); fs.writeFileSync(path.join(moduleB, 'index.js'), 'module.exports = 1;', 'utf8'); diff --git a/test/parallel/test-net-connect-call-socket-connect.js b/test/parallel/test-net-connect-call-socket-connect.js index 8d3413d9aa7f33..88551889fe253c 100644 --- a/test/parallel/test-net-connect-call-socket-connect.js +++ b/test/parallel/test-net-connect-call-socket-connect.js @@ -30,7 +30,7 @@ const server = net.createServer(); server.listen(common.mustCall(function() { const port = server.address().port; - const client = net.connect({port}, common.mustCall(function() { + const client = net.connect({ port }, common.mustCall(function() { client.end(); })); client.on('end', common.mustCall(function() { diff --git a/test/parallel/test-net-connect-immediate-finish.js b/test/parallel/test-net-connect-immediate-finish.js index 209b90d71d0e84..1006a62d330054 100644 --- a/test/parallel/test-net-connect-immediate-finish.js +++ b/test/parallel/test-net-connect-immediate-finish.js @@ -24,7 +24,7 @@ const common = require('../common'); const assert = require('assert'); const net = require('net'); -const client = net.connect({host: '***', port: common.PORT}); +const client = net.connect({ host: '***', port: common.PORT }); client.once('error', common.mustCall((err) => { assert(err); diff --git a/test/parallel/test-net-connect-options-fd.js b/test/parallel/test-net-connect-options-fd.js index 68e63f0ba4cbc9..e0872cf7c5df3f 100644 --- a/test/parallel/test-net-connect-options-fd.js +++ b/test/parallel/test-net-connect-options-fd.js @@ -69,7 +69,7 @@ const forAllClients = (cb) => common.mustCall(cb, CLIENT_VARIANTS); console.error(err); assert.fail(null, null, `[Pipe server]${err}`); }) - .listen({path: serverPath}, common.mustCall(function serverOnListen() { + .listen({ path: serverPath }, common.mustCall(function serverOnListen() { const getSocketOpt = (index) => { const handle = new Pipe(); const err = handle.bind(`${prefix}-client-${socketCounter++}`); diff --git a/test/parallel/test-net-connect-options-ipv6.js b/test/parallel/test-net-connect-options-ipv6.js index 29b07645c452d3..aba07d9fcc8094 100644 --- a/test/parallel/test-net-connect-options-ipv6.js +++ b/test/parallel/test-net-connect-options-ipv6.js @@ -32,7 +32,7 @@ let hostIdx = 0; let host = hosts[hostIdx]; let localhostTries = 10; -const server = net.createServer({allowHalfOpen: true}, function(socket) { +const server = net.createServer({ allowHalfOpen: true }, function(socket) { socket.resume(); socket.on('end', common.mustCall()); socket.end(); diff --git a/test/parallel/test-net-connect-options-path.js b/test/parallel/test-net-connect-options-path.js index 927bd95207370d..07c5446fc6c0ab 100644 --- a/test/parallel/test-net-connect-options-path.js +++ b/test/parallel/test-net-connect-options-path.js @@ -40,14 +40,14 @@ const CLIENT_VARIANTS = 12; new net.Socket().connect(serverPath, getConnectCb()); new net.Socket().connect(serverPath) .on('connect', getConnectCb()); - net.connect({path: serverPath}, getConnectCb()); - net.connect({path: serverPath}) + net.connect({ path: serverPath }, getConnectCb()); + net.connect({ path: serverPath }) .on('connect', getConnectCb()); - net.createConnection({path: serverPath}, getConnectCb()); - net.createConnection({path: serverPath}) + net.createConnection({ path: serverPath }, getConnectCb()); + net.createConnection({ path: serverPath }) .on('connect', getConnectCb()); - new net.Socket().connect({path: serverPath}, getConnectCb()); - new net.Socket().connect({path: serverPath}) + new net.Socket().connect({ path: serverPath }, getConnectCb()); + new net.Socket().connect({ path: serverPath }) .on('connect', getConnectCb()); })); } diff --git a/test/parallel/test-net-connect-options-port.js b/test/parallel/test-net-connect-options-port.js index 1a2bd850f3a54d..bc9e76df6546ee 100644 --- a/test/parallel/test-net-connect-options-port.js +++ b/test/parallel/test-net-connect-options-port.js @@ -63,7 +63,7 @@ const net = require('net'); const regexp = /^TypeError: Invalid argument: hints must use valid flags$/; // connect({hint}, cb) and connect({hint}) const hints = (dns.ADDRCONFIG | dns.V4MAPPED) + 42; - const hintOptBlocks = doConnect([{hints: hints}], + const hintOptBlocks = doConnect([{ hints: hints }], () => common.mustNotCall()); for (const block of hintOptBlocks) { assert.throws(block, regexp, @@ -143,14 +143,14 @@ function syncFailToConnect(port, regexp, optOnly) { } } // connect({port}, cb) and connect({port}) - const portOptBlocks = doConnect([{port}], + const portOptBlocks = doConnect([{ port }], () => common.mustNotCall()); for (const block of portOptBlocks) { assert.throws(block, regexp, `${block.name}({port: ${port}})`); } // connect({port, host}, cb) and connect({port, host}) - const portHostOptBlocks = doConnect([{port: port, host: 'localhost'}], + const portHostOptBlocks = doConnect([{ port: port, host: 'localhost' }], () => common.mustNotCall()); for (const block of portHostOptBlocks) { assert.throws(block, regexp, @@ -174,13 +174,13 @@ function canConnect(port) { } // connect({port}, cb) and connect({port}) - const portOptBlocks = doConnect([{port}], noop); + const portOptBlocks = doConnect([{ port }], noop); for (const block of portOptBlocks) { assert.doesNotThrow(block, `${block.name}({port: ${port}})`); } // connect({port, host}, cb) and connect({port, host}) - const portHostOptBlocks = doConnect([{port: port, host: 'localhost'}], + const portHostOptBlocks = doConnect([{ port: port, host: 'localhost' }], noop); for (const block of portHostOptBlocks) { assert.doesNotThrow(block, @@ -204,7 +204,7 @@ function asyncFailToConnect(port) { } // connect({port}, cb) and connect({port}) - const portOptBlocks = doConnect([{port}], dont); + const portOptBlocks = doConnect([{ port }], dont); for (const block of portOptBlocks) { assert.doesNotThrow(function() { block().on('error', onError()); @@ -212,7 +212,7 @@ function asyncFailToConnect(port) { } // connect({port, host}, cb) and connect({port, host}) - const portHostOptBlocks = doConnect([{port: port, host: 'localhost'}], + const portHostOptBlocks = doConnect([{ port: port, host: 'localhost' }], dont); for (const block of portHostOptBlocks) { assert.doesNotThrow(function() { diff --git a/test/parallel/test-net-listen-fd0.js b/test/parallel/test-net-listen-fd0.js index 58b184ff10f3e9..c9ba56b5aef035 100644 --- a/test/parallel/test-net-listen-fd0.js +++ b/test/parallel/test-net-listen-fd0.js @@ -26,7 +26,7 @@ const net = require('net'); // This should fail with an async EINVAL error, not throw an exception net.createServer(common.mustNotCall()) - .listen({fd: 0}) + .listen({ fd: 0 }) .on('error', common.mustCall(function(e) { assert(e instanceof Error); assert(['EINVAL', 'ENOTSOCK'].includes(e.code)); diff --git a/test/parallel/test-net-server-connections-child-null.js b/test/parallel/test-net-server-connections-child-null.js index a8a1346fec3370..cbe2d22052192d 100644 --- a/test/parallel/test-net-server-connections-child-null.js +++ b/test/parallel/test-net-server-connections-child-null.js @@ -23,7 +23,7 @@ if (process.argv[2] === 'child') { // server.connections should start as 0 assert.strictEqual(server.connections, 0); server.on('connection', (socket) => { - child.send({what: 'socket'}, socket); + child.send({ what: 'socket' }, socket); }); server.on('close', () => { child.kill(); diff --git a/test/parallel/test-net-server-listen-handle.js b/test/parallel/test-net-server-listen-handle.js index 09398bd0e36ceb..db8e639f94885f 100644 --- a/test/parallel/test-net-server-listen-handle.js +++ b/test/parallel/test-net-server-listen-handle.js @@ -91,27 +91,27 @@ if (!common.isWindows) { // Windows doesn't support {fd: } { // Test listen({handle: tcp}, cb) net.createServer() - .listen({handle: randomHandle('tcp')}, closeServer()); + .listen({ handle: randomHandle('tcp') }, closeServer()); // Test listen({handle: tcp}) net.createServer() - .listen({handle: randomHandle('tcp')}) + .listen({ handle: randomHandle('tcp') }) .on('listening', closeServer()); // Test listen({_handle: tcp}, cb) net.createServer() - .listen({_handle: randomHandle('tcp')}, closeServer()); + .listen({ _handle: randomHandle('tcp') }, closeServer()); // Test listen({_handle: tcp}) net.createServer() - .listen({_handle: randomHandle('tcp')}) + .listen({ _handle: randomHandle('tcp') }) .on('listening', closeServer()); } if (!common.isWindows) { // Windows doesn't support {fd: } // Test listen({fd: tcp.fd}, cb) net.createServer() - .listen({fd: randomHandle('tcp').fd}, closeServer()); + .listen({ fd: randomHandle('tcp').fd }, closeServer()); // Test listen({fd: tcp.fd}) net.createServer() - .listen({fd: randomHandle('tcp').fd}) + .listen({ fd: randomHandle('tcp').fd }) .on('listening', closeServer()); } @@ -119,24 +119,24 @@ if (!common.isWindows) { // Windows doesn't support {fd: } const handles = randomPipes(6); // generate pipes in advance // Test listen({handle: pipe}, cb) net.createServer() - .listen({handle: handles[0]}, closePipeServer(handles[0])); + .listen({ handle: handles[0] }, closePipeServer(handles[0])); // Test listen({handle: pipe}) net.createServer() - .listen({handle: handles[1]}) + .listen({ handle: handles[1] }) .on('listening', closePipeServer(handles[1])); // Test listen({_handle: pipe}, cb) net.createServer() - .listen({_handle: handles[2]}, closePipeServer(handles[2])); + .listen({ _handle: handles[2] }, closePipeServer(handles[2])); // Test listen({_handle: pipe}) net.createServer() - .listen({_handle: handles[3]}) + .listen({ _handle: handles[3] }) .on('listening', closePipeServer(handles[3])); // Test listen({fd: pipe.fd}, cb) net.createServer() - .listen({fd: handles[4].fd}, closePipeServer(handles[4])); + .listen({ fd: handles[4].fd }, closePipeServer(handles[4])); // Test listen({fd: pipe.fd}) net.createServer() - .listen({fd: handles[5].fd}) + .listen({ fd: handles[5].fd }) .on('listening', closePipeServer(handles[5])); } @@ -144,7 +144,7 @@ if (!common.isWindows) { // Windows doesn't support {fd: } // Test invalid fd const fd = fs.openSync(__filename, 'r'); net.createServer() - .listen({fd: fd}, common.mustNotCall()) + .listen({ fd: fd }, common.mustNotCall()) .on('error', common.mustCall(function(err) { assert.strictEqual(String(err), 'Error: listen EINVAL'); this.close(); diff --git a/test/parallel/test-net-server-listen-options.js b/test/parallel/test-net-server-listen-options.js index 494a331223fb5d..d2e70215dc1efb 100644 --- a/test/parallel/test-net-server-listen-options.js +++ b/test/parallel/test-net-server-listen-options.js @@ -25,13 +25,13 @@ function listenError(literals, ...values) { // Test listen(port) net.createServer().listen(0).on('listening', common.mustCall(close)); // Test listen({port}) - net.createServer().listen({port: 0}) + net.createServer().listen({ port: 0 }) .on('listening', common.mustCall(close)); } // Test listen(port, cb) and listen({port: port}, cb) combinations const listenOnPort = [ - (port, cb) => net.createServer().listen({port}, cb), + (port, cb) => net.createServer().listen({ port }, cb), (port, cb) => net.createServer().listen(port, cb) ]; diff --git a/test/parallel/test-net-server-listen-path.js b/test/parallel/test-net-server-listen-path.js index 2dbd588bafaf3b..53173fa66d120a 100644 --- a/test/parallel/test-net-server-listen-path.js +++ b/test/parallel/test-net-server-listen-path.js @@ -30,7 +30,7 @@ function randomPipePath() { { const handlePath = randomPipePath(); net.createServer() - .listen({path: handlePath}) + .listen({ path: handlePath }) .on('listening', closeServer()); } @@ -45,5 +45,5 @@ function randomPipePath() { { const handlePath = randomPipePath(); net.createServer() - .listen({path: handlePath}, closeServer()); + .listen({ path: handlePath }, closeServer()); } diff --git a/test/parallel/test-net-server-pause-on-connect.js b/test/parallel/test-net-server-pause-on-connect.js index e015c24323ab86..84cc91d56c3b08 100644 --- a/test/parallel/test-net-server-pause-on-connect.js +++ b/test/parallel/test-net-server-pause-on-connect.js @@ -42,7 +42,7 @@ const server1ConnHandler = (socket) => { server1Sock = socket; }; -const server1 = net.createServer({pauseOnConnect: true}, server1ConnHandler); +const server1 = net.createServer({ pauseOnConnect: true }, server1ConnHandler); const server2ConnHandler = (socket) => { socket.on('data', function(data) { @@ -57,15 +57,15 @@ const server2ConnHandler = (socket) => { }); }; -const server2 = net.createServer({pauseOnConnect: false}, server2ConnHandler); +const server2 = net.createServer({ pauseOnConnect: false }, server2ConnHandler); server1.listen(0, function() { const clientHandler = common.mustCall(function() { server2.listen(0, function() { - net.createConnection({port: this.address().port}).write(msg); + net.createConnection({ port: this.address().port }).write(msg); }); }); - net.createConnection({port: this.address().port}).write(msg, clientHandler); + net.createConnection({ port: this.address().port }).write(msg, clientHandler); }); process.on('exit', function() { diff --git a/test/parallel/test-net-socket-timeout-unref.js b/test/parallel/test-net-socket-timeout-unref.js index 1e95fe6b0fb0f3..ae6bde49ab60cd 100644 --- a/test/parallel/test-net-socket-timeout-unref.js +++ b/test/parallel/test-net-socket-timeout-unref.js @@ -52,5 +52,5 @@ delays.forEach(function(T) { } })); - sockets.push({socket: socket, timeout: T * 1000}); + sockets.push({ socket: socket, timeout: T * 1000 }); }); diff --git a/test/parallel/test-net-socket-write-after-close.js b/test/parallel/test-net-socket-write-after-close.js index 6d2d2fdd026333..d3a3d937d338ab 100644 --- a/test/parallel/test-net-socket-write-after-close.js +++ b/test/parallel/test-net-socket-write-after-close.js @@ -8,7 +8,7 @@ const net = require('net'); server.listen(common.mustCall(() => { const port = server.address().port; - const client = net.connect({port}, common.mustCall(() => { + const client = net.connect({ port }, common.mustCall(() => { client.on('error', common.mustCall((err) => { server.close(); assert.strictEqual(err.constructor, Error); @@ -25,7 +25,7 @@ const net = require('net'); server.listen(common.mustCall(() => { const port = server.address().port; - const client = net.connect({port}, common.mustCall(() => { + const client = net.connect({ port }, common.mustCall(() => { client.on('error', common.mustCall((err) => { server.close(); assert.strictEqual(err.constructor, Error); diff --git a/test/parallel/test-openssl-ca-options.js b/test/parallel/test-openssl-ca-options.js index 83893335f95b46..4f19c804065cb4 100644 --- a/test/parallel/test-openssl-ca-options.js +++ b/test/parallel/test-openssl-ca-options.js @@ -12,7 +12,7 @@ const result = childProcess.spawnSync(process.execPath, [ '--use-bundled-ca', '--use-openssl-ca', '-p', 'process.version'], - {encoding: 'utf8'}); + { encoding: 'utf8' }); assert.strictEqual(result.stderr, `${process.execPath }: either --use-openssl-ca or --use-bundled-ca can be used, not both${os.EOL}` diff --git a/test/parallel/test-path-parse-format.js b/test/parallel/test-path-parse-format.js index 64e9429a2394f0..de9051caa88a14 100644 --- a/test/parallel/test-path-parse-format.js +++ b/test/parallel/test-path-parse-format.js @@ -55,12 +55,12 @@ const winSpecialCaseParseTests = [ ]; const winSpecialCaseFormatTests = [ - [{dir: 'some\\dir'}, 'some\\dir\\'], - [{base: 'index.html'}, 'index.html'], - [{root: 'C:\\'}, 'C:\\'], - [{name: 'index', ext: '.html'}, 'index.html'], - [{dir: 'some\\dir', name: 'index', ext: '.html'}, 'some\\dir\\index.html'], - [{root: 'C:\\', name: 'index', ext: '.html'}, 'C:\\index.html'], + [{ dir: 'some\\dir' }, 'some\\dir\\'], + [{ base: 'index.html' }, 'index.html'], + [{ root: 'C:\\' }, 'C:\\'], + [{ name: 'index', ext: '.html' }, 'index.html'], + [{ dir: 'some\\dir', name: 'index', ext: '.html' }, 'some\\dir\\index.html'], + [{ root: 'C:\\', name: 'index', ext: '.html' }, 'C:\\index.html'], [{}, ''] ]; @@ -89,38 +89,38 @@ const unixPaths = [ ]; const unixSpecialCaseFormatTests = [ - [{dir: 'some/dir'}, 'some/dir/'], - [{base: 'index.html'}, 'index.html'], - [{root: '/'}, '/'], - [{name: 'index', ext: '.html'}, 'index.html'], - [{dir: 'some/dir', name: 'index', ext: '.html'}, 'some/dir/index.html'], - [{root: '/', name: 'index', ext: '.html'}, '/index.html'], + [{ dir: 'some/dir' }, 'some/dir/'], + [{ base: 'index.html' }, 'index.html'], + [{ root: '/' }, '/'], + [{ name: 'index', ext: '.html' }, 'index.html'], + [{ dir: 'some/dir', name: 'index', ext: '.html' }, 'some/dir/index.html'], + [{ root: '/', name: 'index', ext: '.html' }, '/index.html'], [{}, ''] ]; const errors = [ - {method: 'parse', input: [null], - message: /^TypeError: Path must be a string\. Received null$/}, - {method: 'parse', input: [{}], - message: /^TypeError: Path must be a string\. Received {}$/}, - {method: 'parse', input: [true], - message: /^TypeError: Path must be a string\. Received true$/}, - {method: 'parse', input: [1], - message: /^TypeError: Path must be a string\. Received 1$/}, - {method: 'parse', input: [], - message: /^TypeError: Path must be a string\. Received undefined$/}, - {method: 'format', input: [null], - message: - /^TypeError: Parameter "pathObject" must be an object, not object$/}, - {method: 'format', input: [''], - message: - /^TypeError: Parameter "pathObject" must be an object, not string$/}, - {method: 'format', input: [true], - message: - /^TypeError: Parameter "pathObject" must be an object, not boolean$/}, - {method: 'format', input: [1], - message: - /^TypeError: Parameter "pathObject" must be an object, not number$/}, + { method: 'parse', input: [null], + message: /^TypeError: Path must be a string\. Received null$/ }, + { method: 'parse', input: [{}], + message: /^TypeError: Path must be a string\. Received {}$/ }, + { method: 'parse', input: [true], + message: /^TypeError: Path must be a string\. Received true$/ }, + { method: 'parse', input: [1], + message: /^TypeError: Path must be a string\. Received 1$/ }, + { method: 'parse', input: [], + message: /^TypeError: Path must be a string\. Received undefined$/ }, + { method: 'format', input: [null], + message: + /^TypeError: Parameter "pathObject" must be an object, not object$/ }, + { method: 'format', input: [''], + message: + /^TypeError: Parameter "pathObject" must be an object, not string$/ }, + { method: 'format', input: [true], + message: + /^TypeError: Parameter "pathObject" must be an object, not boolean$/ }, + { method: 'format', input: [1], + message: + /^TypeError: Parameter "pathObject" must be an object, not number$/ }, ]; checkParseFormat(path.win32, winPaths); diff --git a/test/parallel/test-pipe-file-to-http.js b/test/parallel/test-pipe-file-to-http.js index ccb1c1c6129e0c..244dcd1a990fbf 100644 --- a/test/parallel/test-pipe-file-to-http.js +++ b/test/parallel/test-pipe-file-to-http.js @@ -49,7 +49,7 @@ const server = http.createServer(function(req, res) { if (timeoutId) { clearTimeout(timeoutId); } - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(); }); }); diff --git a/test/parallel/test-preload.js b/test/parallel/test-preload.js index a7b0b9a66ed7ab..77c30c3ad6bc79 100644 --- a/test/parallel/test-preload.js +++ b/test/parallel/test-preload.js @@ -68,7 +68,7 @@ childProcess.exec( const stdinProc = childProcess.spawn( nodeBinary, ['--require', fixtureA], - {stdio: 'pipe'} + { stdio: 'pipe' } ); stdinProc.stdin.end("console.log('hello');"); let stdinStdout = ''; @@ -84,7 +84,7 @@ stdinProc.on('close', function(code) { const replProc = childProcess.spawn( nodeBinary, ['-i', '--require', fixtureA], - {stdio: 'pipe'} + { stdio: 'pipe' } ); replProc.stdin.end('.exit\n'); let replStdout = ''; diff --git a/test/parallel/test-process-external-stdio-close.js b/test/parallel/test-process-external-stdio-close.js index 798ee00d0511b0..067a75ec93492a 100644 --- a/test/parallel/test-process-external-stdio-close.js +++ b/test/parallel/test-process-external-stdio-close.js @@ -14,7 +14,7 @@ if (process.argv[2] === 'child') { process.disconnect(); })); } else { - const child = cp.fork(__filename, ['child'], {silent: true}); + const child = cp.fork(__filename, ['child'], { silent: true }); child.on('close', common.mustCall((exitCode, signal) => { assert.strictEqual(exitCode, 0); diff --git a/test/parallel/test-process-redirect-warnings.js b/test/parallel/test-process-redirect-warnings.js index b1097469b22b99..d38a2e97e25454 100644 --- a/test/parallel/test-process-redirect-warnings.js +++ b/test/parallel/test-process-redirect-warnings.js @@ -16,7 +16,7 @@ common.refreshTmpDir(); const warnmod = require.resolve(`${common.fixturesDir}/warnings.js`); const warnpath = path.join(common.tmpDir, 'warnings.txt'); -fork(warnmod, {execArgv: [`--redirect-warnings=${warnpath}`]}) +fork(warnmod, { execArgv: [`--redirect-warnings=${warnpath}`] }) .on('exit', common.mustCall(() => { fs.readFile(warnpath, 'utf8', common.mustCall((err, data) => { assert.ifError(err); diff --git a/test/parallel/test-querystring-escape.js b/test/parallel/test-querystring-escape.js index c62f19a0ae858f..fd20a8424fee96 100644 --- a/test/parallel/test-querystring-escape.js +++ b/test/parallel/test-querystring-escape.js @@ -17,16 +17,16 @@ assert.throws(() => qs.escape(String.fromCharCode(0xD800 + 1)), // using toString for objects assert.strictEqual( - qs.escape({test: 5, toString: () => 'test', valueOf: () => 10 }), + qs.escape({ test: 5, toString: () => 'test', valueOf: () => 10 }), 'test' ); // toString is not callable, must throw an error -assert.throws(() => qs.escape({toString: 5}), +assert.throws(() => qs.escape({ toString: 5 }), /^TypeError: Cannot convert object to primitive value$/); // should use valueOf instead of non-callable toString -assert.strictEqual(qs.escape({toString: 5, valueOf: () => 'test'}), 'test'); +assert.strictEqual(qs.escape({ toString: 5, valueOf: () => 'test' }), 'test'); assert.throws(() => qs.escape(Symbol('test')), /^TypeError: Cannot convert a Symbol value to a string$/); diff --git a/test/parallel/test-querystring-maxKeys-non-finite.js b/test/parallel/test-querystring-maxKeys-non-finite.js index da72dbf17cf969..e93577d162cff1 100644 --- a/test/parallel/test-querystring-maxKeys-non-finite.js +++ b/test/parallel/test-querystring-maxKeys-non-finite.js @@ -39,12 +39,13 @@ const params = createManyParams(count); // In this instance split will always return an empty array // this test confirms that the output of parse is the expected length // when passed Infinity as the argument for maxKeys -const resultInfinity = parse(params, undefined, undefined, {maxKeys: Infinity}); -const resultNaN = parse(params, undefined, undefined, {maxKeys: NaN}); +const resultInfinity = + parse(params, undefined, undefined, { maxKeys: Infinity }); +const resultNaN = parse(params, undefined, undefined, { maxKeys: NaN }); const resultInfinityString = parse(params, undefined, undefined, { maxKeys: 'Infinity' }); -const resultNaNString = parse(params, undefined, undefined, {maxKeys: 'NaN'}); +const resultNaNString = parse(params, undefined, undefined, { maxKeys: 'NaN' }); // Non Finite maxKeys should return the length of input assert.strictEqual(Object.keys(resultInfinity).length, count); diff --git a/test/parallel/test-querystring-multichar-separator.js b/test/parallel/test-querystring-multichar-separator.js index a518d8da074445..8eef61e2a28f36 100644 --- a/test/parallel/test-querystring-multichar-separator.js +++ b/test/parallel/test-querystring-multichar-separator.js @@ -12,11 +12,13 @@ function check(actual, expected) { }); } -check(qs.parse('foo=>bar&&bar=>baz', '&&', '=>'), {foo: 'bar', bar: 'baz'}); +check(qs.parse('foo=>bar&&bar=>baz', '&&', '=>'), { foo: 'bar', bar: 'baz' }); -check(qs.stringify({foo: 'bar', bar: 'baz'}, '&&', '=>'), 'foo=>bar&&bar=>baz'); +check(qs.stringify({ foo: 'bar', bar: 'baz' }, '&&', '=>'), + 'foo=>bar&&bar=>baz'); -check(qs.parse('foo==>bar, bar==>baz', ', ', '==>'), {foo: 'bar', bar: 'baz'}); +check(qs.parse('foo==>bar, bar==>baz', ', ', '==>'), + { foo: 'bar', bar: 'baz' }); -check(qs.stringify({foo: 'bar', bar: 'baz'}, ', ', '==>'), +check(qs.stringify({ foo: 'bar', bar: 'baz' }, ', ', '==>'), 'foo==>bar, bar==>baz'); diff --git a/test/parallel/test-querystring.js b/test/parallel/test-querystring.js index 42aa7437dd2c14..0e1900a91bb87c 100644 --- a/test/parallel/test-querystring.js +++ b/test/parallel/test-querystring.js @@ -40,30 +40,30 @@ function createWithNoPrototype(properties) { const qsTestCases = [ ['__proto__=1', '__proto__=1', - createWithNoPrototype([{key: '__proto__', value: '1'}])], + createWithNoPrototype([{ key: '__proto__', value: '1' }])], ['__defineGetter__=asdf', '__defineGetter__=asdf', JSON.parse('{"__defineGetter__":"asdf"}')], ['foo=918854443121279438895193', 'foo=918854443121279438895193', - {'foo': '918854443121279438895193'}], - ['foo=bar', 'foo=bar', {'foo': 'bar'}], - ['foo=bar&foo=quux', 'foo=bar&foo=quux', {'foo': ['bar', 'quux']}], - ['foo=1&bar=2', 'foo=1&bar=2', {'foo': '1', 'bar': '2'}], + { 'foo': '918854443121279438895193' }], + ['foo=bar', 'foo=bar', { 'foo': 'bar' }], + ['foo=bar&foo=quux', 'foo=bar&foo=quux', { 'foo': ['bar', 'quux'] }], + ['foo=1&bar=2', 'foo=1&bar=2', { 'foo': '1', 'bar': '2' }], ['my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F', 'my%20weird%20field=q1!2%22\'w%245%267%2Fz8)%3F', - {'my weird field': 'q1!2"\'w$5&7/z8)?' }], - ['foo%3Dbaz=bar', 'foo%3Dbaz=bar', {'foo=baz': 'bar'}], - ['foo=baz=bar', 'foo=baz%3Dbar', {'foo': 'baz=bar'}], + { 'my weird field': 'q1!2"\'w$5&7/z8)?' }], + ['foo%3Dbaz=bar', 'foo%3Dbaz=bar', { 'foo=baz': 'bar' }], + ['foo=baz=bar', 'foo=baz%3Dbar', { 'foo': 'baz=bar' }], ['str=foo&arr=1&arr=2&arr=3&somenull=&undef=', 'str=foo&arr=1&arr=2&arr=3&somenull=&undef=', { 'str': 'foo', 'arr': ['1', '2', '3'], 'somenull': '', - 'undef': ''}], - [' foo = bar ', '%20foo%20=%20bar%20', {' foo ': ' bar '}], - ['foo=%zx', 'foo=%25zx', {'foo': '%zx'}], - ['foo=%EF%BF%BD', 'foo=%EF%BF%BD', {'foo': '\ufffd' }], + 'undef': '' }], + [' foo = bar ', '%20foo%20=%20bar%20', { ' foo ': ' bar ' }], + ['foo=%zx', 'foo=%25zx', { 'foo': '%zx' }], + ['foo=%EF%BF%BD', 'foo=%EF%BF%BD', { 'foo': '\ufffd' }], // See: https://github.com/joyent/node/issues/1707 ['hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', 'hasOwnProperty=x&toString=foo&valueOf=bar&__defineGetter__=baz', @@ -81,7 +81,7 @@ const qsTestCases = [ ['&', '', {}], ['&&&&', '', {}], ['&=&', '=', { '': '' }], - ['&=&=', '=&=', { '': [ '', '' ]}], + ['&=&=', '=&=', { '': [ '', '' ] }], ['=', '=', { '': '' }], ['+', '%20=', { ' ': '' }], ['+=', '%20=', { ' ': '' }], @@ -112,35 +112,36 @@ const qsTestCases = [ // [ wonkyQS, canonicalQS, obj ] const qsColonTestCases = [ - ['foo:bar', 'foo:bar', {'foo': 'bar'}], - ['foo:bar;foo:quux', 'foo:bar;foo:quux', {'foo': ['bar', 'quux']}], + ['foo:bar', 'foo:bar', { 'foo': 'bar' }], + ['foo:bar;foo:quux', 'foo:bar;foo:quux', { 'foo': ['bar', 'quux'] }], ['foo:1&bar:2;baz:quux', 'foo:1%26bar%3A2;baz:quux', - {'foo': '1&bar:2', 'baz': 'quux'}], - ['foo%3Abaz:bar', 'foo%3Abaz:bar', {'foo:baz': 'bar'}], - ['foo:baz:bar', 'foo:baz%3Abar', {'foo': 'baz:bar'}] + { 'foo': '1&bar:2', 'baz': 'quux' }], + ['foo%3Abaz:bar', 'foo%3Abaz:bar', { 'foo:baz': 'bar' }], + ['foo:baz:bar', 'foo:baz%3Abar', { 'foo': 'baz:bar' }] ]; // [wonkyObj, qs, canonicalObj] function extendedFunction() {} -extendedFunction.prototype = {a: 'b'}; +extendedFunction.prototype = { a: 'b' }; const qsWeirdObjects = [ // eslint-disable-next-line no-unescaped-regexp-dot - [{regexp: /./g}, 'regexp=', {'regexp': ''}], + [{ regexp: /./g }, 'regexp=', { 'regexp': '' }], // eslint-disable-next-line no-unescaped-regexp-dot - [{regexp: new RegExp('.', 'g')}, 'regexp=', {'regexp': ''}], - [{fn: function() {}}, 'fn=', {'fn': ''}], - [{fn: new Function('')}, 'fn=', {'fn': ''}], - [{math: Math}, 'math=', {'math': ''}], - [{e: extendedFunction}, 'e=', {'e': ''}], - [{d: new Date()}, 'd=', {'d': ''}], - [{d: Date}, 'd=', {'d': ''}], - [{f: new Boolean(false), t: new Boolean(true)}, 'f=&t=', {'f': '', 't': ''}], - [{f: false, t: true}, 'f=false&t=true', {'f': 'false', 't': 'true'}], - [{n: null}, 'n=', {'n': ''}], - [{nan: NaN}, 'nan=', {'nan': ''}], - [{inf: Infinity}, 'inf=', {'inf': ''}], - [{a: [], b: []}, '', {}] + [{ regexp: new RegExp('.', 'g') }, 'regexp=', { 'regexp': '' }], + [{ fn: function() {} }, 'fn=', { 'fn': '' }], + [{ fn: new Function('') }, 'fn=', { 'fn': '' }], + [{ math: Math }, 'math=', { 'math': '' }], + [{ e: extendedFunction }, 'e=', { 'e': '' }], + [{ d: new Date() }, 'd=', { 'd': '' }], + [{ d: Date }, 'd=', { 'd': '' }], + [{ f: new Boolean(false), t: new Boolean(true) }, 'f=&t=', + { 'f': '', 't': '' }], + [{ f: false, t: true }, 'f=false&t=true', { 'f': 'false', 't': 'true' }], + [{ n: null }, 'n=', { 'n': '' }], + [{ nan: NaN }, 'nan=', { 'nan': '' }], + [{ inf: Infinity }, 'inf=', { 'inf': '' }], + [{ a: [], b: [] }, '', {}] ]; // }}} @@ -149,17 +150,17 @@ const foreignObject = vm.runInNewContext('({"foo": ["bar", "baz"]})'); const qsNoMungeTestCases = [ ['', {}], - ['foo=bar&foo=baz', {'foo': ['bar', 'baz']}], + ['foo=bar&foo=baz', { 'foo': ['bar', 'baz'] }], ['foo=bar&foo=baz', foreignObject], - ['blah=burp', {'blah': 'burp'}], - ['a=!-._~\'()*', {'a': '!-._~\'()*'}], - ['a=abcdefghijklmnopqrstuvwxyz', {'a': 'abcdefghijklmnopqrstuvwxyz'}], - ['a=ABCDEFGHIJKLMNOPQRSTUVWXYZ', {'a': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}], - ['a=0123456789', {'a': '0123456789'}], - ['gragh=1&gragh=3&goo=2', {'gragh': ['1', '3'], 'goo': '2'}], + ['blah=burp', { 'blah': 'burp' }], + ['a=!-._~\'()*', { 'a': '!-._~\'()*' }], + ['a=abcdefghijklmnopqrstuvwxyz', { 'a': 'abcdefghijklmnopqrstuvwxyz' }], + ['a=ABCDEFGHIJKLMNOPQRSTUVWXYZ', { 'a': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' }], + ['a=0123456789', { 'a': '0123456789' }], + ['gragh=1&gragh=3&goo=2', { 'gragh': ['1', '3'], 'goo': '2' }], ['frappucino=muffin&goat%5B%5D=scone&pond=moose', - {'frappucino': 'muffin', 'goat[]': 'scone', 'pond': 'moose'}], - ['trololol=yes&lololo=no', {'trololol': 'yes', 'lololo': 'no'}] + { 'frappucino': 'muffin', 'goat[]': 'scone', 'pond': 'moose' }], + ['trololol=yes&lololo=no', { 'trololol': 'yes', 'lololo': 'no' }] ]; const qsUnescapeTestCases = [ @@ -224,14 +225,14 @@ qsNoMungeTestCases.forEach(function(testCase) { { const f = qs.parse('a=b&q=x%3Dy%26y%3Dz'); check(f, createWithNoPrototype([ - { key: 'a', value: 'b'}, - {key: 'q', value: 'x=y&y=z'} + { key: 'a', value: 'b' }, + { key: 'q', value: 'x=y&y=z' } ])); f.q = qs.parse(f.q); const expectedInternal = createWithNoPrototype([ - { key: 'x', value: 'y'}, - {key: 'y', value: 'z' } + { key: 'x', value: 'y' }, + { key: 'y', value: 'z' } ]); check(f.q, expectedInternal); } @@ -240,13 +241,13 @@ qsNoMungeTestCases.forEach(function(testCase) { { const f = qs.parse('a:b;q:x%3Ay%3By%3Az', ';', ':'); check(f, createWithNoPrototype([ - {key: 'a', value: 'b'}, - {key: 'q', value: 'x:y;y:z'} + { key: 'a', value: 'b' }, + { key: 'q', value: 'x:y;y:z' } ])); f.q = qs.parse(f.q, ';', ':'); const expectedInternal = createWithNoPrototype([ - { key: 'x', value: 'y'}, - {key: 'y', value: 'z' } + { key: 'x', value: 'y' }, + { key: 'y', value: 'z' } ]); check(f.q, expectedInternal); } @@ -342,7 +343,7 @@ assert.strictEqual( const url = qs.stringify(query); assert.strictEqual( - Object.keys(qs.parse(url, null, null, {maxKeys: 0})).length, + Object.keys(qs.parse(url, null, null, { maxKeys: 0 })).length, 2000); } @@ -392,10 +393,11 @@ check(qs.parse('%\u0100=%\u0101'), { '%Ā': '%ā' }); return str + str; } - check(qs.parse('a=a&b=b&c=c', null, null, {decodeURIComponent: demoDecode}), - {aa: 'aa', bb: 'bb', cc: 'cc'}); - check(qs.parse('a=a&b=b&c=c', null, '==', {decodeURIComponent: (str) => str}), - {'a=a': '', 'b=b': '', 'c=c': ''}); + check(qs.parse('a=a&b=b&c=c', null, null, { decodeURIComponent: demoDecode }), + { aa: 'aa', bb: 'bb', cc: 'cc' }); + check(qs.parse('a=a&b=b&c=c', null, '==', + { decodeURIComponent: (str) => str }), + { 'a=a': '', 'b=b': '', 'c=c': '' }); } // Test QueryString.unescape @@ -404,8 +406,8 @@ check(qs.parse('%\u0100=%\u0101'), { '%Ā': '%ā' }); throw new Error('To jump to the catch scope'); } - check(qs.parse('a=a', null, null, {decodeURIComponent: errDecode}), - {a: 'a'}); + check(qs.parse('a=a', null, null, { decodeURIComponent: errDecode }), + { a: 'a' }); } // Test custom encode @@ -414,9 +416,9 @@ check(qs.parse('%\u0100=%\u0101'), { '%Ā': '%ā' }); return str[0]; } - const obj = {aa: 'aa', bb: 'bb', cc: 'cc'}; + const obj = { aa: 'aa', bb: 'bb', cc: 'cc' }; assert.strictEqual( - qs.stringify(obj, null, null, {encodeURIComponent: demoEncode}), + qs.stringify(obj, null, null, { encodeURIComponent: demoEncode }), 'a=a&b=b&c=c'); } @@ -434,7 +436,7 @@ qsUnescapeTestCases.forEach(function(testCase) { }; check( qs.parse('foo=bor'), - createWithNoPrototype([{key: 'f__', value: 'b_r'}])); + createWithNoPrototype([{ key: 'f__', value: 'b_r' }])); qs.unescape = prevUnescape; } // test separator and "equals" parsing order diff --git a/test/parallel/test-readline-interface.js b/test/parallel/test-readline-interface.js index e1be69af0c90f4..547d4feb8c2b5f 100644 --- a/test/parallel/test-readline-interface.js +++ b/test/parallel/test-readline-interface.js @@ -58,7 +58,7 @@ function isWarned(emitter) { { // Minimum crlfDelay is 100ms const fi = new FakeInput(); - const rli = new readline.Interface({ input: fi, output: fi, crlfDelay: 0}); + const rli = new readline.Interface({ input: fi, output: fi, crlfDelay: 0 }); assert.strictEqual(rli.crlfDelay, 100); rli.close(); } diff --git a/test/parallel/test-readline.js b/test/parallel/test-readline.js index 4ec11fe8d817ab..82bf74549b2343 100644 --- a/test/parallel/test-readline.js +++ b/test/parallel/test-readline.js @@ -56,20 +56,20 @@ const assert = require('assert'); const key = { xterm: { - home: ['\x1b[H', {ctrl: true, name: 'a'}], - end: ['\x1b[F', {ctrl: true, name: 'e'}], + home: ['\x1b[H', { ctrl: true, name: 'a' }], + end: ['\x1b[F', { ctrl: true, name: 'e' }], }, gnome: { - home: ['\x1bOH', {ctrl: true, name: 'a'}], - end: ['\x1bOF', {ctrl: true, name: 'e'}] + home: ['\x1bOH', { ctrl: true, name: 'a' }], + end: ['\x1bOF', { ctrl: true, name: 'e' }] }, rxvt: { - home: ['\x1b[7', {ctrl: true, name: 'a'}], - end: ['\x1b[8', {ctrl: true, name: 'e'}] + home: ['\x1b[7', { ctrl: true, name: 'a' }], + end: ['\x1b[8', { ctrl: true, name: 'e' }] }, putty: { - home: ['\x1b[1~', {ctrl: true, name: 'a'}], - end: ['\x1b[>~', {ctrl: true, name: 'e'}] + home: ['\x1b[1~', { ctrl: true, name: 'a' }], + end: ['\x1b[>~', { ctrl: true, name: 'e' }] } }; @@ -91,27 +91,27 @@ const assert = require('assert'); const key = { xterm: { - home: ['\x1b[H', {ctrl: true, name: 'a'}], - metab: ['\x1bb', {meta: true, name: 'b'}], - metaf: ['\x1bf', {meta: true, name: 'f'}], + home: ['\x1b[H', { ctrl: true, name: 'a' }], + metab: ['\x1bb', { meta: true, name: 'b' }], + metaf: ['\x1bf', { meta: true, name: 'f' }], } }; rl.write('foo bar.hop/zoo'); rl.write.apply(rl, key.xterm.home); [ - {cursor: 4, key: key.xterm.metaf}, - {cursor: 7, key: key.xterm.metaf}, - {cursor: 8, key: key.xterm.metaf}, - {cursor: 11, key: key.xterm.metaf}, - {cursor: 12, key: key.xterm.metaf}, - {cursor: 15, key: key.xterm.metaf}, - {cursor: 12, key: key.xterm.metab}, - {cursor: 11, key: key.xterm.metab}, - {cursor: 8, key: key.xterm.metab}, - {cursor: 7, key: key.xterm.metab}, - {cursor: 4, key: key.xterm.metab}, - {cursor: 0, key: key.xterm.metab}, + { cursor: 4, key: key.xterm.metaf }, + { cursor: 7, key: key.xterm.metaf }, + { cursor: 8, key: key.xterm.metaf }, + { cursor: 11, key: key.xterm.metaf }, + { cursor: 12, key: key.xterm.metaf }, + { cursor: 15, key: key.xterm.metaf }, + { cursor: 12, key: key.xterm.metab }, + { cursor: 11, key: key.xterm.metab }, + { cursor: 8, key: key.xterm.metab }, + { cursor: 7, key: key.xterm.metab }, + { cursor: 4, key: key.xterm.metab }, + { cursor: 0, key: key.xterm.metab }, ].forEach(function(action) { rl.write.apply(rl, action.key); assert.strictEqual(rl.cursor, action.cursor); @@ -127,8 +127,8 @@ const assert = require('assert'); const key = { xterm: { - home: ['\x1b[H', {ctrl: true, name: 'a'}], - metad: ['\x1bd', {meta: true, name: 'd'}] + home: ['\x1b[H', { ctrl: true, name: 'a' }], + metad: ['\x1bd', { meta: true, name: 'd' }] } }; diff --git a/test/parallel/test-regress-GH-2245.js b/test/parallel/test-regress-GH-2245.js index c5b0ae4982d993..37260b59e34721 100644 --- a/test/parallel/test-regress-GH-2245.js +++ b/test/parallel/test-regress-GH-2245.js @@ -25,4 +25,4 @@ function test() { } -assert.deepStrictEqual(test(), {m: 1}); +assert.deepStrictEqual(test(), { m: 1 }); diff --git a/test/parallel/test-regress-GH-4948.js b/test/parallel/test-regress-GH-4948.js index 5ec79b8685b409..d4d63600868470 100644 --- a/test/parallel/test-regress-GH-4948.js +++ b/test/parallel/test-regress-GH-4948.js @@ -16,8 +16,8 @@ const server = http.createServer(function(serverReq, serverRes) { // normally the use case would be to call an external site // does not require connecting locally or to itself to fail - const r = http.request({hostname: 'localhost', - port: this.address().port}, function(res) { + const r = http.request({ hostname: 'localhost', + port: this.address().port }, function(res) { // required, just needs to be in the client response somewhere serverRes.end(); diff --git a/test/parallel/test-repl-editor.js b/test/parallel/test-repl-editor.js index 678d6d5c6d94f8..091eaec1ab41be 100644 --- a/test/parallel/test-repl-editor.js +++ b/test/parallel/test-repl-editor.js @@ -10,7 +10,7 @@ const repl = require('repl'); const terminalCode = '\u001b[1G\u001b[0J> \u001b[3G'; const terminalCodeRegex = new RegExp(terminalCode.replace(/\[/g, '\\['), 'g'); -function run({input, output, event, checkTerminalCodes = true}) { +function run({ input, output, event, checkTerminalCodes = true }) { const stream = new common.ArrayStream(); let found = ''; @@ -45,22 +45,22 @@ const tests = [ { input: '', output: '\n(To exit, press ^C again or type .exit)', - event: {ctrl: true, name: 'c'} + event: { ctrl: true, name: 'c' } }, { input: 'var i = 1;', output: '', - event: {ctrl: true, name: 'c'} + event: { ctrl: true, name: 'c' } }, { input: 'var i = 1;\ni + 3', output: '\n4', - event: {ctrl: true, name: 'd'} + event: { ctrl: true, name: 'd' } }, { input: ' var i = 1;\ni + 3', output: '\n4', - event: {ctrl: true, name: 'd'} + event: { ctrl: true, name: 'd' } }, { input: '', @@ -73,7 +73,7 @@ const tests = [ tests.forEach(run); // Auto code alignment for .editor mode -function testCodeAligment({input, cursor = 0, line = ''}) { +function testCodeAligment({ input, cursor = 0, line = '' }) { const stream = new common.ArrayStream(); const outputStream = new common.ArrayStream(); @@ -93,7 +93,7 @@ function testCodeAligment({input, cursor = 0, line = ''}) { assert.strictEqual(line, replServer.line); assert.strictEqual(cursor, replServer.cursor); - replServer.write('', {ctrl: true, name: 'd'}); + replServer.write('', { ctrl: true, name: 'd' }); replServer.close(); // Ensure that empty lines are not saved in history assert.notStrictEqual(replServer.history[0].trim(), ''); diff --git a/test/parallel/test-repl-eval-scope.js b/test/parallel/test-repl-eval-scope.js index b9bace5f7d982a..00b577cba73f76 100644 --- a/test/parallel/test-repl-eval-scope.js +++ b/test/parallel/test-repl-eval-scope.js @@ -8,7 +8,7 @@ const repl = require('repl'); const options = { eval: common.mustCall((cmd, context) => { assert.strictEqual(cmd, '.scope\n'); - assert.deepStrictEqual(context, {animal: 'Sterrance'}); + assert.deepStrictEqual(context, { animal: 'Sterrance' }); }), input: stream, output: stream, @@ -16,7 +16,7 @@ const repl = require('repl'); }; const r = repl.start(options); - r.context = {animal: 'Sterrance'}; + r.context = { animal: 'Sterrance' }; stream.emit('data', '\t'); stream.emit('.exit\n'); diff --git a/test/parallel/test-repl-eval.js b/test/parallel/test-repl-eval.js index 7508e14d8bd024..d775423fb74a52 100644 --- a/test/parallel/test-repl-eval.js +++ b/test/parallel/test-repl-eval.js @@ -16,7 +16,7 @@ const repl = require('repl'); }; const r = repl.start(options); - r.context = {foo: 'bar'}; + r.context = { foo: 'bar' }; try { // Default preprocessor transforms diff --git a/test/parallel/test-repl-history-perm.js b/test/parallel/test-repl-history-perm.js index 259c96fe8aa0f7..5ca8bf57a432b2 100644 --- a/test/parallel/test-repl-history-perm.js +++ b/test/parallel/test-repl-history-perm.js @@ -45,7 +45,7 @@ const checkResults = common.mustCall(function(err, r) { }); repl.createInternalRepl( - {NODE_REPL_HISTORY: replHistoryPath}, + { NODE_REPL_HISTORY: replHistoryPath }, { terminal: true, input: stream, diff --git a/test/parallel/test-repl-save-load.js b/test/parallel/test-repl-save-load.js index 4ef2a633541494..2be272473b652a 100644 --- a/test/parallel/test-repl-save-load.js +++ b/test/parallel/test-repl-save-load.js @@ -63,7 +63,7 @@ assert.strictEqual(fs.readFileSync(saveFileName, 'utf8'), putIn.run(['.editor']); putIn.run(cmds); - replServer.write('', {ctrl: true, name: 'd'}); + replServer.write('', { ctrl: true, name: 'd' }); putIn.run([`.save ${saveFileName}`]); replServer.close(); diff --git a/test/parallel/test-repl.js b/test/parallel/test-repl.js index d2ff29a4d12e89..6df856a20ec410 100644 --- a/test/parallel/test-repl.js +++ b/test/parallel/test-repl.js @@ -167,7 +167,7 @@ function error_test() { expect: '0.2' }, // Can parse valid JSON { client: client_unix, send: 'JSON.parse(\'{"valid": "json"}\');', - expect: '{ valid: \'json\' }'}, + expect: '{ valid: \'json\' }' }, // invalid input to JSON.parse error is special case of syntax error, // should throw { client: client_unix, send: 'JSON.parse(\'{invalid: \\\'json\\\'}\');', diff --git a/test/parallel/test-require-cache.js b/test/parallel/test-require-cache.js index 098f6fffbb697c..7b62ab57648a2f 100644 --- a/test/parallel/test-require-cache.js +++ b/test/parallel/test-require-cache.js @@ -28,7 +28,7 @@ const assert = require('assert'); const absolutePath = require.resolve(relativePath); const fakeModule = {}; - require.cache[absolutePath] = {exports: fakeModule}; + require.cache[absolutePath] = { exports: fakeModule }; assert.strictEqual(require(relativePath), fakeModule); } @@ -38,7 +38,7 @@ const assert = require('assert'); const relativePath = 'fs'; const fakeModule = {}; - require.cache[relativePath] = {exports: fakeModule}; + require.cache[relativePath] = { exports: fakeModule }; assert.strictEqual(require(relativePath), fakeModule); } diff --git a/test/parallel/test-stream-big-packet.js b/test/parallel/test-stream-big-packet.js index aeddfb2052451a..8575c3e43a46ee 100644 --- a/test/parallel/test-stream-big-packet.js +++ b/test/parallel/test-stream-big-packet.js @@ -53,7 +53,7 @@ const s2 = new PassThrough(); const s3 = new TestStream(); s1.pipe(s3); // Don't let s2 auto close which may close s3 -s2.pipe(s3, {end: false}); +s2.pipe(s3, { end: false }); // We must write a buffer larger than highWaterMark const big = Buffer.alloc(s1._writableState.highWaterMark + 1, 'x'); diff --git a/test/parallel/test-stream-pipe-await-drain-manual-resume.js b/test/parallel/test-stream-pipe-await-drain-manual-resume.js index 96360429e58856..bd7332c7fabc50 100644 --- a/test/parallel/test-stream-pipe-await-drain-manual-resume.js +++ b/test/parallel/test-stream-pipe-await-drain-manual-resume.js @@ -15,7 +15,7 @@ const queue = []; writable._write = (chunk, encoding, cb) => { if (isCurrentlyBufferingWrites) - queue.push({chunk, cb}); + queue.push({ chunk, cb }); else cb(); }; diff --git a/test/parallel/test-stream-pipe-unpipe-streams.js b/test/parallel/test-stream-pipe-unpipe-streams.js index 916bd2cdfacf53..cd29b66365ae0f 100644 --- a/test/parallel/test-stream-pipe-unpipe-streams.js +++ b/test/parallel/test-stream-pipe-unpipe-streams.js @@ -4,9 +4,9 @@ const assert = require('assert'); const { Readable, Writable } = require('stream'); -const source = Readable({read: () => {}}); -const dest1 = Writable({write: () => {}}); -const dest2 = Writable({write: () => {}}); +const source = Readable({ read: () => {} }); +const dest1 = Writable({ write: () => {} }); +const dest2 = Writable({ write: () => {} }); source.pipe(dest1); source.pipe(dest2); diff --git a/test/parallel/test-stream-unpipe-event.js b/test/parallel/test-stream-unpipe-event.js index befa24253d33f5..340502d1a98b7c 100644 --- a/test/parallel/test-stream-unpipe-event.js +++ b/test/parallel/test-stream-unpipe-event.js @@ -1,7 +1,7 @@ 'use strict'; const common = require('../common'); const assert = require('assert'); -const {Writable, Readable} = require('stream'); +const { Writable, Readable } = require('stream'); class NullWriteable extends Writable { _write(chunk, encoding, callback) { return callback(); @@ -55,7 +55,7 @@ class NeverEndReadable extends Readable { const src = new QuickEndReadable(); dest.on('pipe', common.mustCall()); dest.on('unpipe', common.mustCall()); - src.pipe(dest, {end: false}); + src.pipe(dest, { end: false }); setImmediate(() => { assert.strictEqual(src._readableState.pipesCount, 0); }); @@ -66,7 +66,7 @@ class NeverEndReadable extends Readable { const src = new NeverEndReadable(); dest.on('pipe', common.mustCall()); dest.on('unpipe', common.mustNotCall('unpipe should not have been emitted')); - src.pipe(dest, {end: false}); + src.pipe(dest, { end: false }); setImmediate(() => { assert.strictEqual(src._readableState.pipesCount, 1); }); @@ -77,7 +77,7 @@ class NeverEndReadable extends Readable { const src = new NeverEndReadable(); dest.on('pipe', common.mustCall()); dest.on('unpipe', common.mustCall()); - src.pipe(dest, {end: false}); + src.pipe(dest, { end: false }); src.unpipe(dest); setImmediate(() => { assert.strictEqual(src._readableState.pipesCount, 0); diff --git a/test/parallel/test-stream-writable-null.js b/test/parallel/test-stream-writable-null.js index 0bb8aa7bbc1c10..58b61bfdc1e8cf 100644 --- a/test/parallel/test-stream-writable-null.js +++ b/test/parallel/test-stream-writable-null.js @@ -17,11 +17,11 @@ MyWritable.prototype._write = function(chunk, encoding, callback) { }; assert.throws(() => { - const m = new MyWritable({objectMode: true}); + const m = new MyWritable({ objectMode: true }); m.write(null, (err) => assert.ok(err)); }, /^TypeError: May not write null values to stream$/); assert.doesNotThrow(() => { - const m = new MyWritable({objectMode: true}).on('error', (e) => { + const m = new MyWritable({ objectMode: true }).on('error', (e) => { assert.ok(e); }); m.write(null, (err) => { @@ -43,11 +43,11 @@ assert.doesNotThrow(() => { }); assert.doesNotThrow(() => { - const m = new MyWritable({objectMode: true}); + const m = new MyWritable({ objectMode: true }); m.write(false, (err) => assert.ifError(err)); }); assert.doesNotThrow(() => { - const m = new MyWritable({objectMode: true}).on('error', (e) => { + const m = new MyWritable({ objectMode: true }).on('error', (e) => { assert.ifError(e || new Error('should not get here')); }); m.write(false, (err) => { diff --git a/test/parallel/test-stream-writev.js b/test/parallel/test-stream-writev.js index 65aee1d20d48cb..654b46254d8ee7 100644 --- a/test/parallel/test-stream-writev.js +++ b/test/parallel/test-stream-writev.js @@ -71,7 +71,7 @@ function test(decode, uncork, multi, next) { { encoding: 'buffer', chunk: [10, 97, 110, 100, 32, 116, 104, 101, 110, 46, 46, 46] }, { encoding: 'buffer', - chunk: [250, 206, 190, 167, 222, 173, 190, 239, 222, 202, 251, 173]} + chunk: [250, 206, 190, 167, 222, 173, 190, 239, 222, 202, 251, 173] } ] : [ { encoding: 'ascii', chunk: 'hello, ' }, { encoding: 'utf8', chunk: 'world' }, diff --git a/test/parallel/test-stream2-base64-single-char-read-end.js b/test/parallel/test-stream2-base64-single-char-read-end.js index 3c946f3b2f6df8..10259e280454c0 100644 --- a/test/parallel/test-stream2-base64-single-char-read-end.js +++ b/test/parallel/test-stream2-base64-single-char-read-end.js @@ -25,7 +25,7 @@ const R = require('_stream_readable'); const W = require('_stream_writable'); const assert = require('assert'); -const src = new R({encoding: 'base64'}); +const src = new R({ encoding: 'base64' }); const dst = new W(); let hasRead = false; const accum = []; diff --git a/test/parallel/test-stream2-httpclient-response-end.js b/test/parallel/test-stream2-httpclient-response-end.js index 6d3da191b06cb9..27d31e50a96a7e 100644 --- a/test/parallel/test-stream2-httpclient-response-end.js +++ b/test/parallel/test-stream2-httpclient-response-end.js @@ -4,10 +4,10 @@ const assert = require('assert'); const http = require('http'); const msg = 'Hello'; const server = http.createServer(function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); + res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(msg); }).listen(0, function() { - http.get({port: this.address().port}, function(res) { + http.get({ port: this.address().port }, function(res) { let data = ''; res.on('readable', common.mustCall(function() { console.log('readable event'); diff --git a/test/parallel/test-stream2-objects.js b/test/parallel/test-stream2-objects.js index 901f946a931944..f58ea4a32a1e7d 100644 --- a/test/parallel/test-stream2-objects.js +++ b/test/parallel/test-stream2-objects.js @@ -53,7 +53,7 @@ function fromArray(list) { { // Verify that objects can be read from the stream - const r = fromArray([{ one: '1'}, { two: '2' }]); + const r = fromArray([{ one: '1' }, { two: '2' }]); const v1 = r.read(); const v2 = r.read(); @@ -66,7 +66,7 @@ function fromArray(list) { { // Verify that objects can be piped into the stream - const r = fromArray([{ one: '1'}, { two: '2' }]); + const r = fromArray([{ one: '1' }, { two: '2' }]); r.pipe(toArray(common.mustCall(function(list) { assert.deepStrictEqual(list, [ @@ -78,7 +78,7 @@ function fromArray(list) { { // Verify that read(n) is ignored - const r = fromArray([{ one: '1'}, { two: '2' }]); + const r = fromArray([{ one: '1' }, { two: '2' }]); const value = r.read(2); assert.deepStrictEqual(value, { one: '1' }); @@ -87,7 +87,7 @@ function fromArray(list) { { // Verify that objects can be synchronously read const r = new Readable({ objectMode: true }); - const list = [{ one: '1'}, { two: '2' }]; + const list = [{ one: '1' }, { two: '2' }]; r._read = function(n) { const item = list.shift(); r.push(item || null); @@ -104,7 +104,7 @@ function fromArray(list) { { // Verify that objects can be asynchronously read const r = new Readable({ objectMode: true }); - const list = [{ one: '1'}, { two: '2' }]; + const list = [{ one: '1' }, { two: '2' }]; r._read = function(n) { const item = list.shift(); process.nextTick(function() { diff --git a/test/parallel/test-stream2-transform.js b/test/parallel/test-stream2-transform.js index 6b5593d93be9ef..0f12476f506a93 100644 --- a/test/parallel/test-stream2-transform.js +++ b/test/parallel/test-stream2-transform.js @@ -77,7 +77,7 @@ const Transform = require('_stream_transform'); pt.write(0); pt.write('foo'); pt.write(''); - pt.write({ a: 'b'}); + pt.write({ a: 'b' }); pt.end(); assert.strictEqual(pt.read(), 1); @@ -86,7 +86,7 @@ const Transform = require('_stream_transform'); assert.strictEqual(pt.read(), 0); assert.strictEqual(pt.read(), 'foo'); assert.strictEqual(pt.read(), ''); - assert.deepStrictEqual(pt.read(), { a: 'b'}); + assert.deepStrictEqual(pt.read(), { a: 'b' }); } { @@ -131,7 +131,7 @@ const Transform = require('_stream_transform'); pt.write(0); pt.write('foo'); pt.write(''); - pt.write({ a: 'b'}); + pt.write({ a: 'b' }); pt.end(); assert.strictEqual(pt.read(), '1'); @@ -258,7 +258,7 @@ const Transform = require('_stream_transform'); // Verify compex transform behavior let count = 0; let saved = null; - const pt = new Transform({highWaterMark: 3}); + const pt = new Transform({ highWaterMark: 3 }); pt._transform = function(c, e, cb) { if (count++ === 1) saved = c; diff --git a/test/parallel/test-timers-active.js b/test/parallel/test-timers-active.js index 62707cf18c0ab7..a98d32c0b042d1 100644 --- a/test/parallel/test-timers-active.js +++ b/test/parallel/test-timers-active.js @@ -30,5 +30,5 @@ bogusTimers.forEach(function(bogus) { const savedTimeout = bogus._idleTimeout; active(bogus); // active() should not mutate these objects - assert.deepStrictEqual(bogus, {_idleTimeout: savedTimeout}); + assert.deepStrictEqual(bogus, { _idleTimeout: savedTimeout }); }); diff --git a/test/parallel/test-timers-throw-when-cb-not-function.js b/test/parallel/test-timers-throw-when-cb-not-function.js index 4e866726c19c22..7751f0fb2e03a1 100644 --- a/test/parallel/test-timers-throw-when-cb-not-function.js +++ b/test/parallel/test-timers-throw-when-cb-not-function.js @@ -11,7 +11,7 @@ function doSetTimeout(callback, after) { const errMessage = /"callback" argument must be a function/; assert.throws(doSetTimeout('foo'), errMessage); -assert.throws(doSetTimeout({foo: 'bar'}), errMessage); +assert.throws(doSetTimeout({ foo: 'bar' }), errMessage); assert.throws(doSetTimeout(), errMessage); assert.throws(doSetTimeout(undefined, 0), errMessage); assert.throws(doSetTimeout(null, 0), errMessage); @@ -25,7 +25,7 @@ function doSetInterval(callback, after) { } assert.throws(doSetInterval('foo'), errMessage); -assert.throws(doSetInterval({foo: 'bar'}), errMessage); +assert.throws(doSetInterval({ foo: 'bar' }), errMessage); assert.throws(doSetInterval(), errMessage); assert.throws(doSetInterval(undefined, 0), errMessage); assert.throws(doSetInterval(null, 0), errMessage); @@ -39,7 +39,7 @@ function doSetImmediate(callback, after) { } assert.throws(doSetImmediate('foo'), errMessage); -assert.throws(doSetImmediate({foo: 'bar'}), errMessage); +assert.throws(doSetImmediate({ foo: 'bar' }), errMessage); assert.throws(doSetImmediate(), errMessage); assert.throws(doSetImmediate(undefined, 0), errMessage); assert.throws(doSetImmediate(null, 0), errMessage); diff --git a/test/parallel/test-tls-alpn-server-client.js b/test/parallel/test-tls-alpn-server-client.js index e0547300c0a416..44699b20533f9d 100644 --- a/test/parallel/test-tls-alpn-server-client.js +++ b/test/parallel/test-tls-alpn-server-client.js @@ -32,7 +32,7 @@ function runTest(clientsOptions, serverOptions, cb) { const results = []; let index = 0; const server = tls.createServer(serverOptions, function(c) { - results[index].server = {ALPN: c.alpnProtocol, NPN: c.npnProtocol}; + results[index].server = { ALPN: c.alpnProtocol, NPN: c.npnProtocol }; }); server.listen(0, serverIP, function() { @@ -47,8 +47,8 @@ function runTest(clientsOptions, serverOptions, cb) { results[index] = {}; const client = tls.connect(opt, function() { - results[index].client = {ALPN: client.alpnProtocol, - NPN: client.npnProtocol}; + results[index].client = { ALPN: client.alpnProtocol, + NPN: client.npnProtocol }; client.destroy(); if (options.length) { index++; @@ -83,16 +83,16 @@ function Test1() { runTest(clientsOptions, serverOptions, function(results) { // 'a' is selected by ALPN checkResults(results[0], - {server: {ALPN: 'a', NPN: false}, - client: {ALPN: 'a', NPN: undefined}}); + { server: { ALPN: 'a', NPN: false }, + client: { ALPN: 'a', NPN: undefined } }); // 'b' is selected by ALPN checkResults(results[1], - {server: {ALPN: 'b', NPN: false}, - client: {ALPN: 'b', NPN: undefined}}); + { server: { ALPN: 'b', NPN: false }, + client: { ALPN: 'b', NPN: undefined } }); // nothing is selected by ALPN checkResults(results[2], - {server: {ALPN: false, NPN: 'first-priority-unsupported'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'first-priority-unsupported' }, + client: { ALPN: false, NPN: false } }); // execute next test Test2(); }); @@ -116,16 +116,16 @@ function Test2() { runTest(clientsOptions, serverOptions, function(results) { // 'a' is selected by ALPN checkResults(results[0], - {server: {ALPN: 'a', NPN: false}, - client: {ALPN: 'a', NPN: undefined}}); + { server: { ALPN: 'a', NPN: false }, + client: { ALPN: 'a', NPN: undefined } }); // 'b' is selected by ALPN checkResults(results[1], - {server: {ALPN: 'b', NPN: false}, - client: {ALPN: 'b', NPN: undefined}}); + { server: { ALPN: 'b', NPN: false }, + client: { ALPN: 'b', NPN: undefined } }); // nothing is selected by ALPN checkResults(results[2], - {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // execute next test Test3(); }); @@ -149,16 +149,16 @@ function Test3() { runTest(clientsOptions, serverOptions, function(results) { // 'a' is selected by NPN checkResults(results[0], - {server: {ALPN: false, NPN: 'a'}, - client: {ALPN: false, NPN: 'a'}}); + { server: { ALPN: false, NPN: 'a' }, + client: { ALPN: false, NPN: 'a' } }); // nothing is selected by ALPN checkResults(results[1], - {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // nothing is selected by ALPN checkResults(results[2], - {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // execute next test Test4(); }); @@ -176,16 +176,16 @@ function Test4() { runTest(clientsOptions, serverOptions, function(results) { // nothing is selected by ALPN checkResults(results[0], - {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // nothing is selected by ALPN checkResults(results[1], - {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // nothing is selected by ALPN checkResults(results[2], - {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // execute next test Test5(); }); @@ -210,15 +210,15 @@ function Test5() { runTest(clientsOptions, serverOptions, function(results) { // 'a' is selected by ALPN - checkResults(results[0], {server: {ALPN: 'a', NPN: false}, - client: {ALPN: 'a', NPN: undefined}}); + checkResults(results[0], { server: { ALPN: 'a', NPN: false }, + client: { ALPN: 'a', NPN: undefined } }); // 'b' is selected by ALPN - checkResults(results[1], {server: {ALPN: 'b', NPN: false}, - client: {ALPN: 'b', NPN: undefined}}); + checkResults(results[1], { server: { ALPN: 'b', NPN: false }, + client: { ALPN: 'b', NPN: undefined } }); // nothing is selected by ALPN - checkResults(results[2], {server: {ALPN: false, - NPN: 'first-priority-unsupported'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[2], { server: { ALPN: false, + NPN: 'first-priority-unsupported' }, + client: { ALPN: false, NPN: false } }); // execute next test Test6(); }); @@ -240,14 +240,14 @@ function Test6() { runTest(clientsOptions, serverOptions, function(results) { // 'a' is selected by ALPN - checkResults(results[0], {server: {ALPN: 'a', NPN: false}, - client: {ALPN: 'a', NPN: undefined}}); + checkResults(results[0], { server: { ALPN: 'a', NPN: false }, + client: { ALPN: 'a', NPN: undefined } }); // 'b' is selected by ALPN - checkResults(results[1], {server: {ALPN: 'b', NPN: false}, - client: {ALPN: 'b', NPN: undefined}}); + checkResults(results[1], { server: { ALPN: 'b', NPN: false }, + client: { ALPN: 'b', NPN: undefined } }); // nothing is selected by ALPN - checkResults(results[2], {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[2], { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // execute next test Test7(); }); @@ -269,15 +269,15 @@ function Test7() { runTest(clientsOptions, serverOptions, function(results) { // nothing is selected by ALPN - checkResults(results[0], {server: {ALPN: false, NPN: 'a'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[0], { server: { ALPN: false, NPN: 'a' }, + client: { ALPN: false, NPN: false } }); // nothing is selected by ALPN - checkResults(results[1], {server: {ALPN: false, NPN: 'c'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[1], { server: { ALPN: false, NPN: 'c' }, + client: { ALPN: false, NPN: false } }); // nothing is selected by ALPN checkResults(results[2], - {server: {ALPN: false, NPN: 'first-priority-unsupported'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'first-priority-unsupported' }, + client: { ALPN: false, NPN: false } }); // execute next test Test8(); }); @@ -293,15 +293,15 @@ function Test8() { runTest(clientsOptions, serverOptions, function(results) { // nothing is selected by ALPN - checkResults(results[0], {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[0], { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // nothing is selected by ALPN - checkResults(results[1], {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[1], { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // nothing is selected by ALPN checkResults(results[2], - {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // execute next test Test9(); }); @@ -326,15 +326,15 @@ function Test9() { runTest(clientsOptions, serverOptions, function(results) { // 'a' is selected by NPN - checkResults(results[0], {server: {ALPN: false, NPN: 'a'}, - client: {ALPN: false, NPN: 'a'}}); + checkResults(results[0], { server: { ALPN: false, NPN: 'a' }, + client: { ALPN: false, NPN: 'a' } }); // 'b' is selected by NPN - checkResults(results[1], {server: {ALPN: false, NPN: 'b'}, - client: {ALPN: false, NPN: 'b'}}); + checkResults(results[1], { server: { ALPN: false, NPN: 'b' }, + client: { ALPN: false, NPN: 'b' } }); // nothing is selected checkResults(results[2], - {server: {ALPN: false, NPN: 'first-priority-unsupported'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'first-priority-unsupported' }, + client: { ALPN: false, NPN: false } }); // execute next test Test10(); }); @@ -356,14 +356,14 @@ function Test10() { runTest(clientsOptions, serverOptions, function(results) { // nothing is selected - checkResults(results[0], {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[0], { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // nothing is selected - checkResults(results[1], {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[1], { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // nothing is selected - checkResults(results[2], {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[2], { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // execute next test Test11(); }); @@ -385,15 +385,15 @@ function Test11() { runTest(clientsOptions, serverOptions, function(results) { // 'a' is selected by NPN - checkResults(results[0], {server: {ALPN: false, NPN: 'a'}, - client: {ALPN: false, NPN: 'a'}}); + checkResults(results[0], { server: { ALPN: false, NPN: 'a' }, + client: { ALPN: false, NPN: 'a' } }); // 'b' is selected by NPN - checkResults(results[1], {server: {ALPN: false, NPN: 'b'}, - client: {ALPN: false, NPN: 'b'}}); + checkResults(results[1], { server: { ALPN: false, NPN: 'b' }, + client: { ALPN: false, NPN: 'b' } }); // nothing is selected checkResults(results[2], - {server: {ALPN: false, NPN: 'first-priority-unsupported'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'first-priority-unsupported' }, + client: { ALPN: false, NPN: false } }); // execute next test Test12(); }); @@ -409,15 +409,15 @@ function Test12() { runTest(clientsOptions, serverOptions, function(results) { // nothing is selected - checkResults(results[0], {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[0], { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // nothing is selected - checkResults(results[1], {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[1], { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // nothing is selected checkResults(results[2], - {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // execute next test Test13(); }); @@ -440,15 +440,15 @@ function Test13() { runTest(clientsOptions, serverOptions, function(results) { // nothing is selected - checkResults(results[0], {server: {ALPN: false, NPN: 'a'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[0], { server: { ALPN: false, NPN: 'a' }, + client: { ALPN: false, NPN: false } }); // nothing is selected - checkResults(results[1], {server: {ALPN: false, NPN: 'c'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[1], { server: { ALPN: false, NPN: 'c' }, + client: { ALPN: false, NPN: false } }); // nothing is selected checkResults(results[2], - {server: {ALPN: false, NPN: 'first-priority-unsupported'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'first-priority-unsupported' }, + client: { ALPN: false, NPN: false } }); // execute next test Test14(); }); @@ -468,15 +468,15 @@ function Test14() { runTest(clientsOptions, serverOptions, function(results) { // nothing is selected - checkResults(results[0], {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[0], { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // nothing is selected - checkResults(results[1], {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[1], { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // nothing is selected checkResults(results[2], - {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // execute next test Test15(); }); @@ -496,15 +496,15 @@ function Test15() { runTest(clientsOptions, serverOptions, function(results) { // nothing is selected - checkResults(results[0], {server: {ALPN: false, NPN: 'a'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[0], { server: { ALPN: false, NPN: 'a' }, + client: { ALPN: false, NPN: false } }); // nothing is selected - checkResults(results[1], {server: {ALPN: false, NPN: 'c'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[1], { server: { ALPN: false, NPN: 'c' }, + client: { ALPN: false, NPN: false } }); // nothing is selected checkResults(results[2], - {server: {ALPN: false, NPN: 'first-priority-unsupported'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'first-priority-unsupported' }, + client: { ALPN: false, NPN: false } }); // execute next test Test16(); }); @@ -518,15 +518,15 @@ function Test16() { runTest(clientsOptions, serverOptions, function(results) { // nothing is selected - checkResults(results[0], {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[0], { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // nothing is selected - checkResults(results[1], {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + checkResults(results[1], { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); // nothing is selected checkResults(results[2], - {server: {ALPN: false, NPN: 'http/1.1'}, - client: {ALPN: false, NPN: false}}); + { server: { ALPN: false, NPN: 'http/1.1' }, + client: { ALPN: false, NPN: false } }); }); } diff --git a/test/parallel/test-tls-basic-validations.js b/test/parallel/test-tls-basic-validations.js index 1d494b4ed3b76f..4c1e8ddd1974ee 100644 --- a/test/parallel/test-tls-basic-validations.js +++ b/test/parallel/test-tls-basic-validations.js @@ -7,31 +7,31 @@ if (!common.hasCrypto) const assert = require('assert'); const tls = require('tls'); -assert.throws(() => tls.createSecureContext({ciphers: 1}), +assert.throws(() => tls.createSecureContext({ ciphers: 1 }), /TypeError: Ciphers must be a string/); -assert.throws(() => tls.createServer({ciphers: 1}), +assert.throws(() => tls.createServer({ ciphers: 1 }), /TypeError: Ciphers must be a string/); -assert.throws(() => tls.createSecureContext({key: 'dummykey', passphrase: 1}), +assert.throws(() => tls.createSecureContext({ key: 'dummykey', passphrase: 1 }), /TypeError: Pass phrase must be a string/); -assert.throws(() => tls.createServer({key: 'dummykey', passphrase: 1}), +assert.throws(() => tls.createServer({ key: 'dummykey', passphrase: 1 }), /TypeError: Pass phrase must be a string/); -assert.throws(() => tls.createServer({ecdhCurve: 1}), +assert.throws(() => tls.createServer({ ecdhCurve: 1 }), /TypeError: ECDH curve name must be a string/); -assert.throws(() => tls.createServer({handshakeTimeout: 'abcd'}), +assert.throws(() => tls.createServer({ handshakeTimeout: 'abcd' }), /TypeError: handshakeTimeout must be a number/); -assert.throws(() => tls.createServer({sessionTimeout: 'abcd'}), +assert.throws(() => tls.createServer({ sessionTimeout: 'abcd' }), /TypeError: Session timeout must be a 32-bit integer/); -assert.throws(() => tls.createServer({ticketKeys: 'abcd'}), +assert.throws(() => tls.createServer({ ticketKeys: 'abcd' }), /TypeError: Ticket keys must be a buffer/); -assert.throws(() => tls.createServer({ticketKeys: Buffer.alloc(0)}), +assert.throws(() => tls.createServer({ ticketKeys: Buffer.alloc(0) }), /TypeError: Ticket keys length must be 48 bytes/); assert.throws(() => tls.createSecurePair({}), diff --git a/test/parallel/test-tls-client-abort.js b/test/parallel/test-tls-client-abort.js index b12c79fb05b9f5..be81420d154c08 100644 --- a/test/parallel/test-tls-client-abort.js +++ b/test/parallel/test-tls-client-abort.js @@ -31,7 +31,7 @@ const fixtures = require('../common/fixtures'); const cert = fixtures.readSync('test_cert.pem'); const key = fixtures.readSync('test_key.pem'); -const conn = tls.connect({cert, key, port: 0}, common.mustNotCall()); +const conn = tls.connect({ cert, key, port: 0 }, common.mustNotCall()); conn.on('error', function() { }); assert.doesNotThrow(function() { diff --git a/test/parallel/test-tls-connect-address-family.js b/test/parallel/test-tls-connect-address-family.js index afacd5a39027a0..663e9399b610ce 100644 --- a/test/parallel/test-tls-connect-address-family.js +++ b/test/parallel/test-tls-connect-address-family.js @@ -30,7 +30,7 @@ function runTest() { })); } -dns.lookup('localhost', {family: 6, all: true}, (err, addresses) => { +dns.lookup('localhost', { family: 6, all: true }, (err, addresses) => { if (err) { if (err.code === 'ENOTFOUND') common.skip('localhost does not resolve to ::1'); diff --git a/test/parallel/test-tls-connect.js b/test/parallel/test-tls-connect.js index 304b55f1d6de3a..374f22d10e576a 100644 --- a/test/parallel/test-tls-connect.js +++ b/test/parallel/test-tls-connect.js @@ -36,7 +36,7 @@ const tls = require('tls'); const cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); const key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); - const options = {cert: cert, key: key, port: common.PORT}; + const options = { cert: cert, key: key, port: common.PORT }; const conn = tls.connect(options, common.mustNotCall()); conn.on( diff --git a/test/parallel/test-tls-delayed-attach-error.js b/test/parallel/test-tls-delayed-attach-error.js index 94d8e879adcd2d..69a35f011ea774 100644 --- a/test/parallel/test-tls-delayed-attach-error.js +++ b/test/parallel/test-tls-delayed-attach-error.js @@ -30,7 +30,7 @@ const server = net.createServer(common.mustCall(function(c) { }); }), 200); })).listen(0, function() { - const c = net.connect({port: this.address().port}, function() { + const c = net.connect({ port: this.address().port }, function() { c.write(bonkers); }); }); diff --git a/test/parallel/test-tls-env-extra-ca.js b/test/parallel/test-tls-env-extra-ca.js index 4dd12a78b6387c..80d9cc9ec3ecef 100644 --- a/test/parallel/test-tls-env-extra-ca.js +++ b/test/parallel/test-tls-env-extra-ca.js @@ -38,7 +38,7 @@ const server = tls.createServer(options, common.mustCall(function(s) { NODE_EXTRA_CA_CERTS: fixtures.path('keys', 'ca1-cert.pem') }); - fork(__filename, {env: env}).on('exit', common.mustCall(function(status) { + fork(__filename, { env: env }).on('exit', common.mustCall(function(status) { assert.strictEqual(status, 0, 'client did not succeed in connecting'); })); })); diff --git a/test/parallel/test-tls-passphrase.js b/test/parallel/test-tls-passphrase.js index df94d08297d9dd..b183309af71457 100644 --- a/test/parallel/test-tls-passphrase.js +++ b/test/parallel/test-tls-passphrase.js @@ -148,14 +148,14 @@ server.listen(0, common.mustCall(function() { // Object[] tls.connect({ port: this.address().port, - key: [{pem: passKey, passphrase: 'passphrase'}], + key: [{ pem: passKey, passphrase: 'passphrase' }], cert: cert, rejectUnauthorized: false }, common.mustCall()); tls.connect({ port: this.address().port, - key: [{pem: passKey, passphrase: 'passphrase'}], + key: [{ pem: passKey, passphrase: 'passphrase' }], passphrase: 'ignored', cert: cert, rejectUnauthorized: false @@ -163,7 +163,7 @@ server.listen(0, common.mustCall(function() { tls.connect({ port: this.address().port, - key: [{pem: passKey}], + key: [{ pem: passKey }], passphrase: 'passphrase', cert: cert, rejectUnauthorized: false @@ -171,28 +171,28 @@ server.listen(0, common.mustCall(function() { tls.connect({ port: this.address().port, - key: [{pem: passKey.toString(), passphrase: 'passphrase'}], + key: [{ pem: passKey.toString(), passphrase: 'passphrase' }], cert: cert, rejectUnauthorized: false }, common.mustCall()); tls.connect({ port: this.address().port, - key: [{pem: rawKey, passphrase: 'ignored'}], + key: [{ pem: rawKey, passphrase: 'ignored' }], cert: cert, rejectUnauthorized: false }, common.mustCall()); tls.connect({ port: this.address().port, - key: [{pem: rawKey.toString(), passphrase: 'ignored'}], + key: [{ pem: rawKey.toString(), passphrase: 'ignored' }], cert: cert, rejectUnauthorized: false }, common.mustCall()); tls.connect({ port: this.address().port, - key: [{pem: rawKey}], + key: [{ pem: rawKey }], passphrase: 'ignored', cert: cert, rejectUnauthorized: false @@ -200,7 +200,7 @@ server.listen(0, common.mustCall(function() { tls.connect({ port: this.address().port, - key: [{pem: rawKey.toString()}], + key: [{ pem: rawKey.toString() }], passphrase: 'ignored', cert: cert, rejectUnauthorized: false @@ -208,14 +208,14 @@ server.listen(0, common.mustCall(function() { tls.connect({ port: this.address().port, - key: [{pem: rawKey}], + key: [{ pem: rawKey }], cert: cert, rejectUnauthorized: false }, common.mustCall()); tls.connect({ port: this.address().port, - key: [{pem: rawKey.toString()}], + key: [{ pem: rawKey.toString() }], cert: cert, rejectUnauthorized: false }, common.mustCall()); @@ -245,7 +245,7 @@ assert.throws(function() { assert.throws(function() { tls.connect({ port: server.address().port, - key: [{pem: passKey}], + key: [{ pem: passKey }], cert: cert, rejectUnauthorized: false }); @@ -277,7 +277,7 @@ assert.throws(function() { assert.throws(function() { tls.connect({ port: server.address().port, - key: [{pem: passKey}], + key: [{ pem: passKey }], passphrase: 'invalid', cert: cert, rejectUnauthorized: false @@ -287,7 +287,7 @@ assert.throws(function() { assert.throws(function() { tls.connect({ port: server.address().port, - key: [{pem: passKey, passphrase: 'invalid'}], + key: [{ pem: passKey, passphrase: 'invalid' }], passphrase: 'passphrase', // Valid but unused cert: cert, rejectUnauthorized: false diff --git a/test/parallel/test-tls-peer-certificate.js b/test/parallel/test-tls-peer-certificate.js index d2b94d6eaefbd7..14c3d17cd24a76 100644 --- a/test/parallel/test-tls-peer-certificate.js +++ b/test/parallel/test-tls-peer-certificate.js @@ -30,7 +30,7 @@ const { } = require(fixtures.path('tls-connect')); connect({ - client: {rejectUnauthorized: false}, + client: { rejectUnauthorized: false }, server: keys.agent1, }, function(err, pair, cleanup) { assert.ifError(err); diff --git a/test/parallel/test-tls-securepair-server.js b/test/parallel/test-tls-securepair-server.js index 5d44356c661e97..9dceb4c4e4dd88 100644 --- a/test/parallel/test-tls-securepair-server.js +++ b/test/parallel/test-tls-securepair-server.js @@ -42,7 +42,7 @@ function log(a) { const server = net.createServer(common.mustCall(function(socket) { log(`connection fd=${socket.fd}`); - const sslcontext = tls.createSecureContext({key: key, cert: cert}); + const sslcontext = tls.createSecureContext({ key: key, cert: cert }); sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); const pair = tls.createSecurePair(sslcontext, true); diff --git a/test/parallel/test-tls-socket-default-options.js b/test/parallel/test-tls-socket-default-options.js index b59f948b2d6861..0543e98a1667fa 100644 --- a/test/parallel/test-tls-socket-default-options.js +++ b/test/parallel/test-tls-socket-default-options.js @@ -17,19 +17,20 @@ test({}, (err) => { assert.strictEqual(err.message, 'unable to verify the first certificate'); }); -test({secureContext: tls.createSecureContext({ca: keys.agent1.ca})}, (err) => { - assert.ifError(err); -}); +test({ secureContext: tls.createSecureContext({ ca: keys.agent1.ca }) }, + (err) => assert.ifError(err)); -test({ca: keys.agent1.ca}, (err) => { +test({ ca: keys.agent1.ca }, (err) => { assert.ifError(err); }); // Secure context options, like ca, are ignored if a sec ctx is explicitly // provided. -test({secureContext: tls.createSecureContext(), ca: keys.agent1.ca}, (err) => { - assert.strictEqual(err.message, 'unable to verify the first certificate'); -}); +test({ secureContext: tls.createSecureContext(), ca: keys.agent1.ca }, + (err) => { + assert.strictEqual(err.message, + 'unable to verify the first certificate'); + }); function test(client, callback) { callback = common.mustCall(callback); diff --git a/test/parallel/test-tls-socket-failed-handshake-emits-error.js b/test/parallel/test-tls-socket-failed-handshake-emits-error.js index 16175b8898115e..a54b7170f08277 100644 --- a/test/parallel/test-tls-socket-failed-handshake-emits-error.js +++ b/test/parallel/test-tls-socket-failed-handshake-emits-error.js @@ -31,7 +31,7 @@ const server = net.createServer(function(c) { }); }, common.platformTimeout(200)); }).listen(0, function() { - const c = net.connect({port: this.address().port}, function() { + const c = net.connect({ port: this.address().port }, function() { c.write(bonkers); }); }); diff --git a/test/parallel/test-url-parse-query.js b/test/parallel/test-url-parse-query.js index 34c31d8a3ca229..c5a1a051556bd5 100644 --- a/test/parallel/test-url-parse-query.js +++ b/test/parallel/test-url-parse-query.js @@ -25,7 +25,7 @@ const parseTestsWithQueryString = { href: '/foo/bar?baz=quux#frag', hash: '#frag', search: '?baz=quux', - query: createWithNoPrototype([{key: 'baz', value: 'quux'}]), + query: createWithNoPrototype([{ key: 'baz', value: 'quux' }]), pathname: '/foo/bar', path: '/foo/bar?baz=quux' }, diff --git a/test/parallel/test-util-format.js b/test/parallel/test-util-format.js index 649bb63942909f..27e3b62476211c 100644 --- a/test/parallel/test-util-format.js +++ b/test/parallel/test-util-format.js @@ -30,7 +30,7 @@ assert.strictEqual(util.format(''), ''); assert.strictEqual(util.format([]), '[]'); assert.strictEqual(util.format([0]), '[ 0 ]'); assert.strictEqual(util.format({}), '{}'); -assert.strictEqual(util.format({foo: 42}), '{ foo: 42 }'); +assert.strictEqual(util.format({ foo: 42 }), '{ foo: 42 }'); assert.strictEqual(util.format(null), 'null'); assert.strictEqual(util.format(true), 'true'); assert.strictEqual(util.format(false), 'false'); diff --git a/test/parallel/test-util-inspect-proxy.js b/test/parallel/test-util-inspect-proxy.js index ae6da3a34f8727..ed9e9d196af03f 100644 --- a/test/parallel/test-util-inspect-proxy.js +++ b/test/parallel/test-util-inspect-proxy.js @@ -4,7 +4,7 @@ require('../common'); const assert = require('assert'); const util = require('util'); const processUtil = process.binding('util'); -const opts = {showProxy: true}; +const opts = { showProxy: true }; const target = {}; const handler = { diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index 1ebd3c6dee2665..dd174d0a3c4d82 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -52,33 +52,34 @@ assert.strictEqual(util.inspect([1, 2]), '[ 1, 2 ]'); assert.strictEqual(util.inspect([1, [2, 3]]), '[ 1, [ 2, 3 ] ]'); assert.strictEqual(util.inspect({}), '{}'); -assert.strictEqual(util.inspect({a: 1}), '{ a: 1 }'); -assert.strictEqual(util.inspect({a: function() {}}), '{ a: [Function: a] }'); -assert.strictEqual(util.inspect({a: () => {}}), '{ a: [Function: a] }'); -assert.strictEqual(util.inspect({a: async function() {}}), +assert.strictEqual(util.inspect({ a: 1 }), '{ a: 1 }'); +assert.strictEqual(util.inspect({ a: function() {} }), '{ a: [Function: a] }'); +assert.strictEqual(util.inspect({ a: () => {} }), '{ a: [Function: a] }'); +assert.strictEqual(util.inspect({ a: async function() {} }), '{ a: [AsyncFunction: a] }'); -assert.strictEqual(util.inspect({a: async () => {}}), +assert.strictEqual(util.inspect({ a: async () => {} }), '{ a: [AsyncFunction: a] }'); -assert.strictEqual(util.inspect({a: function*() {}}), +assert.strictEqual(util.inspect({ a: function*() {} }), '{ a: [GeneratorFunction: a] }'); -assert.strictEqual(util.inspect({a: 1, b: 2}), '{ a: 1, b: 2 }'); -assert.strictEqual(util.inspect({'a': {}}), '{ a: {} }'); -assert.strictEqual(util.inspect({'a': {'b': 2}}), '{ a: { b: 2 } }'); -assert.strictEqual(util.inspect({'a': {'b': { 'c': { 'd': 2 }}}}), +assert.strictEqual(util.inspect({ a: 1, b: 2 }), '{ a: 1, b: 2 }'); +assert.strictEqual(util.inspect({ 'a': {} }), '{ a: {} }'); +assert.strictEqual(util.inspect({ 'a': { 'b': 2 } }), '{ a: { b: 2 } }'); +assert.strictEqual(util.inspect({ 'a': { 'b': { 'c': { 'd': 2 } } } }), '{ a: { b: { c: [Object] } } }'); -assert.strictEqual(util.inspect({'a': {'b': { 'c': { 'd': 2 }}}}, false, null), +assert.strictEqual(util.inspect({ 'a': { 'b': { 'c': { 'd': 2 } } } }, + false, null), '{ a: { b: { c: { d: 2 } } } }'); assert.strictEqual(util.inspect([1, 2, 3], true), '[ 1, 2, 3, [length]: 3 ]'); -assert.strictEqual(util.inspect({'a': {'b': { 'c': 2}}}, false, 0), +assert.strictEqual(util.inspect({ 'a': { 'b': { 'c': 2 } } }, false, 0), '{ a: [Object] }'); -assert.strictEqual(util.inspect({'a': {'b': { 'c': 2}}}, false, 1), +assert.strictEqual(util.inspect({ 'a': { 'b': { 'c': 2 } } }, false, 1), '{ a: { b: [Object] } }'); -assert.strictEqual(util.inspect({'a': {'b': ['c']}}, false, 1), +assert.strictEqual(util.inspect({ 'a': { 'b': ['c'] } }, false, 1), '{ a: { b: [Array] } }'); assert.strictEqual( util.inspect( Object.create( - {}, {visible: {value: 1, enumerable: true}, hidden: {value: 2}} + {}, { visible: { value: 1, enumerable: true }, hidden: { value: 2 } } ) ), '{ visible: 1 }' @@ -90,14 +91,14 @@ assert.strictEqual(util.inspect((new JSStream())._externalStream), { const regexp = /regexp/; regexp.aprop = 42; - assert.strictEqual(util.inspect({a: regexp}, false, 0), '{ a: /regexp/ }'); + assert.strictEqual(util.inspect({ a: regexp }, false, 0), '{ a: /regexp/ }'); } assert(/Object/.test( - util.inspect({a: {a: {a: {a: {}}}}}, undefined, undefined, true) + util.inspect({ a: { a: { a: { a: {} } } } }, undefined, undefined, true) )); assert(!/Object/.test( - util.inspect({a: {a: {a: {a: {}}}}}, undefined, null, true) + util.inspect({ a: { a: { a: { a: {} } } } }, undefined, null, true) )); for (const showHidden of [true, false]) { @@ -241,7 +242,7 @@ for (const showHidden of [true, false]) { util.inspect( Object.create( {}, - {visible: {value: 1, enumerable: true}, hidden: {value: 2}} + { visible: { value: 1, enumerable: true }, hidden: { value: 2 } } ), true ); @@ -253,10 +254,17 @@ for (const showHidden of [true, false]) { // Objects without prototype { - const out = util.inspect(Object.create(null, - { name: {value: 'Tim', - enumerable: true}, - hidden: {value: 'secret'}}), true); + const out = + util.inspect(Object.create(null, + { + name: { + value: 'Tim', + enumerable: true + }, + hidden: { + value: 'secret' + } + }), true); if (out !== "{ [hidden]: 'secret', name: 'Tim' }" && out !== "{ name: 'Tim', [hidden]: 'secret' }") { assert.fail(`unexpected value for out ${out}`); @@ -265,21 +273,22 @@ for (const showHidden of [true, false]) { assert.strictEqual( util.inspect(Object.create(null, - {name: {value: 'Tim', enumerable: true}, - hidden: {value: 'secret'}})), + { name: { value: 'Tim', enumerable: true }, + hidden: { value: 'secret' } })), '{ name: \'Tim\' }' ); // Dynamic properties { - assert.strictEqual(util.inspect({get readonly() {}}), + assert.strictEqual(util.inspect({ get readonly() {} }), '{ readonly: [Getter] }'); - assert.strictEqual(util.inspect({get readwrite() {}, set readwrite(val) {}}), - '{ readwrite: [Getter/Setter] }'); + assert.strictEqual( + util.inspect({ get readwrite() {}, set readwrite(val) {} }), + '{ readwrite: [Getter/Setter] }'); - assert.strictEqual(util.inspect({set writeonly(val) {}}), + assert.strictEqual(util.inspect({ set writeonly(val) {} }), '{ writeonly: [Setter] }'); const value = {}; @@ -696,7 +705,7 @@ assert.doesNotThrow(() => { function testLines(input) { const countLines = (str) => (str.match(/\n/g) || []).length; const withoutColor = util.inspect(input); - const withColor = util.inspect(input, {colors: true}); + const withColor = util.inspect(input, { colors: true }); assert.strictEqual(countLines(withoutColor), countLines(withColor)); } @@ -704,11 +713,11 @@ assert.doesNotThrow(() => { testLines([1, 2, 3, 4, 5, 6, 7]); testLines(bigArray); - testLines({foo: 'bar', baz: 35, b: {a: 35}}); + testLines({ foo: 'bar', baz: 35, b: { a: 35 } }); testLines({ foo: 'bar', baz: 35, - b: {a: 35}, + b: { a: 35 }, veryLongKey: 'very long value', evenLongerKey: ['with even longer value in array'] }); @@ -764,7 +773,7 @@ if (typeof Symbol !== 'undefined') { Object.defineProperty( subject, Symbol(), - {enumerable: false, value: 'non-enum'}); + { enumerable: false, value: 'non-enum' }); assert.strictEqual(util.inspect(subject), '{ [Symbol(symbol)]: 42 }'); assert.strictEqual( util.inspect(subject, options), @@ -1035,22 +1044,23 @@ if (typeof Symbol !== 'undefined') { } { - const obj = {foo: 'abc', bar: 'xyz'}; - const oneLine = util.inspect(obj, {breakLength: Infinity}); + const obj = { foo: 'abc', bar: 'xyz' }; + const oneLine = util.inspect(obj, { breakLength: Infinity }); // Subtract four for the object's two curly braces and two spaces of padding. // Add one more to satisfy the strictly greater than condition in the code. const breakpoint = oneLine.length - 5; - const twoLines = util.inspect(obj, {breakLength: breakpoint}); + const twoLines = util.inspect(obj, { breakLength: breakpoint }); assert.strictEqual(oneLine, '{ foo: \'abc\', bar: \'xyz\' }'); - assert.strictEqual(oneLine, util.inspect(obj, {breakLength: breakpoint + 1})); + assert.strictEqual(oneLine, + util.inspect(obj, { breakLength: breakpoint + 1 })); assert.strictEqual(twoLines, '{ foo: \'abc\',\n bar: \'xyz\' }'); } // util.inspect.defaultOptions tests { const arr = new Array(101).fill(); - const obj = {a: {a: {a: {a: 1}}}}; + const obj = { a: { a: { a: { a: 1 } } } }; const oldOptions = Object.assign({}, util.inspect.defaultOptions); @@ -1069,7 +1079,7 @@ if (typeof Symbol !== 'undefined') { ); // Set multiple options through object assignment - util.inspect.defaultOptions = {maxArrayLength: null, depth: null}; + util.inspect.defaultOptions = { maxArrayLength: null, depth: null }; assert(!/1 more item/.test(util.inspect(arr))); assert(!/Object/.test(util.inspect(obj))); util.inspect.defaultOptions = oldOptions; diff --git a/test/parallel/test-util-log.js b/test/parallel/test-util-log.js index d660106e1705af..907a361e97ecb8 100644 --- a/test/parallel/test-util-log.js +++ b/test/parallel/test-util-log.js @@ -34,15 +34,15 @@ common.hijackStdout(function(data) { common.hijackStderr(common.mustNotCall('stderr.write must not be called')); const tests = [ - {input: 'foo', output: 'foo'}, - {input: undefined, output: 'undefined'}, - {input: null, output: 'null'}, - {input: false, output: 'false'}, - {input: 42, output: '42'}, - {input: function() {}, output: '[Function: input]'}, - {input: parseInt('not a number', 10), output: 'NaN'}, - {input: {answer: 42}, output: '{ answer: 42 }'}, - {input: [1, 2, 3], output: '[ 1, 2, 3 ]'} + { input: 'foo', output: 'foo' }, + { input: undefined, output: 'undefined' }, + { input: null, output: 'null' }, + { input: false, output: 'false' }, + { input: 42, output: '42' }, + { input: function() {}, output: '[Function: input]' }, + { input: parseInt('not a number', 10), output: 'NaN' }, + { input: { answer: 42 }, output: '{ answer: 42 }' }, + { input: [1, 2, 3], output: '[ 1, 2, 3 ]' } ]; // test util.log() diff --git a/test/parallel/test-util-promisify.js b/test/parallel/test-util-promisify.js index eca6fe9ff7ecd4..b6dd383e1733c3 100644 --- a/test/parallel/test-util-promisify.js +++ b/test/parallel/test-util-promisify.js @@ -55,7 +55,7 @@ const stat = promisify(fs.stat); fn[customPromisifyArgs] = ['first', 'second']; promisify(fn)().then(common.mustCall((obj) => { - assert.deepStrictEqual(obj, {first: firstValue, second: secondValue}); + assert.deepStrictEqual(obj, { first: firstValue, second: secondValue }); })); } diff --git a/test/parallel/test-util.js b/test/parallel/test-util.js index 191f4361b4e356..3b2729c107b4b1 100644 --- a/test/parallel/test-util.js +++ b/test/parallel/test-util.js @@ -100,13 +100,13 @@ assert.strictEqual(false, util.isBuffer('foo')); assert.strictEqual(true, util.isBuffer(Buffer.from('foo'))); // _extend -assert.deepStrictEqual(util._extend({a: 1}), {a: 1}); -assert.deepStrictEqual(util._extend({a: 1}, []), {a: 1}); -assert.deepStrictEqual(util._extend({a: 1}, null), {a: 1}); -assert.deepStrictEqual(util._extend({a: 1}, true), {a: 1}); -assert.deepStrictEqual(util._extend({a: 1}, false), {a: 1}); -assert.deepStrictEqual(util._extend({a: 1}, {b: 2}), {a: 1, b: 2}); -assert.deepStrictEqual(util._extend({a: 1, b: 2}, {b: 3}), {a: 1, b: 3}); +assert.deepStrictEqual(util._extend({ a: 1 }), { a: 1 }); +assert.deepStrictEqual(util._extend({ a: 1 }, []), { a: 1 }); +assert.deepStrictEqual(util._extend({ a: 1 }, null), { a: 1 }); +assert.deepStrictEqual(util._extend({ a: 1 }, true), { a: 1 }); +assert.deepStrictEqual(util._extend({ a: 1 }, false), { a: 1 }); +assert.deepStrictEqual(util._extend({ a: 1 }, { b: 2 }), { a: 1, b: 2 }); +assert.deepStrictEqual(util._extend({ a: 1, b: 2 }, { b: 3 }), { a: 1, b: 3 }); // deprecated assert.strictEqual(util.isBoolean(true), true); diff --git a/test/parallel/test-vm-property-not-on-sandbox.js b/test/parallel/test-vm-property-not-on-sandbox.js index 08ea5890784c37..9f652f5dcfd23b 100644 --- a/test/parallel/test-vm-property-not-on-sandbox.js +++ b/test/parallel/test-vm-property-not-on-sandbox.js @@ -23,8 +23,8 @@ const vm = require('vm'); // // This test case is partially inspired by // https://github.com/nodejs/node/issues/855 -const sandbox = {console}; -sandbox.document = {defaultView: sandbox}; +const sandbox = { console }; +sandbox.document = { defaultView: sandbox }; vm.createContext(sandbox); const code = `Object.defineProperty( this, diff --git a/test/parallel/test-whatwg-url-searchparams-inspect.js b/test/parallel/test-whatwg-url-searchparams-inspect.js index 9a56543637dc55..163fa185ede58d 100644 --- a/test/parallel/test-whatwg-url-searchparams-inspect.js +++ b/test/parallel/test-whatwg-url-searchparams-inspect.js @@ -13,7 +13,7 @@ assert.strictEqual(util.inspect(sp.keys()), "URLSearchParamsIterator { 'a', 'b', 'b' }"); assert.strictEqual(util.inspect(sp.values()), "URLSearchParamsIterator { 'a', 'b', 'c' }"); -assert.strictEqual(util.inspect(sp.keys(), {breakLength: 1}), +assert.strictEqual(util.inspect(sp.keys(), { breakLength: 1 }), "URLSearchParamsIterator {\n 'a',\n 'b',\n 'b' }"); const iterator = sp.entries(); diff --git a/test/parallel/test-whatwg-url-searchparams-sort.js b/test/parallel/test-whatwg-url-searchparams-sort.js index 2dbf5aa1fbd0e4..0e01c627eea6e4 100644 --- a/test/parallel/test-whatwg-url-searchparams-sort.js +++ b/test/parallel/test-whatwg-url-searchparams-sort.js @@ -65,7 +65,7 @@ test(function() { // Tests below are not from WPT. // Test bottom-up iterative stable merge sort -const tests = [{input: '', output: []}]; +const tests = [{ input: '', output: [] }]; const pairs = []; for (let i = 10; i < 100; i++) { pairs.push([`a${i}`, 'b']); diff --git a/test/parallel/test-zerolengthbufferbug.js b/test/parallel/test-zerolengthbufferbug.js index 913e71fa8d7a1a..75aaa2f48dd8f3 100644 --- a/test/parallel/test-zerolengthbufferbug.js +++ b/test/parallel/test-zerolengthbufferbug.js @@ -7,8 +7,8 @@ const http = require('http'); const server = http.createServer(function(req, res) { const buffer = Buffer.alloc(0); // FIXME: WTF gjslint want this? - res.writeHead(200, {'Content-Type': 'text/html', - 'Content-Length': buffer.length}); + res.writeHead(200, { 'Content-Type': 'text/html', + 'Content-Length': buffer.length }); res.end(buffer); }); diff --git a/test/parallel/test-zlib-const.js b/test/parallel/test-zlib-const.js index ba6bb5fb8a26b4..e4c673aff0fe09 100644 --- a/test/parallel/test-zlib-const.js +++ b/test/parallel/test-zlib-const.js @@ -11,7 +11,7 @@ assert.strictEqual(zlib.constants.Z_OK, 0, 'Z_OK should be 0'); assert.strictEqual(zlib.codes.Z_OK, 0, 'Z_OK should be 0'); zlib.codes.Z_OK = 1; assert.strictEqual(zlib.codes.Z_OK, 0, 'zlib.codes.Z_OK should be 0'); -zlib.codes = {Z_OK: 1}; +zlib.codes = { Z_OK: 1 }; assert.strictEqual(zlib.codes.Z_OK, 0, 'zlib.codes.Z_OK should be 0'); assert.ok(Object.isFrozen(zlib.codes), 'zlib.codes should be frozen'); diff --git a/test/parallel/test-zlib-deflate-constructors.js b/test/parallel/test-zlib-deflate-constructors.js index 01930b27207bf0..e4b39002fba724 100644 --- a/test/parallel/test-zlib-deflate-constructors.js +++ b/test/parallel/test-zlib-deflate-constructors.js @@ -14,7 +14,7 @@ assert.ok(new zlib.DeflateRaw() instanceof zlib.DeflateRaw); // Throws if `opts.chunkSize` is invalid assert.throws( - () => { new zlib.Deflate({chunkSize: -Infinity}); }, + () => { new zlib.Deflate({ chunkSize: -Infinity }); }, /^RangeError: Invalid chunk size: -Infinity$/ ); @@ -23,23 +23,23 @@ assert.strictEqual(zlib.constants.Z_MAX_CHUNK, Infinity); // Throws if `opts.windowBits` is invalid assert.throws( - () => { new zlib.Deflate({windowBits: -Infinity}); }, + () => { new zlib.Deflate({ windowBits: -Infinity }); }, /^RangeError: Invalid windowBits: -Infinity$/ ); assert.throws( - () => { new zlib.Deflate({windowBits: Infinity}); }, + () => { new zlib.Deflate({ windowBits: Infinity }); }, /^RangeError: Invalid windowBits: Infinity$/ ); // Throws if `opts.level` is invalid assert.throws( - () => { new zlib.Deflate({level: -Infinity}); }, + () => { new zlib.Deflate({ level: -Infinity }); }, /^RangeError: Invalid compression level: -Infinity$/ ); assert.throws( - () => { new zlib.Deflate({level: Infinity}); }, + () => { new zlib.Deflate({ level: Infinity }); }, /^RangeError: Invalid compression level: Infinity$/ ); @@ -56,34 +56,34 @@ assert.throws( // Throws if `opts.memLevel` is invalid assert.throws( - () => { new zlib.Deflate({memLevel: -Infinity}); }, + () => { new zlib.Deflate({ memLevel: -Infinity }); }, /^RangeError: Invalid memLevel: -Infinity$/ ); assert.throws( - () => { new zlib.Deflate({memLevel: Infinity}); }, + () => { new zlib.Deflate({ memLevel: Infinity }); }, /^RangeError: Invalid memLevel: Infinity$/ ); // Does not throw if opts.strategy is valid assert.doesNotThrow( - () => { new zlib.Deflate({strategy: zlib.constants.Z_FILTERED}); } + () => { new zlib.Deflate({ strategy: zlib.constants.Z_FILTERED }); } ); assert.doesNotThrow( - () => { new zlib.Deflate({strategy: zlib.constants.Z_HUFFMAN_ONLY}); } + () => { new zlib.Deflate({ strategy: zlib.constants.Z_HUFFMAN_ONLY }); } ); assert.doesNotThrow( - () => { new zlib.Deflate({strategy: zlib.constants.Z_RLE}); } + () => { new zlib.Deflate({ strategy: zlib.constants.Z_RLE }); } ); assert.doesNotThrow( - () => { new zlib.Deflate({strategy: zlib.constants.Z_FIXED}); } + () => { new zlib.Deflate({ strategy: zlib.constants.Z_FIXED }); } ); assert.doesNotThrow( - () => { new zlib.Deflate({ strategy: zlib.constants.Z_DEFAULT_STRATEGY}); } + () => { new zlib.Deflate({ strategy: zlib.constants.Z_DEFAULT_STRATEGY }); } ); // Throws if opt.strategy is the wrong type. @@ -94,7 +94,7 @@ assert.throws( // Throws if opts.strategy is invalid assert.throws( - () => { new zlib.Deflate({strategy: 'this is a bogus strategy'}); }, + () => { new zlib.Deflate({ strategy: 'this is a bogus strategy' }); }, /^TypeError: Invalid strategy: this is a bogus strategy$/ ); @@ -106,6 +106,6 @@ assert.throws( // Throws if opts.dictionary is not a Buffer assert.throws( - () => { new zlib.Deflate({dictionary: 'not a buffer'}); }, + () => { new zlib.Deflate({ dictionary: 'not a buffer' }); }, /^TypeError: Invalid dictionary: it should be a Buffer, TypedArray, or DataView$/ ); diff --git a/test/parallel/test-zlib-not-string-or-buffer.js b/test/parallel/test-zlib-not-string-or-buffer.js index 16f127b3e557d3..d03d69fea10576 100644 --- a/test/parallel/test-zlib-not-string-or-buffer.js +++ b/test/parallel/test-zlib-not-string-or-buffer.js @@ -17,4 +17,4 @@ assert.throws(() => { zlib.deflateSync(false); }, expected); assert.throws(() => { zlib.deflateSync(0); }, expected); assert.throws(() => { zlib.deflateSync(1); }, expected); assert.throws(() => { zlib.deflateSync([1, 2, 3]); }, expected); -assert.throws(() => { zlib.deflateSync({foo: 'bar'}); }, expected); +assert.throws(() => { zlib.deflateSync({ foo: 'bar' }); }, expected); diff --git a/test/pummel/test-exec.js b/test/pummel/test-exec.js index 29852528eec95b..671ecce7349e83 100644 --- a/test/pummel/test-exec.js +++ b/test/pummel/test-exec.js @@ -90,7 +90,8 @@ exec(SLEEP3_COMMAND, { timeout: 50 }, function(err, stdout, stderr) { const startSleep3 = new Date(); -const killMeTwice = exec(SLEEP3_COMMAND, {timeout: 1000}, killMeTwiceCallback); +const killMeTwice = + exec(SLEEP3_COMMAND, { timeout: 1000 }, killMeTwiceCallback); process.nextTick(function() { console.log('kill pid %d', killMeTwice.pid); @@ -117,7 +118,7 @@ function killMeTwiceCallback(err, stdout, stderr) { } -exec('python -c "print 200000*\'C\'"', {maxBuffer: 1000}, +exec('python -c "print 200000*\'C\'"', { maxBuffer: 1000 }, function(err, stdout, stderr) { assert.ok(err); assert.ok(/maxBuffer/.test(err.message)); diff --git a/test/pummel/test-fs-watch-file-slow.js b/test/pummel/test-fs-watch-file-slow.js index acccec8a829f46..9ae9922ec8b2d6 100644 --- a/test/pummel/test-fs-watch-file-slow.js +++ b/test/pummel/test-fs-watch-file-slow.js @@ -36,7 +36,7 @@ try { // swallow } -fs.watchFile(FILENAME, {interval: TIMEOUT - 250}, function(curr, prev) { +fs.watchFile(FILENAME, { interval: TIMEOUT - 250 }, function(curr, prev) { console.log([curr, prev]); switch (++nevents) { case 1: diff --git a/test/pummel/test-http-client-reconnect-bug.js b/test/pummel/test-http-client-reconnect-bug.js index 656943ec86c265..d3e540166c27a7 100644 --- a/test/pummel/test-http-client-reconnect-bug.js +++ b/test/pummel/test-http-client-reconnect-bug.js @@ -34,7 +34,7 @@ server.on('listening', common.mustCall(function() { client.on('error', common.mustCall()); client.on('end', common.mustCall()); - const request = client.request('GET', '/', {'host': 'localhost'}); + const request = client.request('GET', '/', { 'host': 'localhost' }); request.end(); request.on('response', function(response) { console.log(`STATUS: ${response.statusCode}`); diff --git a/test/pummel/test-keep-alive.js b/test/pummel/test-keep-alive.js index d2387495c1c288..479ec12948175e 100644 --- a/test/pummel/test-keep-alive.js +++ b/test/pummel/test-keep-alive.js @@ -58,7 +58,7 @@ function runAb(opts, callback) { } args.push(url.format({ hostname: '127.0.0.1', - port: common.PORT, protocol: 'http'})); + port: common.PORT, protocol: 'http' })); const child = spawn('wrk', args); child.stderr.pipe(process.stderr); diff --git a/test/pummel/test-regress-GH-892.js b/test/pummel/test-regress-GH-892.js index 6ac438287112cd..05e27628b14388 100644 --- a/test/pummel/test-regress-GH-892.js +++ b/test/pummel/test-regress-GH-892.js @@ -96,7 +96,7 @@ const server = https.Server(serverOptions, function(req, res) { req.on('end', function() { assert.strictEqual(bytesExpected, uploadCount); - res.writeHead(200, {'content-type': 'text/plain'}); + res.writeHead(200, { 'content-type': 'text/plain' }); res.end('successful upload\n'); }); }); diff --git a/test/pummel/test-tls-securepair-client.js b/test/pummel/test-tls-securepair-client.js index b397197c0cb484..dbcd33d53466dc 100644 --- a/test/pummel/test-tls-securepair-client.js +++ b/test/pummel/test-tls-securepair-client.js @@ -117,7 +117,7 @@ function test(keyfn, certfn, check, next) { function startClient() { const s = new net.Stream(); - const sslcontext = tls.createSecureContext({key: key, cert: cert}); + const sslcontext = tls.createSecureContext({ key: key, cert: cert }); sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); const pair = tls.createSecurePair(sslcontext, false); diff --git a/test/sequential/test-benchmark-http.js b/test/sequential/test-benchmark-http.js index fb0c1390c545e2..b8d47fb8980db1 100644 --- a/test/sequential/test-benchmark-http.js +++ b/test/sequential/test-benchmark-http.js @@ -32,7 +32,7 @@ const child = fork(runjs, ['--set', 'benchmarker=test-double', '--set', 'n=1', '--set', 'res=normal', 'http'], - {env}); + { env }); child.on('exit', (code, signal) => { assert.strictEqual(code, 0); assert.strictEqual(signal, null); diff --git a/test/sequential/test-child-process-execsync.js b/test/sequential/test-child-process-execsync.js index 4fb2915010ef8d..63046517a9ca29 100644 --- a/test/sequential/test-child-process-execsync.js +++ b/test/sequential/test-child-process-execsync.js @@ -34,12 +34,12 @@ let caught = false; // Verify that stderr is not accessed when a bad shell is used assert.throws( - function() { execSync('exit -1', {shell: 'bad_shell'}); }, + function() { execSync('exit -1', { shell: 'bad_shell' }); }, /spawnSync bad_shell ENOENT/, 'execSync did not throw the expected exception!' ); assert.throws( - function() { execFileSync('exit -1', {shell: 'bad_shell'}); }, + function() { execFileSync('exit -1', { shell: 'bad_shell' }); }, /spawnSync bad_shell ENOENT/, 'execFileSync did not throw the expected exception!' ); @@ -47,7 +47,7 @@ assert.throws( let cmd, ret; try { cmd = `"${process.execPath}" -e "setTimeout(function(){}, ${SLEEP});"`; - ret = execSync(cmd, {timeout: TIMER}); + ret = execSync(cmd, { timeout: TIMER }); } catch (e) { caught = true; assert.strictEqual(e.errno, 'ETIMEDOUT'); @@ -97,7 +97,7 @@ assert.strictEqual(ret, `${msg}\n`, { const cwd = common.rootDir; const cmd = common.isWindows ? 'echo %cd%' : 'pwd'; - const response = execSync(cmd, {cwd}); + const response = execSync(cmd, { cwd }); assert.strictEqual(response.toString().trim(), cwd); } @@ -105,7 +105,7 @@ assert.strictEqual(ret, `${msg}\n`, // Verify that stderr is not accessed when stdio = 'ignore' - GH #7966 { assert.throws(function() { - execSync('exit -1', {stdio: 'ignore'}); + execSync('exit -1', { stdio: 'ignore' }); }, /Command failed: exit -1/); } diff --git a/test/sequential/test-child-process-fork-getconnections.js b/test/sequential/test-child-process-fork-getconnections.js index f9dda9ba1d1ce9..931763cf3c7091 100644 --- a/test/sequential/test-child-process-fork-getconnections.js +++ b/test/sequential/test-child-process-fork-getconnections.js @@ -31,7 +31,7 @@ if (process.argv[2] === 'child') { process.on('message', function(m, socket) { function sendClosed(id) { - process.send({ id: id, status: 'closed'}); + process.send({ id: id, status: 'closed' }); } if (m.cmd === 'new') { diff --git a/test/sequential/test-init.js b/test/sequential/test-init.js index 1829905b42d24c..3c3653521d6fd3 100644 --- a/test/sequential/test-init.js +++ b/test/sequential/test-init.js @@ -33,7 +33,7 @@ process.env.TEST_INIT = 1; function test(file, expected) { const path = `"${process.execPath}" ${file}`; - child.exec(path, {env: process.env}, common.mustCall((err, out) => { + child.exec(path, { env: process.env }, common.mustCall((err, out) => { assert.ifError(err); assert.strictEqual(out, expected, `'node ${file}' failed!`); })); diff --git a/test/sequential/test-net-listen-shared-ports.js b/test/sequential/test-net-listen-shared-ports.js index 282380ad271778..be33821bf6518c 100644 --- a/test/sequential/test-net-listen-shared-ports.js +++ b/test/sequential/test-net-listen-shared-ports.js @@ -57,7 +57,7 @@ if (cluster.isMaster) { port: common.PORT, exclusive: false }, common.mustCall(function() { - server2.listen({port: common.PORT + 1, exclusive: true}, + server2.listen({ port: common.PORT + 1, exclusive: true }, common.mustCall(function() { // the first worker should succeed process.send('success'); diff --git a/test/sequential/test-stream2-stderr-sync.js b/test/sequential/test-stream2-stderr-sync.js index c5295c0a2fe459..6eff05513fbec7 100644 --- a/test/sequential/test-stream2-stderr-sync.js +++ b/test/sequential/test-stream2-stderr-sync.js @@ -67,7 +67,7 @@ function child2() { const socket = new net.Socket({ fd: 2, readable: false, - writable: true}); + writable: true }); socket.write('child 2\n'); socket.write('foo\n'); socket.write('bar\n'); diff --git a/tools/doc/json.js b/tools/doc/json.js index aad860f840ae09..455b8252753c27 100644 --- a/tools/doc/json.js +++ b/tools/doc/json.js @@ -39,7 +39,7 @@ marked.setOptions({ }); function doJSON(input, filename, cb) { - const root = {source: filename}; + const root = { source: filename }; const stack = [root]; var depth = 0; var current = root; @@ -329,7 +329,7 @@ function parseSignature(text, sig) { params = params[1]; params = params.split(/,/); var optionalLevel = 0; - const optionalCharDict = {'[': 1, ' ': 0, ']': -1}; + const optionalCharDict = { '[': 1, ' ': 0, ']': -1 }; params.forEach(function(p, i) { p = p.trim(); if (!p) return; diff --git a/tools/eslint-rules/prefer-assert-iferror.js b/tools/eslint-rules/prefer-assert-iferror.js index 0da272d5f670e3..e15287417693e0 100644 --- a/tools/eslint-rules/prefer-assert-iferror.js +++ b/tools/eslint-rules/prefer-assert-iferror.js @@ -33,7 +33,7 @@ module.exports = { context.report({ node: firstStatement, message: 'Use assert.ifError({{argument}}) instead.', - data: {argument: sourceCode.getText(node.test)} + data: { argument: sourceCode.getText(node.test) } }); } } From 45cdbcfee6a79f521f2c0afee780c8afa1c5fab4 Mon Sep 17 00:00:00 2001 From: Jon Moss Date: Thu, 24 Aug 2017 03:15:55 -0400 Subject: [PATCH 081/145] test: create shared runBenchmark function Mostly shared/duplicated logic between all benchmark test files, so creating a new common module to store it. PR-URL: https://github.com/nodejs/node/pull/15004 Reviewed-By: James M Snell Reviewed-By: Ruben Bridgewater Reviewed-By: Joyee Cheung Reviewed-By: Rich Trott Reviewed-By: Refael Ackermann --- test/common/README.md | 12 +++++ test/common/benchmark.js | 30 +++++++++++++ test/parallel/test-benchmark-arrays.js | 18 +------- test/parallel/test-benchmark-cluster.js | 19 +------- test/parallel/test-benchmark-crypto.js | 41 +++++++---------- test/parallel/test-benchmark-dns.js | 21 +-------- test/parallel/test-benchmark-domain.js | 18 +------- test/parallel/test-benchmark-events.js | 17 +------ test/parallel/test-benchmark-os.js | 17 +------ test/parallel/test-benchmark-path.js | 30 +++++-------- test/parallel/test-benchmark-process.js | 26 ++++------- test/parallel/test-benchmark-timers.js | 30 ++++--------- .../test-benchmark-child-process.js | 37 +++++----------- test/sequential/test-benchmark-http.js | 44 +++++++------------ test/sequential/test-benchmark-net.js | 28 ++++-------- 15 files changed, 131 insertions(+), 257 deletions(-) create mode 100644 test/common/benchmark.js diff --git a/test/common/README.md b/test/common/README.md index b8d9af2fcf70f5..c7d4e780f026ab 100644 --- a/test/common/README.md +++ b/test/common/README.md @@ -4,9 +4,21 @@ This directory contains modules used to test the Node.js implementation. ## Table of Contents +* [Benchmark module](#benchmark-module) * [Common module API](#common-module-api) * [WPT module](#wpt-module) +## Benchmark Module + +The `benchmark` module is used by tests to run benchmarks. + +### runBenchmark(name, args, env) + +* `name` [<String>] Name of benchmark suite to be run. +* `args` [<Array>] Array of environment variable key/value pairs (ex: + `n=1`) to be applied via `--set`. +* `env` [<Object>] Environment variables to be applied during the run. + ## Common Module API The `common` module is used by tests for consistency across repeated diff --git a/test/common/benchmark.js b/test/common/benchmark.js new file mode 100644 index 00000000000000..6496da1cfb9fe5 --- /dev/null +++ b/test/common/benchmark.js @@ -0,0 +1,30 @@ +/* eslint-disable required-modules */ + +'use strict'; + +const assert = require('assert'); +const fork = require('child_process').fork; +const path = require('path'); + +const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); + +function runBenchmark(name, args, env) { + const argv = []; + + for (let i = 0; i < args.length; i++) { + argv.push('--set'); + argv.push(args[i]); + } + + argv.push(name); + + const mergedEnv = Object.assign({}, process.env, env); + + const child = fork(runjs, argv, { env: mergedEnv }); + child.on('exit', (code, signal) => { + assert.strictEqual(code, 0); + assert.strictEqual(signal, null); + }); +} + +module.exports = runBenchmark; diff --git a/test/parallel/test-benchmark-arrays.js b/test/parallel/test-benchmark-arrays.js index 2ffdc52c03a592..6e11d9743e0dac 100644 --- a/test/parallel/test-benchmark-arrays.js +++ b/test/parallel/test-benchmark-arrays.js @@ -2,20 +2,6 @@ require('../common'); -// Minimal test for arrays benchmarks. This makes sure the benchmarks aren't -// horribly broken but nothing more than that. +const runBenchmark = require('../common/benchmark'); -const assert = require('assert'); -const fork = require('child_process').fork; -const path = require('path'); - -const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); -const argv = ['--set', 'n=1', - '--set', 'type=Array', - 'arrays']; - -const child = fork(runjs, argv); -child.on('exit', (code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); -}); +runBenchmark('arrays', ['n=1', 'type=Array']); diff --git a/test/parallel/test-benchmark-cluster.js b/test/parallel/test-benchmark-cluster.js index 51a1f31ef3013b..d6e3b27ee89f81 100644 --- a/test/parallel/test-benchmark-cluster.js +++ b/test/parallel/test-benchmark-cluster.js @@ -2,21 +2,6 @@ require('../common'); -// Minimal test for cluster benchmarks. This makes sure the benchmarks aren't -// horribly broken but nothing more than that. +const runBenchmark = require('../common/benchmark'); -const assert = require('assert'); -const fork = require('child_process').fork; -const path = require('path'); - -const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); -const argv = ['--set', 'n=1', - '--set', 'payload=string', - '--set', 'sendsPerBroadcast=1', - 'cluster']; - -const child = fork(runjs, argv); -child.on('exit', (code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); -}); +runBenchmark('cluster', ['n=1', 'payload=string', 'sendsPerBroadcast=1']); diff --git a/test/parallel/test-benchmark-crypto.js b/test/parallel/test-benchmark-crypto.js index 3675c38b9ea280..2e78d78bc93985 100644 --- a/test/parallel/test-benchmark-crypto.js +++ b/test/parallel/test-benchmark-crypto.js @@ -8,29 +8,18 @@ if (!common.hasCrypto) if (common.hasFipsCrypto) common.skip('some benchmarks are FIPS-incompatible'); -// Minimal test for crypto benchmarks. This makes sure the benchmarks aren't -// horribly broken but nothing more than that. - -const assert = require('assert'); -const fork = require('child_process').fork; -const path = require('path'); - -const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); -const argv = ['--set', 'algo=sha256', - '--set', 'api=stream', - '--set', 'keylen=1024', - '--set', 'len=1', - '--set', 'n=1', - '--set', 'out=buffer', - '--set', 'type=buf', - '--set', 'v=crypto', - '--set', 'writes=1', - 'crypto']; - -const child = fork(runjs, argv, { env: Object.assign({}, process.env, { - NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }) }); - -child.on('exit', (code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); -}); +const runBenchmark = require('../common/benchmark'); + +runBenchmark('crypto', + [ + 'n=1', + 'algo=sha256', + 'api=stream', + 'keylen=1024', + 'len=1', + 'out=buffer', + 'type=buf', + 'v=crypto', + 'writes=1' + ], + { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); diff --git a/test/parallel/test-benchmark-dns.js b/test/parallel/test-benchmark-dns.js index ba15ad8c0d2fa9..27c3271c74d86d 100644 --- a/test/parallel/test-benchmark-dns.js +++ b/test/parallel/test-benchmark-dns.js @@ -2,26 +2,9 @@ require('../common'); -// Minimal test for dns benchmarks. This makes sure the benchmarks aren't -// horribly broken but nothing more than that. - -const assert = require('assert'); -const fork = require('child_process').fork; -const path = require('path'); - -const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); +const runBenchmark = require('../common/benchmark'); const env = Object.assign({}, process.env, { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); -const child = fork(runjs, - ['--set', 'n=1', - '--set', 'all=false', - '--set', 'name=127.0.0.1', - 'dns'], - { env }); - -child.on('exit', (code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); -}); +runBenchmark('dns', ['n=1', 'all=false', 'name=127.0.0.1'], env); diff --git a/test/parallel/test-benchmark-domain.js b/test/parallel/test-benchmark-domain.js index cacd45f6dad8c7..b1b56d2b7f5fec 100644 --- a/test/parallel/test-benchmark-domain.js +++ b/test/parallel/test-benchmark-domain.js @@ -2,20 +2,6 @@ require('../common'); -// Minimal test for domain benchmarks. This makes sure the benchmarks aren't -// horribly broken but nothing more than that. +const runBenchmark = require('../common/benchmark'); -const assert = require('assert'); -const fork = require('child_process').fork; -const path = require('path'); - -const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); -const argv = ['--set', 'arguments=0', - '--set', 'n=1', - 'domain']; - -const child = fork(runjs, argv); -child.on('exit', (code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); -}); +runBenchmark('domain', ['n=1', 'arguments=0']); diff --git a/test/parallel/test-benchmark-events.js b/test/parallel/test-benchmark-events.js index 6b7d25c61f007f..a82444c78d766d 100644 --- a/test/parallel/test-benchmark-events.js +++ b/test/parallel/test-benchmark-events.js @@ -2,19 +2,6 @@ require('../common'); -// Minimal test for events benchmarks. This makes sure the benchmarks aren't -// horribly broken but nothing more than that. +const runBenchmark = require('../common/benchmark'); -const assert = require('assert'); -const fork = require('child_process').fork; -const path = require('path'); - -const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); -const argv = ['--set', 'n=1', - 'events']; - -const child = fork(runjs, argv); -child.on('exit', (code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); -}); +runBenchmark('events', ['n=1']); diff --git a/test/parallel/test-benchmark-os.js b/test/parallel/test-benchmark-os.js index 4ad179063afce8..836e0e650483f1 100644 --- a/test/parallel/test-benchmark-os.js +++ b/test/parallel/test-benchmark-os.js @@ -2,19 +2,6 @@ require('../common'); -// Minimal test for os benchmarks. This makes sure the benchmarks aren't -// horribly broken but nothing more than that. +const runBenchmark = require('../common/benchmark'); -const assert = require('assert'); -const fork = require('child_process').fork; -const path = require('path'); - -const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); -const argv = ['--set', 'n=1', - 'os']; - -const child = fork(runjs, argv); -child.on('exit', (code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); -}); +runBenchmark('os', ['n=1']); diff --git a/test/parallel/test-benchmark-path.js b/test/parallel/test-benchmark-path.js index 922a59f03cde8d..9b73b92100880d 100644 --- a/test/parallel/test-benchmark-path.js +++ b/test/parallel/test-benchmark-path.js @@ -2,23 +2,13 @@ require('../common'); -// Minimal test for path benchmarks. This makes sure the benchmarks aren't -// horribly broken but nothing more than that. - -const assert = require('assert'); -const fork = require('child_process').fork; -const path = require('path'); - -const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); -const argv = ['--set', 'n=1', - '--set', 'path=', - '--set', 'pathext=', - '--set', 'paths=', - '--set', 'props=', - 'path']; - -const child = fork(runjs, argv); -child.on('exit', (code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); -}); +const runBenchmark = require('../common/benchmark'); + +runBenchmark('path', + [ + 'n=1', + 'path=', + 'pathext=', + 'paths=', + 'props=' + ]); diff --git a/test/parallel/test-benchmark-process.js b/test/parallel/test-benchmark-process.js index 6abd584379d146..08b28269159a16 100644 --- a/test/parallel/test-benchmark-process.js +++ b/test/parallel/test-benchmark-process.js @@ -2,21 +2,11 @@ require('../common'); -// Minimal test for process benchmarks. This makes sure the benchmarks aren't -// horribly broken but nothing more than that. - -const assert = require('assert'); -const fork = require('child_process').fork; -const path = require('path'); - -const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); -const argv = ['--set', 'millions=0.000001', - '--set', 'n=1', - '--set', 'type=raw', - 'process']; - -const child = fork(runjs, argv); -child.on('exit', (code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); -}); +const runBenchmark = require('../common/benchmark'); + +runBenchmark('process', + [ + 'millions=0.000001', + 'n=1', + 'type=raw' + ]); diff --git a/test/parallel/test-benchmark-timers.js b/test/parallel/test-benchmark-timers.js index 991ffda7186e72..cca9ede3a01c41 100644 --- a/test/parallel/test-benchmark-timers.js +++ b/test/parallel/test-benchmark-timers.js @@ -2,24 +2,12 @@ require('../common'); -// Minimal test for timers benchmarks. This makes sure the benchmarks aren't -// horribly broken but nothing more than that. - -const assert = require('assert'); -const fork = require('child_process').fork; -const path = require('path'); - -const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); -const argv = ['--set', 'type=depth', - '--set', 'millions=0.000001', - '--set', 'thousands=0.001', - 'timers']; - -const env = Object.assign({}, process.env, - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); - -const child = fork(runjs, argv, { env }); -child.on('exit', (code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); -}); +const runBenchmark = require('../common/benchmark'); + +runBenchmark('timers', + [ + 'type=depth', + 'millions=0.000001', + 'thousands=0.001' + ], + { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); diff --git a/test/sequential/test-benchmark-child-process.js b/test/sequential/test-benchmark-child-process.js index f993238549fca4..365777069bc4cf 100644 --- a/test/sequential/test-benchmark-child-process.js +++ b/test/sequential/test-benchmark-child-process.js @@ -2,29 +2,14 @@ require('../common'); -const assert = require('assert'); -const fork = require('child_process').fork; -const path = require('path'); - -const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); - -const env = Object.assign({}, process.env, - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); - -const child = fork( - runjs, - [ - '--set', 'dur=0', - '--set', 'n=1', - '--set', 'len=1', - '--set', 'params=1', - '--set', 'methodName=execSync', - 'child_process' - ], - { env } -); - -child.on('exit', (code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); -}); +const runBenchmark = require('../common/benchmark'); + +runBenchmark('child_process', + [ + 'dur=0', + 'n=1', + 'len=1', + 'params=1', + 'methodName=execSync', + ], + { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); diff --git a/test/sequential/test-benchmark-http.js b/test/sequential/test-benchmark-http.js index b8d47fb8980db1..2989198b77c1d1 100644 --- a/test/sequential/test-benchmark-http.js +++ b/test/sequential/test-benchmark-http.js @@ -5,35 +5,23 @@ const common = require('../common'); if (!common.enoughTestMem) common.skip('Insufficient memory for HTTP benchmark test'); -// Minimal test for http benchmarks. This makes sure the benchmarks aren't -// horribly broken but nothing more than that. - // Because the http benchmarks use hardcoded ports, this should be in sequential // rather than parallel to make sure it does not conflict with tests that choose // random available ports. -const assert = require('assert'); -const fork = require('child_process').fork; -const path = require('path'); - -const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); - -const env = Object.assign({}, process.env, - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); - -const child = fork(runjs, ['--set', 'benchmarker=test-double', - '--set', 'c=1', - '--set', 'chunkedEnc=true', - '--set', 'chunks=0', - '--set', 'dur=0.1', - '--set', 'key=""', - '--set', 'len=1', - '--set', 'method=write', - '--set', 'n=1', - '--set', 'res=normal', - 'http'], - { env }); -child.on('exit', (code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); -}); +const runBenchmark = require('../common/benchmark'); + +runBenchmark('http', + [ + 'benchmarker=test-double', + 'c=1', + 'chunkedEnc=true', + 'chunks=0', + 'dur=0.1', + 'key=""', + 'len=1', + 'method=write', + 'n=1', + 'res=normal' + ], + { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); diff --git a/test/sequential/test-benchmark-net.js b/test/sequential/test-benchmark-net.js index b2d360328504fb..5d3d283fc7903e 100644 --- a/test/sequential/test-benchmark-net.js +++ b/test/sequential/test-benchmark-net.js @@ -2,28 +2,16 @@ require('../common'); -// Minimal test for net benchmarks. This makes sure the benchmarks aren't -// horribly broken but nothing more than that. - // Because the net benchmarks use hardcoded ports, this should be in sequential // rather than parallel to make sure it does not conflict with tests that choose // random available ports. -const assert = require('assert'); -const fork = require('child_process').fork; -const path = require('path'); - -const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); +const runBenchmark = require('../common/benchmark'); -const env = Object.assign({}, process.env, - { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); -const child = fork(runjs, - ['--set', 'dur=0', - '--set', 'len=1024', - '--set', 'type=buf', - 'net'], - { env }); -child.on('exit', (code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); -}); +runBenchmark('net', + [ + 'dur=0', + 'len=1024', + 'type=buf' + ], + { NODEJS_BENCHMARK_ZERO_ALLOWED: 1 }); From a9066459aded144e7200a3596ab56b3a00c6881e Mon Sep 17 00:00:00 2001 From: Jon Moss Date: Mon, 11 Sep 2017 17:34:39 -0400 Subject: [PATCH 082/145] test: convert buffer benchmark to runBenchmark PR-URL: https://github.com/nodejs/node/pull/15349 Reviewed-By: Rich Trott Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Refael Ackermann Reviewed-By: Yuta Hiroto --- test/sequential/test-benchmark-buffer.js | 46 ++++++++++-------------- 1 file changed, 18 insertions(+), 28 deletions(-) diff --git a/test/sequential/test-benchmark-buffer.js b/test/sequential/test-benchmark-buffer.js index 64a9a65058bb24..73d8e0391d1cc3 100644 --- a/test/sequential/test-benchmark-buffer.js +++ b/test/sequential/test-benchmark-buffer.js @@ -2,33 +2,23 @@ require('../common'); -// Minimal test for buffer benchmarks. This makes sure the benchmarks aren't -// completely broken but nothing more than that. +const runBenchmark = require('../common/benchmark'); -const assert = require('assert'); -const fork = require('child_process').fork; -const path = require('path'); +runBenchmark('buffers', + [ + 'aligned=true', + 'args=1', + 'encoding=utf8', + 'len=2', + 'method=', + 'n=1', + 'noAssert=true', + 'pieces=1', + 'pieceSize=1', + 'search=@', + 'size=1', + 'source=array', + 'type=', + 'withTotalLength=0' -const runjs = path.join(__dirname, '..', '..', 'benchmark', 'run.js'); -const argv = ['--set', 'aligned=true', - '--set', 'args=1', - '--set', 'buffer=fast', - '--set', 'encoding=utf8', - '--set', 'len=2', - '--set', 'method=', - '--set', 'n=1', - '--set', 'noAssert=true', - '--set', 'pieces=1', - '--set', 'pieceSize=1', - '--set', 'search=@', - '--set', 'size=1', - '--set', 'source=array', - '--set', 'type=', - '--set', 'withTotalLength=0', - 'buffers']; - -const child = fork(runjs, argv); -child.on('exit', (code, signal) => { - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); -}); + ]); From 7dfd570cad8b781a0afa66902b45790fd8697936 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 3 Sep 2017 14:13:55 -0700 Subject: [PATCH 083/145] test: add test-benchmark-assert MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add minimal test for `assert` benchmarks. PR-URL: https://github.com/nodejs/node/pull/15174 Reviewed-By: Ruben Bridgewater Reviewed-By: Michaël Zasso Reviewed-By: James M Snell --- test/parallel/test-benchmark-assert.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 test/parallel/test-benchmark-assert.js diff --git a/test/parallel/test-benchmark-assert.js b/test/parallel/test-benchmark-assert.js new file mode 100644 index 00000000000000..a83bbf8ad8cf41 --- /dev/null +++ b/test/parallel/test-benchmark-assert.js @@ -0,0 +1,12 @@ +'use strict'; + +require('../common'); + +// Minimal test for assert benchmarks. This makes sure the benchmarks aren't +// completely broken but nothing more than that. + +const runBenchmark = require('../common/benchmark'); + +runBenchmark( + 'assert', ['len=1', 'method=', 'n=1', 'prim=null', 'size=1', 'type=Int8Array'] +); From b09eeb4a3d97c2ae65e326118133377a7dccf28c Mon Sep 17 00:00:00 2001 From: XadillaX Date: Thu, 10 Aug 2017 11:16:44 +0800 Subject: [PATCH 084/145] doc, tls: mark parseCertString() as deprecated `tls.parseCertString()` was made public by mistack. So mark it as deprecated. PR-URL: https://github.com/nodejs/node/pull/14245 Refs: https://github.com/nodejs/node/issues/14193 Reviewed-By: James M Snell Reviewed-By: Rich Trott Reviewed-By: Refael Ackermann Reviewed-By: Rod Vagg Reviewed-By: Colin Ihrig --- doc/api/deprecations.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/doc/api/deprecations.md b/doc/api/deprecations.md index 96b8930834a2cb..8d6dbd347daab2 100644 --- a/doc/api/deprecations.md +++ b/doc/api/deprecations.md @@ -630,6 +630,29 @@ Type: Runtime *Note*: change was made while `async_hooks` was an experimental API. + +### DEP0076: tls.parseCertString() + +Type: Documentation-only + +`tls.parseCertString()` is a trivial parsing helper that was made public by +mistake. This function can usually be replaced with: + +```js +const querystring = require('querystring'); +querystring.parse(str, '\n', '='); +``` + +*Note*: This function is not completely equivalent to `querystring.parse()`. One +difference is that `querystring.parse()` does url encoding: + +```sh +> querystring.parse('%E5%A5%BD=1', '\n', '='); +{ '好': '1' } +> tls.parseCertString('%E5%A5%BD=1'); +{ '%E5%A5%BD': '1' } +``` + [`Buffer.allocUnsafeSlow(size)`]: buffer.html#buffer_class_method_buffer_allocunsafeslow_size [`Buffer.from(array)`]: buffer.html#buffer_class_method_buffer_from_array [`Buffer.from(buffer)`]: buffer.html#buffer_class_method_buffer_from_buffer From 5e4f87ae658733c9a39207778760aa32a10c2e59 Mon Sep 17 00:00:00 2001 From: Anatoli Papirovski Date: Mon, 4 Sep 2017 08:53:43 -0400 Subject: [PATCH 085/145] buffer: improve Buffer.from performance Using == null in code paths that are expected to mostly receive objects, arrays or other more complex data types is not ideal because typecasting these types is very slow. Change to instead check === null || === undefined. Also move one variable assignment in fromString after an if condition that doesn't need it (and returns if truthy). PR-URL: https://github.com/nodejs/node/pull/15178 Refs: https://jsperf.com/triple-equals-vs-double-equals/3 Reviewed-By: Ruben Bridgewater Reviewed-By: James M Snell Reviewed-By: Timothy Gu --- lib/buffer.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index ac4f61bf5d0849..5ef207eb780863 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -175,14 +175,14 @@ Buffer.from = function(value, encodingOrOffset, length) { if (isAnyArrayBuffer(value)) return fromArrayBuffer(value, encodingOrOffset, length); - if (value == null) + if (value === null || value === undefined) throw new TypeError(kFromErrorMsg); if (typeof value === 'number') throw new TypeError('"value" argument must not be a number'); const valueOf = value.valueOf && value.valueOf(); - if (valueOf != null && valueOf !== value) + if (valueOf !== null && valueOf !== undefined && valueOf !== value) return Buffer.from(valueOf, encodingOrOffset, length); var b = fromObject(value); @@ -292,9 +292,9 @@ function allocate(size) { function fromString(string, encoding) { var length; if (typeof encoding !== 'string' || encoding.length === 0) { - encoding = 'utf8'; if (string.length === 0) return new FastBuffer(); + encoding = 'utf8'; length = binding.byteLengthUtf8(string); } else { length = byteLength(string, encoding, true); From b58a2aae1bc469fc8363f4bbaf2bbfc14852b6ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Sat, 9 Sep 2017 11:41:07 +0200 Subject: [PATCH 086/145] errors: fix ERR_MODULE_RESOLUTION_LEGACY message PR-URL: https://github.com/nodejs/node/pull/15290 Refs: https://github.com/nodejs/node/pull/14369 Reviewed-By: Bradley Farias Reviewed-By: James M Snell Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig --- lib/internal/errors.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 3029f504ba6839..48a47bc64102d8 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -215,7 +215,7 @@ E('ERR_IPC_SYNC_FORK', 'IPC cannot be used with synchronous forks'); E('ERR_MISSING_ARGS', missingArgs); E('ERR_MISSING_MODULE', 'Cannot find module %s'); E('ERR_MODULE_RESOLUTION_LEGACY', '%s not found by import in %s.' + - 'Legacy behavior in require would have found it at %s'); + ' Legacy behavior in require() would have found it at %s'); E('ERR_NAPI_CONS_FUNCTION', 'Constructor must be a function'); E('ERR_NAPI_CONS_PROTOTYPE_OBJECT', 'Constructor.prototype must be an object'); E('ERR_NO_CRYPTO', 'Node.js is not compiled with OpenSSL crypto support'); From 5125c08c506fa1ff5f2b6ce7306c39426e7b86d3 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Fri, 1 Sep 2017 14:42:27 -0700 Subject: [PATCH 087/145] test: remove obsolete debugger tests The tests in `test/debugger` all fail since the removal of the pre-inspector debugger (if they weren't already failing). They do not run in CI (probably because they were never reliable). Remove them and associated fixtures. PR-URL: https://github.com/nodejs/node/pull/15139 Reviewed-By: Eugene Ostroukhov Reviewed-By: Anna Henningsen Reviewed-By: Yuta Hiroto Reviewed-By: Colin Ihrig Reviewed-By: Ruben Bridgewater Reviewed-By: Luigi Pinca Reviewed-By: James M Snell --- Makefile | 3 - doc/api/debugger.md | 6 +- test/README.md | 1 - test/debugger/helper-debugger-repl.js | 150 ------------------ .../test-debugger-repl-break-in-module.js | 82 ---------- test/debugger/test-debugger-repl-restart.js | 42 ----- test/debugger/test-debugger-repl-term.js | 65 -------- test/debugger/test-debugger-repl-utf8.js | 27 ---- test/debugger/test-debugger-repl.js | 102 ------------ test/debugger/testcfg.py | 6 - test/fixtures/break-in-module/main.js | 4 - test/fixtures/break-in-module/mod.js | 24 --- test/fixtures/breakpoints.js | 23 --- test/fixtures/breakpoints_utf8.js | 23 --- 14 files changed, 3 insertions(+), 555 deletions(-) delete mode 100644 test/debugger/helper-debugger-repl.js delete mode 100644 test/debugger/test-debugger-repl-break-in-module.js delete mode 100644 test/debugger/test-debugger-repl-restart.js delete mode 100644 test/debugger/test-debugger-repl-term.js delete mode 100644 test/debugger/test-debugger-repl-utf8.js delete mode 100644 test/debugger/test-debugger-repl.js delete mode 100644 test/debugger/testcfg.py delete mode 100644 test/fixtures/break-in-module/main.js delete mode 100644 test/fixtures/break-in-module/mod.js delete mode 100644 test/fixtures/breakpoints.js delete mode 100644 test/fixtures/breakpoints_utf8.js diff --git a/Makefile b/Makefile index 274df0745871cf..e9c5a2e6bbcf17 100644 --- a/Makefile +++ b/Makefile @@ -386,9 +386,6 @@ test-pummel: all test-internet: all $(PYTHON) tools/test.py internet -test-debugger: all - $(PYTHON) tools/test.py debugger - test-inspector: all $(PYTHON) tools/test.py inspector diff --git a/doc/api/debugger.md b/doc/api/debugger.md index b27d83bee34ea0..b0da263f5947b4 100644 --- a/doc/api/debugger.md +++ b/doc/api/debugger.md @@ -125,18 +125,18 @@ It is also possible to set a breakpoint in a file (module) that is not loaded yet: ```txt -$ node inspect test/fixtures/break-in-module/main.js +$ node inspect main.js < Debugger listening on ws://127.0.0.1:9229/4e3db158-9791-4274-8909-914f7facf3bd < For help see https://nodejs.org/en/docs/inspector < Debugger attached. -Break on start in test/fixtures/break-in-module/main.js:1 +Break on start in main.js:1 > 1 (function (exports, require, module, __filename, __dirname) { const mod = require('./mod.js'); 2 mod.hello(); 3 mod.hello(); debug> setBreakpoint('mod.js', 22) Warning: script 'mod.js' was not loaded yet. debug> c -break in test/fixtures/break-in-module/mod.js:22 +break in mod.js:22 20 // USE OR OTHER DEALINGS IN THE SOFTWARE. 21 >22 exports.hello = function() { diff --git a/test/README.md b/test/README.md index 0f3660fbe45da0..3849f32543c69d 100644 --- a/test/README.md +++ b/test/README.md @@ -16,7 +16,6 @@ On how to run tests in this directory, see |addons |Yes |Tests for [addon](https://nodejs.org/api/addons.html) functionality along with some tests that require an addon to function properly.| |cctest |Yes |C++ test that is run as part of the build process.| |common | |Common modules shared among many tests. [Documentation](./common/README.md)| -|debugger |No |Tests for [debugger](https://nodejs.org/api/debugger.html) functionality along with some tests that require an addon to function properly.| |fixtures | |Test fixtures used in various tests throughout the test suite.| |gc |No |Tests for garbage collection related functionality.| |inspector |Yes |Tests for the V8 inspector integration.| diff --git a/test/debugger/helper-debugger-repl.js b/test/debugger/helper-debugger-repl.js deleted file mode 100644 index 365b29e50d6556..00000000000000 --- a/test/debugger/helper-debugger-repl.js +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; -const common = require('../common'); -const assert = require('assert'); -const spawn = require('child_process').spawn; - -process.env.NODE_DEBUGGER_TIMEOUT = 2000; -const port = common.PORT; - -let child; -let buffer = ''; -const expected = []; -let quit; - -function startDebugger(scriptToDebug) { - scriptToDebug = process.env.NODE_DEBUGGER_TEST_SCRIPT || - `${common.fixturesDir}/${scriptToDebug}`; - - child = spawn(process.execPath, ['debug', `--port=${port}`, scriptToDebug]); - - console.error('./node', 'debug', `--port=${port}`, scriptToDebug); - - child.stdout.setEncoding('utf-8'); - child.stdout.on('data', function(data) { - data = (buffer + data).split('\n'); - buffer = data.pop(); - data.forEach(function(line) { - child.emit('line', line); - }); - }); - child.stderr.pipe(process.stderr); - - child.on('line', function(line) { - line = line.replace(/^(?:debug> *)+/, ''); - console.log(line); - assert.ok(expected.length > 0, `Got unexpected line: ${line}`); - - const expectedLine = expected[0].lines.shift(); - assert.ok(expectedLine.test(line), `${line} != ${expectedLine}`); - - if (expected[0].lines.length === 0) { - const callback = expected[0].callback; - expected.shift(); - callback && callback(); - } - }); - - let childClosed = false; - child.on('close', function(code) { - assert(!code); - childClosed = true; - }); - - let quitCalled = false; - quit = function() { - if (quitCalled || childClosed) return; - quitCalled = true; - child.stdin.write('quit'); - child.kill('SIGTERM'); - }; - - setTimeout(function() { - console.error('dying badly buffer=%j', buffer); - let err = 'Timeout'; - if (expected.length > 0 && expected[0].lines) { - err = `${err}. Expected: ${expected[0].lines.shift()}`; - } - - child.on('close', function() { - console.error('child is closed'); - throw new Error(err); - }); - - quit(); - }, 10000).unref(); - - process.once('uncaughtException', function(e) { - console.error('UncaughtException', e, e.stack); - quit(); - console.error(e.toString()); - process.exit(1); - }); - - process.on('exit', function(code) { - console.error('process exit', code); - quit(); - if (code === 0) - assert(childClosed); - }); -} - -function addTest(input, output) { - function next() { - if (expected.length > 0) { - console.log(`debug> ${expected[0].input}`); - child.stdin.write(`${expected[0].input}\n`); - - if (!expected[0].lines) { - const callback = expected[0].callback; - expected.shift(); - - callback && callback(); - } - } else { - quit(); - } - } - expected.push({ input: input, lines: output, callback: next }); -} - -const handshakeLines = [ - /listening on /, - /connecting.* ok/ -]; - -const initialBreakLines = [ - /break in .*:1/, - /1/, /2/, /3/ -]; - -const initialLines = handshakeLines.concat(initialBreakLines); - -// Process initial lines -addTest(null, initialLines); - -exports.startDebugger = startDebugger; -exports.addTest = addTest; -exports.initialLines = initialLines; -exports.handshakeLines = handshakeLines; -exports.initialBreakLines = initialBreakLines; diff --git a/test/debugger/test-debugger-repl-break-in-module.js b/test/debugger/test-debugger-repl-break-in-module.js deleted file mode 100644 index d428b7a6fcaa21..00000000000000 --- a/test/debugger/test-debugger-repl-break-in-module.js +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; -require('../common'); -const repl = require('./helper-debugger-repl.js'); - -repl.startDebugger('break-in-module/main.js'); - -// -- SET BREAKPOINT -- - -// Set breakpoint by file name + line number where the file is not loaded yet -repl.addTest('sb("mod.js", 2)', [ - /Warning: script 'mod\.js' was not loaded yet\./, - /1/, /2/, /3/, /4/, /5/, /6/ -]); - -// Check escaping of regex characters -repl.addTest('sb(")^$*+?}{|][(.js\\\\", 1)', [ - /Warning: script '[^']+' was not loaded yet\./, - /1/, /2/, /3/, /4/, /5/, /6/ -]); - -// continue - the breakpoint should be triggered -repl.addTest('c', [ - /break in .*[\\/]mod\.js:2/, - /1/, /2/, /3/, /4/ -]); - -// -- RESTORE BREAKPOINT ON RESTART -- - -// Restart the application - breakpoint should be restored -repl.addTest('restart', [].concat( - [ - /terminated/ - ], - repl.handshakeLines, - [ - /Restoring breakpoint mod\.js:2/, - /Warning: script 'mod\.js' was not loaded yet\./, - /Restoring breakpoint \).*:\d+/, - /Warning: script '\)[^']*' was not loaded yet\./ - ], - repl.initialBreakLines)); - -// continue - the breakpoint should be triggered -repl.addTest('c', [ - /break in .*[\\/]mod\.js:2/, - /1/, /2/, /3/, /4/ -]); - -// -- CLEAR BREAKPOINT SET IN MODULE TO BE LOADED -- - -repl.addTest('cb("mod.js", 2)', [ - /1/, /2/, /3/, /4/, /5/ -]); - -repl.addTest('c', [ - /break in .*[\\/]main\.js:4/, - /2/, /3/, /4/, /5/, /6/ -]); - -// -- (END) -- -repl.addTest('quit', []); diff --git a/test/debugger/test-debugger-repl-restart.js b/test/debugger/test-debugger-repl-restart.js deleted file mode 100644 index 5345702ca72a67..00000000000000 --- a/test/debugger/test-debugger-repl-restart.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; -require('../common'); -const repl = require('./helper-debugger-repl.js'); - -repl.startDebugger('breakpoints.js'); -const linesWithBreakpoint = [ - /1/, /2/, /3/, /4/, /5/, /\* 6/ -]; -// We slice here, because addTest will change the given array. -repl.addTest('sb(6)', linesWithBreakpoint.slice()); - -const initialLines = repl.initialLines.slice(); -initialLines.splice(2, 0, /Restoring/, /Warning/); - -// Restart the debugged script -repl.addTest('restart', [ - /terminated/, -].concat(initialLines)); - -repl.addTest('list(5)', linesWithBreakpoint); -repl.addTest('quit', []); diff --git a/test/debugger/test-debugger-repl-term.js b/test/debugger/test-debugger-repl-term.js deleted file mode 100644 index 0155df51b262b7..00000000000000 --- a/test/debugger/test-debugger-repl-term.js +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; -require('../common'); -process.env.NODE_FORCE_READLINE = 1; - -const repl = require('./helper-debugger-repl.js'); - -repl.startDebugger('breakpoints.js'); - -const addTest = repl.addTest; - -// next -addTest('n', [ - /debug>.*n/, - /break in .*:11/, - /9/, /10/, /11/, /12/, /13/ -]); - -// should repeat next -addTest('', [ - /debug>/, - /break in .*:5/, - /3/, /4/, /5/, /6/, /7/, -]); - -// continue -addTest('c', [ - /debug>.*c/, - /break in .*:12/, - /10/, /11/, /12/, /13/, /14/ -]); - -// should repeat continue -addTest('', [ - /debug>/, - /break in .*:5/, - /3/, /4/, /5/, /6/, /7/, -]); - -// should repeat continue -addTest('', [ - /debug>/, - /break in .*:23/, - /21/, /22/, /23/, /24/, /25/, -]); diff --git a/test/debugger/test-debugger-repl-utf8.js b/test/debugger/test-debugger-repl-utf8.js deleted file mode 100644 index 76e604dd231d7e..00000000000000 --- a/test/debugger/test-debugger-repl-utf8.js +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; -const common = require('../common'); -const script = `${common.fixturesDir}/breakpoints_utf8.js`; -process.env.NODE_DEBUGGER_TEST_SCRIPT = script; - -require('./test-debugger-repl.js'); diff --git a/test/debugger/test-debugger-repl.js b/test/debugger/test-debugger-repl.js deleted file mode 100644 index 35bb72832b14c8..00000000000000 --- a/test/debugger/test-debugger-repl.js +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -'use strict'; -const common = require('../common'); -const repl = require('./helper-debugger-repl.js'); - -repl.startDebugger('breakpoints.js'); - -const addTest = repl.addTest; - -// Next -addTest('n', [ - /break in .*:11/, - /9/, /10/, /11/, /12/, /13/ -]); - -// Watch -addTest('watch("\'x\'")'); - -// Continue -addTest('c', [ - /break in .*:5/, - /Watchers/, - /0:\s+'x' = "x"/, - /()/, - /3/, /4/, /5/, /6/, /7/ -]); - -// Show watchers -addTest('watchers', [ - /0:\s+'x' = "x"/ -]); - -// Unwatch -addTest('unwatch("\'x\'")'); - -// Step out -addTest('o', [ - /break in .*:12/, - /10/, /11/, /12/, /13/, /14/ -]); - -// Continue -addTest('c', [ - /break in .*:5/, - /3/, /4/, /5/, /6/, /7/ -]); - -// Set breakpoint by function name -addTest('sb("setInterval()", "!(setInterval.flag++)")', [ - /1/, /2/, /3/, /4/, /5/, /6/, /7/, /8/, /9/, /10/ -]); - -// Continue -addTest('c', [ - /break in timers\.js:\d+/, - /\d/, /\d/, /\d/, /\d/, /\d/ -]); - -// Execute -addTest('exec process.title', [ - common.isFreeBSD || common.isOSX || common.isLinux ? /node/ : '' -]); - -// Execute -addTest('exec exec process.title', [ - /SyntaxError: Unexpected identifier/ -]); - -// REPL and process.env regression -addTest('repl', [ - /Ctrl/ -]); - -addTest('for (var i in process.env) delete process.env[i]', []); - -addTest('process.env', [ - /\{\}/ -]); - -addTest('arr = [{foo: "bar"}]', [ - /\[ \{ foo: 'bar' \} \]/ -]); diff --git a/test/debugger/testcfg.py b/test/debugger/testcfg.py deleted file mode 100644 index 4aee90b3eb0154..00000000000000 --- a/test/debugger/testcfg.py +++ /dev/null @@ -1,6 +0,0 @@ -import sys, os -sys.path.append(os.path.join(os.path.dirname(__file__), '..')) -import testpy - -def GetConfiguration(context, root): - return testpy.SimpleTestConfiguration(context, root, 'debugger') diff --git a/test/fixtures/break-in-module/main.js b/test/fixtures/break-in-module/main.js deleted file mode 100644 index cfb44c766abac3..00000000000000 --- a/test/fixtures/break-in-module/main.js +++ /dev/null @@ -1,4 +0,0 @@ -const mod = require('./mod.js'); -mod.hello(); -mod.hello(); -debugger; diff --git a/test/fixtures/break-in-module/mod.js b/test/fixtures/break-in-module/mod.js deleted file mode 100644 index 57bf58bb31aa11..00000000000000 --- a/test/fixtures/break-in-module/mod.js +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -exports.hello = function() { - return 'hello from module'; -}; diff --git a/test/fixtures/breakpoints.js b/test/fixtures/breakpoints.js deleted file mode 100644 index 43cfca1c9b11ab..00000000000000 --- a/test/fixtures/breakpoints.js +++ /dev/null @@ -1,23 +0,0 @@ -debugger; -function a(x) { - var i = 10; - while (--i != 0); - debugger; - return i; -} -function b() { - return ['hello', 'world'].join(' '); -} -a(); -debugger; -a(1); -b(); -b(); - - -setInterval(function() { -}, 5000); - - -now = new Date(); -debugger; diff --git a/test/fixtures/breakpoints_utf8.js b/test/fixtures/breakpoints_utf8.js deleted file mode 100644 index 8f0eb9dfc117e6..00000000000000 --- a/test/fixtures/breakpoints_utf8.js +++ /dev/null @@ -1,23 +0,0 @@ -debugger; -function a(x) { - var i = 10; - while (--i != 0); - debugger; - return i; -} -function b() { - return ['こんにち', 'わ'].join(' '); -} -a(); -a(1); -b(); -b(); - - - -setInterval(function() { -}, 5000); - - -now = new Date(); -debugger; From 29fd88c3e51f557cef1467ce43fd870b10d143c7 Mon Sep 17 00:00:00 2001 From: Vse Mozhet Byt Date: Sun, 17 Sep 2017 23:02:00 +0300 Subject: [PATCH 088/145] doc: fix new nits in links MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/15449 Reviewed-By: Refael Ackermann Reviewed-By: Luigi Pinca Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Tobias Nießen --- doc/api/http.md | 6 +++--- doc/api/n-api.md | 2 +- doc/api/process.md | 1 + 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/doc/api/http.md b/doc/api/http.md index 213c38fcefad0e..9624e359080203 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -1956,7 +1956,7 @@ const req = http.request(options, (res) => { [`agent.createConnection()`]: #http_agent_createconnection_options_callback [`agent.getName()`]: #http_agent_getname_options [`destroy()`]: #http_agent_destroy -[`getHeader(name)`]: #requestgetheadername +[`getHeader(name)`]: #http_request_getheader_name [`http.Agent`]: #http_class_http_agent [`http.ClientRequest`]: #http_class_http_clientrequest [`http.IncomingMessage`]: #http_class_http_incomingmessage @@ -1971,7 +1971,7 @@ const req = http.request(options, (res) => { [`net.Server`]: net.html#net_class_net_server [`net.Socket`]: net.html#net_class_net_socket [`net.createConnection()`]: net.html#net_net_createconnection_options_connectlistener -[`removeHeader(name)`]: #requestremoveheadername +[`removeHeader(name)`]: #http_request_removeheader_name [`request.end()`]: #http_request_end_data_encoding_callback [`request.setTimeout()`]: #http_request_settimeout_timeout_callback [`request.socket`]: #http_request_socket @@ -1985,7 +1985,7 @@ const req = http.request(options, (res) => { [`response.writeContinue()`]: #http_response_writecontinue [`response.writeHead()`]: #http_response_writehead_statuscode_statusmessage_headers [`server.timeout`]: #http_server_timeout -[`setHeader(name, value)`]: #requestsetheadername-value +[`setHeader(name, value)`]: #http_request_setheader_name_value [`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 diff --git a/doc/api/n-api.md b/doc/api/n-api.md index ab33fa3534b746..08788765d2bd56 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -3661,7 +3661,7 @@ NAPI_EXTERN napi_status napi_run_script(napi_env env, - `[out] result`: The value resulting from having executed the script. [Promises]: #n_api_promises -[Simple Asynchronous Operations]: #n_api_asynchronous_operations +[Simple Asynchronous Operations]: #n_api_simple_asynchronous_operations [Custom Asynchronous Operations]: #n_api_custom_asynchronous_operations [Basic N-API Data Types]: #n_api_basic_n_api_data_types [ECMAScript Language Specification]: https://tc39.github.io/ecma262/ diff --git a/doc/api/process.md b/doc/api/process.md index ea474cf30bf576..8b6463b0e873dd 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -1846,6 +1846,7 @@ cases: [`process.kill()`]: #process_process_kill_pid_signal [`promise.catch()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch [`require.main`]: modules.html#modules_accessing_the_main_module +[`require.resolve()`]: modules.html#modules_require_resolve [`setTimeout(fn, 0)`]: timers.html#timers_settimeout_callback_delay_args [Child Process]: child_process.html [Cluster]: cluster.html From ba9012d4bcd751c38a5e3f1ef07673640c7eb856 Mon Sep 17 00:00:00 2001 From: Anatoli Papirovski Date: Wed, 13 Sep 2017 09:34:14 -0400 Subject: [PATCH 089/145] http2: add tests for push stream error handling Add tests that cover errors for wrong arguments, as well as tests for error codes from nghttp2. Fix pushStream to emit NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE on session rather than stream. PR-URL: https://github.com/nodejs/node/pull/15281 Reviewed-By: James M Snell Reviewed-By: Matteo Collina --- lib/internal/http2/core.js | 2 +- ...st-http2-server-push-stream-errors-args.js | 57 ++++++++ .../test-http2-server-push-stream-errors.js | 130 ++++++++++++++++++ .../test-http2-server-push-stream-head.js | 54 ++++++++ .../parallel/test-http2-server-push-stream.js | 4 +- 5 files changed, 244 insertions(+), 3 deletions(-) create mode 100644 test/parallel/test-http2-server-push-stream-errors-args.js create mode 100644 test/parallel/test-http2-server-push-stream-errors.js create mode 100644 test/parallel/test-http2-server-push-stream-head.js diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js index 471fa5b1c5d5a9..0ea3ca75f4d43e 100644 --- a/lib/internal/http2/core.js +++ b/lib/internal/http2/core.js @@ -1790,7 +1790,7 @@ class ServerHttp2Stream extends Http2Stream { break; case NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE: err = new errors.Error('ERR_HTTP2_OUT_OF_STREAMS'); - process.nextTick(() => this.emit('error', err)); + process.nextTick(() => session.emit('error', err)); break; case NGHTTP2_ERR_STREAM_CLOSED: err = new errors.Error('ERR_HTTP2_STREAM_CLOSED'); diff --git a/test/parallel/test-http2-server-push-stream-errors-args.js b/test/parallel/test-http2-server-push-stream-errors-args.js new file mode 100644 index 00000000000000..9924517d406c58 --- /dev/null +++ b/test/parallel/test-http2-server-push-stream-errors-args.js @@ -0,0 +1,57 @@ +// Flags: --expose-http2 +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const assert = require('assert'); +const http2 = require('http2'); + +// Check that pushStream handles being passed wrong arguments +// in the expected manner + +const server = http2.createServer(); +server.on('stream', common.mustCall((stream, headers) => { + const port = server.address().port; + + // Must receive a callback (function) + common.expectsError( + () => stream.pushStream({ + ':scheme': 'http', + ':path': '/foobar', + ':authority': `localhost:${port}`, + }, {}, 'callback'), + { + code: 'ERR_INVALID_CALLBACK', + message: 'callback must be a function' + } + ); + + // Must validate headers + common.expectsError( + () => stream.pushStream({ 'connection': 'test' }, {}, () => {}), + { + code: 'ERR_HTTP2_INVALID_CONNECTION_HEADERS', + message: 'HTTP/1 Connection specific headers are forbidden' + } + ); + + stream.end('test'); +})); + +server.listen(0, common.mustCall(() => { + const port = server.address().port; + const headers = { ':path': '/' }; + const client = http2.connect(`http://localhost:${port}`); + const req = client.request(headers); + req.setEncoding('utf8'); + + let data = ''; + req.on('data', common.mustCall((d) => data += d)); + req.on('end', common.mustCall(() => { + assert.strictEqual(data, 'test'); + server.close(); + client.destroy(); + })); + req.end(); +})); diff --git a/test/parallel/test-http2-server-push-stream-errors.js b/test/parallel/test-http2-server-push-stream-errors.js new file mode 100644 index 00000000000000..ad26874f8a9f91 --- /dev/null +++ b/test/parallel/test-http2-server-push-stream-errors.js @@ -0,0 +1,130 @@ +// Flags: --expose-http2 +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const http2 = require('http2'); +const { + constants, + Http2Session, + nghttp2ErrorString +} = process.binding('http2'); + +// tests error handling within pushStream +// - NGHTTP2_ERR_NOMEM (should emit session error) +// - NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE (should emit session error) +// - NGHTTP2_ERR_STREAM_CLOSED (should emit stream error) +// - every other NGHTTP2 error from binding (should emit stream error) + +const specificTestKeys = [ + 'NGHTTP2_ERR_NOMEM', + 'NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE', + 'NGHTTP2_ERR_STREAM_CLOSED' +]; + +const specificTests = [ + { + ngError: constants.NGHTTP2_ERR_NOMEM, + error: { + code: 'ERR_OUTOFMEMORY', + type: Error, + message: 'Out of memory' + }, + type: 'session' + }, + { + ngError: constants.NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE, + error: { + code: 'ERR_HTTP2_OUT_OF_STREAMS', + type: Error, + message: 'No stream ID is available because ' + + 'maximum stream ID has been reached' + }, + type: 'session' + }, + { + ngError: constants.NGHTTP2_ERR_STREAM_CLOSED, + error: { + code: 'ERR_HTTP2_STREAM_CLOSED', + type: Error, + message: 'The stream is already closed' + }, + type: 'stream' + }, +]; + +const genericTests = Object.getOwnPropertyNames(constants) + .filter((key) => ( + key.indexOf('NGHTTP2_ERR') === 0 && specificTestKeys.indexOf(key) < 0 + )) + .map((key) => ({ + ngError: constants[key], + error: { + code: 'ERR_HTTP2_ERROR', + type: Error, + message: nghttp2ErrorString(constants[key]) + }, + type: 'stream' + })); + + +const tests = specificTests.concat(genericTests); + +let currentError; + +// mock submitPushPromise because we only care about testing error handling +Http2Session.prototype.submitPushPromise = () => currentError.ngError; + +const server = http2.createServer(); +server.on('stream', common.mustCall((stream, headers) => { + const errorMustCall = common.expectsError(currentError.error); + const errorMustNotCall = common.mustNotCall( + `${currentError.error.code} should emit on ${currentError.type}` + ); + console.log(currentError); + + if (currentError.type === 'stream') { + stream.session.on('error', errorMustNotCall); + stream.on('error', errorMustCall); + stream.on('error', common.mustCall(() => { + stream.respond(); + stream.end(); + })); + } else { + stream.session.once('error', errorMustCall); + stream.on('error', errorMustNotCall); + } + + stream.pushStream({}, () => {}); +}, tests.length)); + +server.listen(0, common.mustCall(() => runTest(tests.shift()))); + +function runTest(test) { + const port = server.address().port; + const url = `http://localhost:${port}`; + const headers = { + ':path': '/', + ':method': 'POST', + ':scheme': 'http', + ':authority': `localhost:${port}` + }; + + const client = http2.connect(url); + const req = client.request(headers); + + currentError = test; + req.resume(); + req.end(); + + req.on('end', common.mustCall(() => { + client.destroy(); + + if (!tests.length) { + server.close(); + } else { + runTest(tests.shift()); + } + })); +} diff --git a/test/parallel/test-http2-server-push-stream-head.js b/test/parallel/test-http2-server-push-stream-head.js new file mode 100644 index 00000000000000..a1172b8ecf3789 --- /dev/null +++ b/test/parallel/test-http2-server-push-stream-head.js @@ -0,0 +1,54 @@ +// Flags: --expose-http2 +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const assert = require('assert'); +const http2 = require('http2'); + +// Check that pushStream handles method HEAD correctly +// - stream should end immediately (no body) + +const server = http2.createServer(); +server.on('stream', common.mustCall((stream, headers) => { + const port = server.address().port; + if (headers[':path'] === '/') { + stream.pushStream({ + ':scheme': 'http', + ':method': 'HEAD', + ':authority': `localhost:${port}`, + }, common.mustCall((push, headers) => { + assert.strictEqual(push._writableState.ended, true); + stream.end('test'); + })); + } + stream.respond({ + 'content-type': 'text/html', + ':status': 200 + }); +})); + +server.listen(0, common.mustCall(() => { + const port = server.address().port; + const headers = { ':path': '/' }; + const client = http2.connect(`http://localhost:${port}`); + const req = client.request(headers); + req.setEncoding('utf8'); + + client.on('stream', common.mustCall((stream, headers) => { + assert.strictEqual(headers[':scheme'], 'http'); + assert.strictEqual(headers[':path'], '/'); + assert.strictEqual(headers[':authority'], `localhost:${port}`); + })); + + let data = ''; + + req.on('data', common.mustCall((d) => data += d)); + req.on('end', common.mustCall(() => { + assert.strictEqual(data, 'test'); + server.close(); + client.destroy(); + })); + req.end(); +})); diff --git a/test/parallel/test-http2-server-push-stream.js b/test/parallel/test-http2-server-push-stream.js index c1de1195f76be3..c79ff7caecf0a9 100644 --- a/test/parallel/test-http2-server-push-stream.js +++ b/test/parallel/test-http2-server-push-stream.js @@ -15,7 +15,7 @@ server.on('stream', common.mustCall((stream, headers) => { ':scheme': 'http', ':path': '/foobar', ':authority': `localhost:${port}`, - }, (push, headers) => { + }, common.mustCall((push, headers) => { push.respond({ 'content-type': 'text/html', ':status': 200, @@ -23,7 +23,7 @@ server.on('stream', common.mustCall((stream, headers) => { }); push.end('pushed by server data'); stream.end('test'); - }); + })); } stream.respond({ 'content-type': 'text/html', From 539445890b2df72d5fe6025b372e45f0f8a63075 Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 21 Aug 2017 23:20:59 -0300 Subject: [PATCH 090/145] util: add fast internal array join method PR-URL: https://github.com/nodejs/node/pull/14881 Reviewed-By: Refael Ackermann Reviewed-By: Matteo Collina Reviewed-By: Benjamin Gruenbaum --- lib/internal/util.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/lib/internal/util.js b/lib/internal/util.js index 113c0c66c0fe47..1a4e8d62477f2a 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -252,6 +252,20 @@ function promisify(orig) { promisify.custom = kCustomPromisifiedSymbol; +// The build-in Array#join is slower in v8 6.0 +function join(output, separator) { + var str = ''; + if (output.length !== 0) { + for (var i = 0; i < output.length - 1; i++) { + // It is faster not to use a template string here + str += output[i]; + str += separator; + } + str += output[i]; + } + return str; +} + module.exports = { assertCrypto, cachedResult, @@ -265,6 +279,7 @@ module.exports = { normalizeEncoding, objectToString, promisify, + join, // Symbol used to customize promisify conversion customPromisifyArgs: kCustomPromisifyArgsSymbol, From 757c34276b0571f6637380150a6b442aba2aef1a Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Wed, 13 Sep 2017 14:32:50 -0300 Subject: [PATCH 091/145] test: fix actual and expected order In addition use the newer common.expectsError version. PR-URL: https://github.com/nodejs/node/pull/14881 Reviewed-By: Refael Ackermann Reviewed-By: Matteo Collina Reviewed-By: Benjamin Gruenbaum --- test/parallel/test-console.js | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/test/parallel/test-console.js b/test/parallel/test-console.js index bca70467c0caac..f63c4f9431ab32 100644 --- a/test/parallel/test-console.js +++ b/test/parallel/test-console.js @@ -26,8 +26,8 @@ const assert = require('assert'); assert.ok(process.stdout.writable); assert.ok(process.stderr.writable); // Support legacy API -assert.strictEqual('number', typeof process.stdout.fd); -assert.strictEqual('number', typeof process.stderr.fd); +assert.strictEqual(typeof process.stdout.fd, 'number'); +assert.strictEqual(typeof process.stderr.fd, 'number'); assert.doesNotThrow(function() { process.once('warning', common.mustCall((warning) => { @@ -123,19 +123,19 @@ const expectedStrings = [ ]; for (const expected of expectedStrings) { - assert.strictEqual(`${expected}\n`, strings.shift()); - assert.strictEqual(`${expected}\n`, errStrings.shift()); + assert.strictEqual(strings.shift(), `${expected}\n`); + assert.strictEqual(errStrings.shift(), `${expected}\n`); } for (const expected of expectedStrings) { - assert.strictEqual(`${expected}\n`, strings.shift()); - assert.strictEqual(`${expected}\n`, errStrings.shift()); + assert.strictEqual(strings.shift(), `${expected}\n`); + assert.strictEqual(errStrings.shift(), `${expected}\n`); } -assert.strictEqual("{ foo: 'bar', inspect: [Function: inspect] }\n", - strings.shift()); -assert.strictEqual("{ foo: 'bar', inspect: [Function: inspect] }\n", - strings.shift()); +assert.strictEqual(strings.shift(), + "{ foo: 'bar', inspect: [Function: inspect] }\n"); +assert.strictEqual(strings.shift(), + "{ foo: 'bar', inspect: [Function: inspect] }\n"); assert.ok(strings.shift().includes('foo: [Object]')); assert.strictEqual(strings.shift().includes('baz'), false); assert.ok(/^label: \d+\.\d{3}ms$/.test(strings.shift().trim())); @@ -143,15 +143,15 @@ assert.ok(/^__proto__: \d+\.\d{3}ms$/.test(strings.shift().trim())); assert.ok(/^constructor: \d+\.\d{3}ms$/.test(strings.shift().trim())); assert.ok(/^hasOwnProperty: \d+\.\d{3}ms$/.test(strings.shift().trim())); -assert.strictEqual('Trace: This is a {"formatted":"trace"} 10 foo', - errStrings.shift().split('\n').shift()); +assert.strictEqual(errStrings.shift().split('\n').shift(), + 'Trace: This is a {"formatted":"trace"} 10 foo'); -assert.throws(() => { +common.expectsError(() => { console.assert(false, 'should throw'); -}, common.expectsError({ +}, { code: 'ERR_ASSERTION', message: /^should throw$/ -})); +}); assert.doesNotThrow(() => { console.assert(true, 'this should not throw'); From 66a5f998282f61d619b69458b8bfe73e1a4ee1f2 Mon Sep 17 00:00:00 2001 From: Simon Brewster Date: Mon, 18 Sep 2017 21:33:10 +0200 Subject: [PATCH 092/145] http2: improved coverage of Http2Stream destroy Refs: https://github.com/nodejs/node/issues/14985 PR-URL: https://github.com/nodejs/node/pull/15461 Reviewed-By: Matteo Collina Reviewed-By: James M Snell --- ...st-http2-server-destroy-before-priority.js | 41 +++++++++++++++++++ .../test-http2-server-destroy-before-rst.js | 41 +++++++++++++++++++ .../test-http2-server-destroy-before-state.js | 37 +++++++++++++++++ 3 files changed, 119 insertions(+) create mode 100644 test/parallel/test-http2-server-destroy-before-priority.js create mode 100644 test/parallel/test-http2-server-destroy-before-rst.js create mode 100644 test/parallel/test-http2-server-destroy-before-state.js diff --git a/test/parallel/test-http2-server-destroy-before-priority.js b/test/parallel/test-http2-server-destroy-before-priority.js new file mode 100644 index 00000000000000..74d7c011ba0be1 --- /dev/null +++ b/test/parallel/test-http2-server-destroy-before-priority.js @@ -0,0 +1,41 @@ +// Flags: --expose-http2 +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const assert = require('assert'); +const http2 = require('http2'); + +const server = http2.createServer(); + +// Test that ERR_HTTP2_INVALID_STREAM is thrown when a stream is destroyed +// before calling stream.priority +server.on('stream', common.mustCall(onStream)); + +function onStream(stream, headers, flags) { + stream.session.destroy(); + assert.throws(() => stream.priority(), + common.expectsError({ + code: 'ERR_HTTP2_INVALID_STREAM', + message: /^The stream has been destroyed$/ + })); +} + +server.listen(0); + +server.on('listening', common.mustCall(() => { + + const client = http2.connect(`http://localhost:${server.address().port}`); + + const req = client.request({ ':path': '/' }); + + req.on('response', common.mustNotCall()); + req.resume(); + req.on('end', common.mustCall(() => { + server.close(); + client.destroy(); + })); + req.end(); + +})); diff --git a/test/parallel/test-http2-server-destroy-before-rst.js b/test/parallel/test-http2-server-destroy-before-rst.js new file mode 100644 index 00000000000000..f066e76b5f97de --- /dev/null +++ b/test/parallel/test-http2-server-destroy-before-rst.js @@ -0,0 +1,41 @@ +// Flags: --expose-http2 +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const assert = require('assert'); +const http2 = require('http2'); + +const server = http2.createServer(); + +// Test that ERR_HTTP2_INVALID_STREAM is thrown when a stream is destroyed +// before calling stream.rstStream +server.on('stream', common.mustCall(onStream)); + +function onStream(stream, headers, flags) { + stream.session.destroy(); + assert.throws(() => stream.rstStream(), + common.expectsError({ + code: 'ERR_HTTP2_INVALID_STREAM', + message: /^The stream has been destroyed$/ + })); +} + +server.listen(0); + +server.on('listening', common.mustCall(() => { + + const client = http2.connect(`http://localhost:${server.address().port}`); + + const req = client.request({ ':path': '/' }); + + req.on('response', common.mustNotCall()); + req.resume(); + req.on('end', common.mustCall(() => { + server.close(); + client.destroy(); + })); + req.end(); + +})); diff --git a/test/parallel/test-http2-server-destroy-before-state.js b/test/parallel/test-http2-server-destroy-before-state.js new file mode 100644 index 00000000000000..f5dce3e30a272d --- /dev/null +++ b/test/parallel/test-http2-server-destroy-before-state.js @@ -0,0 +1,37 @@ +// Flags: --expose-http2 +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const assert = require('assert'); +const http2 = require('http2'); + +const server = http2.createServer(); + +// Test that stream.state getter returns and empty object +// if the stream session has been destroyed +server.on('stream', common.mustCall(onStream)); + +function onStream(stream, headers, flags) { + stream.session.destroy(); + assert.deepStrictEqual(Object.create(null), stream.state); +} + +server.listen(0); + +server.on('listening', common.mustCall(() => { + + const client = http2.connect(`http://localhost:${server.address().port}`); + + const req = client.request({ ':path': '/' }); + + req.on('response', common.mustNotCall()); + req.resume(); + req.on('end', common.mustCall(() => { + server.close(); + client.destroy(); + })); + req.end(); + +})); From 25692a985c5c1339e2f9483da58c09ceaa468c2e Mon Sep 17 00:00:00 2001 From: Eugene Ostroukhov Date: Tue, 1 Aug 2017 15:28:51 -0700 Subject: [PATCH 093/145] inspector: break in eval script Fixes: https://github.com/nodejs/node/issues/14577 PR-URL: https://github.com/nodejs/node/pull/14581 Reviewed-By: Anna Henningsen Reviewed-By: Benjamin Gruenbaum Reviewed-By: Ruben Bridgewater Reviewed-By: James M Snell --- lib/internal/bootstrap_node.js | 9 +++++++- .../test-async-hook-setup-at-inspect-brk.js | 9 ++++++-- .../test-async-stack-traces-promise-then.js | 11 ++++++---- .../test-async-stack-traces-set-interval.js | 9 +++++++- test/inspector/test-inspector-break-e.js | 22 +++++++++++++++++++ test/inspector/test-scriptparsed-context.js | 4 +--- 6 files changed, 53 insertions(+), 11 deletions(-) create mode 100644 test/inspector/test-inspector-break-e.js diff --git a/lib/internal/bootstrap_node.js b/lib/internal/bootstrap_node.js index 3f83c08354e58f..3ce558611e46e1 100644 --- a/lib/internal/bootstrap_node.js +++ b/lib/internal/bootstrap_node.js @@ -434,6 +434,13 @@ } } + function wrapForBreakOnFirstLine(source) { + if (!process._breakFirstLine) + return source; + const fn = `function() {\n\n${source};\n\n}`; + return `process.binding('inspector').callAndPauseOnStart(${fn}, {})`; + } + function evalScript(name) { const Module = NativeModule.require('module'); const path = NativeModule.require('path'); @@ -442,7 +449,7 @@ const module = new Module(name); module.filename = path.join(cwd, name); module.paths = Module._nodeModulePaths(cwd); - const body = process._eval; + const body = wrapForBreakOnFirstLine(process._eval); const script = `global.__filename = ${JSON.stringify(name)};\n` + 'global.exports = exports;\n' + 'global.module = module;\n' + diff --git a/test/inspector/test-async-hook-setup-at-inspect-brk.js b/test/inspector/test-async-hook-setup-at-inspect-brk.js index 70887ff63d9d4e..7e290605522a39 100644 --- a/test/inspector/test-async-hook-setup-at-inspect-brk.js +++ b/test/inspector/test-async-hook-setup-at-inspect-brk.js @@ -13,9 +13,14 @@ setTimeout(() => { }, 50); `; +async function skipBreakpointAtStart(session) { + await session.waitForBreakOnLine(0, '[eval]'); + await session.send({ 'method': 'Debugger.resume' }); +} + async function checkAsyncStackTrace(session) { console.error('[test]', 'Verify basic properties of asyncStackTrace'); - const paused = await session.waitForBreakOnLine(2, '[eval]'); + const paused = await session.waitForBreakOnLine(4, '[eval]'); assert(paused.params.asyncStackTrace, `${Object.keys(paused.params)} contains "asyncStackTrace" property`); assert(paused.params.asyncStackTrace.description, 'Timeout'); @@ -35,7 +40,7 @@ async function runTests() { 'params': { 'patterns': [] } }, { 'method': 'Runtime.runIfWaitingForDebugger' } ]); - + await skipBreakpointAtStart(session); await checkAsyncStackTrace(session); await session.runToCompletion(); diff --git a/test/inspector/test-async-stack-traces-promise-then.js b/test/inspector/test-async-stack-traces-promise-then.js index 68584b0a3c5dad..9e28d0d51e3a55 100644 --- a/test/inspector/test-async-stack-traces-promise-then.js +++ b/test/inspector/test-async-stack-traces-promise-then.js @@ -31,15 +31,18 @@ async function runTests() { { 'method': 'Runtime.runIfWaitingForDebugger' } ]); + await session.waitForBreakOnLine(0, '[eval]'); + await session.send({ 'method': 'Debugger.resume' }); + console.error('[test] Waiting for break1'); - debuggerPausedAt(await session.waitForBreakOnLine(4, '[eval]'), - 'break1', 'runTest:3'); + debuggerPausedAt(await session.waitForBreakOnLine(6, '[eval]'), + 'break1', 'runTest:5'); await session.send({ 'method': 'Debugger.resume' }); console.error('[test] Waiting for break2'); - debuggerPausedAt(await session.waitForBreakOnLine(7, '[eval]'), - 'break2', 'runTest:6'); + debuggerPausedAt(await session.waitForBreakOnLine(9, '[eval]'), + 'break2', 'runTest:8'); await session.runToCompletion(); assert.strictEqual(0, (await instance.expectShutdown()).exitCode); diff --git a/test/inspector/test-async-stack-traces-set-interval.js b/test/inspector/test-async-stack-traces-set-interval.js index bc96df9588fc6a..78f7a8e980e3b4 100644 --- a/test/inspector/test-async-stack-traces-set-interval.js +++ b/test/inspector/test-async-stack-traces-set-interval.js @@ -8,9 +8,15 @@ const assert = require('assert'); const script = 'setInterval(() => { debugger; }, 50);'; +async function skipFirstBreakpoint(session) { + console.log('[test]', 'Skipping the first breakpoint in the eval script'); + await session.waitForBreakOnLine(0, '[eval]'); + await session.send({ 'method': 'Debugger.resume' }); +} + async function checkAsyncStackTrace(session) { console.error('[test]', 'Verify basic properties of asyncStackTrace'); - const paused = await session.waitForBreakOnLine(0, '[eval]'); + const paused = await session.waitForBreakOnLine(2, '[eval]'); assert(paused.params.asyncStackTrace, `${Object.keys(paused.params)} contains "asyncStackTrace" property`); assert(paused.params.asyncStackTrace.description, 'Timeout'); @@ -31,6 +37,7 @@ async function runTests() { { 'method': 'Runtime.runIfWaitingForDebugger' } ]); + await skipFirstBreakpoint(session); await checkAsyncStackTrace(session); console.error('[test]', 'Stopping child instance'); diff --git a/test/inspector/test-inspector-break-e.js b/test/inspector/test-inspector-break-e.js new file mode 100644 index 00000000000000..0e5b837bc51298 --- /dev/null +++ b/test/inspector/test-inspector-break-e.js @@ -0,0 +1,22 @@ +'use strict'; +const common = require('../common'); + +common.skipIfInspectorDisabled(); + +const assert = require('assert'); +const { NodeInstance } = require('./inspector-helper.js'); + +async function runTests() { + const instance = new NodeInstance(undefined, 'console.log(10)'); + const session = await instance.connectInspectorSession(); + await session.send([ + { 'method': 'Runtime.enable' }, + { 'method': 'Debugger.enable' }, + { 'method': 'Runtime.runIfWaitingForDebugger' } + ]); + await session.waitForBreakOnLine(0, '[eval]'); + await session.runToCompletion(); + assert.strictEqual(0, (await instance.expectShutdown()).exitCode); +} + +runTests(); diff --git a/test/inspector/test-scriptparsed-context.js b/test/inspector/test-scriptparsed-context.js index f1258639f5d7ab..6e89f05dc63491 100644 --- a/test/inspector/test-scriptparsed-context.js +++ b/test/inspector/test-scriptparsed-context.js @@ -10,8 +10,6 @@ const script = ` const assert = require('assert'); const vm = require('vm'); const { kParsingContext } = process.binding('contextify'); - debugger; - global.outer = true; global.inner = false; const context = vm.createContext({ @@ -61,7 +59,7 @@ async function runTests() { { 'method': 'Debugger.enable' }, { 'method': 'Runtime.runIfWaitingForDebugger' } ]); - await session.waitForBreakOnLine(5, '[eval]'); + await session.waitForBreakOnLine(0, '[eval]'); await session.send({ 'method': 'Runtime.enable' }); const topContext = await getContext(session); From 9d6b0e6f6f835f7f447ef9b2dfe6037a870b58a8 Mon Sep 17 00:00:00 2001 From: Vse Mozhet Byt Date: Tue, 19 Sep 2017 02:56:23 +0300 Subject: [PATCH 094/145] doc: fix external links with 404 status PR-URL: https://github.com/nodejs/node/pull/15463 Fixes: https://github.com/nodejs/node/issues/15462 Reviewed-By: James M Snell Reviewed-By: Joyee Cheung Reviewed-By: Luigi Pinca Reviewed-By: Refael Ackermann --- doc/api/crypto.md | 2 +- doc/api/os.md | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 3d4c1e26c192cb..4e5e54a29d4ef8 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -2272,7 +2272,7 @@ the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL. [Crypto Constants]: #crypto_crypto_constants_1 [HTML5's `keygen` element]: http://www.w3.org/TR/html5/forms.html#the-keygen-element [NIST SP 800-131A]: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf -[NIST SP 800-132]: http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf +[NIST SP 800-132]: http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf [Nonce-Disrespecting Adversaries]: https://github.com/nonce-disrespect/nonce-disrespect [OpenSSL's SPKAC implementation]: https://www.openssl.org/docs/man1.0.2/apps/spkac.html [RFC 2412]: https://www.rfc-editor.org/rfc/rfc2412.txt diff --git a/doc/api/os.md b/doc/api/os.md index 28eff6a13f0b60..818e0204491c6c 100644 --- a/doc/api/os.md +++ b/doc/api/os.md @@ -338,7 +338,7 @@ The `os.release()` method returns a string identifying the operating system release. *Note*: On POSIX systems, the operating system release is determined by -calling uname(3). On Windows, `GetVersionExW()` is used. Please see +calling [uname(3)][]. On Windows, `GetVersionExW()` is used. Please see https://en.wikipedia.org/wiki/Uname#Examples for more information. ## os.tmpdir() @@ -374,11 +374,12 @@ added: v0.3.3 * Returns: {string} The `os.type()` method returns a string identifying the operating system name -as returned by uname(3). For example `'Linux'` on Linux, `'Darwin'` on macOS and -`'Windows_NT'` on Windows. +as returned by [uname(3)][]. For example `'Linux'` on Linux, `'Darwin'` on macOS +and `'Windows_NT'` on Windows. Please see https://en.wikipedia.org/wiki/Uname#Examples for additional -information about the output of running uname(3) on various operating systems. +information about the output of running [uname(3)][] on various operating +systems. ## os.uptime() -* `options` {Object} -* `callback` {Function} Attached as a listener to `'message'` events. +* `options` {Object} Available options are: + * `type` {string} The family of socket. Must be either `'udp4'` or `'udp6'`. + Required. + * `reuseAddr` {boolean} When `true` [`socket.bind()`][] will reuse the + address, even if another process has already bound a socket on it. Optional. + Defaults to `false`. + * `lookup` {Function} Custom lookup function. Defaults to [`dns.lookup()`][]. + Optional. +* `callback` {Function} Attached as a listener for `'message'` events. Optional. * Returns: {dgram.Socket} -Creates a `dgram.Socket` object. The `options` argument is an object that -should contain a `type` field of either `udp4` or `udp6` and an optional -boolean `reuseAddr` field. - -When `reuseAddr` is `true` [`socket.bind()`][] will reuse the address, even if -another process has already bound a socket on it. `reuseAddr` defaults to -`false`. The optional `callback` function is added as a listener for `'message'` -events. - -Once the socket is created, calling [`socket.bind()`][] will instruct the -socket to begin listening for datagram messages. When `address` and `port` are -not passed to [`socket.bind()`][] the method will bind the socket to the "all -interfaces" address on a random port (it does the right thing for both `udp4` -and `udp6` sockets). The bound address and port can be retrieved using -[`socket.address().address`][] and [`socket.address().port`][]. +Creates a `dgram.Socket` object. Once the socket is created, calling +[`socket.bind()`][] will instruct the socket to begin listening for datagram +messages. When `address` and `port` are not passed to [`socket.bind()`][] the +method will bind the socket to the "all interfaces" address on a random port +(it does the right thing for both `udp4` and `udp6` sockets). The bound address +and port can be retrieved using [`socket.address().address`][] and +[`socket.address().port`][]. ### dgram.createSocket(type[, callback]) - -Emitted when the request has been aborted by the server and the network -socket has closed. - ### Event: 'connect' -Emitted when the request has been aborted by the client and the network -socket has closed. +Emitted when the request has been aborted and the network socket has closed. ### Event: 'close' * `multicastInterface` {String} @@ -536,7 +536,7 @@ s.bind(1234, () => { diff --git a/doc/api/n-api.md b/doc/api/n-api.md index 13ec0f3594436d..7bd20c60b60ea1 100644 --- a/doc/api/n-api.md +++ b/doc/api/n-api.md @@ -2932,7 +2932,7 @@ call like the arguments and the `this` pointer from a given callback info. ### *napi_get_new_target* ```C napi_status napi_get_new_target(napi_env env, @@ -3238,7 +3238,7 @@ callback invocation, even when it was cancelled. @@ -3342,7 +3342,7 @@ necessary to ensure an async operation is properly tracked by the runtime. ### *napi_async_init** ```C napi_status napi_async_init(napi_env env, @@ -3363,7 +3363,7 @@ Returns `napi_ok` if the API succeeded. ### *napi_async_destroy** ```C napi_status napi_async_destroy(napi_env env, @@ -3379,7 +3379,7 @@ Returns `napi_ok` if the API succeeded. ```C diff --git a/doc/changelogs/CHANGELOG_V8.md b/doc/changelogs/CHANGELOG_V8.md index e350a21d8c2692..aa347b1183c1f7 100644 --- a/doc/changelogs/CHANGELOG_V8.md +++ b/doc/changelogs/CHANGELOG_V8.md @@ -6,6 +6,7 @@ +8.6.0
8.5.0
8.4.0
8.3.0
@@ -31,13 +32,176 @@ * [io.js](CHANGELOG_IOJS.md) * [Archive](CHANGELOG_ARCHIVE.md) + +## 2017-09-26, Version 8.6.0 (Current), @jasnell + +### Notable Changes + +* **crypto** + * Support for multiple ECDH curves. [#15206](https://github.com/nodejs/node/pull/15206) +* **dgram** + * Added `setMulticastInterface()` API. [#7855](https://github.com/nodejs/node/pull/7855) + * Custom lookup functions are now supported. [#14560](https://github.com/nodejs/node/pull/14560) +* **n-api** + * The command-line flag is no longer required to use N-API. [#14902](https://github.com/nodejs/node/pull/14902) +* **tls** + * Docs-only deprecation of `parseCertString()`. [#14245](https://github.com/nodejs/node/pull/14245) +* **New Contributors** + * Welcome Sebastiaan Deckers (@sebdeckers) as a new Collaborator! [#15354](https://github.com/nodejs/node/pull/15354) + +### Commits + +* [[`4f7d9392e7`](https://github.com/nodejs/node/commit/4f7d9392e7)] - **assert**: improve AssertionError in case of "Errors" (Ruben Bridgewater) [#15025](https://github.com/nodejs/node/pull/15025) +* [[`f6c65e6e19`](https://github.com/nodejs/node/commit/f6c65e6e19)] - **assert**: fix boxed primitives in deepStrictEqual (Ruben Bridgewater) [#15050](https://github.com/nodejs/node/pull/15050) +* [[`7fa175f6d3`](https://github.com/nodejs/node/commit/7fa175f6d3)] - **assert**: fix deepEqual inconsistencies (Ruben Bridgewater) [#14491](https://github.com/nodejs/node/pull/14491) +* [[`17d8dfec70`](https://github.com/nodejs/node/commit/17d8dfec70)] - **async_hooks**: support promise resolve hook (Anna Henningsen) [#15296](https://github.com/nodejs/node/pull/15296) +* [[`81723a9172`](https://github.com/nodejs/node/commit/81723a9172)] - **(SEMVER-MINOR)** **async_hooks,doc**: some async_hooks improvements (James M Snell) [#15103](https://github.com/nodejs/node/pull/15103) +* [[`535f8d5281`](https://github.com/nodejs/node/commit/535f8d5281)] - **benchmark**: var to const (Ruben Bridgewater) [#13757](https://github.com/nodejs/node/pull/13757) +* [[`0f8f37ed45`](https://github.com/nodejs/node/commit/0f8f37ed45)] - **benchmark**: improve and add more inspect benchmarks (Ruben Bridgewater) [#14881](https://github.com/nodejs/node/pull/14881) +* [[`3bf718c3fe`](https://github.com/nodejs/node/commit/3bf718c3fe)] - **benchmark**: enable assert benchmark with short len (Rich Trott) [#15174](https://github.com/nodejs/node/pull/15174) +* [[`d30a5836b6`](https://github.com/nodejs/node/commit/d30a5836b6)] - **benchmark**: provide default methods for assert (Rich Trott) [#15174](https://github.com/nodejs/node/pull/15174) +* [[`142d2ed057`](https://github.com/nodejs/node/commit/142d2ed057)] - **benchmark**: use smaller n value in some http tests (Peter Marshall) [#14002](https://github.com/nodejs/node/pull/14002) +* [[`5e4f87ae65`](https://github.com/nodejs/node/commit/5e4f87ae65)] - **buffer**: improve Buffer.from performance (Anatoli Papirovski) [#15178](https://github.com/nodejs/node/pull/15178) +* [[`8bbbda55e4`](https://github.com/nodejs/node/commit/8bbbda55e4)] - **build**: use generic names for linting tasks (Nikolai Vavilov) [#15272](https://github.com/nodejs/node/pull/15272) +* [[`9685b9ff2f`](https://github.com/nodejs/node/commit/9685b9ff2f)] - **build**: don't fail `make test` on source tarballs (Gibson Fahnestock) [#15441](https://github.com/nodejs/node/pull/15441) +* [[`354f32040d`](https://github.com/nodejs/node/commit/354f32040d)] - **build**: remove unused configuration variable (Ben Noordhuis) [#15266](https://github.com/nodejs/node/pull/15266) +* [[`5d217ad5d7`](https://github.com/nodejs/node/commit/5d217ad5d7)] - **build**: add support for link-module to vcbuild (Bartosz Sosnowski) [#15410](https://github.com/nodejs/node/pull/15410) +* [[`607832d3c3`](https://github.com/nodejs/node/commit/607832d3c3)] - **child_process**: set shell to false in fork() (Alex Gresnel) [#15352](https://github.com/nodejs/node/pull/15352) +* [[`c26e93b309`](https://github.com/nodejs/node/commit/c26e93b309)] - **crypto**: fix Node_SignFinal (David Benjamin) [#15024](https://github.com/nodejs/node/pull/15024) +* [[`bd07574718`](https://github.com/nodejs/node/commit/bd07574718)] - **(SEMVER-MINOR)** **crypto**: support multiple ECDH curves and auto (Roga Pria Sembada) [#15206](https://github.com/nodejs/node/pull/15206) +* [[`5e043a6c78`](https://github.com/nodejs/node/commit/5e043a6c78)] - **deps**: define BUILDING_NGHTTP2 during nghttp2 build (Ben Noordhuis) [#15487](https://github.com/nodejs/node/pull/15487) +* [[`2e75ac028a`](https://github.com/nodejs/node/commit/2e75ac028a)] - **deps**: v8: fix potential segfault in profiler (Ali Ijaz Sheikh) [#15498](https://github.com/nodejs/node/pull/15498) +* [[`2944ea6c6b`](https://github.com/nodejs/node/commit/2944ea6c6b)] - **(SEMVER-MINOR)** **dgram**: add custom lookup function in sockets (cjihrig) [#14560](https://github.com/nodejs/node/pull/14560) +* [[`b24ee68133`](https://github.com/nodejs/node/commit/b24ee68133)] - **(SEMVER-MINOR)** **dgram**: added setMulticastInterface() (Will Young) [#7855](https://github.com/nodejs/node/pull/7855) +* [[`f6b484461c`](https://github.com/nodejs/node/commit/f6b484461c)] - **doc**: ctc -\> tsc in onboarding extras (Bryan English) [#15621](https://github.com/nodejs/node/pull/15621) +* [[`f38666a967`](https://github.com/nodejs/node/commit/f38666a967)] - **doc**: ctc -\> tsc in collab guide (Bryan English) [#15590](https://github.com/nodejs/node/pull/15590) +* [[`02c62df75e`](https://github.com/nodejs/node/commit/02c62df75e)] - **doc**: remove invalid hash in link (Vse Mozhet Byt) [#15542](https://github.com/nodejs/node/pull/15542) +* [[`6cd64f36bc`](https://github.com/nodejs/node/commit/6cd64f36bc)] - **doc**: note caveats in process message serialization (Joyee Cheung) [#12963](https://github.com/nodejs/node/pull/12963) +* [[`1fbb86c64b`](https://github.com/nodejs/node/commit/1fbb86c64b)] - **doc**: fix 'aborted' event documentation (Luigi Pinca) [#15471](https://github.com/nodejs/node/pull/15471) +* [[`2326d655de`](https://github.com/nodejs/node/commit/2326d655de)] - **doc**: fix types and description for dns.resolveTxt (Tobias Nießen) [#15472](https://github.com/nodejs/node/pull/15472) +* [[`fcbee7b4bb`](https://github.com/nodejs/node/commit/fcbee7b4bb)] - **doc**: fix some links in http2.md (Vse Mozhet Byt) [#15481](https://github.com/nodejs/node/pull/15481) +* [[`9d6b0e6f6f`](https://github.com/nodejs/node/commit/9d6b0e6f6f)] - **doc**: fix external links with 404 status (Vse Mozhet Byt) [#15463](https://github.com/nodejs/node/pull/15463) +* [[`29fd88c3e5`](https://github.com/nodejs/node/commit/29fd88c3e5)] - **doc**: fix new nits in links (Vse Mozhet Byt) [#15449](https://github.com/nodejs/node/pull/15449) +* [[`4efc6fec6b`](https://github.com/nodejs/node/commit/4efc6fec6b)] - **doc**: fix some internal links (Vse Mozhet Byt) [#15293](https://github.com/nodejs/node/pull/15293) +* [[`5ea4b88a29`](https://github.com/nodejs/node/commit/5ea4b88a29)] - **doc**: adding sebdeckers to collaborators (Sebastiaan Deckers) [#15354](https://github.com/nodejs/node/pull/15354) +* [[`d5d498b6dc`](https://github.com/nodejs/node/commit/d5d498b6dc)] - **doc**: update AUTHORS list (Michaël Zasso) [#15181](https://github.com/nodejs/node/pull/15181) +* [[`950f7f5fe1`](https://github.com/nodejs/node/commit/950f7f5fe1)] - **doc**: update README with SHASUMS256.txt.sig info (Jon Moss) [#15107](https://github.com/nodejs/node/pull/15107) +* [[`38422d5963`](https://github.com/nodejs/node/commit/38422d5963)] - **doc**: fix nits in esm.md (Vse Mozhet Byt) [#15315](https://github.com/nodejs/node/pull/15315) +* [[`b0f5b2a38c`](https://github.com/nodejs/node/commit/b0f5b2a38c)] - **doc**: fix "added in" for Buffer.allocUnsafeSlow() (Tuan Anh Tran) [#15330](https://github.com/nodejs/node/pull/15330) +* [[`8112f496dc`](https://github.com/nodejs/node/commit/8112f496dc)] - **doc**: add missing heading for error (Jon Moss) [#15325](https://github.com/nodejs/node/pull/15325) +* [[`29707afd82`](https://github.com/nodejs/node/commit/29707afd82)] - **doc**: add missing doc for readable._destroy (Michaël Zasso) [#15316](https://github.com/nodejs/node/pull/15316) +* [[`9f4480ce90`](https://github.com/nodejs/node/commit/9f4480ce90)] - **doc**: use consistent terminology in process doc (Rich Trott) [#15321](https://github.com/nodejs/node/pull/15321) +* [[`a53a0d8b38`](https://github.com/nodejs/node/commit/a53a0d8b38)] - **doc**: fix emitKeypressEvents stream type (Oblosys) [#15399](https://github.com/nodejs/node/pull/15399) +* [[`b5c1a82560`](https://github.com/nodejs/node/commit/b5c1a82560)] - **doc**: fix http.ClientRequest method descriptions (Antoine AMARA) [#15163](https://github.com/nodejs/node/pull/15163) +* [[`f0e411d1b2`](https://github.com/nodejs/node/commit/f0e411d1b2)] - **doc**: prevent displaying empty version picker (Chris Young) [#15420](https://github.com/nodejs/node/pull/15420) +* [[`acb0d012b3`](https://github.com/nodejs/node/commit/acb0d012b3)] - **doc**: make mkdtemp example work on Windows (Bartosz Sosnowski) [#15408](https://github.com/nodejs/node/pull/15408) +* [[`bdfed1ad25`](https://github.com/nodejs/node/commit/bdfed1ad25)] - **doc**: fix entryTypes type and missing link (Mani Maghsoudlou) [#15406](https://github.com/nodejs/node/pull/15406) +* [[`7fa2bee5e7`](https://github.com/nodejs/node/commit/7fa2bee5e7)] - **doc**: add documentation for the 'timeout' event (Luigi Pinca) [#15443](https://github.com/nodejs/node/pull/15443) +* [[`b09eeb4a3d`](https://github.com/nodejs/node/commit/b09eeb4a3d)] - **(SEMVER-MINOR)** **doc, tls**: mark parseCertString() as deprecated (XadillaX) [#14245](https://github.com/nodejs/node/pull/14245) +* [[`e0f5e3a199`](https://github.com/nodejs/node/commit/e0f5e3a199)] - **docs**: clarify usage cli options -e,-p on windows (Łukasz Szewczak) [#15568](https://github.com/nodejs/node/pull/15568) +* [[`a792ea7709`](https://github.com/nodejs/node/commit/a792ea7709)] - **docs**: update 8.5.0 changelog (Myles Borins) [#15384](https://github.com/nodejs/node/pull/15384) +* [[`0a8258b3de`](https://github.com/nodejs/node/commit/0a8258b3de)] - **errors**: remove duplicate error definition (Jon Moss) +* [[`a14b252c5c`](https://github.com/nodejs/node/commit/a14b252c5c)] - **errors**: eliminate circular dependency on assert (James M Snell) [#15002](https://github.com/nodejs/node/pull/15002) +* [[`b58a2aae1b`](https://github.com/nodejs/node/commit/b58a2aae1b)] - **errors**: fix ERR_MODULE_RESOLUTION_LEGACY message (Tobias Nießen) [#15290](https://github.com/nodejs/node/pull/15290) +* [[`da3265ad82`](https://github.com/nodejs/node/commit/da3265ad82)] - **errors**: backport ERR_INVALID_PROTOCOL to v8.x (Myles Borins) [#15388](https://github.com/nodejs/node/pull/15388) +* [[`2e0313865b`](https://github.com/nodejs/node/commit/2e0313865b)] - **errors,tools**: alphabetize-errors lint rule (Jon Moss) [#15083](https://github.com/nodejs/node/pull/15083) +* [[`771c2ac7c2`](https://github.com/nodejs/node/commit/771c2ac7c2)] - **http**: revert #14024 writable is never set to false (Matteo Collina) [#15404](https://github.com/nodejs/node/pull/15404) +* [[`68ec157be0`](https://github.com/nodejs/node/commit/68ec157be0)] - **http2**: fix compat stream read handling, add tests (Anatoli Papirovski) [#15503](https://github.com/nodejs/node/pull/15503) +* [[`9fc8eddfdd`](https://github.com/nodejs/node/commit/9fc8eddfdd)] - **http2**: remove unused onTimeout, add timeout tests (Anatoli Papirovski) [#15539](https://github.com/nodejs/node/pull/15539) +* [[`1691827b8c`](https://github.com/nodejs/node/commit/1691827b8c)] - **http2**: small fixes to compatibility layer (Anatoli Papirovski) [#15473](https://github.com/nodejs/node/pull/15473) +* [[`66a5f99828`](https://github.com/nodejs/node/commit/66a5f99828)] - **http2**: improved coverage of Http2Stream destroy (Simon Brewster) [#15461](https://github.com/nodejs/node/pull/15461) +* [[`ba9012d4bc`](https://github.com/nodejs/node/commit/ba9012d4bc)] - **http2**: add tests for push stream error handling (Anatoli Papirovski) [#15281](https://github.com/nodejs/node/pull/15281) +* [[`b61220ed84`](https://github.com/nodejs/node/commit/b61220ed84)] - **http2**: fix subsequent end calls to not throw (Anatoli Papirovski) [#15414](https://github.com/nodejs/node/pull/15414) +* [[`2e421ff5c9`](https://github.com/nodejs/node/commit/2e421ff5c9)] - **http2**: correct behaviour for enablePush unpack (Anatoli Papirovski) [#15167](https://github.com/nodejs/node/pull/15167) +* [[`9490be353e`](https://github.com/nodejs/node/commit/9490be353e)] - **http2**: cleanup of h2 compat layer, add tests (Anatoli Papirovski) [#15254](https://github.com/nodejs/node/pull/15254) +* [[`aa0917cd0a`](https://github.com/nodejs/node/commit/aa0917cd0a)] - **http2**: improve http2 coverage (James M Snell) [#15210](https://github.com/nodejs/node/pull/15210) +* [[`a6879bfab6`](https://github.com/nodejs/node/commit/a6879bfab6)] - **http2**: custom promisify for http2.connect (James M Snell) [#15207](https://github.com/nodejs/node/pull/15207) +* [[`2ea2725ce0`](https://github.com/nodejs/node/commit/2ea2725ce0)] - **http2**: emit close event if request aborted (Anatoli Papirovski) [#15415](https://github.com/nodejs/node/pull/15415) +* [[`b9a9290e8d`](https://github.com/nodejs/node/commit/b9a9290e8d)] - **http2**: expand list of known headers (Anatoli Papirovski) [#15434](https://github.com/nodejs/node/pull/15434) +* [[`a32c8a566e`](https://github.com/nodejs/node/commit/a32c8a566e)] - **http2,async-wrap**: introduce AliasedBuffer class (Mike Kaufman) [#15077](https://github.com/nodejs/node/pull/15077) +* [[`25692a985c`](https://github.com/nodejs/node/commit/25692a985c)] - **inspector**: break in eval script (Eugene Ostroukhov) [#14581](https://github.com/nodejs/node/pull/14581) +* [[`cf1fe762dc`](https://github.com/nodejs/node/commit/cf1fe762dc)] - **lib**: improve lazy requires (Ruben Bridgewater) [#14167](https://github.com/nodejs/node/pull/14167) +* [[`8ce0e9a619`](https://github.com/nodejs/node/commit/8ce0e9a619)] - **lib**: refactor console startup (Ruben Bridgewater) [#15111](https://github.com/nodejs/node/pull/15111) +* [[`91e96d8f08`](https://github.com/nodejs/node/commit/91e96d8f08)] - **lib,src**: fix consistent spacing inside braces (James M Snell) [#14162](https://github.com/nodejs/node/pull/14162) +* [[`ede09f29d0`](https://github.com/nodejs/node/commit/ede09f29d0)] - **meta**: allow vague objections to be dismissed (James M Snell) [#15233](https://github.com/nodejs/node/pull/15233) +* [[`727d7b5078`](https://github.com/nodejs/node/commit/727d7b5078)] - **meta**: improve contributors guide (James M Snell) [#15123](https://github.com/nodejs/node/pull/15123) +* [[`c005713d05`](https://github.com/nodejs/node/commit/c005713d05)] - **module**: check file url passed to top-level import (guybedford) [#15389](https://github.com/nodejs/node/pull/15389) +* [[`939c8ed084`](https://github.com/nodejs/node/commit/939c8ed084)] - **module**: coverity fixes for ESM C++ (Bradley Farias) [#15275](https://github.com/nodejs/node/pull/15275) +* [[`a95ddc9484`](https://github.com/nodejs/node/commit/a95ddc9484)] - **n-api**: fix warning about size_t compare with int (Sampson Gao) [#15508](https://github.com/nodejs/node/pull/15508) +* [[`cd3a8e8832`](https://github.com/nodejs/node/commit/cd3a8e8832)] - **n-api**: remove n-api module loading flag (Gabriel Schulhof) [#14902](https://github.com/nodejs/node/pull/14902) +* [[`526e78f5cd`](https://github.com/nodejs/node/commit/526e78f5cd)] - **n-api**: add optional string length parameters (Sampson Gao) [#15343](https://github.com/nodejs/node/pull/15343) +* [[`87a3162f85`](https://github.com/nodejs/node/commit/87a3162f85)] - **n-api**: Context for custom async operations (Jason Ginchereau) [#15189](https://github.com/nodejs/node/pull/15189) +* [[`7b7c030adc`](https://github.com/nodejs/node/commit/7b7c030adc)] - **(SEMVER-MINOR)** **n-api**: change async resource name to napi_value (Jason Ginchereau) [#14697](https://github.com/nodejs/node/pull/14697) +* [[`d5b3002572`](https://github.com/nodejs/node/commit/d5b3002572)] - **n-api**: stop creating references to primitives (Gabriel Schulhof) [#15289](https://github.com/nodejs/node/pull/15289) +* [[`a47fe692b1`](https://github.com/nodejs/node/commit/a47fe692b1)] - **(SEMVER-MINOR)** **n-api**: use AsyncResource for Work tracking (Anna Henningsen) [#14697](https://github.com/nodejs/node/pull/14697) +* [[`8f12b9dce4`](https://github.com/nodejs/node/commit/8f12b9dce4)] - **n-api**: refactor napi_addon_register_func (Taylor Woll) [#15088](https://github.com/nodejs/node/pull/15088) +* [[`a2d340fb00`](https://github.com/nodejs/node/commit/a2d340fb00)] - **n-api**: napi_is_construct_call-\>napi_get_new_target (Sampson Gao) [#14698](https://github.com/nodejs/node/pull/14698) +* [[`fe9bb7e51e`](https://github.com/nodejs/node/commit/fe9bb7e51e)] - **net**: support passing null to listen() (cjihrig) [#14221](https://github.com/nodejs/node/pull/14221) +* [[`19d2d6611c`](https://github.com/nodejs/node/commit/19d2d6611c)] - **path**: fix normalize paths ending with two dots (Michaël Zasso) [nodejs-private/node-private#94](https://github.com/nodejs-private/node-private/pull/94) +* [[`8eeaba62bc`](https://github.com/nodejs/node/commit/8eeaba62bc)] - **readline**: name some anonymous functions (Flandre Scarlet) [#14297](https://github.com/nodejs/node/pull/14297) +* [[`4907ae7cb9`](https://github.com/nodejs/node/commit/4907ae7cb9)] - **src**: correct typo in trace_event header (Daniel Bevenius) [#15583](https://github.com/nodejs/node/pull/15583) +* [[`4f88c19cf3`](https://github.com/nodejs/node/commit/4f88c19cf3)] - **src**: add --pending-deprecation to NODE_OPTIONS (Thomas Corbière) [#15494](https://github.com/nodejs/node/pull/15494) +* [[`b87088c0b1`](https://github.com/nodejs/node/commit/b87088c0b1)] - **src**: remove unused constant from node_perf.h (Anna Henningsen) [#15548](https://github.com/nodejs/node/pull/15548) +* [[`90d14df56d`](https://github.com/nodejs/node/commit/90d14df56d)] - **src**: minor c++ refactors to module_wrap (Anna Henningsen) [#15515](https://github.com/nodejs/node/pull/15515) +* [[`24271a7aca`](https://github.com/nodejs/node/commit/24271a7aca)] - **src**: do not include internals from node_buffer.h (Anna Henningsen) [#15554](https://github.com/nodejs/node/pull/15554) +* [[`774e42b575`](https://github.com/nodejs/node/commit/774e42b575)] - **(SEMVER-MINOR)** **src**: refactor `#include` handling (Anna Henningsen) [#14697](https://github.com/nodejs/node/pull/14697) +* [[`29e38ab2a2`](https://github.com/nodejs/node/commit/29e38ab2a2)] - **src**: remove unused perf_hooks uv handles (James M Snell) [#15368](https://github.com/nodejs/node/pull/15368) +* [[`606da2ba43`](https://github.com/nodejs/node/commit/606da2ba43)] - **(SEMVER-MINOR)** **src**: make in_makecallback() getter const (Anna Henningsen) [#14697](https://github.com/nodejs/node/pull/14697) +* [[`98967c988f`](https://github.com/nodejs/node/commit/98967c988f)] - **(SEMVER-MINOR)** **src**: refactor async callback handling (Anna Henningsen) [#14697](https://github.com/nodejs/node/pull/14697) +* [[`f60a2aa982`](https://github.com/nodejs/node/commit/f60a2aa982)] - **(SEMVER-MINOR)** **src**: remove virtually unused ExecScope (Anna Henningsen) [#14697](https://github.com/nodejs/node/pull/14697) +* [[`6c520af6d5`](https://github.com/nodejs/node/commit/6c520af6d5)] - **(SEMVER-MINOR)** **src**: move DomainEnter,DomainExit to node.cc (Anna Henningsen) [#14697](https://github.com/nodejs/node/pull/14697) +* [[`8c480f9d8c`](https://github.com/nodejs/node/commit/8c480f9d8c)] - **src**: remove outdated todo from node_crypto.cc (Bartek Szczepański) [#15104](https://github.com/nodejs/node/pull/15104) +* [[`409576e015`](https://github.com/nodejs/node/commit/409576e015)] - **test**: expand http2 util test coverage for headers (Anatoli Papirovski) [#15493](https://github.com/nodejs/node/pull/15493) +* [[`0503c44835`](https://github.com/nodejs/node/commit/0503c44835)] - **test**: update test-fs-fsync to run from temp (atvoicu) [#15537](https://github.com/nodejs/node/pull/15537) +* [[`29f0ad6ccb`](https://github.com/nodejs/node/commit/29f0ad6ccb)] - **test**: fixing AliasedBuffer tests to enter Isolate (Mike Kaufman) [#15536](https://github.com/nodejs/node/pull/15536) +* [[`eccf503362`](https://github.com/nodejs/node/commit/eccf503362)] - **test**: improve readline test coverage for tty (Claudio Rodriguez) [#12064](https://github.com/nodejs/node/pull/12064) +* [[`58b9495c42`](https://github.com/nodejs/node/commit/58b9495c42)] - **test**: use reserved invalid hostname for tests (icarter09) [#14781](https://github.com/nodejs/node/pull/14781) +* [[`b1227147b9`](https://github.com/nodejs/node/commit/b1227147b9)] - **test**: clean up some assert deepEqual tests (Ruben Bridgewater) [#14491](https://github.com/nodejs/node/pull/14491) +* [[`93c08b0735`](https://github.com/nodejs/node/commit/93c08b0735)] - **test**: improve util inspect tests (Ruben Bridgewater) [#14881](https://github.com/nodejs/node/pull/14881) +* [[`59f183640b`](https://github.com/nodejs/node/commit/59f183640b)] - **test**: refactor test for readability (Refael Ackermann) [#13003](https://github.com/nodejs/node/pull/13003) +* [[`757c34276b`](https://github.com/nodejs/node/commit/757c34276b)] - **test**: fix actual and expected order (Ruben Bridgewater) [#14881](https://github.com/nodejs/node/pull/14881) +* [[`5125c08c50`](https://github.com/nodejs/node/commit/5125c08c50)] - **test**: remove obsolete debugger tests (Rich Trott) [#15139](https://github.com/nodejs/node/pull/15139) +* [[`7dfd570cad`](https://github.com/nodejs/node/commit/7dfd570cad)] - **test**: add test-benchmark-assert (Rich Trott) [#15174](https://github.com/nodejs/node/pull/15174) +* [[`a9066459ad`](https://github.com/nodejs/node/commit/a9066459ad)] - **test**: convert buffer benchmark to runBenchmark (Jon Moss) [#15349](https://github.com/nodejs/node/pull/15349) +* [[`45cdbcfee6`](https://github.com/nodejs/node/commit/45cdbcfee6)] - **test**: create shared runBenchmark function (Jon Moss) [#15004](https://github.com/nodejs/node/pull/15004) +* [[`ba96c8f23e`](https://github.com/nodejs/node/commit/ba96c8f23e)] - **test**: don't skip when common.mustCall() is pending (cjihrig) [#15421](https://github.com/nodejs/node/pull/15421) +* [[`50b6203a33`](https://github.com/nodejs/node/commit/50b6203a33)] - **(SEMVER-MINOR)** **test**: add regression test for 5691 (Anna Henningsen) [#14697](https://github.com/nodejs/node/pull/14697) +* [[`f0a741d178`](https://github.com/nodejs/node/commit/f0a741d178)] - **test**: kill subprocess only after last ACK (Refael Ackermann) [#15186](https://github.com/nodejs/node/pull/15186) +* [[`4d68064493`](https://github.com/nodejs/node/commit/4d68064493)] - **test**: move common.PORT tests to sequential (Jon Moss) [#15151](https://github.com/nodejs/node/pull/15151) +* [[`a92f3dfd8c`](https://github.com/nodejs/node/commit/a92f3dfd8c)] - **test**: make test-http-agent-maxsockets robust (Rich Trott) [#15192](https://github.com/nodejs/node/pull/15192) +* [[`edece30930`](https://github.com/nodejs/node/commit/edece30930)] - **test**: remove random timer in test-tls-fast-writing (Rich Trott) [#15138](https://github.com/nodejs/node/pull/15138) +* [[`b1a0bdcdaf`](https://github.com/nodejs/node/commit/b1a0bdcdaf)] - **test**: remove faulty test case (Ruben Bridgewater) [#15110](https://github.com/nodejs/node/pull/15110) +* [[`cd238e2c0e`](https://github.com/nodejs/node/commit/cd238e2c0e)] - **test**: check inspect array with empty string key (Rahul Mishra) [#15258](https://github.com/nodejs/node/pull/15258) +* [[`3ce501c8ff`](https://github.com/nodejs/node/commit/3ce501c8ff)] - **test**: improve process warning coverage (James M Snell) [#15212](https://github.com/nodejs/node/pull/15212) +* [[`a2c335b973`](https://github.com/nodejs/node/commit/a2c335b973)] - **test**: fix sequential/test-async-wrap-getasyncid (Anna Henningsen) [#15319](https://github.com/nodejs/node/pull/15319) +* [[`94e2b5c371`](https://github.com/nodejs/node/commit/94e2b5c371)] - **test**: refactor test-debug-prompt (Rich Trott) [#15141](https://github.com/nodejs/node/pull/15141) +* [[`5881033138`](https://github.com/nodejs/node/commit/5881033138)] - **test**: remove invalid test (Rich Trott) [#15320](https://github.com/nodejs/node/pull/15320) +* [[`a1abf62cc3`](https://github.com/nodejs/node/commit/a1abf62cc3)] - **test**: allow adding known-globals through ENV (Refael Ackermann) [#15187](https://github.com/nodejs/node/pull/15187) +* [[`427bf80194`](https://github.com/nodejs/node/commit/427bf80194)] - **test**: add test for fork() + shell (cjihrig) [#15352](https://github.com/nodejs/node/pull/15352) +* [[`4d26c68b6b`](https://github.com/nodejs/node/commit/4d26c68b6b)] - **test**: move test-benchmark-buffer to sequential (Rich Trott) [#15373](https://github.com/nodejs/node/pull/15373) +* [[`1fbdf47742`](https://github.com/nodejs/node/commit/1fbdf47742)] - **test**: fix flaky test-http2-session-timeout (Anatoli Papirovski) [#15338](https://github.com/nodejs/node/pull/15338) +* [[`f20fb4ce40`](https://github.com/nodejs/node/commit/f20fb4ce40)] - **test**: do not write fixture in test-require-symlink (Rich Trott) [#15067](https://github.com/nodejs/node/pull/15067) +* [[`389c8c33d7`](https://github.com/nodejs/node/commit/389c8c33d7)] - **test**: expand http2 frameError test case (Anatoli Papirovski) [#15298](https://github.com/nodejs/node/pull/15298) +* [[`d82ae0cb6e`](https://github.com/nodejs/node/commit/d82ae0cb6e)] - **test**: backward compatible api for tty (Gergely Nemeth) [#15235](https://github.com/nodejs/node/pull/15235) +* [[`e014983ec4`](https://github.com/nodejs/node/commit/e014983ec4)] - **test,process**: run 'abort' suite on Windows (Refael Ackermann) [#15056](https://github.com/nodejs/node/pull/15056) +* [[`6a94c1aa3b`](https://github.com/nodejs/node/commit/6a94c1aa3b)] - **timers**: clarify lib/timer.js comment (Daniel Bevenius) [#11018](https://github.com/nodejs/node/pull/11018) +* [[`ee157e5a7f`](https://github.com/nodejs/node/commit/ee157e5a7f)] - **tls**: prefer path over port in connect (Bryan English) [#14564](https://github.com/nodejs/node/pull/14564) +* [[`9049f09e0f`](https://github.com/nodejs/node/commit/9049f09e0f)] - **tools**: enforce consistent spacing inside braces (Sebastiaan Deckers) [#14162](https://github.com/nodejs/node/pull/14162) +* [[`6c221b83e3`](https://github.com/nodejs/node/commit/6c221b83e3)] - **url**: fix windows drive letter handling (Benjamin Coe) [#15490](https://github.com/nodejs/node/pull/15490) +* [[`fc1448f357`](https://github.com/nodejs/node/commit/fc1448f357)] - **util**: improve format performance (Ruben Bridgewater) [#15422](https://github.com/nodejs/node/pull/15422) +* [[`5b47f846b0`](https://github.com/nodejs/node/commit/5b47f846b0)] - **util**: fix out of bounds indices in util.inspect (Ruben Bridgewater) [#14881](https://github.com/nodejs/node/pull/14881) +* [[`9e8b1b3ec6`](https://github.com/nodejs/node/commit/9e8b1b3ec6)] - **util**: refactor inspect for performance and more (Ruben Bridgewater) [#14881](https://github.com/nodejs/node/pull/14881) +* [[`539445890b`](https://github.com/nodejs/node/commit/539445890b)] - **util**: add fast internal array join method (Ruben Bridgewater) [#14881](https://github.com/nodejs/node/pull/14881) +* [[`7d95dc385c`](https://github.com/nodejs/node/commit/7d95dc385c)] - **vm**: support parsing a script in a specific context (Timothy Gu) [#14888](https://github.com/nodejs/node/pull/14888) +james@ubuntu:~/node/main$ + ## 2017-09-12, Version 8.5.0 (Current), @MylesBorins ### Notable Changes * **build** - * Snapshots are now re-enabled in V8 + * Snapshots are now re-enabled in V8 [#14875](https://github.com/nodejs/node/pull/14875) * **console** * Implement minimal `console.group()`. @@ -45,7 +209,7 @@ * **deps** * upgrade libuv to 1.14.1 [#14866](https://github.com/nodejs/node/pull/14866) - * update nghttp2 to v1.25.0 + * update nghttp2 to v1.25.0 [#14955](https://github.com/nodejs/node/pull/14955) * **dns** * Add `verbatim` option to dns.lookup(). When true, results from the DNS diff --git a/src/node_version.h b/src/node_version.h index 242a3be832bae2..4605e38aee7e5b 100644 --- a/src/node_version.h +++ b/src/node_version.h @@ -23,10 +23,10 @@ #define SRC_NODE_VERSION_H_ #define NODE_MAJOR_VERSION 8 -#define NODE_MINOR_VERSION 5 -#define NODE_PATCH_VERSION 1 +#define NODE_MINOR_VERSION 6 +#define NODE_PATCH_VERSION 0 -#define NODE_VERSION_IS_RELEASE 0 +#define NODE_VERSION_IS_RELEASE 1 #ifndef NODE_STRINGIFY #define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n) From 69a2405d90ca1cc518399e4593c99872a02dd77b Mon Sep 17 00:00:00 2001 From: James M Snell Date: Tue, 26 Sep 2017 12:16:15 -0700 Subject: [PATCH 145/145] Working on v8.6.1 PR-URL: https://github.com/nodejs/node/pull/15509 --- src/node_version.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/node_version.h b/src/node_version.h index 4605e38aee7e5b..a90d8686bd889a 100644 --- a/src/node_version.h +++ b/src/node_version.h @@ -24,9 +24,9 @@ #define NODE_MAJOR_VERSION 8 #define NODE_MINOR_VERSION 6 -#define NODE_PATCH_VERSION 0 +#define NODE_PATCH_VERSION 1 -#define NODE_VERSION_IS_RELEASE 1 +#define NODE_VERSION_IS_RELEASE 0 #ifndef NODE_STRINGIFY #define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n)