Skip to content

Commit

Permalink
lib: prefer optional chaining
Browse files Browse the repository at this point in the history
PR-URL: #55045
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Matteo Collina <[email protected]>
Reviewed-By: Yagiz Nizipli <[email protected]>
Reviewed-By: Chemi Atlow <[email protected]>
Reviewed-By: Trivikram Kamat <[email protected]>
Reviewed-By: Paolo Insogna <[email protected]>
Reviewed-By: Marco Ippolito <[email protected]>
Reviewed-By: Stephen Belanger <[email protected]>
  • Loading branch information
RedYetiDev authored Sep 24, 2024
1 parent 04750af commit 574f2dd
Show file tree
Hide file tree
Showing 52 changed files with 228 additions and 121 deletions.
1 change: 1 addition & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,7 @@ export default [
'node-core/no-unescaped-regexp-dot': 'error',
'node-core/no-duplicate-requires': 'error',
'node-core/prefer-proto': 'error',
'node-core/prefer-optional-chaining': 'error',
},
},
// #endregion
Expand Down
6 changes: 3 additions & 3 deletions lib/_http_agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ function Agent(options) {
}

const requests = this.requests[name];
if (requests && requests.length) {
if (requests?.length) {
const req = requests.shift();
const reqAsyncRes = req[kRequestAsyncResource];
if (reqAsyncRes) {
Expand Down Expand Up @@ -437,7 +437,7 @@ Agent.prototype.removeSocket = function removeSocket(s, options) {
}

let req;
if (this.requests[name] && this.requests[name].length) {
if (this.requests[name]?.length) {
debug('removeSocket, have a request, make a socket');
req = this.requests[name][0];
} else {
Expand All @@ -449,7 +449,7 @@ Agent.prototype.removeSocket = function removeSocket(s, options) {
for (let i = 0; i < keys.length; i++) {
const prop = keys[i];
// Check whether this specific origin is already at maxSockets
if (this.sockets[prop] && this.sockets[prop].length) break;
if (this.sockets[prop]?.length) break;
debug('removeSocket, have a request with different origin,' +
' make a socket');
req = this.requests[prop][0];
Expand Down
10 changes: 5 additions & 5 deletions lib/_http_client.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ function ClientRequest(input, options, cb) {

const protocol = options.protocol || defaultAgent.protocol;
let expectedProtocol = defaultAgent.protocol;
if (this.agent && this.agent.protocol)
if (this.agent?.protocol)
expectedProtocol = this.agent.protocol;

if (options.path) {
Expand All @@ -190,7 +190,7 @@ function ClientRequest(input, options, cb) {
}

const defaultPort = options.defaultPort ||
(this.agent && this.agent.defaultPort);
(this.agent?.defaultPort);

const optsWithoutSignal = { __proto__: null, ...options };

Expand Down Expand Up @@ -553,7 +553,7 @@ function socketOnData(d) {
socket.destroy();
req.socket._hadError = true;
emitErrorEvent(req, ret);
} else if (parser.incoming && parser.incoming.upgrade) {
} else if (parser.incoming?.upgrade) {
// Upgrade (if status code 101) or CONNECT
const bytesParsed = ret;
const res = parser.incoming;
Expand Down Expand Up @@ -591,7 +591,7 @@ function socketOnData(d) {
// Requested Upgrade or used CONNECT method, but have no handler.
socket.destroy();
}
} else if (parser.incoming && parser.incoming.complete &&
} else if (parser.incoming?.complete &&
// When the status code is informational (100, 102-199),
// the server will send a final response after this client
// sends a request body, so we must not free the parser.
Expand Down Expand Up @@ -838,7 +838,7 @@ function tickOnSocket(req, socket) {

if (
req.timeout !== undefined ||
(req.agent && req.agent.options && req.agent.options.timeout)
(req.agent?.options?.timeout)
) {
listenSocketTimeout(req);
}
Expand Down
3 changes: 1 addition & 2 deletions lib/_http_common.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,7 @@ function parserOnHeadersComplete(versionMajor, versionMinor, headers, method,
}

// Parser is also used by http client
const ParserIncomingMessage = (socket && socket.server &&
socket.server[kIncomingMessage]) ||
const ParserIncomingMessage = (socket?.server?.[kIncomingMessage]) ||
IncomingMessage;

const incoming = parser.incoming = new ParserIncomingMessage(socket);
Expand Down
2 changes: 1 addition & 1 deletion lib/_http_incoming.js
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ IncomingMessage.prototype._destroy = function _destroy(err, cb) {

IncomingMessage.prototype._addHeaderLines = _addHeaderLines;
function _addHeaderLines(headers, n) {
if (headers && headers.length) {
if (headers?.length) {
let dest;
if (this.complete) {
this.rawTrailers = headers;
Expand Down
8 changes: 4 additions & 4 deletions lib/_http_outgoing.js
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,7 @@ OutgoingMessage.prototype._send = function _send(data, encoding, callback, byteL
OutgoingMessage.prototype._writeRaw = _writeRaw;
function _writeRaw(data, encoding, callback, size) {
const conn = this[kSocket];
if (conn && conn.destroyed) {
if (conn?.destroyed) {
// The socket was destroyed. If we're still trying to write to it,
// then we haven't gotten the 'close' event yet.
return false;
Expand Down Expand Up @@ -789,7 +789,7 @@ OutgoingMessage.prototype.getHeader = function getHeader(name) {
return;

const entry = headers[name.toLowerCase()];
return entry && entry[1];
return entry?.[1];
};


Expand Down Expand Up @@ -1073,7 +1073,7 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {
};

function onFinish(outmsg) {
if (outmsg && outmsg.socket && outmsg.socket._hadError) return;
if (outmsg?.socket?._hadError) return;
outmsg.emit('finish');
}

Expand Down Expand Up @@ -1188,7 +1188,7 @@ OutgoingMessage.prototype._finish = function _finish() {
OutgoingMessage.prototype._flush = function _flush() {
const socket = this[kSocket];

if (socket && socket.writable) {
if (socket?.writable) {
// There might be remaining data in this.output; write it out
const ret = this._flushOutput(socket);

Expand Down
10 changes: 5 additions & 5 deletions lib/_http_server.js
Original file line number Diff line number Diff line change
Expand Up @@ -738,7 +738,7 @@ function connectionListenerInternal(server, socket) {
socket.setEncoding = socketSetEncoding;

// We only consume the socket if it has never been consumed before.
if (socket._handle && socket._handle.isStreamBase &&
if (socket._handle?.isStreamBase &&
!socket._handle._consumed) {
parser._consumed = true;
socket._handle._consumed = true;
Expand Down Expand Up @@ -783,7 +783,7 @@ function socketOnDrain(socket, state) {
}

function socketOnTimeout() {
const req = this.parser && this.parser.incoming;
const req = this.parser?.incoming;
const reqTimeout = req && !req.complete && req.emit('timeout', this);
const res = this._httpMessage;
const resTimeout = res && res.emit('timeout', this);
Expand Down Expand Up @@ -918,7 +918,7 @@ function onParserExecuteCommon(server, socket, parser, state, ret, d) {
prepareError(ret, parser, d);
debug('parse error', ret);
socketOnError.call(socket, ret);
} else if (parser.incoming && parser.incoming.upgrade) {
} else if (parser.incoming?.upgrade) {
// Upgrade or CONNECT
const req = parser.incoming;
debug('SERVER upgrade or connect', req.method);
Expand Down Expand Up @@ -963,7 +963,7 @@ function onParserExecuteCommon(server, socket, parser, state, ret, d) {

function clearIncoming(req) {
req = req || this;
const parser = req.socket && req.socket.parser;
const parser = req.socket?.parser;
// Reset the .incoming property so that the request object can be gc'ed.
if (parser && parser.incoming === req) {
if (req.readableEnded) {
Expand Down Expand Up @@ -1180,7 +1180,7 @@ function onSocketResume() {
}

function onSocketPause() {
if (this._handle && this._handle.reading) {
if (this._handle?.reading) {
this._handle.reading = false;
this._handle.readStop();
}
Expand Down
4 changes: 2 additions & 2 deletions lib/_tls_wrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -489,7 +489,7 @@ function initRead(tlsSocket, socket) {
return;

// Socket already has some buffered data - emulate receiving it
if (socket && socket.readableLength) {
if (socket?.readableLength) {
let buf;
while ((buf = socket.read()) !== null)
tlsSocket._handle.receive(buf);
Expand Down Expand Up @@ -1683,7 +1683,7 @@ function onConnectSecure() {
if (!verifyError && !this.isSessionReused()) {
const hostname = options.servername ||
options.host ||
(options.socket && options.socket._host) ||
(options.socket?._host) ||
'localhost';
const cert = this.getPeerCertificate(true);
verifyError = options.checkServerIdentity(hostname, cert);
Expand Down
6 changes: 3 additions & 3 deletions lib/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ function expectedException(actual, expected, message, fn) {
message = 'The error is expected to be an instance of ' +
`"${expected.name}". Received `;
if (isError(actual)) {
const name = (actual.constructor && actual.constructor.name) ||
const name = (actual.constructor?.name) ||
actual.name;
if (expected.name === name) {
message += 'an error with identical name but a different prototype.';
Expand Down Expand Up @@ -569,7 +569,7 @@ function expectsError(stackStartFn, actual, error, message) {

if (actual === NO_EXCEPTION_SENTINEL) {
let details = '';
if (error && error.name) {
if (error?.name) {
details += ` (${error.name})`;
}
details += message ? `: ${message}` : '.';
Expand Down Expand Up @@ -627,7 +627,7 @@ function expectsNoError(stackStartFn, actual, error, message) {
expected: error,
operator: stackStartFn.name,
message: `Got unwanted ${fnType}${details}\n` +
`Actual message: "${actual && actual.message}"`,
`Actual message: "${actual?.message}"`,
stackStartFn,
});
}
Expand Down
8 changes: 3 additions & 5 deletions lib/child_process.js
Original file line number Diff line number Diff line change
Expand Up @@ -392,17 +392,15 @@ function execFile(file, args, options, callback) {
let stderr;
if (encoding ||
(
child.stdout &&
child.stdout.readableEncoding
child.stdout?.readableEncoding
)) {
stdout = ArrayPrototypeJoin(_stdout, '');
} else {
stdout = Buffer.concat(_stdout);
}
if (encoding ||
(
child.stderr &&
child.stderr.readableEncoding
child.stderr?.readableEncoding
)) {
stderr = ArrayPrototypeJoin(_stderr, '');
} else {
Expand Down Expand Up @@ -855,7 +853,7 @@ function spawnSync(file, args, options) {

// We may want to pass data in on any given fd, ensure it is a valid buffer
for (let i = 0; i < options.stdio.length; i++) {
const input = options.stdio[i] && options.stdio[i].input;
const input = options.stdio[i]?.input;
if (input != null) {
const pipe = options.stdio[i] = { ...options.stdio[i] };
if (isArrayBufferView(input)) {
Expand Down
4 changes: 2 additions & 2 deletions lib/dgram.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,8 @@ function Socket(type, listener) {
bindState: BIND_STATE_UNBOUND,
connectState: CONNECT_STATE_DISCONNECTED,
queue: undefined,
reuseAddr: options && options.reuseAddr, // Use UV_UDP_REUSEADDR if true.
ipv6Only: options && options.ipv6Only,
reuseAddr: options?.reuseAddr, // Use UV_UDP_REUSEADDR if true.
ipv6Only: options?.ipv6Only,
recvBufferSize,
sendBufferSize,
};
Expand Down
2 changes: 1 addition & 1 deletion lib/internal/bootstrap/switches/is_main_thread.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ function getStdin() {
// `stdin` starts out life in a paused state, but node doesn't
// know yet. Explicitly to readStop() it to put it in the
// not-reading state.
if (stdin._handle && stdin._handle.readStop) {
if (stdin._handle?.readStop) {
stdin._handle.reading = false;
stdin._readableState.reading = false;
stdin._handle.readStop();
Expand Down
8 changes: 4 additions & 4 deletions lib/internal/child_process.js
Original file line number Diff line number Diff line change
Expand Up @@ -854,7 +854,7 @@ function setupChannel(target, channel, serializationMode) {
if (handle) {
if (!this._handleQueue)
this._handleQueue = [];
if (obj && obj.postSend)
if (obj?.postSend)
obj.postSend(message, handle, options, callback, target);
}

Expand All @@ -870,7 +870,7 @@ function setupChannel(target, channel, serializationMode) {
}
} else {
// Cleanup handle on error
if (obj && obj.postSend)
if (obj?.postSend)
obj.postSend(message, handle, options, callback);

if (!options.swallowErrors) {
Expand Down Expand Up @@ -1115,8 +1115,8 @@ function spawnSync(options) {
}
}

result.stdout = result.output && result.output[1];
result.stderr = result.output && result.output[2];
result.stdout = result.output?.[1];
result.stderr = result.output?.[2];

if (result.error) {
result.error = new ErrnoException(result.error, 'spawnSync ' + options.file);
Expand Down
2 changes: 1 addition & 1 deletion lib/internal/cluster/child.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ cluster._getServer = function(obj, options, cb) {
cluster.worker.state = 'listening';
const address = obj.address();
message.act = 'listening';
message.port = (address && address.port) || options.port;
message.port = (address?.port) || options.port;
send(message);
});
};
Expand Down
2 changes: 1 addition & 1 deletion lib/internal/crypto/hashnames.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ function normalizeHashName(name, context = kHashContextNode) {
if (typeof name !== 'string')
return name;
name = StringPrototypeToLowerCase(name);
const alias = kHashNames[name] && kHashNames[name][context];
const alias = kHashNames[name]?.[context];
return alias || name;
}

Expand Down
4 changes: 2 additions & 2 deletions lib/internal/debugger/inspect_repl.js
Original file line number Diff line number Diff line change
Expand Up @@ -694,7 +694,7 @@ function createRepl(inspector) {

function handleBreakpointResolved({ breakpointId, location }) {
const script = knownScripts[location.scriptId];
const scriptUrl = script && script.url;
const scriptUrl = script?.url;
if (scriptUrl) {
ObjectAssign(location, { scriptUrl });
}
Expand Down Expand Up @@ -733,7 +733,7 @@ function createRepl(inspector) {
function setBreakpoint(script, line, condition, silent) {
function registerBreakpoint({ breakpointId, actualLocation }) {
handleBreakpointResolved({ breakpointId, location: actualLocation });
if (actualLocation && actualLocation.scriptId) {
if (actualLocation?.scriptId) {
if (!silent) return getSourceSnippet(actualLocation, 5);
} else {
print(`Warning: script '${script}' was not loaded yet.`);
Expand Down
2 changes: 1 addition & 1 deletion lib/internal/dns/callback_resolver.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ function resolver(bindingName) {
req.callback = callback;
req.hostname = name;
req.oncomplete = onresolve;
req.ttl = !!(options && options.ttl);
req.ttl = !!(options?.ttl);
const err = this._handle[bindingName](req, name);
if (err) throw new DNSException(err, bindingName, name);
if (hasObserver('dns')) {
Expand Down
2 changes: 1 addition & 1 deletion lib/internal/dns/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ function resolver(bindingName) {
function query(name, options) {
validateString(name, 'name');

const ttl = !!(options && options.ttl);
const ttl = !!(options?.ttl);
return createResolverPromise(this, bindingName, name, ttl);
}

Expand Down
4 changes: 2 additions & 2 deletions lib/internal/error_serdes.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ function GetConstructors(object) {
current !== null;
current = ObjectGetPrototypeOf(current)) {
const desc = ObjectGetOwnPropertyDescriptor(current, 'constructor');
if (desc && desc.value) {
if (desc?.value) {
ObjectDefineProperty(constructors, constructors.length, {
__proto__: null,
value: desc.value, enumerable: true,
Expand All @@ -98,7 +98,7 @@ function GetConstructors(object) {

function GetName(object) {
const desc = ObjectGetOwnPropertyDescriptor(object, 'name');
return desc && desc.value;
return desc?.value;
}

let internalUtilInspect;
Expand Down
2 changes: 1 addition & 1 deletion lib/internal/modules/esm/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ class ModuleLoader {
if (cjsModule) {
assert(finalFormat === 'commonjs-sync');
// Check if the ESM initiating import CJS is being required by the same CJS module.
if (cjsModule && cjsModule[kIsExecuting]) {
if (cjsModule?.[kIsExecuting]) {
const parentFilename = urlToFilename(parentURL);
let message = `Cannot import CommonJS Module ${specifier} in a cycle.`;
if (parentFilename) {
Expand Down
Loading

0 comments on commit 574f2dd

Please sign in to comment.