diff --git a/lib/_http_common.js b/lib/_http_common.js index 5ccf43e1d66668..3ae96f50f327d7 100644 --- a/lib/_http_common.js +++ b/lib/_http_common.js @@ -27,7 +27,7 @@ const { } = primordials; const { setImmediate } = require('timers'); -const { methods, allMethods, HTTPParser } = internalBinding('http_parser'); +const httpParserBinding = internalBinding('http_parser'); const { getOptionValue } = require('internal/options'); const insecureHTTPParser = getOptionValue('--insecure-http-parser'); @@ -40,13 +40,13 @@ const { } = incoming; const kIncomingMessage = Symbol('IncomingMessage'); -const kOnMessageBegin = HTTPParser.kOnMessageBegin | 0; -const kOnHeaders = HTTPParser.kOnHeaders | 0; -const kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; -const kOnBody = HTTPParser.kOnBody | 0; -const kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; -const kOnExecute = HTTPParser.kOnExecute | 0; -const kOnTimeout = HTTPParser.kOnTimeout | 0; +const kOnMessageBegin = httpParserBinding.HTTPParser.kOnMessageBegin | 0; +const kOnHeaders = httpParserBinding.HTTPParser.kOnHeaders | 0; +const kOnHeadersComplete = httpParserBinding.HTTPParser.kOnHeadersComplete | 0; +const kOnBody = httpParserBinding.HTTPParser.kOnBody | 0; +const kOnMessageComplete = httpParserBinding.HTTPParser.kOnMessageComplete | 0; +const kOnExecute = httpParserBinding.HTTPParser.kOnExecute | 0; +const kOnTimeout = httpParserBinding.HTTPParser.kOnTimeout | 0; const MAX_HEADER_PAIRS = 2000; @@ -108,7 +108,7 @@ function parserOnHeadersComplete(versionMajor, versionMinor, headers, method, if (typeof method === 'number') { // server only - incoming.method = allMethods[method]; + incoming.method = httpParserBinding.allMethods[method]; } else { // client only incoming.statusCode = statusCode; @@ -157,7 +157,7 @@ function parserOnMessageComplete() { const parsers = new FreeList('parsers', 1000, function parsersCb() { - const parser = new HTTPParser(); + const parser = new httpParserBinding.HTTPParser(); cleanParser(parser); @@ -261,10 +261,10 @@ module.exports = { continueExpression: /(?:^|\W)100-continue(?:$|\W)/i, CRLF: '\r\n', // TODO: Deprecate this. freeParser, - methods, + methods: httpParserBinding.methods, parsers, kIncomingMessage, - HTTPParser, + HTTPParser: httpParserBinding.HTTPParser, isLenient, prepareError, }; diff --git a/lib/_http_server.js b/lib/_http_server.js index b6e2ba69bc0648..865241b329f481 100644 --- a/lib/_http_server.js +++ b/lib/_http_server.js @@ -47,7 +47,7 @@ const { _checkInvalidHeaderChar: checkInvalidHeaderChar, prepareError, } = require('_http_common'); -const { ConnectionsList } = internalBinding('http_parser'); +const httpParserBinding = internalBinding('http_parser'); const { kUniqueHeaders, parseUniqueHeadersOption, @@ -509,7 +509,7 @@ function storeHTTPOptions(options) { function setupConnectionsTracking() { // Start connection handling if (!this[kConnections]) { - this[kConnections] = new ConnectionsList(); + this[kConnections] = new httpParserBinding.ConnectionsList(); } if (this[kConnectionsCheckingInterval]) { diff --git a/lib/_tls_common.js b/lib/_tls_common.js index 362b8e41893c0e..582dfa7f5835b9 100644 --- a/lib/_tls_common.js +++ b/lib/_tls_common.js @@ -27,22 +27,10 @@ const { const tls = require('tls'); -const { - codes: { - ERR_TLS_INVALID_PROTOCOL_VERSION, - ERR_TLS_PROTOCOL_VERSION_CONFLICT, - }, -} = require('internal/errors'); +// eslint-disable-next-line node-core/alphabetize-errors +const internalErrorsBinding = require('internal/errors'); -const { - crypto: { - SSL_OP_CIPHER_SERVER_PREFERENCE, - TLS1_VERSION, - TLS1_1_VERSION, - TLS1_2_VERSION, - TLS1_3_VERSION, - }, -} = internalBinding('constants'); +const constantsBinding = internalBinding('constants'); const { kEmptyObject, @@ -58,16 +46,14 @@ const { function toV(which, v, def) { if (v == null) v = def; - if (v === 'TLSv1') return TLS1_VERSION; - if (v === 'TLSv1.1') return TLS1_1_VERSION; - if (v === 'TLSv1.2') return TLS1_2_VERSION; - if (v === 'TLSv1.3') return TLS1_3_VERSION; - throw new ERR_TLS_INVALID_PROTOCOL_VERSION(v, which); + if (v === 'TLSv1') return constantsBinding.crypto.TLS1_VERSION; + if (v === 'TLSv1.1') return constantsBinding.crypto.TLS1_1_VERSION; + if (v === 'TLSv1.2') return constantsBinding.crypto.TLS1_2_VERSION; + if (v === 'TLSv1.3') return constantsBinding.crypto.TLS1_3_VERSION; + throw new internalErrorsBinding.codes.ERR_TLS_INVALID_PROTOCOL_VERSION(v, which); } -const { - SecureContext: NativeSecureContext, -} = internalBinding('crypto'); +const cryptoBinding = internalBinding('crypto'); function SecureContext(secureProtocol, secureOptions, minVersion, maxVersion) { if (!(this instanceof SecureContext)) { @@ -77,12 +63,12 @@ function SecureContext(secureProtocol, secureOptions, minVersion, maxVersion) { if (secureProtocol) { if (minVersion != null) - throw new ERR_TLS_PROTOCOL_VERSION_CONFLICT(minVersion, secureProtocol); + throw new internalErrorsBinding.codes.ERR_TLS_PROTOCOL_VERSION_CONFLICT(minVersion, secureProtocol); if (maxVersion != null) - throw new ERR_TLS_PROTOCOL_VERSION_CONFLICT(maxVersion, secureProtocol); + throw new internalErrorsBinding.codes.ERR_TLS_PROTOCOL_VERSION_CONFLICT(maxVersion, secureProtocol); } - this.context = new NativeSecureContext(); + this.context = new cryptoBinding.SecureContext(); this.context.init(secureProtocol, toV('minimum', minVersion, tls.DEFAULT_MIN_VERSION), toV('maximum', maxVersion, tls.DEFAULT_MAX_VERSION)); @@ -106,7 +92,7 @@ function createSecureContext(options) { let { secureOptions } = options; if (honorCipherOrder) - secureOptions |= SSL_OP_CIPHER_SERVER_PREFERENCE; + secureOptions |= constantsBinding.crypto.SSL_OP_CIPHER_SERVER_PREFERENCE; const c = new SecureContext(secureProtocol, secureOptions, minVersion, maxVersion); diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index 2273b3c91b62b4..079a7aae31fe9a 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -52,12 +52,12 @@ const { Buffer } = require('buffer'); let debug = require('internal/util/debuglog').debuglog('tls', (fn) => { debug = fn; }); -const { TCP, constants: TCPConstants } = internalBinding('tcp_wrap'); +const tcpWrapBinding = internalBinding('tcp_wrap'); const tls_wrap = internalBinding('tls_wrap'); -const { Pipe, constants: PipeConstants } = internalBinding('pipe_wrap'); -const { owner_symbol } = require('internal/async_hooks').symbols; -const { isArrayBufferView } = require('internal/util/types'); -const { SecureContext: NativeSecureContext } = internalBinding('crypto'); +const pipeWrapBinding = internalBinding('pipe_wrap'); +const asyncHooksBinding = require('internal/async_hooks').symbols; +const utilBinding = require('internal/util/types'); +const cryptoBinding = internalBinding('crypto'); const { ConnResetException, codes: { @@ -77,7 +77,7 @@ const { ERR_TLS_SNI_FROM_SERVER, }, } = require('internal/errors'); -const { onpskexchange: kOnPskExchange } = internalBinding('symbols'); +const symbolsBinding = internalBinding('symbols'); const { getOptionValue, getAllowUnauthorized, @@ -136,7 +136,7 @@ function onhandshakestart(now) { else this.handshakes++; - const owner = this[owner_symbol]; + const owner = this[asyncHooksBinding.owner_symbol]; assert(owner._tlsOptions.isServer); @@ -152,7 +152,7 @@ function onhandshakestart(now) { function onhandshakedone() { debug('server onhandshakedone'); - const owner = this[owner_symbol]; + const owner = this[asyncHooksBinding.owner_symbol]; assert(owner._tlsOptions.isServer); // `newSession` callback wasn't called yet @@ -170,7 +170,7 @@ function loadSession(hello) { 'sessionid.len', hello.sessionId.length, 'ticket?', hello.tlsTicket, ); - const owner = this[owner_symbol]; + const owner = this[asyncHooksBinding.owner_symbol]; let once = false; function onSession(err, session) { @@ -205,7 +205,7 @@ function loadSession(hello) { function loadSNI(info) { - const owner = this[owner_symbol]; + const owner = this[asyncHooksBinding.owner_symbol]; const servername = info.servername; if (!servername || !owner._SNICallback) return requestOCSP(owner, info); @@ -233,7 +233,7 @@ function loadSNI(info) { function callALPNCallback(protocolsBuffer) { const handle = this; - const socket = handle[owner_symbol]; + const socket = handle[asyncHooksBinding.owner_symbol]; const servername = handle.getServername(); @@ -331,7 +331,7 @@ function requestOCSPDone(socket) { function onnewsessionclient(sessionId, session) { debug('client emit session'); - const owner = this[owner_symbol]; + const owner = this[asyncHooksBinding.owner_symbol]; if (owner[kIsVerified]) { owner.emit('session', session); } else { @@ -341,7 +341,7 @@ function onnewsessionclient(sessionId, session) { function onnewsession(sessionId, session) { debug('onnewsession'); - const owner = this[owner_symbol]; + const owner = this[asyncHooksBinding.owner_symbol]; // TODO(@sam-github) no server to emit the event on, but handshake won't // continue unless newSessionDone() is called, should it be, or is that @@ -373,13 +373,13 @@ function onnewsession(sessionId, session) { } function onPskServerCallback(identity, maxPskLen) { - const owner = this[owner_symbol]; + const owner = this[asyncHooksBinding.owner_symbol]; const ret = owner[kPskCallback](owner, identity); if (ret == null) return undefined; let psk; - if (isArrayBufferView(ret)) { + if (utilBinding.isArrayBufferView(ret)) { psk = ret; } else { if (typeof ret !== 'object') { @@ -405,7 +405,7 @@ function onPskServerCallback(identity, maxPskLen) { } function onPskClientCallback(hint, maxPskLen, maxIdentityLen) { - const owner = this[owner_symbol]; + const owner = this[asyncHooksBinding.owner_symbol]; const ret = owner[kPskCallback](hint); if (ret == null) return undefined; @@ -435,16 +435,16 @@ function onPskClientCallback(hint, maxPskLen, maxIdentityLen) { function onkeylog(line) { debug('onkeylog'); - this[owner_symbol].emit('keylog', line); + this[asyncHooksBinding.owner_symbol].emit('keylog', line); } function onocspresponse(resp) { debug('client onocspresponse'); - this[owner_symbol].emit('OCSPResponse', resp); + this[asyncHooksBinding.owner_symbol].emit('OCSPResponse', resp); } function onerror(err) { - const owner = this[owner_symbol]; + const owner = this[asyncHooksBinding.owner_symbol]; debug('%s onerror %s had? %j', (typeof owner._tlsOptions === 'object' && owner._tlsOptions !== null) ? owner._tlsOptions.isServer ? 'server' : 'client' : @@ -631,9 +631,9 @@ for (const proxiedMethod of proxiedMethods) { tls_wrap.TLSWrap.prototype.close = function close(cb) { let ssl; - if (this[owner_symbol]) { - ssl = this[owner_symbol].ssl; - this[owner_symbol].ssl = null; + if (this[asyncHooksBinding.owner_symbol]) { + ssl = this[asyncHooksBinding.owner_symbol].ssl; + this[asyncHooksBinding.owner_symbol].ssl = null; } // Invoke `destroySSL` on close to clean up possibly pending write requests @@ -682,9 +682,9 @@ TLSSocket.prototype._wrapHandle = function(wrap, handle, wrapHasActiveWriteFromP const options = this._tlsOptions; if (!handle) { handle = options.pipe ? - new Pipe(PipeConstants.SOCKET) : - new TCP(TCPConstants.SOCKET); - handle[owner_symbol] = this; + new pipeWrapBinding.Pipe(pipeWrapBinding.constants.SOCKET) : + new tcpWrapBinding.TCP(tcpWrapBinding.constants.SOCKET); + handle[asyncHooksBinding.owner_symbol] = this; } // Wrap socket's handle @@ -692,7 +692,7 @@ TLSSocket.prototype._wrapHandle = function(wrap, handle, wrapHasActiveWriteFromP options.credentials || tls.createSecureContext(options); assert(handle.isStreamBase, 'handle must be a StreamBase'); - if (!(context.context instanceof NativeSecureContext)) { + if (!(context.context instanceof cryptoBinding.SecureContext)) { throw new ERR_TLS_INVALID_CONTEXT('context'); } @@ -913,7 +913,7 @@ TLSSocket.prototype._init = function(socket, wrap) { if (options.pskCallback && ssl.enablePskCallback) { validateFunction(options.pskCallback, 'pskCallback'); - ssl[kOnPskExchange] = options.isServer ? + ssl[symbolsBinding.onpskexchange] = options.isServer ? onPskServerCallback : onPskClientCallback; this[kPskCallback] = options.pskCallback; diff --git a/lib/buffer.js b/lib/buffer.js index 823a9249eccc52..2cff5ff95c183e 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -52,41 +52,9 @@ const { Uint8ArrayPrototype, } = primordials; -const { - byteLengthUtf8, - compare: _compare, - compareOffset, - createFromString, - fill: bindingFill, - isAscii: bindingIsAscii, - isUtf8: bindingIsUtf8, - indexOfBuffer, - indexOfNumber, - indexOfString, - swap16: _swap16, - swap32: _swap32, - swap64: _swap64, - kMaxLength, - kStringMaxLength, - atob: _atob, - btoa: _btoa, -} = internalBinding('buffer'); -const { - constants: { - ALL_PROPERTIES, - ONLY_ENUMERABLE, - }, - getOwnNonIndexProperties, -} = internalBinding('util'); -const { - customInspectSymbol, - isInsideNodeModules, - lazyDOMException, - normalizeEncoding, - kIsEncodingSymbol, - defineLazyProperties, - encodingsMap, -} = require('internal/util'); +const bufferBinding = internalBinding('buffer'); +const utilBinding = internalBinding('util'); +const internalUtilBinding = require('internal/util'); const { isAnyArrayBuffer, isArrayBufferView, @@ -117,7 +85,7 @@ const { validateString, } = require('internal/validators'); // Provide validateInteger() but with kMaxLength as the default maximum value. -const validateOffset = (value, name, min = 0, max = kMaxLength) => +const validateOffset = (value, name, min = 0, max = bufferBinding.kMaxLength) => validateInteger(value, name, min, max); const { @@ -134,13 +102,13 @@ addBufferPrototypeMethods(Buffer.prototype); const constants = ObjectDefineProperties({}, { MAX_LENGTH: { __proto__: null, - value: kMaxLength, + value: bufferBinding.kMaxLength, writable: false, enumerable: true, }, MAX_STRING_LENGTH: { __proto__: null, - value: kStringMaxLength, + value: bufferBinding.kStringMaxLength, writable: false, enumerable: true, }, @@ -175,7 +143,7 @@ function showFlaggedDeprecation() { if (bufferWarningAlreadyEmitted || ++nodeModulesCheckCounter > 10000 || (!require('internal/options').getOptionValue('--pending-deprecation') && - isInsideNodeModules())) { + internalUtilBinding.isInsideNodeModules())) { // We don't emit a warning, because we either: // - Already did so, or // - Already checked too many times whether a call is coming @@ -386,7 +354,7 @@ ObjectSetPrototypeOf(Buffer, Uint8Array); * alloc(size[, fill[, encoding]]) */ Buffer.alloc = function alloc(size, fill, encoding) { - validateNumber(size, 'size', 0, kMaxLength); + validateNumber(size, 'size', 0, bufferBinding.kMaxLength); if (fill !== undefined && fill !== 0 && size > 0) { const buf = createUnsafeBuffer(size); return _fill(buf, fill, 0, buf.length, encoding); @@ -399,7 +367,7 @@ Buffer.alloc = function alloc(size, fill, encoding) { * instance. If `--zero-fill-buffers` is set, will zero-fill the buffer. */ Buffer.allocUnsafe = function allocUnsafe(size) { - validateNumber(size, 'size', 0, kMaxLength); + validateNumber(size, 'size', 0, bufferBinding.kMaxLength); return allocate(size); }; @@ -409,14 +377,14 @@ Buffer.allocUnsafe = function allocUnsafe(size) { * If `--zero-fill-buffers` is set, will zero-fill the buffer. */ Buffer.allocUnsafeSlow = function allocUnsafeSlow(size) { - validateNumber(size, 'size', 0, kMaxLength); + validateNumber(size, 'size', 0, bufferBinding.kMaxLength); return createUnsafeBuffer(size); }; // If --zero-fill-buffers command line argument is set, a zero-filled // buffer is returned. function SlowBuffer(size) { - validateNumber(size, 'size', 0, kMaxLength); + validateNumber(size, 'size', 0, bufferBinding.kMaxLength); return createUnsafeBuffer(size); } @@ -442,7 +410,7 @@ function fromStringFast(string, ops) { const length = ops.byteLength(string); if (length >= (Buffer.poolSize >>> 1)) - return createFromString(string, ops.encodingVal); + return bufferBinding.createFromString(string, ops.encodingVal); if (length > (poolSize - poolOffset)) createPool(); @@ -551,14 +519,14 @@ Buffer.compare = function compare(buf1, buf2) { return 0; } - return _compare(buf1, buf2); + return bufferBinding.compare(buf1, buf2); }; Buffer.isEncoding = function isEncoding(encoding) { return typeof encoding === 'string' && encoding.length !== 0 && - normalizeEncoding(encoding) !== undefined; + internalUtilBinding.normalizeEncoding(encoding) !== undefined; }; -Buffer[kIsEncodingSymbol] = Buffer.isEncoding; +Buffer[internalUtilBinding.kIsEncodingSymbol] = Buffer.isEncoding; Buffer.concat = function concat(list, length) { validateArray(list, 'list'); @@ -615,92 +583,92 @@ function base64ByteLength(str, bytes) { const encodingOps = { utf8: { encoding: 'utf8', - encodingVal: encodingsMap.utf8, - byteLength: byteLengthUtf8, + encodingVal: internalUtilBinding.encodingsMap.utf8, + byteLength: bufferBinding.byteLengthUtf8, write: (buf, string, offset, len) => buf.utf8Write(string, offset, len), slice: (buf, start, end) => buf.utf8Slice(start, end), indexOf: (buf, val, byteOffset, dir) => - indexOfString(buf, val, byteOffset, encodingsMap.utf8, dir), + bufferBinding.indexOfString(buf, val, byteOffset, internalUtilBinding.encodingsMap.utf8, dir), }, ucs2: { encoding: 'ucs2', - encodingVal: encodingsMap.utf16le, + encodingVal: internalUtilBinding.encodingsMap.utf16le, byteLength: (string) => string.length * 2, write: (buf, string, offset, len) => buf.ucs2Write(string, offset, len), slice: (buf, start, end) => buf.ucs2Slice(start, end), indexOf: (buf, val, byteOffset, dir) => - indexOfString(buf, val, byteOffset, encodingsMap.utf16le, dir), + bufferBinding.indexOfString(buf, val, byteOffset, internalUtilBinding.encodingsMap.utf16le, dir), }, utf16le: { encoding: 'utf16le', - encodingVal: encodingsMap.utf16le, + encodingVal: internalUtilBinding.encodingsMap.utf16le, byteLength: (string) => string.length * 2, write: (buf, string, offset, len) => buf.ucs2Write(string, offset, len), slice: (buf, start, end) => buf.ucs2Slice(start, end), indexOf: (buf, val, byteOffset, dir) => - indexOfString(buf, val, byteOffset, encodingsMap.utf16le, dir), + bufferBinding.indexOfString(buf, val, byteOffset, internalUtilBinding.encodingsMap.utf16le, dir), }, latin1: { encoding: 'latin1', - encodingVal: encodingsMap.latin1, + encodingVal: internalUtilBinding.encodingsMap.latin1, byteLength: (string) => string.length, write: (buf, string, offset, len) => buf.latin1Write(string, offset, len), slice: (buf, start, end) => buf.latin1Slice(start, end), indexOf: (buf, val, byteOffset, dir) => - indexOfString(buf, val, byteOffset, encodingsMap.latin1, dir), + bufferBinding.indexOfString(buf, val, byteOffset, internalUtilBinding.encodingsMap.latin1, dir), }, ascii: { encoding: 'ascii', - encodingVal: encodingsMap.ascii, + encodingVal: internalUtilBinding.encodingsMap.ascii, byteLength: (string) => string.length, write: (buf, string, offset, len) => buf.asciiWrite(string, offset, len), slice: (buf, start, end) => buf.asciiSlice(start, end), indexOf: (buf, val, byteOffset, dir) => - indexOfBuffer(buf, - fromStringFast(val, encodingOps.ascii), - byteOffset, - encodingsMap.ascii, - dir), + bufferBinding.indexOfBuffer(buf, + fromStringFast(val, encodingOps.ascii), + byteOffset, + internalUtilBinding.encodingsMap.ascii, + dir), }, base64: { encoding: 'base64', - encodingVal: encodingsMap.base64, + encodingVal: internalUtilBinding.encodingsMap.base64, byteLength: (string) => base64ByteLength(string, string.length), write: (buf, string, offset, len) => buf.base64Write(string, offset, len), slice: (buf, start, end) => buf.base64Slice(start, end), indexOf: (buf, val, byteOffset, dir) => - indexOfBuffer(buf, - fromStringFast(val, encodingOps.base64), - byteOffset, - encodingsMap.base64, - dir), + bufferBinding.indexOfBuffer(buf, + fromStringFast(val, encodingOps.base64), + byteOffset, + internalUtilBinding.encodingsMap.base64, + dir), }, base64url: { encoding: 'base64url', - encodingVal: encodingsMap.base64url, + encodingVal: internalUtilBinding.encodingsMap.base64url, byteLength: (string) => base64ByteLength(string, string.length), write: (buf, string, offset, len) => buf.base64urlWrite(string, offset, len), slice: (buf, start, end) => buf.base64urlSlice(start, end), indexOf: (buf, val, byteOffset, dir) => - indexOfBuffer(buf, - fromStringFast(val, encodingOps.base64url), - byteOffset, - encodingsMap.base64url, - dir), + bufferBinding.indexOfBuffer(buf, + fromStringFast(val, encodingOps.base64url), + byteOffset, + internalUtilBinding.encodingsMap.base64url, + dir), }, hex: { encoding: 'hex', - encodingVal: encodingsMap.hex, + encodingVal: internalUtilBinding.encodingsMap.hex, byteLength: (string) => string.length >>> 1, write: (buf, string, offset, len) => buf.hexWrite(string, offset, len), slice: (buf, start, end) => buf.hexSlice(start, end), indexOf: (buf, val, byteOffset, dir) => - indexOfBuffer(buf, - fromStringFast(val, encodingOps.hex), - byteOffset, - encodingsMap.hex, - dir), + bufferBinding.indexOfBuffer(buf, + fromStringFast(val, encodingOps.hex), + byteOffset, + internalUtilBinding.encodingsMap.hex, + dir), }, }; function getEncodingOps(encoding) { @@ -774,7 +742,7 @@ function byteLength(string, encoding) { return ops.byteLength(string); } } - return byteLengthUtf8(string); + return bufferBinding.byteLengthUtf8(string); } Buffer.byteLength = byteLength; @@ -852,12 +820,12 @@ Buffer.prototype.equals = function equals(otherBuffer) { if (len !== TypedArrayPrototypeGetByteLength(otherBuffer)) return false; - return len === 0 || _compare(this, otherBuffer) === 0; + return len === 0 || bufferBinding.compare(this, otherBuffer) === 0; }; let INSPECT_MAX_BYTES = 50; // Override how buffers are presented by util.inspect(). -Buffer.prototype[customInspectSymbol] = function inspect(recurseTimes, ctx) { +Buffer.prototype[internalUtilBinding.customInspectSymbol] = function inspect(recurseTimes, ctx) { const max = INSPECT_MAX_BYTES; const actualMax = MathMin(max, this.length); const remaining = this.length - max; @@ -868,9 +836,9 @@ Buffer.prototype[customInspectSymbol] = function inspect(recurseTimes, ctx) { // Inspect special properties as well, if possible. if (ctx) { let extras = false; - const filter = ctx.showHidden ? ALL_PROPERTIES : ONLY_ENUMERABLE; + const filter = ctx.showHidden ? utilBinding.constants.ALL_PROPERTIES : utilBinding.constants.ONLY_ENUMERABLE; const obj = { __proto__: null }; - ArrayPrototypeForEach(getOwnNonIndexProperties(this, filter), + ArrayPrototypeForEach(utilBinding.getOwnNonIndexProperties(this, filter), (key) => { extras = true; obj[key] = this[key]; @@ -889,7 +857,7 @@ Buffer.prototype[customInspectSymbol] = function inspect(recurseTimes, ctx) { } return `<${this.constructor.name} ${str}>`; }; -Buffer.prototype.inspect = Buffer.prototype[customInspectSymbol]; +Buffer.prototype.inspect = Buffer.prototype[internalUtilBinding.customInspectSymbol]; Buffer.prototype.compare = function compare(target, targetStart, @@ -900,7 +868,7 @@ Buffer.prototype.compare = function compare(target, throw new ERR_INVALID_ARG_TYPE('target', ['Buffer', 'Uint8Array'], target); } if (arguments.length === 1) - return _compare(this, target); + return bufferBinding.compare(this, target); if (targetStart === undefined) targetStart = 0; @@ -927,8 +895,8 @@ Buffer.prototype.compare = function compare(target, if (targetStart >= targetEnd) return 1; - return compareOffset(this, target, targetStart, sourceStart, targetEnd, - sourceEnd); + return bufferBinding.compareOffset(this, target, targetStart, sourceStart, targetEnd, + sourceEnd); }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, @@ -960,7 +928,7 @@ function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { dir = !!dir; // Cast to bool. if (typeof val === 'number') - return indexOfNumber(buffer, val >>> 0, byteOffset, dir); + return bufferBinding.indexOfNumber(buffer, val >>> 0, byteOffset, dir); let ops; if (encoding === undefined) @@ -976,8 +944,8 @@ function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { if (isUint8Array(val)) { const encodingVal = - (ops === undefined ? encodingsMap.utf8 : ops.encodingVal); - return indexOfBuffer(buffer, val, byteOffset, encodingVal, dir); + (ops === undefined ? internalUtilBinding.encodingsMap.utf8 : ops.encodingVal); + return bufferBinding.indexOfBuffer(buffer, val, byteOffset, encodingVal, dir); } throw new ERR_INVALID_ARG_TYPE( @@ -1016,7 +984,7 @@ function _fill(buf, value, offset, end, encoding) { end = buf.length; } - const normalizedEncoding = normalizeEncoding(encoding); + const normalizedEncoding = internalUtilBinding.normalizeEncoding(encoding); if (normalizedEncoding === undefined) { validateString(encoding, 'encoding'); throw new ERR_UNKNOWN_ENCODING(encoding); @@ -1065,7 +1033,7 @@ function _fill(buf, value, offset, end, encoding) { TypedArrayPrototypeFill(buf, value, offset, end); } else { - const res = bindingFill(buf, value, offset, end, encoding); + const res = bufferBinding.fill(buf, value, offset, end, encoding); if (res < 0) { if (res === -1) throw new ERR_INVALID_ARG_VALUE('value', value); @@ -1171,7 +1139,7 @@ Buffer.prototype.swap16 = function swap16() { swap(this, i, i + 1); return this; } - return _swap16(this); + return bufferBinding.swap16(this); }; Buffer.prototype.swap32 = function swap32() { @@ -1188,7 +1156,7 @@ Buffer.prototype.swap32 = function swap32() { } return this; } - return _swap32(this); + return bufferBinding.swap32(this); }; Buffer.prototype.swap64 = function swap64() { @@ -1207,17 +1175,14 @@ Buffer.prototype.swap64 = function swap64() { } return this; } - return _swap64(this); + return bufferBinding.swap64(this); }; Buffer.prototype.toLocaleString = Buffer.prototype.toString; let transcode; if (internalBinding('config').hasIntl) { - const { - icuErrName, - transcode: _transcode, - } = internalBinding('icu'); + const icuBinding = internalBinding('icu'); // Transcodes the Buffer from one encoding to another, returning a new // Buffer instance. @@ -1228,13 +1193,13 @@ if (internalBinding('config').hasIntl) { } if (source.length === 0) return Buffer.alloc(0); - fromEncoding = normalizeEncoding(fromEncoding) || fromEncoding; - toEncoding = normalizeEncoding(toEncoding) || toEncoding; - const result = _transcode(source, fromEncoding, toEncoding); + fromEncoding = internalUtilBinding.normalizeEncoding(fromEncoding) || fromEncoding; + toEncoding = internalUtilBinding.normalizeEncoding(toEncoding) || toEncoding; + const result = icuBinding.transcode(source, fromEncoding, toEncoding); if (typeof result !== 'number') return result; - const code = icuErrName(result); + const code = icuBinding.icuErrName(result); const err = genericNodeError( `Unable to transcode Buffer [${code}]`, { code: code, errno: result }, @@ -1250,9 +1215,9 @@ function btoa(input) { if (arguments.length === 0) { throw new ERR_MISSING_ARGS('input'); } - const result = _btoa(`${input}`); + const result = bufferBinding.btoa(`${input}`); if (result === -1) { - throw lazyDOMException('Invalid character', 'InvalidCharacterError'); + throw internalUtilBinding.lazyDOMException('Invalid character', 'InvalidCharacterError'); } return result; } @@ -1262,18 +1227,18 @@ function atob(input) { throw new ERR_MISSING_ARGS('input'); } - const result = _atob(`${input}`); + const result = bufferBinding.atob(`${input}`); switch (result) { case -2: // Invalid character - throw lazyDOMException('Invalid character', 'InvalidCharacterError'); + throw internalUtilBinding.lazyDOMException('Invalid character', 'InvalidCharacterError'); case -1: // Single character remained - throw lazyDOMException( + throw internalUtilBinding.lazyDOMException( 'The string to be decoded is not correctly encoded.', 'InvalidCharacterError'); case -3: // Possible overflow // TODO(@anonrig): Throw correct error in here. - throw lazyDOMException('The input causes overflow.', 'InvalidCharacterError'); + throw internalUtilBinding.lazyDOMException('The input causes overflow.', 'InvalidCharacterError'); default: return result; } @@ -1281,7 +1246,7 @@ function atob(input) { function isUtf8(input) { if (isTypedArray(input) || isAnyArrayBuffer(input)) { - return bindingIsUtf8(input); + return bufferBinding.isUtf8(input); } throw new ERR_INVALID_ARG_TYPE('input', ['ArrayBuffer', 'Buffer', 'TypedArray'], input); @@ -1289,7 +1254,7 @@ function isUtf8(input) { function isAscii(input) { if (isTypedArray(input) || isAnyArrayBuffer(input)) { - return bindingIsAscii(input); + return bufferBinding.isAscii(input); } throw new ERR_INVALID_ARG_TYPE('input', ['ArrayBuffer', 'Buffer', 'TypedArray'], input); @@ -1303,8 +1268,8 @@ module.exports = { isAscii, // Legacy - kMaxLength, - kStringMaxLength, + kMaxLength: bufferBinding.kMaxLength, + kStringMaxLength: bufferBinding.kStringMaxLength, btoa, atob, }; @@ -1328,12 +1293,12 @@ ObjectDefineProperties(module.exports, { }, }); -defineLazyProperties( +internalUtilBinding.defineLazyProperties( module.exports, 'internal/blob', ['Blob', 'resolveObjectURL'], ); -defineLazyProperties( +internalUtilBinding.defineLazyProperties( module.exports, 'internal/file', ['File'], diff --git a/lib/child_process.js b/lib/child_process.js index 41206dc7eda1f7..c13e1dc1b465c2 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -60,7 +60,7 @@ let debug = require('internal/util/debuglog').debuglog( }, ); const { Buffer } = require('buffer'); -const { Pipe, constants: PipeConstants } = internalBinding('pipe_wrap'); +const pipeWrapBinding = internalBinding('pipe_wrap'); const { AbortError, @@ -173,7 +173,7 @@ function fork(modulePath, args = [], options) { function _forkChild(fd, serializationMode) { // set process.send() - const p = new Pipe(PipeConstants.IPC); + const p = new pipeWrapBinding.Pipe(pipeWrapBinding.constants.IPC); p.open(fd); p.unref(); const control = setupChannel(process, p, serializationMode); diff --git a/lib/crypto.js b/lib/crypto.js index 73c2525e082e9c..fa9abc5b8a9b74 100644 --- a/lib/crypto.js +++ b/lib/crypto.js @@ -41,11 +41,7 @@ const { } = require('internal/errors').codes; const constants = internalBinding('constants').crypto; const { getOptionValue } = require('internal/options'); -const { - getFipsCrypto, - setFipsCrypto, - timingSafeEqual, -} = internalBinding('crypto'); +const cryptoBinding = internalBinding('crypto'); const { checkPrime, checkPrimeSync, @@ -216,7 +212,7 @@ module.exports = { scryptSync, sign: signOneShot, setEngine, - timingSafeEqual, + timingSafeEqual: cryptoBinding.timingSafeEqual, getFips, setFips, verify: verifyOneShot, @@ -241,7 +237,7 @@ module.exports = { }; function getFips() { - return getOptionValue('--force-fips') ? 1 : getFipsCrypto(); + return getOptionValue('--force-fips') ? 1 : cryptoBinding.getFipsCrypto(); } function setFips(val) { @@ -252,7 +248,7 @@ function setFips(val) { if (!lazyOwnsProcessState()) { throw new ERR_WORKER_UNSUPPORTED_OPERATION('Calling crypto.setFips()'); } - setFipsCrypto(val); + cryptoBinding.setFipsCrypto(val); } } diff --git a/lib/dgram.js b/lib/dgram.js index 9b411246afc545..f360a3f25d97df 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -73,11 +73,7 @@ const { } = require('internal/async_hooks'); const { UV_UDP_REUSEADDR } = internalBinding('constants').os; -const { - constants: { UV_UDP_IPV6ONLY }, - UDP, - SendWrap, -} = internalBinding('udp_wrap'); +const udpWrap = internalBinding('udp_wrap'); const dc = require('diagnostics_channel'); const udpSocketChannel = dc.channel('udp.socket'); @@ -345,7 +341,7 @@ Socket.prototype.bind = function(port_, address_ /* , callback */) { if (state.reuseAddr) flags |= UV_UDP_REUSEADDR; if (state.ipv6Only) - flags |= UV_UDP_IPV6ONLY; + flags |= udpWrap.constants.UV_UDP_IPV6ONLY; if (cluster.isWorker && !exclusive) { bindServerHandle(this, { @@ -692,7 +688,7 @@ function doSend(ex, self, ip, list, address, port, callback) { return; } - const req = new SendWrap(); + const req = new udpWrap.SendWrap(); req.list = list; // Keep reference alive. req.address = address; req.port = port; @@ -1066,7 +1062,7 @@ Socket.prototype._stopReceiving = deprecate(function() { // Legacy alias on the C++ wrapper object. This is not public API, so we may // want to runtime-deprecate it at some point. There's no hurry, though. -ObjectDefineProperty(UDP.prototype, 'owner', { +ObjectDefineProperty(udpWrap.UDP.prototype, 'owner', { __proto__: null, get() { return this[owner_symbol]; }, set(v) { return this[owner_symbol] = v; }, diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index 59a95b08226e6b..010dd7eec7dd09 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -27,7 +27,7 @@ const { validateFunction, } = require('internal/validators'); -const { triggerUncaughtException } = internalBinding('errors'); +const errorsBinding = internalBinding('errors'); const { WeakReference } = require('internal/util'); @@ -84,7 +84,7 @@ function wrapStoreRun(store, data, next, transform = defaultTransform) { context = transform(data); } catch (err) { process.nextTick(() => { - triggerUncaughtException(err, false); + errorsBinding.triggerUncaughtException(err, false); }); return next(); } @@ -143,7 +143,7 @@ class ActiveChannel { onMessage(data, this.name); } catch (err) { process.nextTick(() => { - triggerUncaughtException(err, false); + errorsBinding.triggerUncaughtException(err, false); }); } } diff --git a/lib/eslint.config_partial.mjs b/lib/eslint.config_partial.mjs index a51fafafaf1592..5ee36c31c76107 100644 --- a/lib/eslint.config_partial.mjs +++ b/lib/eslint.config_partial.mjs @@ -509,4 +509,18 @@ export default [ ], }, }, + { + files: [ + 'lib/*.js', + ], + rules: { + 'no-restricted-syntax': [ + ...noRestrictedSyntax, + { + selector: 'VariableDeclarator:has(.init.callee[name="internalBinding"]) > ObjectPattern', + message: 'We should not destructure internalBinding objects', + }, + ], + }, + }, ]; diff --git a/lib/fs.js b/lib/fs.js index 2119554c0e72c1..49eb7a61a4936b 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -43,7 +43,7 @@ const { uncurryThis, } = primordials; -const { fs: constants } = internalBinding('constants'); +const constantsBinding = internalBinding('constants'); const { S_IFIFO, S_IFLNK, @@ -56,13 +56,13 @@ const { X_OK, O_WRONLY, O_SYMLINK, -} = constants; +} = constantsBinding.fs; const pathModule = require('path'); const { isAbsolute } = pathModule; const { isArrayBufferView } = require('internal/util/types'); -const binding = internalBinding('fs'); +const fsBinding = internalBinding('fs'); const { createBlobFromFilePath } = require('internal/blob'); @@ -79,10 +79,6 @@ const { }, } = require('internal/errors'); -const { - FSReqCallback, - statValues, -} = binding; const { toPathIfFileURL } = require('internal/url'); const { customPromisifyArgs: kCustomPromisifyArgsSymbol, @@ -227,9 +223,9 @@ function access(path, mode, callback) { path = getValidatedPath(path); callback = makeCallback(callback); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.access(path, mode, req); + fsBinding.access(path, mode, req); } /** @@ -240,7 +236,7 @@ function access(path, mode, callback) { * @returns {void} */ function accessSync(path, mode) { - binding.access(getValidatedPath(path), mode); + fsBinding.access(getValidatedPath(path), mode); } /** @@ -288,7 +284,7 @@ function existsSync(path) { return false; } - return binding.existsSync(path); + return fsBinding.existsSync(path); } function readFileAfterOpen(err, fd) { @@ -301,10 +297,10 @@ function readFileAfterOpen(err, fd) { context.fd = fd; - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = readFileAfterStat; req.context = context; - binding.fstat(fd, false, req); + fsBinding.fstat(fd, false, req); } function readFileAfterStat(err, stats) { @@ -381,14 +377,14 @@ function readFile(path, options, callback) { return; const flagsNumber = stringToFlags(options.flag, 'options.flag'); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.context = context; req.oncomplete = readFileAfterOpen; - binding.open(getValidatedPath(path), flagsNumber, 0o666, req); + fsBinding.open(getValidatedPath(path), flagsNumber, 0o666, req); } function tryStatSync(fd, isUserFd) { - const stats = binding.fstat(fd, false, undefined, true /* shouldNotThrow */); + const stats = fsBinding.fstat(fd, false, undefined, true /* shouldNotThrow */); if (stats === undefined && !isUserFd) { fs.closeSync(fd); } @@ -438,7 +434,7 @@ function readFileSync(path, options) { if (!isInt32(path)) { path = getValidatedPath(path); } - return binding.readFileUtf8(path, stringToFlags(options.flag)); + return fsBinding.readFileUtf8(path, stringToFlags(options.flag)); } const isUserFd = isFd(path); // File descriptor ownership @@ -504,9 +500,9 @@ function close(fd, callback = defaultCloseCallback) { if (callback !== defaultCloseCallback) callback = makeCallback(callback); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.close(fd, req); + fsBinding.close(fd, req); } /** @@ -515,7 +511,7 @@ function close(fd, callback = defaultCloseCallback) { * @returns {void} */ function closeSync(fd) { - binding.close(fd); + fsBinding.close(fd); } /** @@ -544,10 +540,10 @@ function open(path, flags, mode, callback) { const flagsNumber = stringToFlags(flags); callback = makeCallback(callback); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.open(path, flagsNumber, mode, req); + fsBinding.open(path, flagsNumber, mode, req); } /** @@ -558,7 +554,7 @@ function open(path, flags, mode, callback) { * @returns {number} */ function openSync(path, flags, mode) { - return binding.open( + return fsBinding.open( getValidatedPath(path), stringToFlags(flags), parseFileMode(mode, 'mode', 0o666), @@ -671,10 +667,10 @@ function read(fd, buffer, offsetOrOptions, length, position, callback) { callback(err, bytesRead || 0, buffer); } - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = wrapper; - binding.read(fd, buffer, offset, length, position, req); + fsBinding.read(fd, buffer, offset, length, position, req); } ObjectDefineProperty(read, kCustomPromisifyArgsSymbol, @@ -737,7 +733,7 @@ function readSync(fd, buffer, offsetOrOptions, length, position) { validatePosition(position, 'position', length); } - return binding.read(fd, buffer, offset, length, position); + return fsBinding.read(fd, buffer, offset, length, position); } /** @@ -763,13 +759,13 @@ function readv(fd, buffers, position, callback) { callback ||= position; validateFunction(callback, 'cb'); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = wrapper; if (typeof position !== 'number') position = null; - binding.readBuffers(fd, buffers, position, req); + fsBinding.readBuffers(fd, buffers, position, req); } ObjectDefineProperty(readv, kCustomPromisifyArgsSymbol, @@ -791,7 +787,7 @@ function readvSync(fd, buffers, position) { if (typeof position !== 'number') position = null; - return binding.readBuffers(fd, buffers, position); + return fsBinding.readBuffers(fd, buffers, position); } /** @@ -840,9 +836,9 @@ function write(fd, buffer, offsetOrOptions, length, position, callback) { position = null; validateOffsetLengthWrite(offset, length, buffer.byteLength); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = wrapper; - binding.writeBuffer(fd, buffer, offset, length, position, req); + fsBinding.writeBuffer(fd, buffer, offset, length, position, req); return; } @@ -863,9 +859,9 @@ function write(fd, buffer, offsetOrOptions, length, position, callback) { callback = position; validateFunction(callback, 'cb'); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = wrapper; - binding.writeString(fd, str, offset, length, req); + fsBinding.writeString(fd, str, offset, length, req); } ObjectDefineProperty(write, kCustomPromisifyArgsSymbol, @@ -909,16 +905,16 @@ function writeSync(fd, buffer, offsetOrOptions, length, position) { if (typeof length !== 'number') length = buffer.byteLength - offset; validateOffsetLengthWrite(offset, length, buffer.byteLength); - result = binding.writeBuffer(fd, buffer, offset, length, position, - undefined, ctx); + result = fsBinding.writeBuffer(fd, buffer, offset, length, position, + undefined, ctx); } else { validateStringAfterArrayBufferView(buffer, 'buffer'); validateEncoding(buffer, length); if (offset === undefined) offset = null; - result = binding.writeString(fd, buffer, offset, length, - undefined, ctx); + result = fsBinding.writeString(fd, buffer, offset, length, + undefined, ctx); } handleErrorFromBinding(ctx); return result; @@ -952,13 +948,13 @@ function writev(fd, buffers, position, callback) { return; } - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = wrapper; if (typeof position !== 'number') position = null; - binding.writeBuffers(fd, buffers, position, req); + fsBinding.writeBuffers(fd, buffers, position, req); } ObjectDefineProperty(writev, kCustomPromisifyArgsSymbol, { @@ -986,7 +982,7 @@ function writevSync(fd, buffers, position) { if (typeof position !== 'number') position = null; - return binding.writeBuffers(fd, buffers, position); + return fsBinding.writeBuffers(fd, buffers, position); } /** @@ -999,9 +995,9 @@ function writevSync(fd, buffers, position) { */ function rename(oldPath, newPath, callback) { callback = makeCallback(callback); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.rename( + fsBinding.rename( getValidatedPath(oldPath, 'oldPath'), getValidatedPath(newPath, 'newPath'), req, @@ -1017,7 +1013,7 @@ function rename(oldPath, newPath, callback) { * @returns {void} */ function renameSync(oldPath, newPath) { - binding.rename( + fsBinding.rename( getValidatedPath(oldPath, 'oldPath'), getValidatedPath(newPath, 'newPath'), ); @@ -1047,13 +1043,13 @@ function truncate(path, len, callback) { validateFunction(callback, 'cb'); fs.open(path, 'r+', (er, fd) => { if (er) return callback(er); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = function oncomplete(er) { fs.close(fd, (er2) => { callback(aggregateTwoErrors(er2, er)); }); }; - binding.ftruncate(fd, len, req); + fsBinding.ftruncate(fd, len, req); }); } @@ -1097,9 +1093,9 @@ function ftruncate(fd, len = 0, callback) { len = MathMax(0, len); callback = makeCallback(callback); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.ftruncate(fd, len, req); + fsBinding.ftruncate(fd, len, req); } /** @@ -1110,7 +1106,7 @@ function ftruncate(fd, len = 0, callback) { */ function ftruncateSync(fd, len = 0) { validateInteger(len, 'len'); - binding.ftruncate(fd, len < 0 ? 0 : len); + fsBinding.ftruncate(fd, len < 0 ? 0 : len); } function lazyLoadCp() { @@ -1154,9 +1150,9 @@ function rmdir(path, options, callback) { true, (err, options) => { if (err === false) { - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.rmdir(path, req); + fsBinding.rmdir(path, req); return; } if (err) { @@ -1168,9 +1164,9 @@ function rmdir(path, options, callback) { }); } else { validateRmdirOptions(options); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.rmdir(path, req); + fsBinding.rmdir(path, req); } } @@ -1191,13 +1187,13 @@ function rmdirSync(path, options) { emitRecursiveRmdirWarning(); options = validateRmOptionsSync(path, { ...options, force: false }, true); if (options !== false) { - return binding.rmSync(path, options.maxRetries, options.recursive, options.retryDelay); + return fsBinding.rmSync(path, options.maxRetries, options.recursive, options.retryDelay); } } else { validateRmdirOptions(options); } - binding.rmdir(path); + fsBinding.rmdir(path); } /** @@ -1243,7 +1239,7 @@ function rm(path, options, callback) { */ function rmSync(path, options) { const opts = validateRmOptionsSync(path, options, false); - return binding.rmSync(getValidatedPath(path), opts.maxRetries, opts.recursive, opts.retryDelay); + return fsBinding.rmSync(getValidatedPath(path), opts.maxRetries, opts.recursive, opts.retryDelay); } /** @@ -1255,9 +1251,9 @@ function rmSync(path, options) { * @returns {void} */ function fdatasync(fd, callback) { - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = makeCallback(callback); - binding.fdatasync(fd, req); + fsBinding.fdatasync(fd, req); } /** @@ -1268,7 +1264,7 @@ function fdatasync(fd, callback) { * @returns {void} */ function fdatasyncSync(fd) { - binding.fdatasync(fd); + fsBinding.fdatasync(fd); } /** @@ -1279,9 +1275,9 @@ function fdatasyncSync(fd) { * @returns {void} */ function fsync(fd, callback) { - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = makeCallback(callback); - binding.fsync(fd, req); + fsBinding.fsync(fd, req); } /** @@ -1291,7 +1287,7 @@ function fsync(fd, callback) { * @returns {void} */ function fsyncSync(fd) { - binding.fsync(fd); + fsBinding.fsync(fd); } /** @@ -1322,9 +1318,9 @@ function mkdir(path, options, callback) { validateBoolean(recursive, 'options.recursive'); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.mkdir( + fsBinding.mkdir( path, parseFileMode(mode, 'mode'), recursive, @@ -1356,7 +1352,7 @@ function mkdirSync(path, options) { } } - const result = binding.mkdir( + const result = fsBinding.mkdir( getValidatedPath(path), mode, recursive, @@ -1383,7 +1379,7 @@ function readdirSyncRecursive(basePath, options) { const pathsQueue = [basePath]; function read(path) { - const readdirResult = binding.readdir( + const readdirResult = fsBinding.readdir( path, encoding, withFileTypes, @@ -1410,7 +1406,7 @@ function readdirSyncRecursive(basePath, options) { for (let i = 0; i < readdirResult.length; i++) { const resultPath = pathModule.join(path, readdirResult[i]); const relativeResultPath = pathModule.relative(basePath, resultPath); - const stat = binding.internalModuleStat(resultPath); + const stat = fsBinding.internalModuleStat(resultPath); ArrayPrototypePush(readdirResults, relativeResultPath); // 1 indicates directory if (stat === 1) { @@ -1454,7 +1450,7 @@ function readdir(path, options, callback) { return; } - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); if (!options.withFileTypes) { req.oncomplete = callback; } else { @@ -1466,7 +1462,7 @@ function readdir(path, options, callback) { getDirents(path, result, callback); }; } - binding.readdir( + fsBinding.readdir( path, options.encoding, !!options.withFileTypes, @@ -1495,7 +1491,7 @@ function readdirSync(path, options) { return readdirSyncRecursive(path, options); } - const result = binding.readdir( + const result = fsBinding.readdir( path, options.encoding, !!options.withFileTypes, @@ -1522,9 +1518,9 @@ function fstat(fd, options = { bigint: false }, callback) { } callback = makeStatsCallback(callback); - const req = new FSReqCallback(options.bigint); + const req = new fsBinding.FSReqCallback(options.bigint); req.oncomplete = callback; - binding.fstat(fd, options.bigint, req); + fsBinding.fstat(fd, options.bigint, req); } /** @@ -1550,9 +1546,9 @@ function lstat(path, options = { bigint: false }, callback) { return; } - const req = new FSReqCallback(options.bigint); + const req = new fsBinding.FSReqCallback(options.bigint); req.oncomplete = callback; - binding.lstat(path, options.bigint, req); + fsBinding.lstat(path, options.bigint, req); } /** @@ -1572,9 +1568,9 @@ function stat(path, options = { bigint: false }, callback) { } callback = makeStatsCallback(callback); - const req = new FSReqCallback(options.bigint); + const req = new fsBinding.FSReqCallback(options.bigint); req.oncomplete = callback; - binding.stat(getValidatedPath(path), options.bigint, req); + fsBinding.stat(getValidatedPath(path), options.bigint, req); } function statfs(path, options = { bigint: false }, callback) { @@ -1584,7 +1580,7 @@ function statfs(path, options = { bigint: false }, callback) { } validateFunction(callback, 'cb'); path = getValidatedPath(path); - const req = new FSReqCallback(options.bigint); + const req = new fsBinding.FSReqCallback(options.bigint); req.oncomplete = (err, stats) => { if (err) { return callback(err); @@ -1592,7 +1588,7 @@ function statfs(path, options = { bigint: false }, callback) { callback(err, getStatFsFromBinding(stats)); }; - binding.statfs(getValidatedPath(path), options.bigint, req); + fsBinding.statfs(getValidatedPath(path), options.bigint, req); } /** @@ -1603,7 +1599,7 @@ function statfs(path, options = { bigint: false }, callback) { * @returns {Stats | undefined} */ function fstatSync(fd, options = { bigint: false }) { - const stats = binding.fstat(fd, options.bigint, undefined, false); + const stats = fsBinding.fstat(fd, options.bigint, undefined, false); if (stats === undefined) { return; } @@ -1625,7 +1621,7 @@ function lstatSync(path, options = { bigint: false, throwIfNoEntry: true }) { if (permission.isEnabled() && !permission.has('fs.read', path)) { throw new ERR_ACCESS_DENIED('Access to this API has been restricted', 'FileSystemRead', path); } - const stats = binding.lstat( + const stats = fsBinding.lstat( getValidatedPath(path), options.bigint, undefined, @@ -1649,7 +1645,7 @@ function lstatSync(path, options = { bigint: false, throwIfNoEntry: true }) { * @returns {Stats} */ function statSync(path, options = { bigint: false, throwIfNoEntry: true }) { - const stats = binding.stat( + const stats = fsBinding.stat( getValidatedPath(path), options.bigint, undefined, @@ -1662,7 +1658,7 @@ function statSync(path, options = { bigint: false, throwIfNoEntry: true }) { } function statfsSync(path, options = { bigint: false }) { - const stats = binding.statfs(getValidatedPath(path), options.bigint); + const stats = fsBinding.statfs(getValidatedPath(path), options.bigint); return getStatFsFromBinding(stats); } @@ -1680,9 +1676,9 @@ function statfsSync(path, options = { bigint: false }) { function readlink(path, options, callback) { callback = makeCallback(typeof options === 'function' ? options : callback); options = getOptions(options); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.readlink(getValidatedPath(path), options.encoding, req); + fsBinding.readlink(getValidatedPath(path), options.encoding, req); } /** @@ -1694,7 +1690,7 @@ function readlink(path, options, callback) { */ function readlinkSync(path, options) { options = getOptions(options); - return binding.readlink(getValidatedPath(path), options.encoding); + return fsBinding.readlink(getValidatedPath(path), options.encoding); } /** @@ -1750,9 +1746,9 @@ function symlink(target, path, type, callback) { resolvedType, path); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.symlink( + fsBinding.symlink( destination, path, resolvedFlags, @@ -1766,9 +1762,9 @@ function symlink(target, path, type, callback) { const destination = preprocessSymlinkDestination(target, type, path); const flags = stringToSymlinkType(type); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.symlink(destination, path, flags, req); + fsBinding.symlink(destination, path, flags, req); } /** @@ -1803,7 +1799,7 @@ function symlinkSync(target, path, type) { target = getValidatedPath(target, 'target'); path = getValidatedPath(path); - binding.symlink( + fsBinding.symlink( preprocessSymlinkDestination(target, type, path), path, stringToSymlinkType(type), @@ -1824,10 +1820,10 @@ function link(existingPath, newPath, callback) { existingPath = getValidatedPath(existingPath, 'existingPath'); newPath = getValidatedPath(newPath, 'newPath'); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.link(existingPath, newPath, req); + fsBinding.link(existingPath, newPath, req); } /** @@ -1841,7 +1837,7 @@ function linkSync(existingPath, newPath) { existingPath = getValidatedPath(existingPath, 'existingPath'); newPath = getValidatedPath(newPath, 'newPath'); - binding.link( + fsBinding.link( existingPath, newPath, ); @@ -1855,9 +1851,9 @@ function linkSync(existingPath, newPath) { */ function unlink(path, callback) { callback = makeCallback(callback); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.unlink(getValidatedPath(path), req); + fsBinding.unlink(getValidatedPath(path), req); } /** @@ -1866,7 +1862,7 @@ function unlink(path, callback) { * @returns {void} */ function unlinkSync(path) { - binding.unlink(getValidatedPath(path)); + fsBinding.unlink(getValidatedPath(path)); } /** @@ -1885,9 +1881,9 @@ function fchmod(fd, mode, callback) { return; } - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.fchmod(fd, mode, req); + fsBinding.fchmod(fd, mode, req); } /** @@ -1900,7 +1896,7 @@ function fchmodSync(fd, mode) { if (permission.isEnabled()) { throw new ERR_ACCESS_DENIED('fchmod API is disabled when Permission Model is enabled.'); } - binding.fchmod( + fsBinding.fchmod( fd, parseFileMode(mode, 'mode'), ); @@ -1961,9 +1957,9 @@ function chmod(path, mode, callback) { mode = parseFileMode(mode, 'mode'); callback = makeCallback(callback); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.chmod(path, mode, req); + fsBinding.chmod(path, mode, req); } /** @@ -1976,7 +1972,7 @@ function chmodSync(path, mode) { path = getValidatedPath(path); mode = parseFileMode(mode, 'mode'); - binding.chmod(path, mode); + fsBinding.chmod(path, mode); } /** @@ -1992,9 +1988,9 @@ function lchown(path, uid, gid, callback) { path = getValidatedPath(path); validateInteger(uid, 'uid', -1, kMaxUserId); validateInteger(gid, 'gid', -1, kMaxUserId); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.lchown(path, uid, gid, req); + fsBinding.lchown(path, uid, gid, req); } /** @@ -2008,7 +2004,7 @@ function lchownSync(path, uid, gid) { path = getValidatedPath(path); validateInteger(uid, 'uid', -1, kMaxUserId); validateInteger(gid, 'gid', -1, kMaxUserId); - binding.lchown(path, uid, gid); + fsBinding.lchown(path, uid, gid); } /** @@ -2028,9 +2024,9 @@ function fchown(fd, uid, gid, callback) { return; } - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.fchown(fd, uid, gid, req); + fsBinding.fchown(fd, uid, gid, req); } /** @@ -2047,7 +2043,7 @@ function fchownSync(fd, uid, gid) { throw new ERR_ACCESS_DENIED('fchown API is disabled when Permission Model is enabled.'); } - binding.fchown(fd, uid, gid); + fsBinding.fchown(fd, uid, gid); } /** @@ -2065,9 +2061,9 @@ function chown(path, uid, gid, callback) { validateInteger(uid, 'uid', -1, kMaxUserId); validateInteger(gid, 'gid', -1, kMaxUserId); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.chown(path, uid, gid, req); + fsBinding.chown(path, uid, gid, req); } /** @@ -2082,7 +2078,7 @@ function chownSync(path, uid, gid) { path = getValidatedPath(path); validateInteger(uid, 'uid', -1, kMaxUserId); validateInteger(gid, 'gid', -1, kMaxUserId); - binding.chown(path, uid, gid); + fsBinding.chown(path, uid, gid); } /** @@ -2098,9 +2094,9 @@ function utimes(path, atime, mtime, callback) { callback = makeCallback(callback); path = getValidatedPath(path); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.utimes( + fsBinding.utimes( path, toUnixTimestamp(atime), toUnixTimestamp(mtime), @@ -2117,7 +2113,7 @@ function utimes(path, atime, mtime, callback) { * @returns {void} */ function utimesSync(path, atime, mtime) { - binding.utimes( + fsBinding.utimes( getValidatedPath(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), @@ -2138,9 +2134,9 @@ function futimes(fd, atime, mtime, callback) { mtime = toUnixTimestamp(mtime, 'mtime'); callback = makeCallback(callback); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.futimes(fd, atime, mtime, req); + fsBinding.futimes(fd, atime, mtime, req); } /** @@ -2153,7 +2149,7 @@ function futimes(fd, atime, mtime, callback) { * @returns {void} */ function futimesSync(fd, atime, mtime) { - binding.futimes( + fsBinding.futimes( fd, toUnixTimestamp(atime, 'atime'), toUnixTimestamp(mtime, 'mtime'), @@ -2173,9 +2169,9 @@ function lutimes(path, atime, mtime, callback) { callback = makeCallback(callback); path = getValidatedPath(path); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.lutimes( + fsBinding.lutimes( path, toUnixTimestamp(atime), toUnixTimestamp(mtime), @@ -2192,7 +2188,7 @@ function lutimes(path, atime, mtime, callback) { * @returns {void} */ function lutimesSync(path, atime, mtime) { - binding.lutimes( + fsBinding.lutimes( getValidatedPath(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), @@ -2339,7 +2335,7 @@ function writeFileSync(path, data, options) { path = getValidatedPath(path); } - return binding.writeFileUtf8( + return fsBinding.writeFileUtf8( path, data, stringToFlags(flag), @@ -2658,7 +2654,7 @@ function realpathSync(p, options) { // On windows, check that the root exists. On unix there is no need. if (isWindows) { - const out = binding.lstat(base, false, undefined, true /* throwIfNoEntry */); + const out = fsBinding.lstat(base, false, undefined, true /* throwIfNoEntry */); if (out === undefined) { return; } @@ -2685,8 +2681,8 @@ function realpathSync(p, options) { // Continue if not a symlink, break if a pipe/socket if (knownHard.has(base) || cache?.get(base) === base) { - if (isFileType(statValues, S_IFIFO) || - isFileType(statValues, S_IFSOCK)) { + if (isFileType(fsBinding.statValues, S_IFIFO) || + isFileType(fsBinding.statValues, S_IFSOCK)) { break; } continue; @@ -2700,7 +2696,7 @@ function realpathSync(p, options) { // Use stats array directly to avoid creating an fs.Stats instance just // for our internal use. - const stats = binding.lstat(base, true, undefined, true /* throwIfNoEntry */); + const stats = fsBinding.lstat(base, true, undefined, true /* throwIfNoEntry */); if (stats === undefined) { return; } @@ -2724,8 +2720,8 @@ function realpathSync(p, options) { } } if (linkTarget === null) { - binding.stat(base, false, undefined, true); - linkTarget = binding.readlink(base, undefined); + fsBinding.stat(base, false, undefined, true); + linkTarget = fsBinding.readlink(base, undefined); } resolvedLink = pathModule.resolve(previous, linkTarget); @@ -2742,7 +2738,7 @@ function realpathSync(p, options) { // On windows, check that the root exists. On unix there is no need. if (isWindows && !knownHard.has(base)) { - const out = binding.lstat(base, false, undefined, true /* throwIfNoEntry */); + const out = fsBinding.lstat(base, false, undefined, true /* throwIfNoEntry */); if (out === undefined) { return; } @@ -2762,7 +2758,7 @@ function realpathSync(p, options) { */ realpathSync.native = (path, options) => { options = getOptions(options); - return binding.realpath( + return fsBinding.realpath( getValidatedPath(path), options.encoding, ); @@ -2844,8 +2840,8 @@ function realpath(p, options, callback) { // Continue if not a symlink, break if a pipe/socket if (knownHard.has(base)) { - if (isFileType(statValues, S_IFIFO) || - isFileType(statValues, S_IFSOCK)) { + if (isFileType(fsBinding.statValues, S_IFIFO) || + isFileType(fsBinding.statValues, S_IFSOCK)) { return callback(null, encodeRealpathResult(p, options)); } return process.nextTick(LOOP); @@ -2925,9 +2921,9 @@ realpath.native = (path, options, callback) => { callback = makeCallback(callback || options); options = getOptions(options); path = getValidatedPath(path); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.realpath(path, options.encoding, req); + fsBinding.realpath(path, options.encoding, req); }; /** @@ -2947,9 +2943,9 @@ function mkdtemp(prefix, options, callback) { prefix = getValidatedPath(prefix, 'prefix'); warnOnNonPortableTemplate(prefix); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.mkdtemp(prefix, options.encoding, req); + fsBinding.mkdtemp(prefix, options.encoding, req); } /** @@ -2963,7 +2959,7 @@ function mkdtempSync(prefix, options) { prefix = getValidatedPath(prefix, 'prefix'); warnOnNonPortableTemplate(prefix); - return binding.mkdtemp(prefix, options.encoding); + return fsBinding.mkdtemp(prefix, options.encoding); } /** @@ -2985,9 +2981,9 @@ function copyFile(src, dest, mode, callback) { dest = getValidatedPath(dest, 'dest'); callback = makeCallback(callback); - const req = new FSReqCallback(); + const req = new fsBinding.FSReqCallback(); req.oncomplete = callback; - binding.copyFile(src, dest, mode, req); + fsBinding.copyFile(src, dest, mode, req); } /** @@ -2999,7 +2995,7 @@ function copyFile(src, dest, mode, callback) { * @returns {void} */ function copyFileSync(src, dest, mode) { - binding.copyFile( + fsBinding.copyFile( getValidatedPath(src, 'src'), getValidatedPath(dest, 'dest'), mode, @@ -3168,8 +3164,8 @@ module.exports = fs = { globSync, lchown, lchownSync, - lchmod: constants.O_SYMLINK !== undefined ? lchmod : undefined, - lchmodSync: constants.O_SYMLINK !== undefined ? lchmodSync : undefined, + lchmod: constantsBinding.fs.O_SYMLINK !== undefined ? lchmod : undefined, + lchmodSync: constantsBinding.fs.O_SYMLINK !== undefined ? lchmodSync : undefined, link, linkSync, lstat, @@ -3282,7 +3278,7 @@ ObjectDefineProperties(fs, { __proto__: null, configurable: false, enumerable: true, - value: constants, + value: constantsBinding.fs, }, promises: { __proto__: null, diff --git a/lib/inspector.js b/lib/inspector.js index b38bb1af974819..8d02feed6e321f 100644 --- a/lib/inspector.js +++ b/lib/inspector.js @@ -18,8 +18,8 @@ const { ERR_INSPECTOR_NOT_WORKER, } = require('internal/errors').codes; -const { hasInspector } = internalBinding('config'); -if (!hasInspector) +const configBinding = internalBinding('config'); +if (!configBinding.hasInspector) throw new ERR_INSPECTOR_NOT_AVAILABLE(); const EventEmitter = require('events'); @@ -32,18 +32,9 @@ const { validateString, } = require('internal/validators'); const { isMainThread } = require('worker_threads'); -const { _debugEnd } = internalBinding('process_methods'); +const processMethodsBinding = internalBinding('process_methods'); -const { - Connection, - MainThreadConnection, - open, - url, - isEnabled, - waitForDebugger, - console, - emitProtocolEvent, -} = internalBinding('inspector'); +const inspectorBinding = internalBinding('inspector'); class Session extends EventEmitter { #connection = null; @@ -57,7 +48,7 @@ class Session extends EventEmitter { connect() { if (this.#connection) throw new ERR_INSPECTOR_ALREADY_CONNECTED('The inspector session'); - this.#connection = new Connection((message) => this.#onMessage(message)); + this.#connection = new inspectorBinding.Connection((message) => this.#onMessage(message)); } /** @@ -71,7 +62,7 @@ class Session extends EventEmitter { if (this.#connection) throw new ERR_INSPECTOR_ALREADY_CONNECTED('The inspector session'); this.#connection = - new MainThreadConnection( + new inspectorBinding.MainThreadConnection( (message) => queueMicrotask(() => this.#onMessage(message))); } @@ -161,7 +152,7 @@ class Session extends EventEmitter { * @returns {void} */ function inspectorOpen(port, host, wait) { - if (isEnabled()) { + if (inspectorBinding.isEnabled()) { throw new ERR_INSPECTOR_ALREADY_ACTIVATED(); } // inspectorOpen() currently does not typecheck its arguments and adding @@ -171,11 +162,11 @@ function inspectorOpen(port, host, wait) { if (isUint32(port)) { validateInt32(port, 'port', 0, 65535); } - open(port, host); + inspectorBinding.open(port, host); if (wait) - waitForDebugger(); + inspectorBinding.waitForDebugger(); - return { __proto__: null, [SymbolDispose]() { _debugEnd(); } }; + return { __proto__: null, [SymbolDispose]() { processMethodsBinding._debugEnd(); } }; } /** @@ -185,7 +176,7 @@ function inspectorOpen(port, host, wait) { * @returns {void} */ function inspectorWaitForDebugger() { - if (!waitForDebugger()) + if (!inspectorBinding.waitForDebugger()) throw new ERR_INSPECTOR_NOT_ACTIVE(); } @@ -194,7 +185,7 @@ function broadcastToFrontend(eventName, params) { if (params) { validateObject(params, 'params'); } - emitProtocolEvent(eventName, JSONStringify(params ?? {})); + inspectorBinding.emitProtocolEvent(eventName, JSONStringify(params ?? {})); } const Network = { @@ -205,10 +196,10 @@ const Network = { module.exports = { open: inspectorOpen, - close: _debugEnd, - url, + close: processMethodsBinding._debugEnd, + url: inspectorBinding.url, waitForDebugger: inspectorWaitForDebugger, - console, + console: inspectorBinding.console, Session, Network, }; diff --git a/lib/net.js b/lib/net.js index 4de6f9c5f6f23a..4bb94f2ae90bd9 100644 --- a/lib/net.js +++ b/lib/net.js @@ -55,26 +55,12 @@ const { makeSyncWrite, } = require('internal/net'); const assert = require('internal/assert'); -const { - UV_EADDRINUSE, - UV_EINVAL, - UV_ENOTCONN, - UV_ECANCELED, - UV_ETIMEDOUT, -} = internalBinding('uv'); +const uvBinding = internalBinding('uv'); const { Buffer } = require('buffer'); -const { ShutdownWrap } = internalBinding('stream_wrap'); -const { - TCP, - TCPConnectWrap, - constants: TCPConstants, -} = internalBinding('tcp_wrap'); -const { - Pipe, - PipeConnectWrap, - constants: PipeConstants, -} = internalBinding('pipe_wrap'); +const streamWrapBinding = internalBinding('stream_wrap'); +const tcpWrapBinding = internalBinding('tcp_wrap'); +const pipeWrapBinding = internalBinding('pipe_wrap'); const { newAsyncId, defaultTriggerAsyncIdScope, @@ -159,21 +145,21 @@ const { const { getDefaultHighWaterMark } = require('internal/streams/state'); function getFlags(ipv6Only) { - return ipv6Only === true ? TCPConstants.UV_TCP_IPV6ONLY : 0; + return ipv6Only === true ? tcpWrapBinding.constants.UV_TCP_IPV6ONLY : 0; } function createHandle(fd, is_server) { validateInt32(fd, 'fd', 0); const type = guessHandleType(fd); if (type === 'PIPE') { - return new Pipe( - is_server ? PipeConstants.SERVER : PipeConstants.SOCKET, + return new pipeWrapBinding.Pipe( + is_server ? pipeWrapBinding.constants.SERVER : pipeWrapBinding.constants.SOCKET, ); } if (type === 'TCP') { - return new TCP( - is_server ? TCPConstants.SERVER : TCPConstants.SOCKET, + return new tcpWrapBinding.TCP( + is_server ? tcpWrapBinding.constants.SERVER : tcpWrapBinding.constants.SOCKET, ); } @@ -430,7 +416,7 @@ function Socket(options) { this[async_id_symbol] = this._handle.getAsyncId(); if ((fd === 1 || fd === 2) && - (this._handle instanceof Pipe) && isWindows) { + (this._handle instanceof pipeWrapBinding.Pipe) && isWindows) { // Make stdout and stderr blocking on Windows err = this._handle.setBlocking(true); if (err) @@ -524,13 +510,13 @@ Socket.prototype._final = function(cb) { debug('_final: not ended, call shutdown()'); - const req = new ShutdownWrap(); + const req = new streamWrapBinding.ShutdownWrap(); req.oncomplete = afterShutdown; req.handle = this._handle; req.callback = cb; const err = this._handle.shutdown(req); - if (err === 1 || err === UV_ENOTCONN) // synchronous finish + if (err === 1 || err === uvBinding.UV_ENOTCONN) // synchronous finish return cb(); else if (err !== 0) return cb(new ErrnoException(err, 'shutdown')); @@ -726,7 +712,7 @@ Socket.prototype.end = function(data, encoding, callback) { Socket.prototype.resetAndDestroy = function() { if (this._handle) { - if (!(this._handle instanceof TCP)) + if (!(this._handle instanceof tcpWrapBinding.TCP)) throw new ERR_INVALID_HANDLE_TYPE(); if (this.connecting) { debug('reset wait for connection'); @@ -1022,7 +1008,7 @@ function checkBindError(err, port, handle) { err = handle.getsockname(out); if (err === 0 && port !== out.port) { debug(`checkBindError, bound to ${out.port} instead of ${port}`); - err = UV_EADDRINUSE; + err = uvBinding.UV_EADDRINUSE; } } return err; @@ -1061,7 +1047,7 @@ function internalConnect( self.emit('connectionAttempt', address, port, addressType); if (addressType === 6 || addressType === 4) { - const req = new TCPConnectWrap(); + const req = new tcpWrapBinding.TCPConnectWrap(); req.oncomplete = afterConnect; req.address = address; req.port = port; @@ -1074,7 +1060,7 @@ function internalConnect( else err = self._handle.connect6(req, address, port); } else { - const req = new PipeConnectWrap(); + const req = new pipeWrapBinding.PipeConnectWrap(); req.address = address; req.oncomplete = afterConnect; @@ -1122,7 +1108,7 @@ function internalConnectMultiple(context, canceled) { const current = context.current++; if (current > 0) { - self[kReinitializeHandle](new TCP(TCPConstants.SOCKET)); + self[kReinitializeHandle](new tcpWrapBinding.TCP(tcpWrapBinding.constants.SOCKET)); } const { localPort, port, flags } = context; @@ -1153,7 +1139,7 @@ function internalConnectMultiple(context, canceled) { debug('connect/multiple: attempting to connect to %s:%d (addressType: %d)', address, port, addressType); self.emit('connectionAttempt', address, port, addressType); - const req = new TCPConnectWrap(); + const req = new tcpWrapBinding.TCPConnectWrap(); req.oncomplete = FunctionPrototypeBind(afterConnectMultiple, undefined, context, current); req.address = address; req.port = port; @@ -1235,8 +1221,8 @@ Socket.prototype.connect = function(...args) { if (!this._handle) { this._handle = pipe ? - new Pipe(PipeConstants.SOCKET) : - new TCP(TCPConstants.SOCKET); + new pipeWrapBinding.Pipe(pipeWrapBinding.constants.SOCKET) : + new tcpWrapBinding.TCP(tcpWrapBinding.constants.SOCKET); initSocketHandle(this); } @@ -1680,7 +1666,7 @@ function afterConnectMultiple(context, current, status, handle, req, readable, w // Try the next address, unless we were aborted if (context.socket.connecting) { - internalConnectMultiple(context, status === UV_ECANCELED); + internalConnectMultiple(context, status === uvBinding.UV_ECANCELED); } return; @@ -1702,7 +1688,7 @@ function internalConnectMultipleTimeout(context, req, handle) { context.socket.emit('connectionAttemptTimeout', req.address, req.port, req.addressType); req.oncomplete = undefined; - ArrayPrototypePush(context.errors, createConnectionError(req, UV_ETIMEDOUT)); + ArrayPrototypePush(context.errors, createConnectionError(req, uvBinding.UV_ETIMEDOUT)); handle.close(); // Try the next address, unless we were aborted @@ -1801,7 +1787,7 @@ function createServerHandle(address, port, addressType, fd, flags) { } catch (e) { // Not a fd we can listen on. This will trigger an error. debug('listen invalid fd=%d:', fd, e.message); - return UV_EINVAL; + return uvBinding.UV_EINVAL; } err = handle.open(fd); @@ -1810,7 +1796,7 @@ function createServerHandle(address, port, addressType, fd, flags) { assert(!address && !port); } else if (port === -1 && addressType === -1) { - handle = new Pipe(PipeConstants.SERVER); + handle = new pipeWrapBinding.Pipe(pipeWrapBinding.constants.SERVER); if (isWindows) { const instances = NumberParseInt(process.env.NODE_PENDING_PIPE_INSTANCES); if (!NumberIsNaN(instances)) { @@ -1818,7 +1804,7 @@ function createServerHandle(address, port, addressType, fd, flags) { } } } else { - handle = new TCP(TCPConstants.SERVER); + handle = new tcpWrapBinding.TCP(tcpWrapBinding.constants.SERVER); isTCP = true; } @@ -2023,7 +2009,7 @@ Server.prototype.listen = function(...args) { // Refresh the id to make the previous call invalid this._listeningId++; // (handle[, backlog][, cb]) where handle is an object with a handle - if (options instanceof TCP) { + if (options instanceof tcpWrapBinding.TCP) { this._handle = options; this[async_id_symbol] = this._handle.getAsyncId(); listenInCluster(this, null, -1, -1, backlogFromArgs, undefined, true); @@ -2096,9 +2082,9 @@ Server.prototype.listen = function(...args) { let mode = 0; if (options.readableAll === true) - mode |= PipeConstants.UV_READABLE; + mode |= pipeWrapBinding.constants.UV_READABLE; if (options.writableAll === true) - mode |= PipeConstants.UV_WRITABLE; + mode |= pipeWrapBinding.constants.UV_WRITABLE; if (mode !== 0) { const err = this._handle.fchmod(mode); if (err) { @@ -2354,7 +2340,7 @@ Server.prototype[EventEmitter.captureRejectionSymbol] = function( // Legacy alias on the C++ wrapper object. This is not public API, so we may // want to runtime-deprecate it at some point. There's no hurry, though. -ObjectDefineProperty(TCP.prototype, 'owner', { +ObjectDefineProperty(tcpWrapBinding.TCP.prototype, 'owner', { __proto__: null, get() { return this[owner_symbol]; }, set(v) { return this[owner_symbol] = v; }, diff --git a/lib/os.js b/lib/os.js index bef4936c7c0bbe..ac2e4cad920755 100644 --- a/lib/os.js +++ b/lib/os.js @@ -31,7 +31,7 @@ const { SymbolToPrimitive, } = primordials; -const { safeGetenv } = internalBinding('credentials'); +const credentialsBinding = internalBinding('credentials'); const constants = internalBinding('constants').os; const isWindows = process.platform === 'win32'; @@ -43,22 +43,7 @@ const { } = require('internal/errors'); const { validateInt32 } = require('internal/validators'); -const { - getAvailableParallelism, - getCPUs, - getFreeMem, - getHomeDirectory: _getHomeDirectory, - getHostname: _getHostname, - getInterfaceAddresses: _getInterfaceAddresses, - getLoadAvg, - getPriority: _getPriority, - getOSInformation: _getOSInformation, - getTotalMem, - getUserInfo, - getUptime: _getUptime, - isBigEndian, - setPriority: _setPriority, -} = internalBinding('os'); +const osBinding = internalBinding('os'); function getCheckedFunction(fn) { return hideStackFrames(function checkError() { @@ -76,12 +61,12 @@ const { 1: version, 2: release, 3: machine, -} = _getOSInformation(); +} = osBinding.getOSInformation(); -const getHomeDirectory = getCheckedFunction(_getHomeDirectory); -const getHostname = getCheckedFunction(_getHostname); -const getInterfaceAddresses = getCheckedFunction(_getInterfaceAddresses); -const getUptime = getCheckedFunction(_getUptime); +const getHomeDirectory = getCheckedFunction(osBinding.getHomeDirectory); +const getHostname = getCheckedFunction(osBinding.getHostname); +const getInterfaceAddresses = getCheckedFunction(osBinding.getInterfaceAddresses); +const getUptime = getCheckedFunction(osBinding.getUptime); /** * @returns {string} @@ -100,18 +85,18 @@ const getOSVersion = () => version; */ const getMachine = () => machine; -getAvailableParallelism[SymbolToPrimitive] = () => getAvailableParallelism(); -getFreeMem[SymbolToPrimitive] = () => getFreeMem(); +osBinding.getAvailableParallelism[SymbolToPrimitive] = () => osBinding.getAvailableParallelism(); +osBinding.getFreeMem[SymbolToPrimitive] = () => osBinding.getFreeMem(); getHostname[SymbolToPrimitive] = () => getHostname(); getOSVersion[SymbolToPrimitive] = () => getOSVersion(); getOSType[SymbolToPrimitive] = () => getOSType(); getOSRelease[SymbolToPrimitive] = () => getOSRelease(); getMachine[SymbolToPrimitive] = () => getMachine(); getHomeDirectory[SymbolToPrimitive] = () => getHomeDirectory(); -getTotalMem[SymbolToPrimitive] = () => getTotalMem(); +osBinding.getTotalMem[SymbolToPrimitive] = () => osBinding.getTotalMem(); getUptime[SymbolToPrimitive] = () => getUptime(); -const kEndianness = isBigEndian ? 'BE' : 'LE'; +const kEndianness = osBinding.isBigEndian ? 'BE' : 'LE'; const avgValues = new Float64Array(3); @@ -119,7 +104,7 @@ const avgValues = new Float64Array(3); * @returns {[number, number, number]} */ function loadavg() { - getLoadAvg(avgValues); + osBinding.getLoadAvg(avgValues); return [avgValues[0], avgValues[1], avgValues[2]]; } @@ -140,7 +125,7 @@ function loadavg() { */ function cpus() { // [] is a bugfix for a regression introduced in 51cea61 - const data = getCPUs() || []; + const data = osBinding.getCPUs() || []; const result = []; let i = 0; while (i < data.length) { @@ -188,9 +173,9 @@ function tmpdir() { !StringPrototypeEndsWith(path, ':\\')) path = StringPrototypeSlice(path, 0, -1); } else { - path = safeGetenv('TMPDIR') || - safeGetenv('TMP') || - safeGetenv('TEMP') || + path = credentialsBinding.safeGetenv('TMPDIR') || + credentialsBinding.safeGetenv('TMP') || + credentialsBinding.safeGetenv('TEMP') || '/tmp'; if (path.length > 1 && StringPrototypeEndsWith(path, '/')) path = StringPrototypeSlice(path, 0, -1); @@ -319,7 +304,7 @@ function setPriority(pid, priority) { const ctx = {}; - if (_setPriority(pid, priority, ctx) !== 0) + if (osBinding.setPriority(pid, priority, ctx) !== 0) throw new ERR_SYSTEM_ERROR(ctx); } @@ -334,7 +319,7 @@ function getPriority(pid) { validateInt32(pid, 'pid'); const ctx = {}; - const priority = _getPriority(pid, ctx); + const priority = osBinding.getPriority(pid, ctx); if (priority === undefined) throw new ERR_SYSTEM_ERROR(ctx); @@ -359,7 +344,7 @@ function userInfo(options) { options = null; const ctx = {}; - const user = getUserInfo(options, ctx); + const user = osBinding.getUserInfo(options, ctx); if (user === undefined) throw new ERR_SYSTEM_ERROR(ctx); @@ -374,10 +359,10 @@ function userInfo(options) { module.exports = { arch, - availableParallelism: getAvailableParallelism, + availableParallelism: osBinding.getAvailableParallelism, cpus, endianness, - freemem: getFreeMem, + freemem: osBinding.getFreeMem, getPriority, homedir: getHomeDirectory, hostname: getHostname, @@ -387,7 +372,7 @@ module.exports = { release: getOSRelease, setPriority, tmpdir, - totalmem: getTotalMem, + totalmem: osBinding.getTotalMem, type: getOSType, userInfo, uptime: getUptime, diff --git a/lib/perf_hooks.js b/lib/perf_hooks.js index 2b9bd92c82ee21..dc161b13f098ea 100644 --- a/lib/perf_hooks.js +++ b/lib/perf_hooks.js @@ -4,9 +4,7 @@ const { ObjectDefineProperty, } = primordials; -const { - constants, -} = internalBinding('performance'); +const performanceBinding = internalBinding('performance'); const { PerformanceEntry } = require('internal/perf/performance_entry'); const { PerformanceResourceTiming } = require('internal/perf/resource_timing'); @@ -46,5 +44,5 @@ ObjectDefineProperty(module.exports, 'constants', { __proto__: null, configurable: false, enumerable: true, - value: constants, + value: performanceBinding.constants, }); diff --git a/lib/repl.js b/lib/repl.js index 6e2d8120ad2167..675ad14a223053 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -172,17 +172,8 @@ const { setupPreview, setupReverseSearch, } = require('internal/repl/utils'); -const { - constants: { - ALL_PROPERTIES, - SKIP_SYMBOLS, - }, - getOwnNonIndexProperties, -} = internalBinding('util'); -const { - startSigintWatchdog, - stopSigintWatchdog, -} = internalBinding('contextify'); +const utilBinding = internalBinding('util'); +const contextifyBinding = internalBinding('contextify'); const history = require('internal/repl/history'); const { @@ -582,7 +573,7 @@ function REPLServer(prompt, if (self.breakEvalOnSigint) { // Start the SIGINT watchdog before entering raw mode so that a very // quick Ctrl+C doesn't lead to aborting the process completely. - if (!startSigintWatchdog()) + if (!contextifyBinding.startSigintWatchdog()) throw new ERR_CANNOT_WATCH_SIGINT(); previouslyInRawMode = self._setRawMode(false); } @@ -606,7 +597,7 @@ function REPLServer(prompt, // Returns true if there were pending SIGINTs *after* the script // has terminated without being interrupted itself. - if (stopSigintWatchdog()) { + if (contextifyBinding.stopSigintWatchdog()) { self.emit('SIGINT'); } } @@ -1256,9 +1247,9 @@ function filteredOwnPropertyNames(obj) { isObjectPrototype = ctorProto && ObjectGetPrototypeOf(ctorProto) === obj; } } - const filter = ALL_PROPERTIES | SKIP_SYMBOLS; + const filter = utilBinding.constants.ALL_PROPERTIES | utilBinding.constants.SKIP_SYMBOLS; return ArrayPrototypeFilter( - getOwnNonIndexProperties(obj, filter), + utilBinding.getOwnNonIndexProperties(obj, filter), isObjectPrototype ? isNotLegacyObjectPrototypeMethod : isIdentifier); } diff --git a/lib/sea.js b/lib/sea.js index f7727014c4e3c9..5960846b1c4864 100644 --- a/lib/sea.js +++ b/lib/sea.js @@ -3,7 +3,7 @@ const { ArrayBufferPrototypeSlice, } = primordials; -const { isSea, getAsset: getAssetInternal } = internalBinding('sea'); +const seaBinding = internalBinding('sea'); const { TextDecoder } = require('internal/encoding'); const { validateString } = require('internal/validators'); const { @@ -23,11 +23,11 @@ const { Blob } = require('internal/blob'); function getRawAsset(key) { validateString(key, 'key'); - if (!isSea()) { + if (!seaBinding.isSea()) { throw new ERR_NOT_IN_SINGLE_EXECUTABLE_APPLICATION(); } - const asset = getAssetInternal(key); + const asset = seaBinding.getAsset(key); if (asset === undefined) { throw new ERR_SINGLE_EXECUTABLE_APPLICATION_ASSET_NOT_FOUND(key); } @@ -69,7 +69,7 @@ function getAssetAsBlob(key, options) { } module.exports = { - isSea, + isSea: seaBinding.isSea, getAsset, getRawAsset, getAssetAsBlob, diff --git a/lib/string_decoder.js b/lib/string_decoder.js index c0dbfe2b5e92a8..43320150a513b2 100644 --- a/lib/string_decoder.js +++ b/lib/string_decoder.js @@ -29,16 +29,7 @@ const { } = primordials; const { Buffer } = require('buffer'); -const { - kIncompleteCharactersStart, - kIncompleteCharactersEnd, - kMissingBytes, - kBufferedBytes, - kEncodingField, - kSize, - decode, - flush, -} = internalBinding('string_decoder'); +const stringDecoderBinding = internalBinding('string_decoder'); const { kIsEncodingSymbol, encodingsMap, @@ -80,8 +71,8 @@ function normalizeEncoding(enc) { */ function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); - this[kNativeDecoder] = Buffer.alloc(kSize); - this[kNativeDecoder][kEncodingField] = encodingsMap[this.encoding]; + this[kNativeDecoder] = Buffer.alloc(stringDecoderBinding.kSize); + this[kNativeDecoder][stringDecoderBinding.kEncodingField] = encodingsMap[this.encoding]; } /** @@ -101,7 +92,7 @@ StringDecoder.prototype.write = function write(buf) { if (!this[kNativeDecoder]) { throw new ERR_INVALID_THIS('StringDecoder'); } - return decode(this[kNativeDecoder], buf); + return stringDecoderBinding.decode(this[kNativeDecoder], buf); }; /** @@ -115,8 +106,8 @@ StringDecoder.prototype.end = function end(buf) { let ret = ''; if (buf !== undefined) ret = this.write(buf); - if (this[kNativeDecoder][kBufferedBytes] > 0) - ret += flush(this[kNativeDecoder]); + if (this[kNativeDecoder][stringDecoderBinding.kBufferedBytes] > 0) + ret += stringDecoderBinding.flush(this[kNativeDecoder]); return ret; }; @@ -128,8 +119,8 @@ StringDecoder.prototype.end = function end(buf) { * @returns {string} */ StringDecoder.prototype.text = function text(buf, offset) { - this[kNativeDecoder][kMissingBytes] = 0; - this[kNativeDecoder][kBufferedBytes] = 0; + this[kNativeDecoder][stringDecoderBinding.kMissingBytes] = 0; + this[kNativeDecoder][stringDecoderBinding.kBufferedBytes] = 0; return this.write(buf.slice(offset)); }; @@ -140,8 +131,8 @@ ObjectDefineProperties(StringDecoder.prototype, { enumerable: true, get() { return TypedArrayPrototypeSubarray(this[kNativeDecoder], - kIncompleteCharactersStart, - kIncompleteCharactersEnd); + stringDecoderBinding.kIncompleteCharactersStart, + stringDecoderBinding.kIncompleteCharactersEnd); }, }, lastNeed: { @@ -149,7 +140,7 @@ ObjectDefineProperties(StringDecoder.prototype, { configurable: true, enumerable: true, get() { - return this[kNativeDecoder][kMissingBytes]; + return this[kNativeDecoder][stringDecoderBinding.kMissingBytes]; }, }, lastTotal: { @@ -157,8 +148,8 @@ ObjectDefineProperties(StringDecoder.prototype, { configurable: true, enumerable: true, get() { - return this[kNativeDecoder][kBufferedBytes] + - this[kNativeDecoder][kMissingBytes]; + return this[kNativeDecoder][stringDecoderBinding.kBufferedBytes] + + this[kNativeDecoder][stringDecoderBinding.kMissingBytes]; }, }, }); diff --git a/lib/tls.js b/lib/tls.js index 0c1b3350618020..b4c40394bc117d 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -43,10 +43,10 @@ const { } = require('internal/util/types'); const net = require('net'); -const { getOptionValue } = require('internal/options'); -const { getRootCertificates, getSSLCiphers } = internalBinding('crypto'); +const optionsBinding = require('internal/options'); +const cryptoBinding = internalBinding('crypto'); const { Buffer } = require('buffer'); -const { canonicalizeIP } = internalBinding('cares_wrap'); +const caresWrapBinding = internalBinding('cares_wrap'); const _tls_common = require('_tls_common'); const _tls_wrap = require('_tls_wrap'); const { createSecurePair } = require('internal/tls/secure-pair'); @@ -58,37 +58,37 @@ const { createSecurePair } = require('internal/tls/secure-pair'); exports.CLIENT_RENEG_LIMIT = 3; exports.CLIENT_RENEG_WINDOW = 600; -exports.DEFAULT_CIPHERS = getOptionValue('--tls-cipher-list'); +exports.DEFAULT_CIPHERS = optionsBinding.getOptionValue('--tls-cipher-list'); exports.DEFAULT_ECDH_CURVE = 'auto'; -if (getOptionValue('--tls-min-v1.0')) +if (optionsBinding.getOptionValue('--tls-min-v1.0')) exports.DEFAULT_MIN_VERSION = 'TLSv1'; -else if (getOptionValue('--tls-min-v1.1')) +else if (optionsBinding.getOptionValue('--tls-min-v1.1')) exports.DEFAULT_MIN_VERSION = 'TLSv1.1'; -else if (getOptionValue('--tls-min-v1.2')) +else if (optionsBinding.getOptionValue('--tls-min-v1.2')) exports.DEFAULT_MIN_VERSION = 'TLSv1.2'; -else if (getOptionValue('--tls-min-v1.3')) +else if (optionsBinding.getOptionValue('--tls-min-v1.3')) exports.DEFAULT_MIN_VERSION = 'TLSv1.3'; else exports.DEFAULT_MIN_VERSION = 'TLSv1.2'; -if (getOptionValue('--tls-max-v1.3')) +if (optionsBinding.getOptionValue('--tls-max-v1.3')) exports.DEFAULT_MAX_VERSION = 'TLSv1.3'; -else if (getOptionValue('--tls-max-v1.2')) +else if (optionsBinding.getOptionValue('--tls-max-v1.2')) exports.DEFAULT_MAX_VERSION = 'TLSv1.2'; else exports.DEFAULT_MAX_VERSION = 'TLSv1.3'; // Will depend on node version. exports.getCiphers = internalUtil.cachedResult( - () => internalUtil.filterDuplicateStrings(getSSLCiphers(), true), + () => internalUtil.filterDuplicateStrings(cryptoBinding.getSSLCiphers(), true), ); let rootCertificates; function cacheRootCertificates() { - rootCertificates = ObjectFreeze(getRootCertificates()); + rootCertificates = ObjectFreeze(cryptoBinding.getRootCertificates()); } ObjectDefineProperty(exports, 'rootCertificates', { @@ -273,7 +273,7 @@ exports.checkServerIdentity = function checkServerIdentity(hostname, cert) { if (name.startsWith('DNS:')) { dnsNames.push(name.slice(4)); } else if (name.startsWith('IP Address:')) { - ips.push(canonicalizeIP(name.slice(11))); + ips.push(caresWrapBinding.canonicalizeIP(name.slice(11))); } }); } @@ -284,7 +284,7 @@ exports.checkServerIdentity = function checkServerIdentity(hostname, cert) { hostname = unfqdn(hostname); // Remove trailing dot for error messages. if (net.isIP(hostname)) { - valid = ips.includes(canonicalizeIP(hostname)); + valid = ips.includes(caresWrapBinding.canonicalizeIP(hostname)); if (!valid) reason = `IP: ${hostname} is not in the cert's list: ` + ips.join(', '); } else if (dnsNames.length > 0 || subject?.CN) { diff --git a/lib/trace_events.js b/lib/trace_events.js index b4b9be242737e2..5123d0c386e11a 100644 --- a/lib/trace_events.js +++ b/lib/trace_events.js @@ -5,7 +5,7 @@ const { SafeSet, } = primordials; -const { hasTracing } = internalBinding('config'); +const configBinding = internalBinding('config'); const kMaxTracingCount = 10; @@ -15,10 +15,10 @@ const { } = require('internal/errors').codes; const { ownsProcessState } = require('internal/worker'); -if (!hasTracing || !ownsProcessState) +if (!configBinding.hasTracing || !ownsProcessState) throw new ERR_TRACE_EVENTS_UNAVAILABLE(); -const { CategorySet, getEnabledCategories } = internalBinding('trace_events'); +const traceEventsBinding = internalBinding('trace_events'); const { customInspectSymbol } = require('internal/util'); const { format } = require('internal/util/inspect'); const { @@ -34,7 +34,7 @@ class Tracing { #enabled = false; constructor(categories) { - this.#handle = new CategorySet(categories); + this.#handle = new traceEventsBinding.CategorySet(categories); this.#categories = categories; } @@ -92,5 +92,5 @@ function createTracing(options) { module.exports = { createTracing, - getEnabledCategories, + getEnabledCategories: traceEventsBinding.getEnabledCategories, }; diff --git a/lib/tty.js b/lib/tty.js index 1a3fa5afe53a41..1e540b20c477f9 100644 --- a/lib/tty.js +++ b/lib/tty.js @@ -28,7 +28,7 @@ const { } = primordials; const net = require('net'); -const { TTY, isTTY } = internalBinding('tty_wrap'); +const binding = internalBinding('tty_wrap'); const { ErrnoException, codes: { @@ -46,7 +46,7 @@ let readline; function isatty(fd) { return NumberIsInteger(fd) && fd >= 0 && fd <= 2147483647 && - isTTY(fd); + binding.isTTY(fd); } function ReadStream(fd, options) { @@ -56,7 +56,7 @@ function ReadStream(fd, options) { throw new ERR_INVALID_FD(fd); const ctx = {}; - const tty = new TTY(fd, ctx); + const tty = new binding.TTY(fd, ctx); if (ctx.code !== undefined) { throw new ERR_TTY_INIT_FAILED(ctx); } @@ -93,7 +93,7 @@ function WriteStream(fd) { throw new ERR_INVALID_FD(fd); const ctx = {}; - const tty = new TTY(fd, ctx); + const tty = new binding.TTY(fd, ctx); if (ctx.code !== undefined) { throw new ERR_TTY_INIT_FAILED(ctx); } diff --git a/lib/v8.js b/lib/v8.js index b687d8709c99a0..ad625855c87654 100644 --- a/lib/v8.js +++ b/lib/v8.js @@ -35,10 +35,8 @@ const { const { Buffer } = require('buffer'); const { validateString, validateUint32 } = require('internal/validators'); -const { - Serializer, - Deserializer, -} = internalBinding('serdes'); +const serdesBinding = internalBinding('serdes'); +const { Serializer, Deserializer } = serdesBinding; const { namespace: startupSnapshot, } = require('internal/v8/startup_snapshot'); @@ -49,14 +47,11 @@ if (internalBinding('config').hasInspector) { } const assert = require('internal/assert'); -const { copy } = internalBinding('buffer'); +const bufferBinding = internalBinding('buffer'); const { inspect } = require('internal/util/inspect'); const { FastBuffer } = require('internal/buffer'); const { getValidatedPath } = require('internal/fs/utils'); -const { - createHeapSnapshotStream, - triggerHeapSnapshot, -} = internalBinding('heap_utils'); +const heapUtilsBinding = internalBinding('heap_utils'); const { HeapSnapshotStream, getHeapSnapshotOptions, @@ -79,7 +74,7 @@ function writeHeapSnapshot(filename, options) { filename = getValidatedPath(filename); } const optionArray = getHeapSnapshotOptions(options); - return triggerHeapSnapshot(filename, optionArray); + return heapUtilsBinding.triggerHeapSnapshot(filename, optionArray); } /** @@ -93,7 +88,7 @@ function writeHeapSnapshot(filename, options) { */ function getHeapSnapshot(options) { const optionArray = getHeapSnapshotOptions(options); - const handle = createHeapSnapshotStream(optionArray); + const handle = heapUtilsBinding.createHeapSnapshotStream(optionArray); assert(handle); return new HeapSnapshotStream(handle); } @@ -368,7 +363,7 @@ class DefaultDeserializer extends Deserializer { } // Copy to an aligned buffer first. const buffer_copy = Buffer.allocUnsafe(byteLength); - copy(this.buffer, buffer_copy, 0, byteOffset, byteOffset + byteLength); + bufferBinding.copy(this.buffer, buffer_copy, 0, byteOffset, byteOffset + byteLength); return new ctor(buffer_copy.buffer, buffer_copy.byteOffset, byteLength / BYTES_PER_ELEMENT); diff --git a/lib/vm.js b/lib/vm.js index e1ad4e30c33b66..e1cf9fd746afe3 100644 --- a/lib/vm.js +++ b/lib/vm.js @@ -29,12 +29,7 @@ const { Symbol, } = primordials; -const { - ContextifyScript, - makeContext, - constants, - measureMemory: _measureMemory, -} = internalBinding('contextify'); +const contextifyBinding = internalBinding('contextify'); const { ERR_CONTEXT_NOT_INITIALIZED, ERR_INVALID_ARG_TYPE, @@ -63,9 +58,7 @@ const { isContext: _isContext, registerImportModuleDynamically, } = require('internal/vm'); -const { - vm_dynamic_import_main_context_default, -} = internalBinding('symbols'); +const symbolsBinding = internalBinding('symbols'); const kParsingContext = Symbol('script parsing context'); /** @@ -80,7 +73,7 @@ function isContext(object) { return _isContext(object); } -class Script extends ContextifyScript { +class Script extends contextifyBinding.ContextifyScript { constructor(code, options = kEmptyObject) { code = `${code}`; if (typeof options === 'string') { @@ -258,7 +251,7 @@ function createContext(contextObject = {}, options = kEmptyObject) { const hostDefinedOptionId = getHostDefinedOptionId(importModuleDynamically, name); - makeContext(contextObject, name, origin, strings, wasm, microtaskQueue, hostDefinedOptionId); + contextifyBinding.makeContext(contextObject, name, origin, strings, wasm, microtaskQueue, hostDefinedOptionId); // Register the context scope callback after the context was initialized. registerImportModuleDynamically(contextObject, importModuleDynamically); return contextObject; @@ -368,13 +361,13 @@ function compileFunction(code, params, options = kEmptyObject) { } const measureMemoryModes = { - summary: constants.measureMemory.mode.SUMMARY, - detailed: constants.measureMemory.mode.DETAILED, + summary: contextifyBinding.constants.measureMemory.mode.SUMMARY, + detailed: contextifyBinding.constants.measureMemory.mode.DETAILED, }; const measureMemoryExecutions = { - default: constants.measureMemory.execution.DEFAULT, - eager: constants.measureMemory.execution.EAGER, + default: contextifyBinding.constants.measureMemory.execution.DEFAULT, + eager: contextifyBinding.constants.measureMemory.execution.EAGER, }; function measureMemory(options = kEmptyObject) { @@ -383,8 +376,8 @@ function measureMemory(options = kEmptyObject) { const { mode = 'summary', execution = 'default' } = options; validateOneOf(mode, 'options.mode', ['summary', 'detailed']); validateOneOf(execution, 'options.execution', ['default', 'eager']); - const result = _measureMemory(measureMemoryModes[mode], - measureMemoryExecutions[execution]); + const result = contextifyBinding.measureMemory(measureMemoryModes[mode], + measureMemoryExecutions[execution]); if (result === undefined) { return PromiseReject(new ERR_CONTEXT_NOT_INITIALIZED()); } @@ -393,7 +386,7 @@ function measureMemory(options = kEmptyObject) { const vmConstants = { __proto__: null, - USE_MAIN_CONTEXT_DEFAULT_LOADER: vm_dynamic_import_main_context_default, + USE_MAIN_CONTEXT_DEFAULT_LOADER: symbolsBinding.vm_dynamic_import_main_context_default, }; ObjectFreeze(vmConstants); diff --git a/typings/globals.d.ts b/typings/globals.d.ts index e2721c7c480371..21dd0f3f0507a5 100644 --- a/typings/globals.d.ts +++ b/typings/globals.d.ts @@ -1,7 +1,10 @@ import {AsyncWrapBinding} from "./internalBinding/async_wrap"; import {BlobBinding} from "./internalBinding/blob"; import {ConfigBinding} from "./internalBinding/config"; +import {ContextifyBinding} from "./internalBinding/contextify"; import {ConstantsBinding} from "./internalBinding/constants"; +import {CryptoBinding} from "./internalBinding/crypto"; +import {HeapUtilsBinding} from "./internalBinding/heap_utils"; import {HttpParserBinding} from "./internalBinding/http_parser"; import {FsBinding} from "./internalBinding/fs"; import {FsDirBinding} from "./internalBinding/fs_dir"; @@ -11,6 +14,7 @@ import {OSBinding} from "./internalBinding/os"; import {SerdesBinding} from "./internalBinding/serdes"; import {SymbolsBinding} from "./internalBinding/symbols"; import {TimersBinding} from "./internalBinding/timers"; +import {TTYBinding} from "./internalBinding/tty"; import {TypesBinding} from "./internalBinding/types"; import {URLBinding} from "./internalBinding/url"; import {UtilBinding} from "./internalBinding/util"; @@ -35,8 +39,11 @@ interface InternalBindingMap { blob: BlobBinding; config: ConfigBinding; constants: ConstantsBinding; + contextify: ContextifyBinding; + crypto: CryptoBinding; fs: FsBinding; fs_dir: FsDirBinding; + heap_utils: HeapUtilsBinding; http_parser: HttpParserBinding; messaging: MessagingBinding; modules: ModulesBinding; @@ -45,6 +52,7 @@ interface InternalBindingMap { serdes: SerdesBinding; symbols: SymbolsBinding; timers: TimersBinding; + tty: TTYBinding; types: TypesBinding; url: URLBinding; util: UtilBinding; diff --git a/typings/internalBinding/contextify.d.ts b/typings/internalBinding/contextify.d.ts new file mode 100644 index 00000000000000..dcc9f044b88a97 --- /dev/null +++ b/typings/internalBinding/contextify.d.ts @@ -0,0 +1,8 @@ +export interface ContextifyBinding { + constants: { + measureMemory: Record; + } + measureMemory(mode: string, execution: string): number | undefined; + makeContext(contextObject: unknown, name: string, origin: string, strings: boolean, wasm: boolean, microtaskQueue: boolean, hostDefinedOptionId: string): void; + ContextifyContext: new (code: string, filename?: string, lineOffset?: number, columnOffset?: number, cachedData?: string, produceCachedData?: boolean, parsingContext?: unknown, hostDefinedOptionId?: string) => unknown; +} diff --git a/typings/internalBinding/crypto.d.ts b/typings/internalBinding/crypto.d.ts new file mode 100644 index 00000000000000..7e14363a111b59 --- /dev/null +++ b/typings/internalBinding/crypto.d.ts @@ -0,0 +1,10 @@ +type Buffer = Uint8Array; + +export interface CryptoBinding { + SecureContext: new () => unknown; + timingSafeEqual: (a: Buffer | ArrayBuffer | TypedArray | DataView, b: Buffer | ArrayBuffer | TypedArray | DataView) => boolean; + getFipsCrypto(): boolean; + setFipsCrypto(bool: boolean): void; + getSSLCiphers(): unknown; + getRootCertificates(): unknown; +} diff --git a/typings/internalBinding/heap_utils.d.ts b/typings/internalBinding/heap_utils.d.ts new file mode 100644 index 00000000000000..cb7272b73e89e8 --- /dev/null +++ b/typings/internalBinding/heap_utils.d.ts @@ -0,0 +1,4 @@ +export interface HeapUtilsBinding { + createHeapSnapshotStream(options: string[]): unknown; + triggerHeapSnapshot(filename: string, options: string[]): string; +} diff --git a/typings/internalBinding/symbols.d.ts b/typings/internalBinding/symbols.d.ts index 96310970d5cdee..084ea7ef031807 100644 --- a/typings/internalBinding/symbols.d.ts +++ b/typings/internalBinding/symbols.d.ts @@ -9,6 +9,7 @@ export const oninit_symbol: unique symbol; export const owner_symbol: unique symbol; export const onpskexchange_symbol: unique symbol; export const trigger_async_id_symbol: unique symbol; +export const vm_dynamic_import_main_context_default: unique symbol; export interface SymbolsBinding { async_id_symbol: typeof async_id_symbol; @@ -22,4 +23,5 @@ export interface SymbolsBinding { owner_symbol: typeof owner_symbol; onpskexchange_symbol: typeof onpskexchange_symbol; trigger_async_id_symbol: typeof trigger_async_id_symbol; + vm_dynamic_import_main_context_default: typeof vm_dynamic_import_main_context_default; } diff --git a/typings/internalBinding/tty.d.ts b/typings/internalBinding/tty.d.ts new file mode 100644 index 00000000000000..3a47d9ee6a93ec --- /dev/null +++ b/typings/internalBinding/tty.d.ts @@ -0,0 +1,15 @@ +declare namespace InternalTTYBinding { + interface TTYContext { + code?: number; + message?: string; + } + + class TTY { + constructor(fd: number, ctx: TTYContext); + } +} + +export interface TTYBinding { + isTTY(fd: number): boolean; + TTY: typeof InternalTTYBinding.TTY; +}