meta: enable jsdoc/check-tag-names rule

PR-URL: https://github.com/nodejs/node/pull/58521
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: LiviaMedeiros <livia@cirno.name>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
Yagiz Nizipli 2025-07-18 05:28:21 -04:00 committed by GitHub
parent 036b1fd66d
commit 0fd1ecded6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
86 changed files with 495 additions and 247 deletions

View file

@ -386,7 +386,7 @@ function getUrlData(withBase) {
* @param {number} e The repetition of the data, as exponent of 2 * @param {number} e The repetition of the data, as exponent of 2
* @param {boolean} withBase Whether to include a base URL * @param {boolean} withBase Whether to include a base URL
* @param {boolean} asUrl Whether to return the results as URL objects * @param {boolean} asUrl Whether to return the results as URL objects
* @return {string[] | string[][] | URL[]} * @returns {string[] | string[][] | URL[]}
*/ */
function bakeUrlData(type, e = 0, withBase = false, asUrl = false) { function bakeUrlData(type, e = 0, withBase = false, asUrl = false) {
let result = []; let result = [];

View file

@ -262,17 +262,21 @@ export default [
// ESLint recommended rules that we disable. // ESLint recommended rules that we disable.
'no-inner-declarations': 'off', 'no-inner-declarations': 'off',
// JSDoc recommended rules that we disable. // JSDoc rules.
'jsdoc/require-jsdoc': 'off', 'jsdoc/require-jsdoc': 'off',
'jsdoc/require-param-description': 'off', 'jsdoc/require-param-description': 'off',
'jsdoc/newline-after-description': 'off',
'jsdoc/require-returns-description': 'off', 'jsdoc/require-returns-description': 'off',
'jsdoc/valid-types': 'off', 'jsdoc/valid-types': 'error',
'jsdoc/no-defaults': 'off', 'jsdoc/no-defaults': 'error',
'jsdoc/no-undefined-types': 'off', 'jsdoc/no-undefined-types': 'off',
'jsdoc/require-param': 'off', 'jsdoc/require-param': 'off',
'jsdoc/check-tag-names': 'off', 'jsdoc/check-tag-names': 'error',
'jsdoc/require-returns': 'off', 'jsdoc/require-returns': 'error',
'jsdoc/check-line-alignment': ['error', 'any', {
tags: ['param', 'property', 'returns', 'file'],
wrapIndent: ' ',
}],
'jsdoc/check-alignment': 'error',
// Stylistic rules. // Stylistic rules.
'@stylistic/js/arrow-parens': 'error', '@stylistic/js/arrow-parens': 'error',

View file

@ -206,6 +206,8 @@ const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/;
* Verifies that the given val is a valid HTTP token * Verifies that the given val is a valid HTTP token
* per the rules defined in RFC 7230 * per the rules defined in RFC 7230
* See https://tools.ietf.org/html/rfc7230#section-3.2.6 * See https://tools.ietf.org/html/rfc7230#section-3.2.6
* @param {string} val
* @returns {boolean}
*/ */
function checkIsHttpToken(val) { function checkIsHttpToken(val) {
return tokenRegExp.test(val); return tokenRegExp.test(val);
@ -217,6 +219,8 @@ const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
* field-value = *( field-content / obs-fold ) * field-value = *( field-content / obs-fold )
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
* field-vchar = VCHAR / obs-text * field-vchar = VCHAR / obs-text
* @param {string} val
* @returns {boolean}
*/ */
function checkInvalidHeaderChar(val) { function checkInvalidHeaderChar(val) {
return headerCharRegex.test(val); return headerCharRegex.test(val);

View file

@ -266,6 +266,7 @@ function _copyActual(source, target, targetStart, sourceStart, sourceEnd) {
* runtime deprecation would introduce too much breakage at this time. It's not * runtime deprecation would introduce too much breakage at this time. It's not
* likely that the Buffer constructors would ever actually be removed. * likely that the Buffer constructors would ever actually be removed.
* Deprecation Code: DEP0005 * Deprecation Code: DEP0005
* @returns {Buffer}
*/ */
function Buffer(arg, encodingOrOffset, length) { function Buffer(arg, encodingOrOffset, length) {
showFlaggedDeprecation(); showFlaggedDeprecation();
@ -293,6 +294,10 @@ ObjectDefineProperty(Buffer, SymbolSpecies, {
* Buffer.from(array) * Buffer.from(array)
* Buffer.from(buffer) * Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]]) * Buffer.from(arrayBuffer[, byteOffset[, length]])
* @param {any} value
* @param {BufferEncoding|number} encodingOrOffset
* @param {number} [length]
* @returns {Buffer}
*/ */
Buffer.from = function from(value, encodingOrOffset, length) { Buffer.from = function from(value, encodingOrOffset, length) {
if (typeof value === 'string') if (typeof value === 'string')
@ -389,6 +394,7 @@ ObjectSetPrototypeOf(Buffer, Uint8Array);
/** /**
* Creates a new filled Buffer instance. * Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]]) * alloc(size[, fill[, encoding]])
* @returns {FastBuffer}
*/ */
Buffer.alloc = function alloc(size, fill, encoding) { Buffer.alloc = function alloc(size, fill, encoding) {
validateNumber(size, 'size', 0, kMaxLength); validateNumber(size, 'size', 0, kMaxLength);
@ -402,6 +408,7 @@ Buffer.alloc = function alloc(size, fill, encoding) {
/** /**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer
* instance. If `--zero-fill-buffers` is set, will zero-fill the buffer. * instance. If `--zero-fill-buffers` is set, will zero-fill the buffer.
* @returns {FastBuffer}
*/ */
Buffer.allocUnsafe = function allocUnsafe(size) { Buffer.allocUnsafe = function allocUnsafe(size) {
validateNumber(size, 'size', 0, kMaxLength); validateNumber(size, 'size', 0, kMaxLength);
@ -412,6 +419,8 @@ Buffer.allocUnsafe = function allocUnsafe(size) {
* By default creates a non-zero-filled Buffer instance that is not allocated * By default creates a non-zero-filled Buffer instance that is not allocated
* off the pre-initialized pool. If `--zero-fill-buffers` is set, will zero-fill * off the pre-initialized pool. If `--zero-fill-buffers` is set, will zero-fill
* the buffer. * the buffer.
* @param {number} size
* @returns {FastBuffer|undefined}
*/ */
Buffer.allocUnsafeSlow = function allocUnsafeSlow(size) { Buffer.allocUnsafeSlow = function allocUnsafeSlow(size) {
validateNumber(size, 'size', 0, kMaxLength); validateNumber(size, 'size', 0, kMaxLength);

View file

@ -157,8 +157,8 @@ function lazyEventEmitterAsyncResource() {
} }
/** /**
* @param {symbol,string} event * @param {symbol|string} event
* @param {...any} args * @param {any[]} args
* @returns {boolean} * @returns {boolean}
*/ */
emit(event, ...args) { emit(event, ...args) {
@ -203,7 +203,7 @@ function lazyEventEmitterAsyncResource() {
/** /**
* Creates a new `EventEmitter` instance. * Creates a new `EventEmitter` instance.
* @param {{ captureRejections?: boolean; }} [opts] * @param {{ captureRejections?: boolean; }} [opts]
* @constructs {EventEmitter} * @constructs EventEmitter
*/ */
function EventEmitter(opts) { function EventEmitter(opts) {
EventEmitter.init.call(this, opts); EventEmitter.init.call(this, opts);
@ -1115,24 +1115,28 @@ function on(emitter, event, options = kEmptyObject) {
[kWatermarkData]: { [kWatermarkData]: {
/** /**
* The current queue size * The current queue size
* @returns {number}
*/ */
get size() { get size() {
return size; return size;
}, },
/** /**
* The low watermark. The emitter is resumed every time size is lower than it * The low watermark. The emitter is resumed every time size is lower than it
* @returns {number}
*/ */
get low() { get low() {
return lowWatermark; return lowWatermark;
}, },
/** /**
* The high watermark. The emitter is paused every time size is higher than it * The high watermark. The emitter is paused every time size is higher than it
* @returns {number}
*/ */
get high() { get high() {
return highWatermark; return highWatermark;
}, },
/** /**
* It checks whether the emitter is paused by the watermark controller or not * It checks whether the emitter is paused by the watermark controller or not
* @returns {boolean}
*/ */
get isPaused() { get isPaused() {
return paused; return paused;

View file

@ -442,7 +442,7 @@ function createConnection(...args) {
* protocol?: string; * protocol?: string;
* proxyEnv?: object; * proxyEnv?: object;
* }} [options] * }} [options]
* @constructor * @class
*/ */
function Agent(options) { function Agent(options) {
if (!(this instanceof Agent)) if (!(this instanceof Agent))

View file

@ -534,6 +534,7 @@ function transferableAbortSignal(signal) {
/** /**
* Creates an AbortController with a transferable AbortSignal * Creates an AbortController with a transferable AbortSignal
* @returns {AbortController}
*/ */
function transferableAbortController() { function transferableAbortController() {
return AbortController[kMakeTransferable](); return AbortController[kMakeTransferable]();

View file

@ -449,7 +449,7 @@ function clearDefaultTriggerAsyncId() {
* @template {unknown} R * @template {unknown} R
* @param {number} triggerAsyncId * @param {number} triggerAsyncId
* @param { (...T: args) => R } block * @param { (...T: args) => R } block
* @param {T} args * @param {T} args
* @returns {R} * @returns {R}
*/ */
function defaultTriggerAsyncIdScope(triggerAsyncId, block, ...args) { function defaultTriggerAsyncIdScope(triggerAsyncId, block, ...args) {

View file

@ -137,7 +137,7 @@ class Blob {
* endings? : string, * endings? : string,
* type? : string, * type? : string,
* }} [options] * }} [options]
* @constructs {Blob} * @constructs Blob
*/ */
constructor(sources = [], options) { constructor(sources = [], options) {
markTransferMode(this, true, false); markTransferMode(this, true, false);

View file

@ -68,6 +68,7 @@ const kFinalized = Symbol('kFinalized');
/** /**
* @param {string} name * @param {string} name
* @returns {string}
*/ */
function normalizeAlgorithm(name) { function normalizeAlgorithm(name) {
return StringPrototypeReplace(StringPrototypeToLowerCase(name), '-', ''); return StringPrototypeReplace(StringPrototypeToLowerCase(name), '-', '');

View file

@ -503,13 +503,13 @@ function generatePrimeSync(size, options = kEmptyObject) {
* 48 is the ASCII code for '0', 97 is the ASCII code for 'a'. * 48 is the ASCII code for '0', 97 is the ASCII code for 'a'.
* @param {number} number An integer between 0 and 15. * @param {number} number An integer between 0 and 15.
* @returns {number} corresponding to the ASCII code of the hex representation * @returns {number} corresponding to the ASCII code of the hex representation
* of the parameter. * of the parameter.
*/ */
const numberToHexCharCode = (number) => (number < 10 ? 48 : 87) + number; const numberToHexCharCode = (number) => (number < 10 ? 48 : 87) + number;
/** /**
* @param {ArrayBuffer} buf An ArrayBuffer. * @param {ArrayBuffer} buf An ArrayBuffer.
* @return {bigint} * @returns {bigint}
*/ */
function arrayBufferToUnsignedBigInt(buf) { function arrayBufferToUnsignedBigInt(buf) {
const length = ArrayBufferPrototypeGetByteLength(buf); const length = ArrayBufferPrototypeGetByteLength(buf);

View file

@ -28,7 +28,10 @@ function lazyEncoder() {
const ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g // eslint-disable-line const ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g // eslint-disable-line
// https://fetch.spec.whatwg.org/#data-url-processor // https://fetch.spec.whatwg.org/#data-url-processor
/** @param {URL} dataURL */ /**
* @param {URL} dataURL
* @returns {object|'failure'}
*/
function dataURLProcessor(dataURL) { function dataURLProcessor(dataURL) {
// 1. Assert: dataURL's scheme is "data". // 1. Assert: dataURL's scheme is "data".
assert(dataURL.protocol === 'data:'); assert(dataURL.protocol === 'data:');
@ -132,6 +135,7 @@ function dataURLProcessor(dataURL) {
/** /**
* @param {URL} url * @param {URL} url
* @param {boolean} excludeFragment * @param {boolean} excludeFragment
* @returns {string}
*/ */
function URLSerializer(url, excludeFragment = false) { function URLSerializer(url, excludeFragment = false) {
const { href } = url; const { href } = url;
@ -155,6 +159,7 @@ function URLSerializer(url, excludeFragment = false) {
* @param {string} char * @param {string} char
* @param {string} input * @param {string} input
* @param {{ position: number }} position * @param {{ position: number }} position
* @returns {string}
*/ */
function collectASequenceOfCodePointsFast(char, input, position) { function collectASequenceOfCodePointsFast(char, input, position) {
const idx = StringPrototypeIndexOf(input, char, position.position); const idx = StringPrototypeIndexOf(input, char, position.position);
@ -170,7 +175,10 @@ function collectASequenceOfCodePointsFast(char, input, position) {
} }
// https://url.spec.whatwg.org/#string-percent-decode // https://url.spec.whatwg.org/#string-percent-decode
/** @param {string} input */ /**
* @param {string} input
* @returns {Uint8Array}
*/
function stringPercentDecode(input) { function stringPercentDecode(input) {
// 1. Let bytes be the UTF-8 encoding of input. // 1. Let bytes be the UTF-8 encoding of input.
const bytes = lazyEncoder().encode(input); const bytes = lazyEncoder().encode(input);
@ -181,6 +189,7 @@ function stringPercentDecode(input) {
/** /**
* @param {number} byte * @param {number} byte
* @returns {boolean}
*/ */
function isHexCharByte(byte) { function isHexCharByte(byte) {
// 0-9 A-F a-f // 0-9 A-F a-f
@ -189,6 +198,7 @@ function isHexCharByte(byte) {
/** /**
* @param {number} byte * @param {number} byte
* @returns {number}
*/ */
function hexByteToNumber(byte) { function hexByteToNumber(byte) {
return ( return (
@ -202,7 +212,10 @@ function hexByteToNumber(byte) {
} }
// https://url.spec.whatwg.org/#percent-decode // https://url.spec.whatwg.org/#percent-decode
/** @param {Uint8Array} input */ /**
* @param {Uint8Array} input
* @returns {Uint8Array}
*/
function percentDecode(input) { function percentDecode(input) {
const length = input.length; const length = input.length;
// 1. Let output be an empty byte sequence. // 1. Let output be an empty byte sequence.
@ -245,7 +258,10 @@ function percentDecode(input) {
} }
// https://infra.spec.whatwg.org/#forgiving-base64-decode // https://infra.spec.whatwg.org/#forgiving-base64-decode
/** @param {string} data */ /**
* @param {string} data
* @returns {object|'failure'}
*/
function forgivingBase64(data) { function forgivingBase64(data) {
// 1. Remove all ASCII whitespace from data. // 1. Remove all ASCII whitespace from data.
data = RegExpPrototypeSymbolReplace(ASCII_WHITESPACE_REPLACE_REGEX, data, ''); data = RegExpPrototypeSymbolReplace(ASCII_WHITESPACE_REPLACE_REGEX, data, '');
@ -286,6 +302,7 @@ function forgivingBase64(data) {
/** /**
* @see https://infra.spec.whatwg.org/#ascii-whitespace * @see https://infra.spec.whatwg.org/#ascii-whitespace
* @param {number} char * @param {number} char
* @returns {boolean}
*/ */
function isASCIIWhitespace(char) { function isASCIIWhitespace(char) {
// "\r\n\t\f " // "\r\n\t\f "
@ -295,8 +312,9 @@ function isASCIIWhitespace(char) {
/** /**
* @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
* @param {string} str * @param {string} str
* @param {boolean} [leading=true] * @param {boolean} [leading]
* @param {boolean} [trailing=true] * @param {boolean} [trailing]
* @returns {string}
*/ */
function removeASCIIWhitespace(str, leading = true, trailing = true) { function removeASCIIWhitespace(str, leading = true, trailing = true) {
return removeChars(str, leading, trailing, isASCIIWhitespace); return removeChars(str, leading, trailing, isASCIIWhitespace);
@ -307,6 +325,7 @@ function removeASCIIWhitespace(str, leading = true, trailing = true) {
* @param {boolean} leading * @param {boolean} leading
* @param {boolean} trailing * @param {boolean} trailing
* @param {(charCode: number) => boolean} predicate * @param {(charCode: number) => boolean} predicate
* @returns {string}
*/ */
function removeChars(str, leading, trailing, predicate) { function removeChars(str, leading, trailing, predicate) {
let lead = 0; let lead = 0;

View file

@ -124,7 +124,7 @@ function onlookupall(err, addresses) {
* @param {string} hostname - The hostname to resolve. * @param {string} hostname - The hostname to resolve.
* @param {boolean} all - Whether to resolve with all IP addresses for the hostname. * @param {boolean} all - Whether to resolve with all IP addresses for the hostname.
* @param {number} hints - One or more supported getaddrinfo flags (supply multiple via * @param {number} hints - One or more supported getaddrinfo flags (supply multiple via
* bitwise OR). * bitwise OR).
* @param {number} dnsOrder - How to sort results. Must be `ipv4first`, `ipv6first` or `verbatim`. * @param {number} dnsOrder - How to sort results. Must be `ipv4first`, `ipv6first` or `verbatim`.
* @returns {Promise<DNSLookupResult | DNSLookupResult[]>} The IP address(es) of the hostname. * @returns {Promise<DNSLookupResult | DNSLookupResult[]>} The IP address(es) of the hostname.
* @typedef {object} DNSLookupResult * @typedef {object} DNSLookupResult
@ -184,13 +184,13 @@ function createLookupPromise(family, hostname, all, hints, dnsOrder) {
* Get the IP address for a given hostname. * Get the IP address for a given hostname.
* @param {string} hostname - The hostname to resolve (ex. 'nodejs.org'). * @param {string} hostname - The hostname to resolve (ex. 'nodejs.org').
* @param {object} [options] - Optional settings. * @param {object} [options] - Optional settings.
* @param {boolean} [options.all=false] - Whether to return all or just the first resolved address. * @param {boolean} [options.all] - Whether to return all or just the first resolved address.
* @param {0 | 4 | 6} [options.family=0] - The record family. Must be 4, 6, or 0 (for both). * @param {0 | 4 | 6} [options.family] - The record family. Must be 4, 6, or 0 (for both).
* @param {number} [options.hints] - One or more supported getaddrinfo flags (supply multiple via * @param {number} [options.hints] - One or more supported getaddrinfo flags (supply multiple via
* bitwise OR). * bitwise OR).
* @param {string} [options.order='verbatim'] - Return results in same order DNS resolved them; * @param {'ipv4first' | 'ipv6first' | 'verbatim'} [options.order] - Return results in same order DNS resolved them;
* Must be `ipv4first`, `ipv6first` or `verbatim`. * New code should supply `verbatim`.
* New code should supply `verbatim`. * @returns {Promise<object>}
*/ */
function lookup(hostname, options) { function lookup(hostname, options) {
let hints = 0; let hints = 0;

View file

@ -90,6 +90,7 @@ let internalPrepareStackTrace = defaultPrepareStackTrace;
* The default implementation of `Error.prepareStackTrace` with simple * The default implementation of `Error.prepareStackTrace` with simple
* concatenation of stack frames. * concatenation of stack frames.
* Read more about `Error.prepareStackTrace` at https://v8.dev/docs/stack-trace-api#customizing-stack-traces. * Read more about `Error.prepareStackTrace` at https://v8.dev/docs/stack-trace-api#customizing-stack-traces.
* @returns {string}
*/ */
function defaultPrepareStackTrace(error, trace) { function defaultPrepareStackTrace(error, trace) {
// Normal error formatting: // Normal error formatting:
@ -161,6 +162,7 @@ function prepareStackTraceCallback(globalThis, error, trace) {
/** /**
* The default Error.prepareStackTrace implementation. * The default Error.prepareStackTrace implementation.
* @returns {string}
*/ */
function ErrorPrepareStackTrace(error, trace) { function ErrorPrepareStackTrace(error, trace) {
return internalPrepareStackTrace(error, trace); return internalPrepareStackTrace(error, trace);

View file

@ -375,7 +375,6 @@ function isCustomEvent(value) {
class CustomEvent extends Event { class CustomEvent extends Event {
/** /**
* @constructor
* @param {string} type * @param {string} type
* @param {{ * @param {{
* bubbles?: boolean, * bubbles?: boolean,
@ -746,6 +745,7 @@ class EventTarget {
/** /**
* @param {Event} event * @param {Event} event
* @returns {boolean}
*/ */
dispatchEvent(event) { dispatchEvent(event) {
if (!isEventTarget(this)) if (!isEventTarget(this))

View file

@ -615,6 +615,7 @@ const assertValidPseudoHeaderTrailer = hideStackFrames((key) => {
/** /**
* Takes a request headers array, validates it and sets defaults, and returns * Takes a request headers array, validates it and sets defaults, and returns
* the resulting headers in NgHeaders string list format. * the resulting headers in NgHeaders string list format.
* @returns {object}
*/ */
function prepareRequestHeadersArray(headers, session) { function prepareRequestHeadersArray(headers, session) {
let method; let method;
@ -696,6 +697,7 @@ function prepareRequestHeadersArray(headers, session) {
/** /**
* Takes a request headers object, validates it and sets defaults, and returns * Takes a request headers object, validates it and sets defaults, and returns
* the resulting headers in object format and NgHeaders string list format. * the resulting headers in object format and NgHeaders string list format.
* @returns {object}
*/ */
function prepareRequestHeadersObject(headers, session) { function prepareRequestHeadersObject(headers, session) {
const headersObject = ObjectAssign({ __proto__: null }, headers); const headersObject = ObjectAssign({ __proto__: null }, headers);
@ -742,6 +744,7 @@ const kNoHeaderFlags = StringFromCharCode(NGHTTP2_NV_FLAG_NONE);
* format, rejecting illegal header configurations, and marking sensitive headers * format, rejecting illegal header configurations, and marking sensitive headers
* that should not be indexed en route. This takes either a flat map of * that should not be indexed en route. This takes either a flat map of
* raw headers ([k1, v1, k2, v2]) or a header object ({ k1: v1, k2: [v2, v3] }). * raw headers ([k1, v1, k2, v2]) or a header object ({ k1: v1, k2: [v2, v3] }).
* @returns {[string, number]}
*/ */
function buildNgHeaderString(arrayOrMap, function buildNgHeaderString(arrayOrMap,
assertValuePseudoHeader = assertValidPseudoHeader, assertValuePseudoHeader = assertValidPseudoHeader,

View file

@ -131,6 +131,7 @@ class MIMEParams {
/** /**
* Used to instantiate a MIMEParams object within the MIMEType class and * Used to instantiate a MIMEParams object within the MIMEType class and
* to allow it to be parsed lazily. * to allow it to be parsed lazily.
* @returns {MIMEParams}
*/ */
static instantiateMimeParams(str) { static instantiateMimeParams(str) {
const instance = new MIMEParams(); const instance = new MIMEParams();
@ -139,6 +140,10 @@ class MIMEParams {
return instance; return instance;
} }
/**
* @param {string} name
* @returns {void}
*/
delete(name) { delete(name) {
this.#parse(); this.#parse();
this.#data.delete(name); this.#data.delete(name);

View file

@ -224,6 +224,7 @@ let statCache = null;
* Internal method to add tracing capabilities for Module._load. * Internal method to add tracing capabilities for Module._load.
* *
* See more {@link Module._load} * See more {@link Module._load}
* @returns {object}
*/ */
function wrapModuleLoad(request, parent, isMain) { function wrapModuleLoad(request, parent, isMain) {
const logLabel = `[${parent?.id || ''}] [${request}]`; const logLabel = `[${parent?.id || ''}] [${request}]`;
@ -245,6 +246,7 @@ function wrapModuleLoad(request, parent, isMain) {
/** /**
* Get a path's properties, using an in-memory cache to minimize lookups. * Get a path's properties, using an in-memory cache to minimize lookups.
* @param {string} filename Absolute path to the file * @param {string} filename Absolute path to the file
* @returns {number}
*/ */
function stat(filename) { function stat(filename) {
// Guard against internal bugs where a non-string filename is passed in by mistake. // Guard against internal bugs where a non-string filename is passed in by mistake.
@ -280,6 +282,7 @@ ObjectDefineProperty(Module, '_stat', {
* @param {Module} parent Module requiring the children * @param {Module} parent Module requiring the children
* @param {Module} child Module being required * @param {Module} child Module being required
* @param {boolean} scan Add the child to the parent's children if not already present * @param {boolean} scan Add the child to the parent's children if not already present
* @returns {void}
*/ */
function updateChildren(parent, child, scan) { function updateChildren(parent, child, scan) {
const children = parent?.children; const children = parent?.children;
@ -291,6 +294,7 @@ function updateChildren(parent, child, scan) {
/** /**
* Tell the watch mode that a module was required. * Tell the watch mode that a module was required.
* @param {string} filename Absolute path of the module * @param {string} filename Absolute path of the module
* @returns {void}
*/ */
function reportModuleToWatchMode(filename) { function reportModuleToWatchMode(filename) {
if (shouldReportRequiredModules() && process.send) { if (shouldReportRequiredModules() && process.send) {
@ -302,6 +306,7 @@ function reportModuleToWatchMode(filename) {
* Tell the watch mode that a module was not found. * Tell the watch mode that a module was not found.
* @param {string} basePath The absolute path that errored * @param {string} basePath The absolute path that errored
* @param {string[]} extensions The extensions that were tried * @param {string[]} extensions The extensions that were tried
* @returns {void}
*/ */
function reportModuleNotFoundToWatchMode(basePath, extensions) { function reportModuleNotFoundToWatchMode(basePath, extensions) {
if (shouldReportRequiredModules() && process.send) { if (shouldReportRequiredModules() && process.send) {
@ -313,6 +318,7 @@ function reportModuleNotFoundToWatchMode(basePath, extensions) {
* Create a new module instance. * Create a new module instance.
* @param {string} id * @param {string} id
* @param {Module} parent * @param {Module} parent
* @returns {void}
*/ */
function Module(id = '', parent) { function Module(id = '', parent) {
this.id = id; this.id = id;
@ -329,7 +335,7 @@ function Module(id = '', parent) {
Module._cache = { __proto__: null }; Module._cache = { __proto__: null };
/** @type {Record<string, string>} */ /** @type {Record<string, string>} */
Module._pathCache = { __proto__: null }; Module._pathCache = { __proto__: null };
/** @type {Record<string, (module: Module, filename: string) => void>} */ /** @type {{[key: string]: function(Module, string): void}} */
Module._extensions = { __proto__: null }; Module._extensions = { __proto__: null };
/** @type {string[]} */ /** @type {string[]} */
let modulePaths = []; let modulePaths = [];
@ -341,6 +347,7 @@ let patched = false;
/** /**
* Add the CommonJS wrapper around a module's source code. * Add the CommonJS wrapper around a module's source code.
* @param {string} script Module source code * @param {string} script Module source code
* @returns {string}
*/ */
let wrap = function(script) { // eslint-disable-line func-style let wrap = function(script) { // eslint-disable-line func-style
return Module.wrapper[0] + script + Module.wrapper[1]; return Module.wrapper[0] + script + Module.wrapper[1];
@ -396,6 +403,7 @@ ObjectDefineProperty(BuiltinModule.prototype, 'isPreloading', isPreloadingDesc);
/** /**
* Get the parent of the current module from our cache. * Get the parent of the current module from our cache.
* @this {Module} * @this {Module}
* @returns {object}
*/ */
function getModuleParent() { function getModuleParent() {
return this[kModuleParent]; return this[kModuleParent];
@ -405,6 +413,7 @@ function getModuleParent() {
* Set the parent of the current module in our cache. * Set the parent of the current module in our cache.
* @this {Module} * @this {Module}
* @param {Module} value * @param {Module} value
* @returns {void}
*/ */
function setModuleParent(value) { function setModuleParent(value) {
this[kModuleParent] = value; this[kModuleParent] = value;
@ -434,6 +443,7 @@ Module.isBuiltin = BuiltinModule.isBuiltin;
/** /**
* Prepare to run CommonJS code. * Prepare to run CommonJS code.
* This function is called during pre-execution, before any user code is run. * This function is called during pre-execution, before any user code is run.
* @returns {void}
*/ */
function initializeCJS() { function initializeCJS() {
// This need to be done at runtime in case --expose-internals is set. // This need to be done at runtime in case --expose-internals is set.
@ -484,6 +494,7 @@ ObjectDefineProperty(Module, '_readPackage', {
* @param {string[]} exts File extensions to try appending in order to resolve the file * @param {string[]} exts File extensions to try appending in order to resolve the file
* @param {boolean} isMain Whether the file is the main entry point of the app * @param {boolean} isMain Whether the file is the main entry point of the app
* @param {string} originalPath The specifier passed to `require` * @param {string} originalPath The specifier passed to `require`
* @returns {any}
*/ */
function tryPackage(requestPath, exts, isMain, originalPath) { function tryPackage(requestPath, exts, isMain, originalPath) {
const { main: pkg, pjsonPath } = _readPackage(requestPath); const { main: pkg, pjsonPath } = _readPackage(requestPath);
@ -526,6 +537,7 @@ function tryPackage(requestPath, exts, isMain, originalPath) {
* `--preserve-symlinks-main` and `isMain` is true , keep symlinks intact, otherwise resolve to the absolute realpath. * `--preserve-symlinks-main` and `isMain` is true , keep symlinks intact, otherwise resolve to the absolute realpath.
* @param {string} requestPath The path to the file to load. * @param {string} requestPath The path to the file to load.
* @param {boolean} isMain Whether the file is the main module. * @param {boolean} isMain Whether the file is the main module.
* @returns {string|undefined}
*/ */
function tryFile(requestPath, isMain) { function tryFile(requestPath, isMain) {
const rc = _stat(requestPath); const rc = _stat(requestPath);
@ -541,6 +553,7 @@ function tryFile(requestPath, isMain) {
* @param {string} basePath The path and filename without extension * @param {string} basePath The path and filename without extension
* @param {string[]} exts The extensions to try * @param {string[]} exts The extensions to try
* @param {boolean} isMain Whether the module is the main module * @param {boolean} isMain Whether the module is the main module
* @returns {string|false}
*/ */
function tryExtensions(basePath, exts, isMain) { function tryExtensions(basePath, exts, isMain) {
for (let i = 0; i < exts.length; i++) { for (let i = 0; i < exts.length; i++) {
@ -556,6 +569,7 @@ function tryExtensions(basePath, exts, isMain) {
/** /**
* Find the longest (possibly multi-dot) extension registered in `Module._extensions`. * Find the longest (possibly multi-dot) extension registered in `Module._extensions`.
* @param {string} filename The filename to find the longest registered extension for. * @param {string} filename The filename to find the longest registered extension for.
* @returns {string}
*/ */
function findLongestRegisteredExtension(filename) { function findLongestRegisteredExtension(filename) {
const name = path.basename(filename); const name = path.basename(filename);
@ -574,6 +588,7 @@ function findLongestRegisteredExtension(filename) {
/** /**
* Tries to get the absolute file path of the parent module. * Tries to get the absolute file path of the parent module.
* @param {Module} parent The parent module object. * @param {Module} parent The parent module object.
* @returns {string|false|void}
*/ */
function trySelfParentPath(parent) { function trySelfParentPath(parent) {
if (!parent) { return false; } if (!parent) { return false; }
@ -593,6 +608,8 @@ function trySelfParentPath(parent) {
* Attempt to resolve a module request using the parent module package metadata. * Attempt to resolve a module request using the parent module package metadata.
* @param {string} parentPath The path of the parent module * @param {string} parentPath The path of the parent module
* @param {string} request The module request to resolve * @param {string} request The module request to resolve
* @param {unknown} conditions
* @returns {false|string}
*/ */
function trySelf(parentPath, request, conditions) { function trySelf(parentPath, request, conditions) {
if (!parentPath) { return false; } if (!parentPath) { return false; }
@ -635,6 +652,8 @@ const EXPORTS_PATTERN = /^((?:@[^/\\%]+\/)?[^./\\%][^/\\%]*)(\/.*)?$/;
* Resolves the exports for a given module path and request. * Resolves the exports for a given module path and request.
* @param {string} nmPath The path to the module. * @param {string} nmPath The path to the module.
* @param {string} request The request for the module. * @param {string} request The request for the module.
* @param {unknown} conditions
* @returns {undefined|string}
*/ */
function resolveExports(nmPath, request, conditions) { function resolveExports(nmPath, request, conditions) {
// The implementation's behavior is meant to mirror resolution in ESM. // The implementation's behavior is meant to mirror resolution in ESM.
@ -785,6 +804,7 @@ if (isWindows) {
/** /**
* Get the paths to the `node_modules` folder for a given path. * Get the paths to the `node_modules` folder for a given path.
* @param {string} from `__dirname` of the module * @param {string} from `__dirname` of the module
* @returns {string[]}
*/ */
Module._nodeModulePaths = function(from) { Module._nodeModulePaths = function(from) {
// Guarantee that 'from' is absolute. // Guarantee that 'from' is absolute.
@ -837,6 +857,7 @@ if (isWindows) {
/** /**
* Get the paths to the `node_modules` folder for a given path. * Get the paths to the `node_modules` folder for a given path.
* @param {string} from `__dirname` of the module * @param {string} from `__dirname` of the module
* @returns {string[]}
*/ */
Module._nodeModulePaths = function(from) { Module._nodeModulePaths = function(from) {
// Guarantee that 'from' is absolute. // Guarantee that 'from' is absolute.
@ -883,6 +904,7 @@ if (isWindows) {
* Get the paths for module resolution. * Get the paths for module resolution.
* @param {string} request * @param {string} request
* @param {Module} parent * @param {Module} parent
* @returns {null|string[]}
*/ */
Module._resolveLookupPaths = function(request, parent) { Module._resolveLookupPaths = function(request, parent) {
if (BuiltinModule.normalizeRequirableId(request)) { if (BuiltinModule.normalizeRequirableId(request)) {
@ -930,6 +952,7 @@ Module._resolveLookupPaths = function(request, parent) {
/** /**
* Emits a warning when a non-existent property of module exports is accessed inside a circular dependency. * Emits a warning when a non-existent property of module exports is accessed inside a circular dependency.
* @param {string} prop The name of the non-existent property. * @param {string} prop The name of the non-existent property.
* @returns {void}
*/ */
function emitCircularRequireWarning(prop) { function emitCircularRequireWarning(prop) {
process.emitWarning( process.emitWarning(
@ -966,6 +989,7 @@ const CircularRequirePrototypeWarningProxy = new Proxy({}, {
* If the exports object is a plain object, it is wrapped in a proxy that warns * If the exports object is a plain object, it is wrapped in a proxy that warns
* about circular dependencies. * about circular dependencies.
* @param {Module} module The module instance * @param {Module} module The module instance
* @returns {object}
*/ */
function getExportsForCircularRequire(module) { function getExportsForCircularRequire(module) {
const requiredESM = module[kRequiredModuleSymbol]; const requiredESM = module[kRequiredModuleSymbol];
@ -1068,8 +1092,8 @@ function resolveForCJSWithHooks(specifier, parent, isMain) {
} }
/** /**
* @typedef {import('internal/modules/customization_hooks').ModuleLoadContext} ModuleLoadContext; * @typedef {import('internal/modules/customization_hooks').ModuleLoadContext} ModuleLoadContext
* @typedef {import('internal/modules/customization_hooks').ModuleLoadResult} ModuleLoadResult; * @typedef {import('internal/modules/customization_hooks').ModuleLoadResult} ModuleLoadResult
*/ */
/** /**
@ -1119,10 +1143,10 @@ function getDefaultLoad(url, filename) {
/** /**
* Load a specified builtin module, invoking load hooks if necessary. * Load a specified builtin module, invoking load hooks if necessary.
* @param {string} id The module ID (without the node: prefix) * @param {string} id The module ID (without the node: prefix)
* @param {string} url The module URL (with the node: prefix) * @param {string} url The module URL (with the node: prefix)
* @param {string} format Format from resolution. * @param {string} format Format from resolution.
* @returns {any} If there are no load hooks or the load hooks do not override the format of the * @returns {any} If there are no load hooks or the load hooks do not override the format of the
* builtin, load and return the exports of the builtin. Otherwise, return undefined. * builtin, load and return the exports of the builtin. Otherwise, return undefined.
*/ */
function loadBuiltinWithHooks(id, url, format) { function loadBuiltinWithHooks(id, url, format) {
if (loadHooks.length) { if (loadHooks.length) {
@ -1151,6 +1175,7 @@ function loadBuiltinWithHooks(id, url, format) {
* @param {string} request Specifier of module to load via `require` * @param {string} request Specifier of module to load via `require`
* @param {Module} parent Absolute path of the module importing the child * @param {Module} parent Absolute path of the module importing the child
* @param {boolean} isMain Whether the module is the main entry point * @param {boolean} isMain Whether the module is the main entry point
* @returns {object}
*/ */
Module._load = function(request, parent, isMain) { Module._load = function(request, parent, isMain) {
let relResolveCacheIdentifier; let relResolveCacheIdentifier;
@ -1281,6 +1306,7 @@ Module._load = function(request, parent, isMain) {
* @typedef {object} ResolveFilenameOptions * @typedef {object} ResolveFilenameOptions
* @property {string[]} paths Paths to search for modules in * @property {string[]} paths Paths to search for modules in
* @property {string[]} conditions Conditions used for resolution. * @property {string[]} conditions Conditions used for resolution.
* @returns {void|string}
*/ */
Module._resolveFilename = function(request, parent, isMain, options) { Module._resolveFilename = function(request, parent, isMain, options) {
if (BuiltinModule.normalizeRequirableId(request)) { if (BuiltinModule.normalizeRequirableId(request)) {
@ -1378,6 +1404,7 @@ Module._resolveFilename = function(request, parent, isMain, options) {
* @param {string} pkgPath The path of the package.json file * @param {string} pkgPath The path of the package.json file
* @throws {ERR_INVALID_MODULE_SPECIFIER} If the resolved module specifier contains encoded `/` or `\\` characters * @throws {ERR_INVALID_MODULE_SPECIFIER} If the resolved module specifier contains encoded `/` or `\\` characters
* @throws {Error} If the module cannot be found * @throws {Error} If the module cannot be found
* @returns {void|string|undefined}
*/ */
function finalizeEsmResolution(resolved, parentPath, pkgPath) { function finalizeEsmResolution(resolved, parentPath, pkgPath) {
const { encodedSepRegEx } = require('internal/modules/esm/resolve'); const { encodedSepRegEx } = require('internal/modules/esm/resolve');
@ -1390,14 +1417,14 @@ function finalizeEsmResolution(resolved, parentPath, pkgPath) {
if (actual) { if (actual) {
return actual; return actual;
} }
const err = createEsmNotFoundErr(filename, pkgPath); throw createEsmNotFoundErr(filename, pkgPath);
throw err;
} }
/** /**
* Creates an error object for when a requested ES module cannot be found. * Creates an error object for when a requested ES module cannot be found.
* @param {string} request The name of the requested module * @param {string} request The name of the requested module
* @param {string} [path] The path to the requested module * @param {string} [path] The path to the requested module
* @returns {Error}
*/ */
function createEsmNotFoundErr(request, path) { function createEsmNotFoundErr(request, path) {
// eslint-disable-next-line no-restricted-syntax // eslint-disable-next-line no-restricted-syntax
@ -1413,6 +1440,7 @@ function createEsmNotFoundErr(request, path) {
/** /**
* Given a file name, pass it to the proper extension handler. * Given a file name, pass it to the proper extension handler.
* @param {string} filename The `require` specifier * @param {string} filename The `require` specifier
* @returns {void}
*/ */
Module.prototype.load = function(filename) { Module.prototype.load = function(filename) {
debug('load %j for module %j', filename, this.id); debug('load %j for module %j', filename, this.id);
@ -1436,6 +1464,7 @@ Module.prototype.load = function(filename) {
* Loads a module at the given file path. Returns that module's `exports` property. * Loads a module at the given file path. Returns that module's `exports` property.
* @param {string} id * @param {string} id
* @throws {ERR_INVALID_ARG_TYPE} When `id` is not a string * @throws {ERR_INVALID_ARG_TYPE} When `id` is not a string
* @returns {any}
*/ */
Module.prototype.require = function(id) { Module.prototype.require = function(id) {
validateString(id, 'id'); validateString(id, 'id');
@ -1577,6 +1606,7 @@ function loadESMFromCJS(mod, filename, format, source) {
* @param {string} content The content of the file being loaded * @param {string} content The content of the file being loaded
* @param {Module|undefined} cjsModuleInstance The CommonJS loader instance * @param {Module|undefined} cjsModuleInstance The CommonJS loader instance
* @param {'commonjs'|undefined} format Intended format of the module. * @param {'commonjs'|undefined} format Intended format of the module.
* @returns {object}
*/ */
function wrapSafe(filename, content, cjsModuleInstance, format) { function wrapSafe(filename, content, cjsModuleInstance, format) {
assert(format !== 'module', 'ESM should be handled in loadESMFromCJS()'); assert(format !== 'module', 'ESM should be handled in loadESMFromCJS()');
@ -1636,7 +1666,8 @@ function wrapSafe(filename, content, cjsModuleInstance, format) {
* @param {string} content The source code of the module * @param {string} content The source code of the module
* @param {string} filename The file path of the module * @param {string} filename The file path of the module
* @param {'module'|'commonjs'|'commonjs-typescript'|'module-typescript'|'typescript'} format * @param {'module'|'commonjs'|'commonjs-typescript'|'module-typescript'|'typescript'} format
* Intended format of the module. * Intended format of the module.
* @returns {any}
*/ */
Module.prototype._compile = function(content, filename, format) { Module.prototype._compile = function(content, filename, format) {
if (format === 'commonjs-typescript' || format === 'module-typescript' || format === 'typescript') { if (format === 'commonjs-typescript' || format === 'module-typescript' || format === 'typescript') {
@ -1843,6 +1874,7 @@ Module._extensions['.json'] = function(module, filename) {
* Native handler for `.node` files. * Native handler for `.node` files.
* @param {Module} module The module to compile * @param {Module} module The module to compile
* @param {string} filename The file path of the module * @param {string} filename The file path of the module
* @returns {any}
*/ */
Module._extensions['.node'] = function(module, filename) { Module._extensions['.node'] = function(module, filename) {
// Be aware this doesn't use `content` // Be aware this doesn't use `content`
@ -1852,6 +1884,7 @@ Module._extensions['.node'] = function(module, filename) {
/** /**
* Creates a `require` function that can be used to load modules from the specified path. * Creates a `require` function that can be used to load modules from the specified path.
* @param {string} filename The path to the module * @param {string} filename The path to the module
* @returns {any}
*/ */
function createRequireFromPath(filename) { function createRequireFromPath(filename) {
// Allow a directory to be passed as the filename // Allow a directory to be passed as the filename
@ -1878,6 +1911,7 @@ const createRequireError = 'must be a file URL object, file URL string, or ' +
* @param {string | URL} filename The path or URL to the module context for this `require` * @param {string | URL} filename The path or URL to the module context for this `require`
* @throws {ERR_INVALID_ARG_VALUE} If `filename` is not a string or URL, or if it is a relative path that cannot be * @throws {ERR_INVALID_ARG_VALUE} If `filename` is not a string or URL, or if it is a relative path that cannot be
* resolved to an absolute path. * resolved to an absolute path.
* @returns {object}
*/ */
function createRequire(filename) { function createRequire(filename) {
let filepath; let filepath;

View file

@ -29,29 +29,27 @@ let debug = require('internal/util/debuglog').debuglog('module_hooks', (fn) => {
/** /**
* @typedef {import('internal/modules/cjs/loader.js').Module} Module * @typedef {import('internal/modules/cjs/loader.js').Module} Module
*/ * @typedef {((
/**
* @typedef {(
* specifier: string, * specifier: string,
* context: Partial<ModuleResolveContext>, * context: Partial<ModuleResolveContext>,
* ) => ModuleResolveResult * ) => ModuleResolveResult)
* } NextResolve * } NextResolve
* @typedef {( * @typedef {((
* specifier: string, * specifier: string,
* context: ModuleResolveContext, * context: ModuleResolveContext,
* nextResolve: NextResolve, * nextResolve: NextResolve,
* ) => ModuleResolveResult * ) => ModuleResolveResult)
* } ResolveHook * } ResolveHook
* @typedef {( * @typedef {((
* url: string, * url: string,
* context: Partial<ModuleLoadContext>, * context: Partial<ModuleLoadContext>,
* ) => ModuleLoadResult * ) => ModuleLoadResult)
* } NextLoad * } NextLoad
* @typedef {( * @typedef {((
* url: string, * url: string,
* context: ModuleLoadContext, * context: ModuleLoadContext,
* nextLoad: NextLoad, * nextLoad: NextLoad,
* ) => ModuleLoadResult * ) => ModuleLoadResult)
* } LoadHook * } LoadHook
*/ */
@ -167,6 +165,8 @@ function convertURLToCJSFilename(url) {
* @param {'load'|'resolve'} name Name of the hook in ModuleHooks. * @param {'load'|'resolve'} name Name of the hook in ModuleHooks.
* @param {Function} defaultStep The default step in the chain. * @param {Function} defaultStep The default step in the chain.
* @param {Function} validate A function that validates and sanitize the result returned by the chain. * @param {Function} validate A function that validates and sanitize the result returned by the chain.
* @param {object} mergedContext
* @returns {any}
*/ */
function buildHooks(hooks, name, defaultStep, validate, mergedContext) { function buildHooks(hooks, name, defaultStep, validate, mergedContext) {
let lastRunIndex = hooks.length; let lastRunIndex = hooks.length;
@ -175,7 +175,7 @@ function buildHooks(hooks, name, defaultStep, validate, mergedContext) {
* in order to fill in missing arguments or check returned results. * in order to fill in missing arguments or check returned results.
* Due to the merging of the context, this must be a closure. * Due to the merging of the context, this must be a closure.
* @param {number} index Index in the chain. Default step is 0, last added hook is 1, * @param {number} index Index in the chain. Default step is 0, last added hook is 1,
* and so on. * and so on.
* @param {Function} userHookOrDefault Either the user hook or the default step to invoke. * @param {Function} userHookOrDefault Either the user hook or the default step to invoke.
* @param {Function|undefined} next The next wrapped step. If this is the default step, it's undefined. * @param {Function|undefined} next The next wrapped step. If this is the default step, it's undefined.
* @returns {Function} Wrapped hook or default step. * @returns {Function} Wrapped hook or default step.

View file

@ -48,7 +48,7 @@ const supportedTypeAttributes = ArrayPrototypeFilter(
* @param {string} url The URL of the imported module, for error reporting. * @param {string} url The URL of the imported module, for error reporting.
* @param {string} format One of Node's supported translators * @param {string} format One of Node's supported translators
* @param {Record<string, string>} importAttributes Validations for the * @param {Record<string, string>} importAttributes Validations for the
* module import. * module import.
* @returns {true} * @returns {true}
* @throws {TypeError} If the format and type attribute are incompatible. * @throws {TypeError} If the format and type attribute are incompatible.
*/ */

View file

@ -15,6 +15,7 @@ let debug = require('internal/util/debuglog').debuglog('esm', (fn) => {
* Creates an import statement for a given module path and index. * Creates an import statement for a given module path and index.
* @param {string} impt - The module path to import. * @param {string} impt - The module path to import.
* @param {number} index - The index of the import statement. * @param {number} index - The index of the import statement.
* @returns {string}
*/ */
function createImport(impt, index) { function createImport(impt, index) {
const imptPath = JSONStringify(impt); const imptPath = JSONStringify(impt);
@ -26,6 +27,7 @@ import.meta.imports[${imptPath}] = $import_${index};`;
* Creates an export for a given module. * Creates an export for a given module.
* @param {string} expt - The name of the export. * @param {string} expt - The name of the export.
* @param {number} index - The index of the export statement. * @param {number} index - The index of the export statement.
* @returns {string}
*/ */
function createExport(expt, index) { function createExport(expt, index) {
const nameStringLit = JSONStringify(expt); const nameStringLit = JSONStringify(expt);
@ -41,12 +43,13 @@ import.meta.exports[${nameStringLit}] = {
* Creates a dynamic module with the given imports, exports, URL, and evaluate function. * Creates a dynamic module with the given imports, exports, URL, and evaluate function.
* @param {string[]} imports - An array of imports. * @param {string[]} imports - An array of imports.
* @param {string[]} exports - An array of exports. * @param {string[]} exports - An array of exports.
* @param {string} [url=''] - The URL of the module. * @param {string} [url] - The URL of the module.
* @param {(reflect: DynamicModuleReflect) => void} evaluate - The function to evaluate the module. * @param {(reflect: DynamicModuleReflect) => void} evaluate - The function to evaluate the module.
* @typedef {object} DynamicModuleReflect * @typedef {object} DynamicModuleReflect
* @property {Record<string, Record<string, any>>} imports - The imports of the module. * @property {Record<string, Record<string, any>>} imports - The imports of the module.
* @property {string[]} exports - The exports of the module. * @property {string[]} exports - The exports of the module.
* @property {(cb: (reflect: DynamicModuleReflect) => void) => void} onReady - Callback to evaluate the module. * @property {(cb: (reflect: DynamicModuleReflect) => void) => void} onReady - Callback to evaluate the module.
* @returns {object}
*/ */
const createDynamicModule = (imports, exports, url = '', evaluate) => { const createDynamicModule = (imports, exports, url = '', evaluate) => {
debug('creating ESM facade for %s with exports: %j', url, exports); debug('creating ESM facade for %s with exports: %j', url, exports);

View file

@ -55,6 +55,7 @@ function mimeToFormat(mime) {
* JavaScript and Wasm. * JavaScript and Wasm.
* We do this by taking advantage of the fact that all Wasm files start with the header `0x00 0x61 0x73 0x6d` (`_asm`). * We do this by taking advantage of the fact that all Wasm files start with the header `0x00 0x61 0x73 0x6d` (`_asm`).
* @param {URL} url * @param {URL} url
* @returns {'wasm'|'module'}
*/ */
function getFormatOfExtensionlessFile(url) { function getFormatOfExtensionlessFile(url) {
if (!experimentalWasmModules) { return 'module'; } if (!experimentalWasmModules) { return 'module'; }

View file

@ -30,8 +30,9 @@ const protocolHandlers = {
/** /**
* Determine whether the given ambiguous source contains CommonJS or ES module syntax. * Determine whether the given ambiguous source contains CommonJS or ES module syntax.
* @param {string | Buffer | undefined} source * @param {string | Buffer | undefined} [source]
* @param {URL} url * @param {URL} url
* @returns {'module'|'commonjs'}
*/ */
function detectModuleFormat(source, url) { function detectModuleFormat(source, url) {
if (!source) { return detectModule ? null : 'commonjs'; } if (!source) { return detectModule ? null : 'commonjs'; }
@ -81,6 +82,7 @@ function extname(url) {
* This function assumes that the input has already been verified to be a `file:` URL, * This function assumes that the input has already been verified to be a `file:` URL,
* and is a file rather than a folder. * and is a file rather than a folder.
* @param {URL} url * @param {URL} url
* @returns {boolean}
*/ */
function underNodeModules(url) { function underNodeModules(url) {
if (url.protocol !== 'file:') { return false; } // We determine module types for other protocols based on MIME header if (url.protocol !== 'file:') { return false; } // We determine module types for other protocols based on MIME header

View file

@ -143,7 +143,7 @@ class Hooks {
* @param {string} urlOrSpecifier * @param {string} urlOrSpecifier
* @param {string} parentURL * @param {string} parentURL
* @param {any} [data] Arbitrary data to be passed from the custom * @param {any} [data] Arbitrary data to be passed from the custom
* loader (user-land) to the worker. * loader (user-land) to the worker.
*/ */
async register(urlOrSpecifier, parentURL, data, isInternal) { async register(urlOrSpecifier, parentURL, data, isInternal) {
const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader(); const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader();
@ -162,7 +162,7 @@ class Hooks {
* @param {string} url Custom loader specifier * @param {string} url Custom loader specifier
* @param {Record<string, unknown>} exports * @param {Record<string, unknown>} exports
* @param {any} [data] Arbitrary data to be passed from the custom loader (user-land) * @param {any} [data] Arbitrary data to be passed from the custom loader (user-land)
* to the worker. * to the worker.
* @returns {any | Promise<any>} User data, ignored unless it's a promise, in which case it will be awaited. * @returns {any | Promise<any>} User data, ignored unless it's a promise, in which case it will be awaited.
*/ */
addCustomLoader(url, exports, data) { addCustomLoader(url, exports, data) {
@ -190,10 +190,10 @@ class Hooks {
* hooks starts at the top and each call to `nextResolve()` moves down 1 step * hooks starts at the top and each call to `nextResolve()` moves down 1 step
* until it reaches the bottom or short-circuits. * until it reaches the bottom or short-circuits.
* @param {string} originalSpecifier The specified URL path of the module to * @param {string} originalSpecifier The specified URL path of the module to
* be resolved. * be resolved.
* @param {string} [parentURL] The URL path of the module's parent. * @param {string} [parentURL] The URL path of the module's parent.
* @param {ImportAttributes} [importAttributes] Attributes from the import * @param {ImportAttributes} [importAttributes] Attributes from the import
* statement or expression. * statement or expression.
* @returns {Promise<{ format: string, url: URL['href'] }>} * @returns {Promise<{ format: string, url: URL['href'] }>}
*/ */
async resolve( async resolve(
@ -537,7 +537,7 @@ class HooksProxy {
* Invoke a remote method asynchronously. * Invoke a remote method asynchronously.
* @param {string} method Method to invoke * @param {string} method Method to invoke
* @param {any[]} [transferList] Objects in `args` to be transferred * @param {any[]} [transferList] Objects in `args` to be transferred
* @param {any[]} args Arguments to pass to `method` * @param {any[]} args Arguments to pass to `method`
* @returns {Promise<any>} * @returns {Promise<any>}
*/ */
async makeAsyncRequest(method, transferList, ...args) { async makeAsyncRequest(method, transferList, ...args) {
@ -592,7 +592,7 @@ class HooksProxy {
* Invoke a remote method synchronously. * Invoke a remote method synchronously.
* @param {string} method Method to invoke * @param {string} method Method to invoke
* @param {any[]} [transferList] Objects in `args` to be transferred * @param {any[]} [transferList] Objects in `args` to be transferred
* @param {any[]} args Arguments to pass to `method` * @param {any[]} args Arguments to pass to `method`
* @returns {any} * @returns {any}
*/ */
makeSyncRequest(method, transferList, ...args) { makeSyncRequest(method, transferList, ...args) {
@ -651,7 +651,7 @@ let globalPreloadWarningWasEmitted = false;
/** /**
* A utility function to pluck the hooks from a user-defined loader. * A utility function to pluck the hooks from a user-defined loader.
* @param {import('./loader.js).ModuleExports} exports * @param {import('./loader.js').ModuleExports} exports
* @returns {ExportedHooks} * @returns {ExportedHooks}
*/ */
function pluckHooks({ function pluckHooks({
@ -688,19 +688,19 @@ function pluckHooks({
* chain, and generate and supply the `next<HookName>` argument to the custom * chain, and generate and supply the `next<HookName>` argument to the custom
* hook. * hook.
* @param {KeyedHook} current The (currently) first hook in the chain (this shifts * @param {KeyedHook} current The (currently) first hook in the chain (this shifts
* on every call). * on every call).
* @param {object} meta Properties that change as the current hook advances * @param {object} meta Properties that change as the current hook advances
* along the chain. * along the chain.
* @param {boolean} meta.chainFinished Whether the end of the chain has been * @param {boolean} meta.chainFinished Whether the end of the chain has been
* reached AND invoked. * reached AND invoked.
* @param {string} meta.hookErrIdentifier A user-facing identifier to help * @param {string} meta.hookErrIdentifier A user-facing identifier to help
* pinpoint where an error occurred. Ex "file:///foo.mjs 'resolve'". * pinpoint where an error occurred. Ex "file:///foo.mjs 'resolve'".
* @param {string} meta.hookName The kind of hook the chain is (ex 'resolve') * @param {string} meta.hookName The kind of hook the chain is (ex 'resolve')
* @param {boolean} meta.shortCircuited Whether a hook signaled a short-circuit. * @param {boolean} meta.shortCircuited Whether a hook signaled a short-circuit.
* @param {(hookErrIdentifier, hookArgs) => void} validate A wrapper function * @param {function(string, unknown): void} validate A wrapper function
* containing all validation of a custom loader hook's intermediary output. Any * containing all validation of a custom loader hook's intermediary output. Any
* validation within MUST throw. * validation within MUST throw.
* @returns {function next<HookName>(...hookArgs)} The next hook in the chain. * @returns {Function} The next hook in the chain.
*/ */
function nextHookFactory(current, meta, { validateArgs, validateOutput }) { function nextHookFactory(current, meta, { validateArgs, validateOutput }) {
// First, prepare the current // First, prepare the current

View file

@ -22,7 +22,8 @@ function createImportMetaResolve(defaultParentURL, loader, allowParentURL) {
/** /**
* @param {string} specifier * @param {string} specifier
* @param {URL['href']} [parentURL] When `--experimental-import-meta-resolve` is specified, a * @param {URL['href']} [parentURL] When `--experimental-import-meta-resolve` is specified, a
* second argument can be provided. * second argument can be provided.
* @returns {string}
*/ */
return function resolve(specifier, parentURL = defaultParentURL) { return function resolve(specifier, parentURL = defaultParentURL) {
let url; let url;

View file

@ -189,7 +189,7 @@ function throwIfUnsupportedURLScheme(parsed) {
* This could happen from either a custom user loader _or_ from the default loader, because the default loader tries to * This could happen from either a custom user loader _or_ from the default loader, because the default loader tries to
* determine formats for data URLs. * determine formats for data URLs.
* @param {string} url The resolved URL of the module * @param {string} url The resolved URL of the module
* @param {null | undefined | false | 0 | -0 | 0n | ''} format Falsy format returned from `load` * @param {(null|undefined|false|0|'')} format Falsy format returned from `load`
*/ */
function throwUnknownModuleFormat(url, format) { function throwUnknownModuleFormat(url, format) {
const dataUrl = RegExpPrototypeExec( const dataUrl = RegExpPrototypeExec(

View file

@ -299,9 +299,9 @@ class ModuleLoader {
/** /**
* Get a (possibly not yet fully linked) module job from the cache, or create one and return its Promise. * Get a (possibly not yet fully linked) module job from the cache, or create one and return its Promise.
* @param {string} specifier The module request of the module to be resolved. Typically, what's * @param {string} specifier The module request of the module to be resolved. Typically, what's
* requested by `import '<specifier>'` or `import('<specifier>')`. * requested by `import '<specifier>'` or `import('<specifier>')`.
* @param {string} [parentURL] The URL of the module where the module request is initiated. * @param {string} [parentURL] The URL of the module where the module request is initiated.
* It's undefined if it's from the root module. * It's undefined if it's from the root module.
* @param {ImportAttributes} importAttributes Attributes from the import statement or expression. * @param {ImportAttributes} importAttributes Attributes from the import statement or expression.
* @param {number} phase Import phase. * @param {number} phase Import phase.
* @returns {Promise<ModuleJobBase>} * @returns {Promise<ModuleJobBase>}
@ -534,7 +534,7 @@ class ModuleLoader {
* but the translator may return the ModuleWrap in a Promise. * but the translator may return the ModuleWrap in a Promise.
* @param {string} url URL of the module to be translated. * @param {string} url URL of the module to be translated.
* @param {string} format Format of the module to be translated. This is used to find * @param {string} format Format of the module to be translated. This is used to find
* matching translators. * matching translators.
* @param {ModuleSource} source Source of the module to be translated. * @param {ModuleSource} source Source of the module to be translated.
* @param {boolean} isMain Whether the module to be translated is the entry point. * @param {boolean} isMain Whether the module to be translated is the entry point.
* @returns {ModuleWrap | Promise<ModuleWrap>} * @returns {ModuleWrap | Promise<ModuleWrap>}
@ -607,7 +607,7 @@ class ModuleLoader {
* @param {string} [parentURL] See {@link getModuleJobForImport} * @param {string} [parentURL] See {@link getModuleJobForImport}
* @param {string} [format] The format hint possibly returned by the `resolve` hook * @param {string} [format] The format hint possibly returned by the `resolve` hook
* @param {boolean} isForRequireInImportedCJS Whether this module job is created for require() * @param {boolean} isForRequireInImportedCJS Whether this module job is created for require()
* in imported CJS. * in imported CJS.
* @returns {ModuleJobBase} The (possibly pending) module job * @returns {ModuleJobBase} The (possibly pending) module job
*/ */
#createModuleJob(url, importAttributes, phase, parentURL, format, isForRequireInImportedCJS) { #createModuleJob(url, importAttributes, phase, parentURL, format, isForRequireInImportedCJS) {
@ -653,7 +653,7 @@ class ModuleLoader {
* @param {string} specifier The first parameter of an `import()` expression. * @param {string} specifier The first parameter of an `import()` expression.
* @param {string} parentURL Path of the parent importing the module. * @param {string} parentURL Path of the parent importing the module.
* @param {Record<string, string>} importAttributes Validations for the * @param {Record<string, string>} importAttributes Validations for the
* module import. * module import.
* @param {number} [phase] The phase of the import. * @param {number} [phase] The phase of the import.
* @param {boolean} [isEntryPoint] Whether this is the realm-level entry point. * @param {boolean} [isEntryPoint] Whether this is the realm-level entry point.
* @returns {Promise<ModuleExports>} * @returns {Promise<ModuleExports>}
@ -677,6 +677,7 @@ class ModuleLoader {
/** /**
* @see {@link CustomizedModuleLoader.register} * @see {@link CustomizedModuleLoader.register}
* @returns {any}
*/ */
register(specifier, parentURL, data, transferList, isInternal) { register(specifier, parentURL, data, transferList, isInternal) {
if (!this.#customizations) { if (!this.#customizations) {
@ -693,10 +694,9 @@ class ModuleLoader {
* Resolve a module request to a URL identifying the location of the module. Handles customization hooks, * Resolve a module request to a URL identifying the location of the module. Handles customization hooks,
* if any. * if any.
* @param {string|URL} specifier The module request of the module to be resolved. Typically, what's * @param {string|URL} specifier The module request of the module to be resolved. Typically, what's
* requested by `import specifier`, `import(specifier)` or * requested by `import specifier`, `import(specifier)` or `import.meta.resolve(specifier)`.
* `import.meta.resolve(specifier)`.
* @param {string} [parentURL] The URL of the module where the module request is initiated. * @param {string} [parentURL] The URL of the module where the module request is initiated.
* It's undefined if it's from the root module. * It's undefined if it's from the root module.
* @param {ImportAttributes} importAttributes Attributes from the import statement or expression. * @param {ImportAttributes} importAttributes Attributes from the import statement or expression.
* @returns {Promise<{format: string, url: string}>} * @returns {Promise<{format: string, url: string}>}
*/ */
@ -791,6 +791,7 @@ class ModuleLoader {
* Our `defaultResolve` is synchronous and can be used in both * Our `defaultResolve` is synchronous and can be used in both
* `resolve` and `resolveSync`. This function is here just to avoid * `resolve` and `resolveSync`. This function is here just to avoid
* repeating the same code block twice in those functions. * repeating the same code block twice in those functions.
* @returns {string}
*/ */
defaultResolve(originalSpecifier, parentURL, importAttributes) { defaultResolve(originalSpecifier, parentURL, importAttributes) {
defaultResolve ??= require('internal/modules/esm/resolve').defaultResolve; defaultResolve ??= require('internal/modules/esm/resolve').defaultResolve;
@ -900,11 +901,11 @@ class CustomizedModuleLoader {
/** /**
* Register some loader specifier. * Register some loader specifier.
* @param {string} originalSpecifier The specified URL path of the loader to * @param {string} originalSpecifier The specified URL path of the loader to
* be registered. * be registered.
* @param {string} parentURL The parent URL from where the loader will be * @param {string} parentURL The parent URL from where the loader will be
* registered if using it package name as specifier * registered if using it package name as specifier
* @param {any} [data] Arbitrary data to be passed from the custom loader * @param {any} [data] Arbitrary data to be passed from the custom loader
* (user-land) to the worker. * (user-land) to the worker.
* @param {any[]} [transferList] Objects in `data` that are changing ownership * @param {any[]} [transferList] Objects in `data` that are changing ownership
* @param {boolean} [isInternal] For internal loaders that should not be publicly exposed. * @param {boolean} [isInternal] For internal loaders that should not be publicly exposed.
* @returns {{ format: string, url: URL['href'] }} * @returns {{ format: string, url: URL['href'] }}
@ -916,10 +917,10 @@ class CustomizedModuleLoader {
/** /**
* Resolve the location of the module. * Resolve the location of the module.
* @param {string} originalSpecifier The specified URL path of the module to * @param {string} originalSpecifier The specified URL path of the module to
* be resolved. * be resolved.
* @param {string} [parentURL] The URL path of the module's parent. * @param {string} [parentURL] The URL path of the module's parent.
* @param {ImportAttributes} importAttributes Attributes from the import * @param {ImportAttributes} importAttributes Attributes from the import
* statement or expression. * statement or expression.
* @returns {{ format: string, url: URL['href'] }} * @returns {{ format: string, url: URL['href'] }}
*/ */
resolve(originalSpecifier, parentURL, importAttributes) { resolve(originalSpecifier, parentURL, importAttributes) {
@ -1029,7 +1030,7 @@ function getOrInitializeCascadedLoader() {
* Register a single loader programmatically. * Register a single loader programmatically.
* @param {string|URL} specifier * @param {string|URL} specifier
* @param {string|URL} [parentURL] Base to use when resolving `specifier`; optional if * @param {string|URL} [parentURL] Base to use when resolving `specifier`; optional if
* `specifier` is absolute. Same as `options.parentUrl`, just inline * `specifier` is absolute. Same as `options.parentUrl`, just inline
* @param {object} [options] Additional options to apply, described below. * @param {object} [options] Additional options to apply, described below.
* @param {string|URL} [options.parentURL] Base to use when resolving `specifier` * @param {string|URL} [options.parentURL] Base to use when resolving `specifier`
* @param {any} [options.data] Arbitrary data passed to the loader's `initialize` hook * @param {any} [options.data] Arbitrary data passed to the loader's `initialize` hook

View file

@ -129,7 +129,7 @@ class ModuleJob extends ModuleJobBase {
* @param {number} phase The phase to load the module to. * @param {number} phase The phase to load the module to.
* @param {boolean} isMain Whether the module is the entry point. * @param {boolean} isMain Whether the module is the entry point.
* @param {boolean} inspectBrk Whether this module should be evaluated with the * @param {boolean} inspectBrk Whether this module should be evaluated with the
* first line paused in the debugger (because --inspect-brk is passed). * first line paused in the debugger (because --inspect-brk is passed).
* @param {boolean} isForRequireInImportedCJS Whether this is created for require() in imported CJS. * @param {boolean} isForRequireInImportedCJS Whether this is created for require() in imported CJS.
*/ */
constructor(loader, url, importAttributes = { __proto__: null }, moduleOrModulePromise, constructor(loader, url, importAttributes = { __proto__: null }, moduleOrModulePromise,
@ -398,7 +398,7 @@ class ModuleJobSync extends ModuleJobBase {
* @param {number} phase The phase to load the module to. * @param {number} phase The phase to load the module to.
* @param {boolean} isMain Whether the module is the entry point. * @param {boolean} isMain Whether the module is the entry point.
* @param {boolean} inspectBrk Whether this module should be evaluated with the * @param {boolean} inspectBrk Whether this module should be evaluated with the
* first line paused in the debugger (because --inspect-brk is passed). * first line paused in the debugger (because --inspect-brk is passed).
*/ */
constructor(loader, url, importAttributes, moduleWrap, phase = kEvaluationPhase, isMain, constructor(loader, url, importAttributes, moduleWrap, phase = kEvaluationPhase, isMain,
inspectBrk) { inspectBrk) {

View file

@ -72,12 +72,18 @@ class ResolveCache extends SafeMap {
* @param {string} serializedKey * @param {string} serializedKey
* @param {string} parentURL * @param {string} parentURL
* @param {{ format: string, url: URL['href'] }} result * @param {{ format: string, url: URL['href'] }} result
* @returns {ResolveCache}
*/ */
set(serializedKey, parentURL, result) { set(serializedKey, parentURL, result) {
this.#getModuleCachedImports(parentURL)[serializedKey] = result; this.#getModuleCachedImports(parentURL)[serializedKey] = result;
return this; return this;
} }
/**
* @param {string} serializedKey
* @param {URL|string} parentURL
* @returns {boolean}
*/
has(serializedKey, parentURL) { has(serializedKey, parentURL) {
return serializedKey in this.#getModuleCachedImports(parentURL); return serializedKey in this.#getModuleCachedImports(parentURL);
} }

View file

@ -550,6 +550,7 @@ function resolvePackageTarget(packageJSONUrl, target, subpath, packageSubpath,
* @param {import('internal/modules/esm/package_config.js').PackageConfig['exports']} exports * @param {import('internal/modules/esm/package_config.js').PackageConfig['exports']} exports
* @param {URL} packageJSONUrl The URL of the package.json file. * @param {URL} packageJSONUrl The URL of the package.json file.
* @param {string | URL | undefined} base The base URL. * @param {string | URL | undefined} base The base URL.
* @returns {boolean}
*/ */
function isConditionalExportsMainSugar(exports, packageJSONUrl, base) { function isConditionalExportsMainSugar(exports, packageJSONUrl, base) {
if (typeof exports === 'string' || ArrayIsArray(exports)) { return true; } if (typeof exports === 'string' || ArrayIsArray(exports)) { return true; }
@ -665,7 +666,7 @@ function packageExportsResolve(
* @param {string} a - The first string to compare. * @param {string} a - The first string to compare.
* @param {string} b - The second string to compare. * @param {string} b - The second string to compare.
* @returns {number} - A negative number if `a` should come before `b`, a positive number if `a` should come after `b`, * @returns {number} - A negative number if `a` should come before `b`, a positive number if `a` should come after `b`,
* or 0 if they are equal. * or 0 if they are equal.
*/ */
function patternKeyCompare(a, b) { function patternKeyCompare(a, b) {
const aPatternIndex = StringPrototypeIndexOf(a, '*'); const aPatternIndex = StringPrototypeIndexOf(a, '*');
@ -787,6 +788,7 @@ function packageResolve(specifier, base, conditions) {
/** /**
* Checks if a specifier is a bare specifier. * Checks if a specifier is a bare specifier.
* @param {string} specifier - The specifier to check. * @param {string} specifier - The specifier to check.
* @returns {boolean}
*/ */
function isBareSpecifier(specifier) { function isBareSpecifier(specifier) {
return specifier[0] && specifier[0] !== '/' && specifier[0] !== '.'; return specifier[0] && specifier[0] !== '/' && specifier[0] !== '.';
@ -795,6 +797,7 @@ function isBareSpecifier(specifier) {
/** /**
* Determines whether a specifier is a relative path. * Determines whether a specifier is a relative path.
* @param {string} specifier - The specifier to check. * @param {string} specifier - The specifier to check.
* @returns {boolean}
*/ */
function isRelativeSpecifier(specifier) { function isRelativeSpecifier(specifier) {
if (specifier[0] === '.') { if (specifier[0] === '.') {
@ -809,6 +812,7 @@ function isRelativeSpecifier(specifier) {
/** /**
* Determines whether a specifier should be treated as a relative or absolute path. * Determines whether a specifier should be treated as a relative or absolute path.
* @param {string} specifier - The specifier to check. * @param {string} specifier - The specifier to check.
* @returns {boolean}
*/ */
function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) { function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
if (specifier === '') { return false; } if (specifier === '') { return false; }
@ -822,6 +826,7 @@ function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
* @param {string | URL | undefined} base - The base URL to resolve against. * @param {string | URL | undefined} base - The base URL to resolve against.
* @param {Set<string>} conditions - An object containing environment conditions. * @param {Set<string>} conditions - An object containing environment conditions.
* @param {boolean} preserveSymlinks - Whether to preserve symlinks in the resolved URL. * @param {boolean} preserveSymlinks - Whether to preserve symlinks in the resolved URL.
* @returns {URL}
*/ */
function moduleResolve(specifier, base, conditions, preserveSymlinks) { function moduleResolve(specifier, base, conditions, preserveSymlinks) {
const protocol = typeof base === 'string' ? const protocol = typeof base === 'string' ?
@ -917,6 +922,7 @@ function resolveAsCommonJS(specifier, parentURL) {
/** /**
* Validate user-input in `context` supplied by a custom loader. * Validate user-input in `context` supplied by a custom loader.
* @param {string | URL | undefined} parentURL - The parent URL. * @param {string | URL | undefined} parentURL - The parent URL.
* @returns {void}
*/ */
function throwIfInvalidParentURL(parentURL) { function throwIfInvalidParentURL(parentURL) {
if (parentURL === undefined) { if (parentURL === undefined) {
@ -931,9 +937,10 @@ function throwIfInvalidParentURL(parentURL) {
* Resolves the given specifier using the provided context, which includes the parent URL and conditions. * Resolves the given specifier using the provided context, which includes the parent URL and conditions.
* Attempts to resolve the specifier and returns the resulting URL and format. * Attempts to resolve the specifier and returns the resulting URL and format.
* @param {string} specifier - The specifier to resolve. * @param {string} specifier - The specifier to resolve.
* @param {object} [context={}] - The context object containing the parent URL and conditions. * @param {object} [context] - The context object containing the parent URL and conditions.
* @param {string} [context.parentURL] - The URL of the parent module. * @param {string} [context.parentURL] - The URL of the parent module.
* @param {string[]} [context.conditions] - The conditions for resolving the specifier. * @param {string[]} [context.conditions] - The conditions for resolving the specifier.
* @returns {{url: string, format?: string}}
*/ */
function defaultResolve(specifier, context = {}) { function defaultResolve(specifier, context = {}) {
let { parentURL, conditions } = context; let { parentURL, conditions } = context;

View file

@ -88,6 +88,7 @@ exports.translators = translators;
/** /**
* Converts a URL to a file path if the URL protocol is 'file:'. * Converts a URL to a file path if the URL protocol is 'file:'.
* @param {string} url - The URL to convert. * @param {string} url - The URL to convert.
* @returns {string|URL}
*/ */
function errPath(url) { function errPath(url) {
const parsed = new URL(url); const parsed = new URL(url);
@ -176,7 +177,7 @@ const cjsCache = new SafeMap();
* @param {string} source - The source code of the module. * @param {string} source - The source code of the module.
* @param {boolean} isMain - Whether the module is the main module. * @param {boolean} isMain - Whether the module is the main module.
* @param {string} format - Format of the module. * @param {string} format - Format of the module.
* @param {typeof loadCJSModule} [loadCJS=loadCJSModule] - The function to load the CommonJS module. * @param {typeof loadCJSModule} [loadCJS] - The function to load the CommonJS module.
* @returns {ModuleWrap} The ModuleWrap object for the CommonJS module. * @returns {ModuleWrap} The ModuleWrap object for the CommonJS module.
*/ */
function createCJSModuleWrap(url, source, isMain, format, loadCJS = loadCJSModule) { function createCJSModuleWrap(url, source, isMain, format, loadCJS = loadCJSModule) {
@ -351,6 +352,7 @@ function cjsEmplaceModuleCacheEntry(filename, exportNames) {
* @param {string} filename - The filename of the module. * @param {string} filename - The filename of the module.
* @param {string} [source] - The source code of the module. * @param {string} [source] - The source code of the module.
* @param {string} [format] * @param {string} [format]
* @returns {{module: CJSModule, exportNames: string[]}}
*/ */
function cjsPreparseModuleExports(filename, source, format) { function cjsPreparseModuleExports(filename, source, format) {
const module = cjsEmplaceModuleCacheEntry(filename); const module = cjsEmplaceModuleCacheEntry(filename);

View file

@ -52,6 +52,7 @@ const {
let defaultConditions; let defaultConditions;
/** /**
* Returns the default conditions for ES module loading. * Returns the default conditions for ES module loading.
* @returns {object}
*/ */
function getDefaultConditions() { function getDefaultConditions() {
assert(defaultConditions !== undefined); assert(defaultConditions !== undefined);
@ -62,6 +63,7 @@ function getDefaultConditions() {
let defaultConditionsSet; let defaultConditionsSet;
/** /**
* Returns the default conditions for ES module loading, as a Set. * Returns the default conditions for ES module loading, as a Set.
* @returns {Set<any>}
*/ */
function getDefaultConditionsSet() { function getDefaultConditionsSet() {
assert(defaultConditionsSet !== undefined); assert(defaultConditionsSet !== undefined);
@ -71,6 +73,7 @@ function getDefaultConditionsSet() {
/** /**
* Initializes the default conditions for ESM module loading. * Initializes the default conditions for ESM module loading.
* This function is called during pre-execution, before any user code is run. * This function is called during pre-execution, before any user code is run.
* @returns {void}
*/ */
function initializeDefaultConditions() { function initializeDefaultConditions() {
const userConditions = getOptionValue('--conditions'); const userConditions = getOptionValue('--conditions');
@ -102,9 +105,10 @@ function getConditionsSet(conditions) {
return getDefaultConditionsSet(); return getDefaultConditionsSet();
} }
/* eslint-disable jsdoc/valid-types */
/** /**
* @typedef {{ * @typedef {{
* [Symbol.toStringTag]: 'Module', * [Symbol.toStringTag]: () => 'Module'
* }} ModuleNamespaceObject * }} ModuleNamespaceObject
*/ */
@ -186,6 +190,7 @@ function registerModule(referrer, registry) {
* Proxy the import meta handling to the default loader for source text modules. * Proxy the import meta handling to the default loader for source text modules.
* @param {Record<string, string | Function>} meta - The import.meta object to initialize. * @param {Record<string, string | Function>} meta - The import.meta object to initialize.
* @param {ModuleWrap} wrap - The ModuleWrap of the SourceTextModule where `import.meta` is referenced. * @param {ModuleWrap} wrap - The ModuleWrap of the SourceTextModule where `import.meta` is referenced.
* @returns {object}
*/ */
function defaultInitializeImportMetaForModule(meta, wrap) { function defaultInitializeImportMetaForModule(meta, wrap) {
const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader(); const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader();
@ -283,7 +288,7 @@ let _forceDefaultLoader = false;
* Initializes handling of ES modules. * Initializes handling of ES modules.
* This is configured during pre-execution. Specifically it's set to true for * This is configured during pre-execution. Specifically it's set to true for
* the loader worker in internal/main/worker_thread.js. * the loader worker in internal/main/worker_thread.js.
* @param {boolean} [forceDefaultLoader=false] - A boolean indicating disabling custom loaders. * @param {boolean} [forceDefaultLoader] - A boolean indicating disabling custom loaders.
*/ */
function initializeESM(forceDefaultLoader = false) { function initializeESM(forceDefaultLoader = false) {
_forceDefaultLoader = forceDefaultLoader; _forceDefaultLoader = forceDefaultLoader;
@ -305,6 +310,7 @@ function forceDefaultLoader() {
/** /**
* Register module customization hooks. * Register module customization hooks.
* @returns {Promise<any>}
*/ */
async function initializeHooks() { async function initializeHooks() {
const customLoaderURLs = getOptionValue('--experimental-loader'); const customLoaderURLs = getOptionValue('--experimental-loader');
@ -342,7 +348,7 @@ async function initializeHooks() {
* @param {string} url URL of the module. * @param {string} url URL of the module.
* @param {string} source Source code of the module. * @param {string} source Source code of the module.
* @param {typeof import('./loader.js').ModuleLoader|undefined} cascadedLoader If provided, * @param {typeof import('./loader.js').ModuleLoader|undefined} cascadedLoader If provided,
* register the module for default handling. * register the module for default handling.
* @param {{ isMain?: boolean }|undefined} context - context object containing module metadata. * @param {{ isMain?: boolean }|undefined} context - context object containing module metadata.
* @returns {ModuleWrap} * @returns {ModuleWrap}
*/ */

View file

@ -31,7 +31,8 @@ const { isMarkedAsUntransferable } = require('internal/buffer');
/** /**
* Transfers an ArrayBuffer, TypedArray, or DataView to a worker thread. * Transfers an ArrayBuffer, TypedArray, or DataView to a worker thread.
* @param {boolean} hasError - Whether an error occurred during transfer. * @param {boolean} hasError - Whether an error occurred during transfer.
* @param {ArrayBuffer | TypedArray | DataView} source - The data to transfer. * @param {ArrayBuffer[] | TypedArray | DataView} source - The data to transfer.
* @returns {ArrayBuffer[]|undefined}
*/ */
function transferArrayBuffer(hasError, source) { function transferArrayBuffer(hasError, source) {
if (hasError || source == null) { return; } if (hasError || source == null) { return; }
@ -51,7 +52,8 @@ function transferArrayBuffer(hasError, source) {
/** /**
* Wraps a message with a status and body, and serializes the body if necessary. * Wraps a message with a status and body, and serializes the body if necessary.
* @param {string} status - The status of the message. * @param {string} status - The status of the message.
* @param {unknown} body - The body of the message. * @param {any} body - The body of the message.
* @returns {{status: string, body: any}}
*/ */
function wrapMessage(status, body) { function wrapMessage(status, body) {
if (status === 'success' || body === null || if (status === 'success' || body === null ||
@ -83,7 +85,7 @@ function wrapMessage(status, body) {
* Initializes a worker thread for a customized module loader. * Initializes a worker thread for a customized module loader.
* @param {SharedArrayBuffer} lock - The lock used to synchronize communication between the worker and the main thread. * @param {SharedArrayBuffer} lock - The lock used to synchronize communication between the worker and the main thread.
* @param {MessagePort} syncCommPort - The message port used for synchronous communication between the worker and the * @param {MessagePort} syncCommPort - The message port used for synchronous communication between the worker and the
* main thread. * main thread.
* @param {(err: Error, origin?: string) => void} errorHandler - The function to use for uncaught exceptions. * @param {(err: Error, origin?: string) => void} errorHandler - The function to use for uncaught exceptions.
* @returns {Promise<void>} A promise that resolves when the worker thread has been initialized. * @returns {Promise<void>} A promise that resolves when the worker thread has been initialized.
*/ */
@ -235,6 +237,7 @@ async function customizedModuleWorker(lock, syncCommPort, errorHandler) {
* ! Run everything possible within this function so errors get reported. * ! Run everything possible within this function so errors get reported.
* @param {{lock: SharedArrayBuffer}} workerData - The lock used to synchronize with the main thread. * @param {{lock: SharedArrayBuffer}} workerData - The lock used to synchronize with the main thread.
* @param {MessagePort} syncCommPort - The communication port used to communicate with the main thread. * @param {MessagePort} syncCommPort - The communication port used to communicate with the main thread.
* @returns {object}
*/ */
module.exports = function setupModuleWorker(workerData, syncCommPort) { module.exports = function setupModuleWorker(workerData, syncCommPort) {
const lock = new Int32Array(workerData.lock); const lock = new Int32Array(workerData.lock);
@ -242,7 +245,7 @@ module.exports = function setupModuleWorker(workerData, syncCommPort) {
/** /**
* Handles errors that occur in the worker thread. * Handles errors that occur in the worker thread.
* @param {Error} err - The error that occurred. * @param {Error} err - The error that occurred.
* @param {string} [origin='unhandledRejection'] - The origin of the error. * @param {string} [origin] - The origin of the error.
*/ */
function errorHandler(err, origin = 'unhandledRejection') { function errorHandler(err, origin = 'unhandledRejection') {
AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1); AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1);

View file

@ -56,6 +56,7 @@ const realpathCache = new SafeMap();
/** /**
* Resolves the path of a given `require` specifier, following symlinks. * Resolves the path of a given `require` specifier, following symlinks.
* @param {string} requestPath The `require` specifier * @param {string} requestPath The `require` specifier
* @returns {string}
*/ */
function toRealPath(requestPath) { function toRealPath(requestPath) {
return fs.realpathSync(requestPath, { return fs.realpathSync(requestPath, {
@ -67,6 +68,7 @@ function toRealPath(requestPath) {
let cjsConditions; let cjsConditions;
/** /**
* Define the conditions that apply to the CommonJS loader. * Define the conditions that apply to the CommonJS loader.
* @returns {void}
*/ */
function initializeCjsConditions() { function initializeCjsConditions() {
const userConditions = getOptionValue('--conditions'); const userConditions = getOptionValue('--conditions');
@ -86,6 +88,7 @@ function initializeCjsConditions() {
/** /**
* Get the conditions that apply to the CommonJS loader. * Get the conditions that apply to the CommonJS loader.
* @returns {Set<string>}
*/ */
function getCjsConditions() { function getCjsConditions() {
if (cjsConditions === undefined) { if (cjsConditions === undefined) {
@ -97,6 +100,7 @@ function getCjsConditions() {
/** /**
* Provide one of Node.js' public modules to user code. * Provide one of Node.js' public modules to user code.
* @param {string} id - The identifier/specifier of the builtin module to load * @param {string} id - The identifier/specifier of the builtin module to load
* @returns {object|undefined}
*/ */
function loadBuiltinModule(id) { function loadBuiltinModule(id) {
if (!BuiltinModule.canBeRequiredByUsers(id)) { if (!BuiltinModule.canBeRequiredByUsers(id)) {
@ -114,6 +118,7 @@ function loadBuiltinModule(id) {
let $Module = null; let $Module = null;
/** /**
* Import the Module class on first use. * Import the Module class on first use.
* @returns {object}
*/ */
function lazyModule() { function lazyModule() {
return $Module ??= require('internal/modules/cjs/loader').Module; return $Module ??= require('internal/modules/cjs/loader').Module;
@ -122,7 +127,7 @@ function lazyModule() {
/** /**
* Create the module-scoped `require` function to pass into CommonJS modules. * Create the module-scoped `require` function to pass into CommonJS modules.
* @param {Module} mod - The module to create the `require` function for. * @param {Module} mod - The module to create the `require` function for.
* @typedef {(specifier: string) => unknown} RequireFunction * @returns {function(string): unknown}
*/ */
function makeRequireFunction(mod) { function makeRequireFunction(mod) {
// lazy due to cycle // lazy due to cycle
@ -139,6 +144,7 @@ function makeRequireFunction(mod) {
* The `resolve` method that gets attached to module-scope `require`. * The `resolve` method that gets attached to module-scope `require`.
* @param {string} request * @param {string} request
* @param {Parameters<Module['_resolveFilename']>[3]} options * @param {Parameters<Module['_resolveFilename']>[3]} options
* @returns {string}
*/ */
function resolve(request, options) { function resolve(request, options) {
validateString(request, 'request'); validateString(request, 'request');
@ -150,6 +156,7 @@ function makeRequireFunction(mod) {
/** /**
* The `paths` method that gets attached to module-scope `require`. * The `paths` method that gets attached to module-scope `require`.
* @param {string} request * @param {string} request
* @returns {object}
*/ */
function paths(request) { function paths(request) {
validateString(request, 'request'); validateString(request, 'request');
@ -173,6 +180,7 @@ function makeRequireFunction(mod) {
* because the buffer-to-string conversion in `fs.readFileSync()` * because the buffer-to-string conversion in `fs.readFileSync()`
* translates it to FEFF, the UTF-16 BOM. * translates it to FEFF, the UTF-16 BOM.
* @param {string} content * @param {string} content
* @returns {string}
*/ */
function stripBOM(content) { function stripBOM(content) {
if (StringPrototypeCharCodeAt(content) === 0xFEFF) { if (StringPrototypeCharCodeAt(content) === 0xFEFF) {
@ -274,9 +282,9 @@ function normalizeReferrerURL(referrerName) {
assert.fail('Unreachable code reached by ' + inspect(referrerName)); assert.fail('Unreachable code reached by ' + inspect(referrerName));
} }
/** /**
* @param {string|undefined} url URL to convert to filename * @param {string|undefined} url URL to convert to filename
* @returns {string|undefined}
*/ */
function urlToFilename(url) { function urlToFilename(url) {
if (url && StringPrototypeStartsWith(url, 'file://')) { if (url && StringPrototypeStartsWith(url, 'file://')) {
@ -302,7 +310,7 @@ let _hasStartedUserESMExecution = false;
* will be normalized. * will be normalized.
* @param {string} id ID of the built-in to be loaded. * @param {string} id ID of the built-in to be loaded.
* @returns {object|undefined} exports of the built-in. Undefined if the built-in * @returns {object|undefined} exports of the built-in. Undefined if the built-in
* does not exist. * does not exist.
*/ */
function getBuiltinModule(id) { function getBuiltinModule(id) {
validateString(id, 'id'); validateString(id, 'id');
@ -314,6 +322,7 @@ function getBuiltinModule(id) {
let _TYPES = null; let _TYPES = null;
/** /**
* Lazily loads and returns the internal/util/types module. * Lazily loads and returns the internal/util/types module.
* @returns {object}
*/ */
function lazyTypes() { function lazyTypes() {
if (_TYPES !== null) { return _TYPES; } if (_TYPES !== null) { return _TYPES; }
@ -328,6 +337,7 @@ function lazyTypes() {
* @param {boolean} allowString - Whether or not to allow a string as a valid buffer source. * @param {boolean} allowString - Whether or not to allow a string as a valid buffer source.
* @param {string} hookName - The name of the hook being called. * @param {string} hookName - The name of the hook being called.
* @throws {ERR_INVALID_RETURN_PROPERTY_VALUE} If the body is not a buffer source. * @throws {ERR_INVALID_RETURN_PROPERTY_VALUE} If the body is not a buffer source.
* @returns {void}
*/ */
function assertBufferSource(body, allowString, hookName) { function assertBufferSource(body, allowString, hookName) {
if (allowString && typeof body === 'string') { if (allowString && typeof body === 'string') {
@ -394,7 +404,7 @@ ObjectFreeze(constants);
/** /**
* Get the compile cache directory if on-disk compile cache is enabled. * Get the compile cache directory if on-disk compile cache is enabled.
* @returns {string|undefined} Path to the module compile cache directory if it is enabled, * @returns {string|undefined} Path to the module compile cache directory if it is enabled,
* or undefined otherwise. * or undefined otherwise.
*/ */
function getCompileCacheDir() { function getCompileCacheDir() {
return _getCompileCacheDir() || undefined; return _getCompileCacheDir() || undefined;

View file

@ -172,6 +172,7 @@ function getPackageScopeConfig(resolved) {
/** /**
* Returns the package type for a given URL. * Returns the package type for a given URL.
* @param {URL} url - The URL to get the package type for. * @param {URL} url - The URL to get the package type for.
* @returns {string}
*/ */
function getPackageType(url) { function getPackageType(url) {
const type = modulesBinding.getPackageType(`${url}`); const type = modulesBinding.getPackageType(`${url}`);
@ -183,6 +184,7 @@ const invalidPackageNameRegEx = /^\.|%|\\/;
* Parse a package name from a specifier. * Parse a package name from a specifier.
* @param {string} specifier - The import specifier. * @param {string} specifier - The import specifier.
* @param {string | URL | undefined} base - The parent URL. * @param {string | URL | undefined} base - The parent URL.
* @returns {object}
*/ */
function parsePackageName(specifier, base) { function parsePackageName(specifier, base) {
let separatorIndex = StringPrototypeIndexOf(specifier, '/'); let separatorIndex = StringPrototypeIndexOf(specifier, '/');
@ -258,8 +260,9 @@ function getPackageJSONURL(specifier, base) {
/** @type {import('./esm/resolve.js').defaultResolve} */ /** @type {import('./esm/resolve.js').defaultResolve} */
let defaultResolve; let defaultResolve;
/** /**
* @param {URL['href'] | string | URL} specifier The location for which to get the "root" package.json * @param {string | URL} specifier The location for which to get the "root" package.json
* @param {URL['href'] | string | URL} [base] The location of the current module (ex file://tmp/foo.js). * @param {string | URL} [base] The location of the current module (ex file://tmp/foo.js).
* @returns {string}
*/ */
function findPackageJSON(specifier, base = 'data:') { function findPackageJSON(specifier, base = 'data:') {
if (arguments.length === 0) { if (arguments.length === 0) {

View file

@ -24,6 +24,7 @@ const {
/** /**
* Get the absolute path to the main entry point. * Get the absolute path to the main entry point.
* @param {string} main - Entry point path * @param {string} main - Entry point path
* @returns {string|undefined}
*/ */
function resolveMainPath(main) { function resolveMainPath(main) {
/** @type {string} */ /** @type {string} */
@ -46,6 +47,7 @@ function resolveMainPath(main) {
/** /**
* Determine whether the main entry point should be loaded through the ESM Loader. * Determine whether the main entry point should be loaded through the ESM Loader.
* @param {string} mainPath - Absolute path to the main entry point * @param {string} mainPath - Absolute path to the main entry point
* @returns {boolean}
*/ */
function shouldUseESMLoader(mainPath) { function shouldUseESMLoader(mainPath) {
/** /**

View file

@ -93,7 +93,7 @@ class Navigator {
} }
/** /**
* @return {number} * @returns {number}
*/ */
get hardwareConcurrency() { get hardwareConcurrency() {
this.#availableParallelism ??= getAvailableParallelism(); this.#availableParallelism ??= getAvailableParallelism();
@ -101,7 +101,7 @@ class Navigator {
} }
/** /**
* @return {string} * @returns {string}
*/ */
get language() { get language() {
// The default locale might be changed dynamically, so always invoke the // The default locale might be changed dynamically, so always invoke the
@ -110,7 +110,7 @@ class Navigator {
} }
/** /**
* @return {Array<string>} * @returns {Array<string>}
*/ */
get languages() { get languages() {
this.#languages ??= ObjectFreeze([this.language]); this.#languages ??= ObjectFreeze([this.language]);
@ -118,7 +118,7 @@ class Navigator {
} }
/** /**
* @return {string} * @returns {string}
*/ */
get userAgent() { get userAgent() {
this.#userAgent ??= `Node.js/${StringPrototypeSlice(nodeVersion, 1, StringPrototypeIndexOf(nodeVersion, '.'))}`; this.#userAgent ??= `Node.js/${StringPrototypeSlice(nodeVersion, 1, StringPrototypeIndexOf(nodeVersion, '.'))}`;
@ -126,7 +126,7 @@ class Navigator {
} }
/** /**
* @return {string} * @returns {string}
*/ */
get platform() { get platform() {
this.#platform ??= getNavigatorPlatform(arch, platform); this.#platform ??= getNavigatorPlatform(arch, platform);

View file

@ -30,6 +30,10 @@ const IPv6Reg = new RegExp('^(?:' +
`(?::(?:(?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` + `(?::(?:(?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
')(?:%[0-9a-zA-Z-.:]{1,})?$'); ')(?:%[0-9a-zA-Z-.:]{1,})?$');
/**
* @param {string} s
* @returns {boolean}
*/
function isIPv4(s) { function isIPv4(s) {
// TODO(aduh95): Replace RegExpPrototypeTest with RegExpPrototypeExec when it // TODO(aduh95): Replace RegExpPrototypeTest with RegExpPrototypeExec when it
// no longer creates a perf regression in the dns benchmark. // no longer creates a perf regression in the dns benchmark.
@ -37,6 +41,10 @@ function isIPv4(s) {
return RegExpPrototypeTest(IPv4Reg, s); return RegExpPrototypeTest(IPv4Reg, s);
} }
/**
* @param {string} s
* @returns {boolean}
*/
function isIPv6(s) { function isIPv6(s) {
// TODO(aduh95): Replace RegExpPrototypeTest with RegExpPrototypeExec when it // TODO(aduh95): Replace RegExpPrototypeTest with RegExpPrototypeExec when it
// no longer creates a perf regression in the dns benchmark. // no longer creates a perf regression in the dns benchmark.
@ -44,6 +52,10 @@ function isIPv6(s) {
return RegExpPrototypeTest(IPv6Reg, s); return RegExpPrototypeTest(IPv6Reg, s);
} }
/**
* @param {string} s
* @returns {4|6|0}
*/
function isIP(s) { function isIP(s) {
if (isIPv4(s)) return 4; if (isIPv4(s)) return 4;
if (isIPv6(s)) return 6; if (isIPv6(s)) return 6;
@ -72,6 +84,8 @@ function makeSyncWrite(fd) {
* https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml * https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
* https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml * https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
* https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml * https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml
* @param {string} host
* @returns {boolean}
*/ */
function isLoopback(host) { function isLoopback(host) {
const hostLower = host.toLowerCase(); const hostLower = host.toLowerCase();

View file

@ -458,7 +458,7 @@ const SafePromise = makeSafe(
* Prefer using async functions when possible. * Prefer using async functions when possible.
* @param {Promise<any>} thisPromise * @param {Promise<any>} thisPromise
* @param {(() => void) | undefined | null} onFinally The callback to execute * @param {(() => void) | undefined | null} onFinally The callback to execute
* when the Promise is settled (fulfilled or rejected). * when the Promise is settled (fulfilled or rejected).
* @returns {Promise} A Promise for the completion of the callback. * @returns {Promise} A Promise for the completion of the callback.
*/ */
primordials.SafePromisePrototypeFinally = (thisPromise, onFinally) => primordials.SafePromisePrototypeFinally = (thisPromise, onFinally) =>

View file

@ -212,7 +212,8 @@ function refreshRuntimeOptions() {
* Replace `process.argv[0]` with `process.execPath`, preserving the original `argv[0]` value as `process.argv0`. * Replace `process.argv[0]` with `process.execPath`, preserving the original `argv[0]` value as `process.argv0`.
* Replace `process.argv[1]` with the resolved absolute file path of the entry point, if found. * Replace `process.argv[1]` with the resolved absolute file path of the entry point, if found.
* @param {boolean} expandArgv1 - Whether to replace `process.argv[1]` with the resolved absolute file path of * @param {boolean} expandArgv1 - Whether to replace `process.argv[1]` with the resolved absolute file path of
* the main entry point. * the main entry point.
* @returns {string}
*/ */
function patchProcessObject(expandArgv1) { function patchProcessObject(expandArgv1) {
const binding = internalBinding('process_methods'); const binding = internalBinding('process_methods');

View file

@ -312,7 +312,7 @@ const onSessionHandshakeChannel = dc.channel('quic.session.handshake');
/** /**
* @callback OnBlockedCallback * @callback OnBlockedCallback
* @this {QuicStream} stream * @this {QuicStream}
* @returns {void} * @returns {void}
*/ */
@ -1892,6 +1892,7 @@ function readOnlyConstant(value) {
/** /**
* @param {EndpointOptions} endpoint * @param {EndpointOptions} endpoint
* @returns {{ endpoint: Endpoint_, created: boolean }}
*/ */
function processEndpointOption(endpoint) { function processEndpointOption(endpoint) {
if (endpoint === undefined) { if (endpoint === undefined) {
@ -1914,6 +1915,8 @@ function processEndpointOption(endpoint) {
/** /**
* @param {SessionOptions} tls * @param {SessionOptions} tls
* @param {boolean} forServer
* @returns {object}
*/ */
function processTlsOptions(tls, forServer) { function processTlsOptions(tls, forServer) {
const { const {

View file

@ -1543,11 +1543,7 @@ class Interface extends InterfaceConstructor {
/** /**
* Creates an `AsyncIterator` object that iterates through * Creates an `AsyncIterator` object that iterates through
* each line in the input stream as a string. * each line in the input stream as a string.
* @typedef {{ * @returns {AsyncIterableIterator<string>}
* [Symbol.asyncIterator]: () => InterfaceAsyncIterator,
* next: () => Promise<string>
* }} InterfaceAsyncIterator
* @returns {InterfaceAsyncIterator}
*/ */
[SymbolAsyncIterator]() { [SymbolAsyncIterator]() {
if (this[kLineObjectStream] === undefined) { if (this[kLineObjectStream] === undefined) {

View file

@ -87,7 +87,7 @@ class Readline {
* @param {-1|0|1} dir Direction to clear: * @param {-1|0|1} dir Direction to clear:
* -1 for left of the cursor * -1 for left of the cursor
* +1 for right of the cursor * +1 for right of the cursor
* 0 for the entire line * 0 for the entire line
* @returns {Readline} this * @returns {Readline} this
*/ */
clearLine(dir) { clearLine(dir) {
@ -119,7 +119,7 @@ class Readline {
* Sends all the pending actions to the associated `stream` and clears the * Sends all the pending actions to the associated `stream` and clears the
* internal list of pending actions. * internal list of pending actions.
* @returns {Promise<void>} Resolves when all pending actions have been * @returns {Promise<void>} Resolves when all pending actions have been
* flushed to the associated `stream`. * flushed to the associated `stream`.
*/ */
commit() { commit() {
return new Promise((resolve) => { return new Promise((resolve) => {

View file

@ -88,7 +88,6 @@ const kMappings = Symbol('kMappings');
class StringCharIterator { class StringCharIterator {
/** /**
* @constructor
* @param {string} string * @param {string} string
*/ */
constructor(string) { constructor(string) {
@ -97,21 +96,21 @@ class StringCharIterator {
} }
/** /**
* @return {string} * @returns {string}
*/ */
next() { next() {
return StringPrototypeCharAt(this._string, this._position++); return StringPrototypeCharAt(this._string, this._position++);
} }
/** /**
* @return {string} * @returns {string}
*/ */
peek() { peek() {
return StringPrototypeCharAt(this._string, this._position); return StringPrototypeCharAt(this._string, this._position);
} }
/** /**
* @return {boolean} * @returns {boolean}
*/ */
hasNext() { hasNext() {
return this._position < this._string.length; return this._position < this._string.length;
@ -119,6 +118,7 @@ class StringCharIterator {
} }
/** /**
* @class
* Implements Source Map V3 model. * Implements Source Map V3 model.
* See https://github.com/google/closure-compiler/wiki/Source-Maps * See https://github.com/google/closure-compiler/wiki/Source-Maps
* for format description. * for format description.
@ -131,7 +131,6 @@ class SourceMap {
#lineLengths = undefined; #lineLengths = undefined;
/** /**
* @constructor
* @param {SourceMapV3} payload * @param {SourceMapV3} payload
*/ */
constructor(payload, { lineLengths } = { __proto__: null }) { constructor(payload, { lineLengths } = { __proto__: null }) {
@ -150,7 +149,7 @@ class SourceMap {
} }
/** /**
* @return {object} raw source map v3 payload. * @returns {object} raw source map v3 payload.
*/ */
get payload() { get payload() {
return cloneSourceMapV3(this.#payload); return cloneSourceMapV3(this.#payload);
@ -161,7 +160,7 @@ class SourceMap {
} }
/** /**
* @return {number[] | undefined} line lengths of generated source code * @returns {number[] | undefined} line lengths of generated source code
*/ */
get lineLengths() { get lineLengths() {
if (this.#lineLengths) { if (this.#lineLengths) {
@ -192,7 +191,7 @@ class SourceMap {
/** /**
* @param {number} lineOffset 0-indexed line offset in compiled resource * @param {number} lineOffset 0-indexed line offset in compiled resource
* @param {number} columnOffset 0-indexed column offset in compiled resource * @param {number} columnOffset 0-indexed column offset in compiled resource
* @return {object} representing start of range if found, or empty object * @returns {object} representing start of range if found, or empty object
*/ */
findEntry(lineOffset, columnOffset) { findEntry(lineOffset, columnOffset) {
let first = 0; let first = 0;
@ -229,7 +228,7 @@ class SourceMap {
/** /**
* @param {number} lineNumber 1-indexed line number in compiled resource call site * @param {number} lineNumber 1-indexed line number in compiled resource call site
* @param {number} columnNumber 1-indexed column number in compiled resource call site * @param {number} columnNumber 1-indexed column number in compiled resource call site
* @return {object} representing origin call site if found, or empty object * @returns {object} representing origin call site if found, or empty object
*/ */
findOrigin(lineNumber, columnNumber) { findOrigin(lineNumber, columnNumber) {
const range = this.findEntry(lineNumber - 1, columnNumber - 1); const range = this.findEntry(lineNumber - 1, columnNumber - 1);
@ -319,7 +318,7 @@ class SourceMap {
/** /**
* @param {string} char * @param {string} char
* @return {boolean} * @returns {boolean}
*/ */
function isSeparator(char) { function isSeparator(char) {
return char === ',' || char === ';'; return char === ',' || char === ';';
@ -327,7 +326,7 @@ function isSeparator(char) {
/** /**
* @param {SourceMap.StringCharIterator} stringCharIterator * @param {SourceMap.StringCharIterator} stringCharIterator
* @return {number} * @returns {number}
*/ */
function decodeVLQ(stringCharIterator) { function decodeVLQ(stringCharIterator) {
// Read unsigned value. // Read unsigned value.
@ -359,7 +358,7 @@ function decodeVLQ(stringCharIterator) {
/** /**
* @param {SourceMapV3} payload * @param {SourceMapV3} payload
* @return {SourceMapV3} * @returns {SourceMapV3}
*/ */
function cloneSourceMapV3(payload) { function cloneSourceMapV3(payload) {
validateObject(payload, 'payload'); validateObject(payload, 'payload');
@ -375,9 +374,9 @@ function cloneSourceMapV3(payload) {
/** /**
* @param {Array} entry1 source map entry [lineNumber, columnNumber, sourceURL, * @param {Array} entry1 source map entry [lineNumber, columnNumber, sourceURL,
* sourceLineNumber, sourceColumnNumber] * sourceLineNumber, sourceColumnNumber]
* @param {Array} entry2 source map entry. * @param {Array} entry2 source map entry.
* @return {number} * @returns {number}
*/ */
function compareSourceMapEntry(entry1, entry2) { function compareSourceMapEntry(entry1, entry2) {
const { 0: lineNumber1, 1: columnNumber1 } = entry1; const { 0: lineNumber1, 1: columnNumber1 } = entry1;

View file

@ -145,7 +145,7 @@ function extractSourceMapURLMagicComment(content) {
* @param {string} filename - the actual filename * @param {string} filename - the actual filename
* @param {string} content - the actual source content * @param {string} content - the actual source content
* @param {import('internal/modules/cjs/loader').Module | ModuleWrap} moduleInstance - a module instance that * @param {import('internal/modules/cjs/loader').Module | ModuleWrap} moduleInstance - a module instance that
* associated with the source, once this is reclaimed, the source map entry will be removed from the cache * associated with the source, once this is reclaimed, the source map entry will be removed from the cache
* @param {boolean} isGeneratedSource - if the source was generated and evaluated with the global eval * @param {boolean} isGeneratedSource - if the source was generated and evaluated with the global eval
* @param {string | undefined} sourceURL - the source url * @param {string | undefined} sourceURL - the source url
* @param {string | undefined} sourceMapURL - the source map url * @param {string | undefined} sourceMapURL - the source map url

View file

@ -58,7 +58,7 @@ class SourceMapCacheMap {
* @param {string[]} keys array of urls to index the value entry. * @param {string[]} keys array of urls to index the value entry.
* @param {*} sourceMapData the value entry. * @param {*} sourceMapData the value entry.
* @param {object} moduleInstance an object that can be weakly referenced and * @param {object} moduleInstance an object that can be weakly referenced and
* invalidate the [key, value] entry after this object is reclaimed. * invalidate the [key, value] entry after this object is reclaimed.
*/ */
set(keys, sourceMapData, moduleInstance) { set(keys, sourceMapData, moduleInstance) {
const weakRef = new SafeWeakRef(moduleInstance); const weakRef = new SafeWeakRef(moduleInstance);
@ -70,6 +70,7 @@ class SourceMapCacheMap {
/** /**
* Get an entry by the given key. * Get an entry by the given key.
* @param {string} key a file url or source url * @param {string} key a file url or source url
* @returns {object|undefined}
*/ */
get(key) { get(key) {
const weakRef = this.#weakModuleMap.get(key); const weakRef = this.#weakModuleMap.get(key);
@ -83,6 +84,7 @@ class SourceMapCacheMap {
/** /**
* Estimate the size of the cache. The actual size may be smaller because * Estimate the size of the cache. The actual size may be smaller because
* some entries may be reclaimed with the module instance. * some entries may be reclaimed with the module instance.
* @returns {number}
*/ */
get size() { get size() {
return this.#weakModuleMap.size; return this.#weakModuleMap.size;

View file

@ -428,7 +428,7 @@ class MockTracker {
* @param {Function} [original] - The original function to be tracked. * @param {Function} [original] - The original function to be tracked.
* @param {Function} [implementation] - An optional replacement function for the original one. * @param {Function} [implementation] - An optional replacement function for the original one.
* @param {object} [options] - Additional tracking options. * @param {object} [options] - Additional tracking options.
* @param {number} [options.times=Infinity] - The maximum number of times the mock function can be called. * @param {number} [options.times] - The maximum number of times the mock function can be called.
* @returns {ProxyConstructor} The mock function tracker. * @returns {ProxyConstructor} The mock function tracker.
*/ */
fn( fn(
@ -460,9 +460,9 @@ class MockTracker {
* @param {string} methodName - The name of the method to be tracked. * @param {string} methodName - The name of the method to be tracked.
* @param {Function} [implementation] - An optional replacement function for the original method. * @param {Function} [implementation] - An optional replacement function for the original method.
* @param {object} [options] - Additional tracking options. * @param {object} [options] - Additional tracking options.
* @param {boolean} [options.getter=false] - Indicates whether this is a getter method. * @param {boolean} [options.getter] - Indicates whether this is a getter method.
* @param {boolean} [options.setter=false] - Indicates whether this is a setter method. * @param {boolean} [options.setter] - Indicates whether this is a setter method.
* @param {number} [options.times=Infinity] - The maximum number of times the mock method can be called. * @param {number} [options.times] - The maximum number of times the mock method can be called.
* @returns {ProxyConstructor} The mock method tracker. * @returns {ProxyConstructor} The mock method tracker.
*/ */
method( method(
@ -551,9 +551,9 @@ class MockTracker {
* @param {string} methodName - The name of the getter method to be mocked. * @param {string} methodName - The name of the getter method to be mocked.
* @param {Function} [implementation] - An optional replacement function for the targeted method. * @param {Function} [implementation] - An optional replacement function for the targeted method.
* @param {object} [options] - Additional tracking options. * @param {object} [options] - Additional tracking options.
* @param {boolean} [options.getter=true] - Indicates whether this is a getter method. * @param {boolean} [options.getter] - Indicates whether this is a getter method.
* @param {boolean} [options.setter=false] - Indicates whether this is a setter method. * @param {boolean} [options.setter] - Indicates whether this is a setter method.
* @param {number} [options.times=Infinity] - The maximum number of times the mock method can be called. * @param {number} [options.times] - The maximum number of times the mock method can be called.
* @returns {ProxyConstructor} The mock method tracker. * @returns {ProxyConstructor} The mock method tracker.
*/ */
getter( getter(
@ -588,12 +588,12 @@ class MockTracker {
* Mocks a setter method of an object. * Mocks a setter method of an object.
* This function is a syntax sugar for MockTracker.method with options.setter set to true. * This function is a syntax sugar for MockTracker.method with options.setter set to true.
* @param {object} object - The target object. * @param {object} object - The target object.
* @param {string} methodName - The setter method to be mocked. * @param {string} methodName - The setter method to be mocked.
* @param {Function} [implementation] - An optional replacement function for the targeted method. * @param {Function} [implementation] - An optional replacement function for the targeted method.
* @param {object} [options] - Additional tracking options. * @param {object} [options] - Additional tracking options.
* @param {boolean} [options.getter=false] - Indicates whether this is a getter method. * @param {boolean} [options.getter] - Indicates whether this is a getter method.
* @param {boolean} [options.setter=true] - Indicates whether this is a setter method. * @param {boolean} [options.setter] - Indicates whether this is a setter method.
* @param {number} [options.times=Infinity] - The maximum number of times the mock method can be called. * @param {number} [options.times] - The maximum number of times the mock method can be called.
* @returns {ProxyConstructor} The mock method tracker. * @returns {ProxyConstructor} The mock method tracker.
*/ */
setter( setter(

View file

@ -60,7 +60,7 @@ function abortIt(signal) {
} }
/** /**
* @enum {('setTimeout'|'setInterval'|'setImmediate'|'Date', 'scheduler.wait')[]} Supported timers * @enum {('setTimeout'|'setInterval'|'setImmediate'|'Date'|'scheduler.wait')[]} Supported timers
*/ */
const SUPPORTED_APIS = ['setTimeout', 'setInterval', 'setImmediate', 'Date', 'scheduler.wait']; const SUPPORTED_APIS = ['setTimeout', 'setInterval', 'setImmediate', 'Date', 'scheduler.wait'];
const TIMERS_DEFAULT_INTERVAL = { const TIMERS_DEFAULT_INTERVAL = {
@ -632,7 +632,7 @@ class MockTimers {
/** /**
* Advances the virtual time of MockTimers by the specified duration (in milliseconds). * Advances the virtual time of MockTimers by the specified duration (in milliseconds).
* This method simulates the passage of time and triggers any scheduled timers that are due. * This method simulates the passage of time and triggers any scheduled timers that are due.
* @param {number} [time=1] - The amount of time (in milliseconds) to advance the virtual time. * @param {number} [time] - The amount of time (in milliseconds) to advance the virtual time.
* @throws {ERR_INVALID_STATE} If MockTimers are not enabled. * @throws {ERR_INVALID_STATE} If MockTimers are not enabled.
* @throws {ERR_INVALID_ARG_VALUE} If a negative time value is provided. * @throws {ERR_INVALID_ARG_VALUE} If a negative time value is provided.
*/ */

View file

@ -729,6 +729,7 @@ class Test extends AsyncResource {
* Ex."grandparent parent test" * Ex."grandparent parent test"
* *
* It's needed to match a single test with non-unique name by pattern * It's needed to match a single test with non-unique name by pattern
* @returns {string}
*/ */
getTestNameWithAncestors() { getTestNameWithAncestors() {
if (!this.parent) return ''; if (!this.parent) return '';
@ -736,14 +737,24 @@ class Test extends AsyncResource {
return `${this.parent.getTestNameWithAncestors()} ${this.name}`; return `${this.parent.getTestNameWithAncestors()} ${this.name}`;
} }
/**
* @returns {boolean}
*/
hasConcurrency() { hasConcurrency() {
return this.concurrency > this.activeSubtests; return this.concurrency > this.activeSubtests;
} }
/**
* @param {any} deferred
* @returns {void}
*/
addPendingSubtest(deferred) { addPendingSubtest(deferred) {
ArrayPrototypePush(this.pendingSubtests, deferred); ArrayPrototypePush(this.pendingSubtests, deferred);
} }
/**
* @returns {Promise<void>}
*/
async processPendingSubtests() { async processPendingSubtests() {
while (this.pendingSubtests.length > 0 && this.hasConcurrency()) { while (this.pendingSubtests.length > 0 && this.hasConcurrency()) {
const deferred = ArrayPrototypeShift(this.pendingSubtests); const deferred = ArrayPrototypeShift(this.pendingSubtests);
@ -754,6 +765,10 @@ class Test extends AsyncResource {
} }
} }
/**
* @param {any} subtest
* @returns {void}
*/
addReadySubtest(subtest) { addReadySubtest(subtest) {
this.readySubtests.set(subtest.childNumber, subtest); this.readySubtests.set(subtest.childNumber, subtest);
@ -763,6 +778,10 @@ class Test extends AsyncResource {
} }
} }
/**
* @param {boolean} canSend
* @returns {void}
*/
processReadySubtestRange(canSend) { processReadySubtestRange(canSend) {
const start = this.waitingOn; const start = this.waitingOn;
const end = start + this.readySubtests.size; const end = start + this.readySubtests.size;

View file

@ -22,9 +22,9 @@ function validateInput(value, name) {
* @param {Array | string} actual - The first value to compare * @param {Array | string} actual - The first value to compare
* @param {Array | string} expected - The second value to compare * @param {Array | string} expected - The second value to compare
* @returns {Array} - An array of differences between the two values. * @returns {Array} - An array of differences between the two values.
* The returned data is an array of arrays, where each sub-array has two elements: * The returned data is an array of arrays, where each sub-array has two elements:
* 1. The operation to perform: -1 for delete, 0 for no-op, 1 for insert * 1. The operation to perform: -1 for delete, 0 for no-op, 1 for insert
* 2. The value to perform the operation on * 2. The value to perform the operation on
*/ */
function diff(actual, expected) { function diff(actual, expected) {
if (actual === expected) { if (actual === expected) {

View file

@ -2445,7 +2445,9 @@ if (internalBinding('config').hasIntl) {
}; };
} else { } else {
/** /**
* Returns the number of columns required to display the given string. * @param {string} str
* @param {boolean} [removeControlChars]
* @returns {number} number of columns required to display the given string.
*/ */
getStringWidth = function getStringWidth(str, removeControlChars = true) { getStringWidth = function getStringWidth(str, removeControlChars = true) {
let width = 0; let width = 0;
@ -2468,6 +2470,8 @@ if (internalBinding('config').hasIntl) {
/** /**
* Returns true if the character represented by a given * Returns true if the character represented by a given
* Unicode code point is full-width. Otherwise returns false. * Unicode code point is full-width. Otherwise returns false.
* @param {string} code
* @returns {boolean}
*/ */
const isFullWidthCodePoint = (code) => { const isFullWidthCodePoint = (code) => {
// Code points are partially derived from: // Code points are partially derived from:
@ -2511,6 +2515,8 @@ if (internalBinding('config').hasIntl) {
/** /**
* Remove all VT control characters. Use to estimate displayed string width. * Remove all VT control characters. Use to estimate displayed string width.
* @param {string} str
* @returns {string}
*/ */
function stripVTControlCharacters(str) { function stripVTControlCharacters(str) {
validateString(str, 'str'); validateString(str, 'str');

View file

@ -186,6 +186,7 @@ function storeDefaultOption(longOption, optionValue, values) {
* - option-terminator * - option-terminator
* @param {string[]} args - from parseArgs({ args }) or mainArgs * @param {string[]} args - from parseArgs({ args }) or mainArgs
* @param {object} options - option configs, from parseArgs({ options }) * @param {object} options - option configs, from parseArgs({ options })
* @returns {any[]}
*/ */
function argsToTokens(args, options) { function argsToTokens(args, options) {
const tokens = []; const tokens = [];

View file

@ -22,6 +22,7 @@ const {
/** /**
* Return the named property, but only if it is an own property. * Return the named property, but only if it is an own property.
* @returns {any|undefined}
*/ */
function objectGetOwn(obj, prop) { function objectGetOwn(obj, prop) {
if (ObjectHasOwn(obj, prop)) if (ObjectHasOwn(obj, prop))
@ -30,6 +31,7 @@ function objectGetOwn(obj, prop) {
/** /**
* Return the named options property, but only if it is an own property. * Return the named options property, but only if it is an own property.
* @returns {any|undefined}
*/ */
function optionsGetOwn(options, longOption, prop) { function optionsGetOwn(options, longOption, prop) {
if (ObjectHasOwn(options, longOption)) if (ObjectHasOwn(options, longOption))
@ -39,10 +41,13 @@ function optionsGetOwn(options, longOption, prop) {
/** /**
* Determines if the argument may be used as an option value. * Determines if the argument may be used as an option value.
* @example * @example
* ```
* isOptionValue('V') // returns true * isOptionValue('V') // returns true
* isOptionValue('-v') // returns true (greedy) * isOptionValue('-v') // returns true (greedy)
* isOptionValue('--foo') // returns true (greedy) * isOptionValue('--foo') // returns true (greedy)
* isOptionValue(undefined) // returns false * isOptionValue(undefined) // returns false
* ```
* @returns {boolean}
*/ */
function isOptionValue(value) { function isOptionValue(value) {
if (value == null) return false; if (value == null) return false;
@ -56,6 +61,7 @@ function isOptionValue(value) {
* Detect whether there is possible confusion and user may have omitted * Detect whether there is possible confusion and user may have omitted
* the option argument, like `--port --verbose` when `port` of type:string. * the option argument, like `--port --verbose` when `port` of type:string.
* In strict mode we throw errors if value is option-like. * In strict mode we throw errors if value is option-like.
* @returns {boolean}
*/ */
function isOptionLikeValue(value) { function isOptionLikeValue(value) {
if (value == null) return false; if (value == null) return false;
@ -66,6 +72,7 @@ function isOptionLikeValue(value) {
/** /**
* Determines if `arg` is just a short option. * Determines if `arg` is just a short option.
* @example '-f' * @example '-f'
* @returns {boolean}
*/ */
function isLoneShortOption(arg) { function isLoneShortOption(arg) {
return arg.length === 2 && return arg.length === 2 &&
@ -76,10 +83,13 @@ function isLoneShortOption(arg) {
/** /**
* Determines if `arg` is a lone long option. * Determines if `arg` is a lone long option.
* @example * @example
* ```
* isLoneLongOption('a') // returns false * isLoneLongOption('a') // returns false
* isLoneLongOption('-a') // returns false * isLoneLongOption('-a') // returns false
* isLoneLongOption('--foo') // returns true * isLoneLongOption('--foo') // returns true
* isLoneLongOption('--foo=bar') // returns false * isLoneLongOption('--foo=bar') // returns false
* ```
* @returns {boolean}
*/ */
function isLoneLongOption(arg) { function isLoneLongOption(arg) {
return arg.length > 2 && return arg.length > 2 &&
@ -90,8 +100,11 @@ function isLoneLongOption(arg) {
/** /**
* Determines if `arg` is a long option and value in the same argument. * Determines if `arg` is a long option and value in the same argument.
* @example * @example
* ```
* isLongOptionAndValue('--foo') // returns false * isLongOptionAndValue('--foo') // returns false
* isLongOptionAndValue('--foo=bar') // returns true * isLongOptionAndValue('--foo=bar') // returns true
* ```
* @returns {boolean}
*/ */
function isLongOptionAndValue(arg) { function isLongOptionAndValue(arg) {
return arg.length > 2 && return arg.length > 2 &&
@ -107,6 +120,7 @@ function isLongOptionAndValue(arg) {
* option that takes an option-argument, should be accepted when grouped * option that takes an option-argument, should be accepted when grouped
* behind one '-' delimiter. * behind one '-' delimiter.
* @example * @example
* ```
* isShortOptionGroup('-a', {}) // returns false * isShortOptionGroup('-a', {}) // returns false
* isShortOptionGroup('-ab', {}) // returns true * isShortOptionGroup('-ab', {}) // returns true
* // -fb is an option and a value, not a short option group * // -fb is an option and a value, not a short option group
@ -120,6 +134,8 @@ function isLongOptionAndValue(arg) {
* isShortOptionGroup('-bfb', { * isShortOptionGroup('-bfb', {
* options: { f: { type: 'string' } } * options: { f: { type: 'string' } }
* }) // returns true * }) // returns true
* ```
* @returns {boolean}
*/ */
function isShortOptionGroup(arg, options) { function isShortOptionGroup(arg, options) {
if (arg.length <= 2) return false; if (arg.length <= 2) return false;
@ -134,11 +150,14 @@ function isShortOptionGroup(arg, options) {
/** /**
* Determine if arg is a short string option followed by its value. * Determine if arg is a short string option followed by its value.
* @example * @example
* ```
* isShortOptionAndValue('-a', {}); // returns false * isShortOptionAndValue('-a', {}); // returns false
* isShortOptionAndValue('-ab', {}); // returns false * isShortOptionAndValue('-ab', {}); // returns false
* isShortOptionAndValue('-fFILE', { * isShortOptionAndValue('-fFILE', {
* options: { foo: { short: 'f', type: 'string' }} * options: { foo: { short: 'f', type: 'string' }}
* }) // returns true * }) // returns true
* ```
* @returns {boolean}
*/ */
function isShortOptionAndValue(arg, options) { function isShortOptionAndValue(arg, options) {
validateObject(options, 'options'); validateObject(options, 'options');
@ -156,10 +175,13 @@ function isShortOptionAndValue(arg, options) {
* Find the long option associated with a short option. Looks for a configured * Find the long option associated with a short option. Looks for a configured
* `short` and returns the short option itself if a long option is not found. * `short` and returns the short option itself if a long option is not found.
* @example * @example
* ```
* findLongOptionForShort('a', {}) // returns 'a' * findLongOptionForShort('a', {}) // returns 'a'
* findLongOptionForShort('b', { * findLongOptionForShort('b', {
* options: { bar: { short: 'b' } } * options: { bar: { short: 'b' } }
* }) // returns 'bar' * }) // returns 'bar'
* ```
* @returns {boolean}
*/ */
function findLongOptionForShort(shortOption, options) { function findLongOptionForShort(shortOption, options) {
validateObject(options, 'options'); validateObject(options, 'options');
@ -176,6 +198,7 @@ function findLongOptionForShort(shortOption, options) {
* @param {string} longOption - long option name e.g. 'foo' * @param {string} longOption - long option name e.g. 'foo'
* @param {object} optionConfig - the option configuration properties * @param {object} optionConfig - the option configuration properties
* @param {object} values - option values returned in `values` by parseArgs * @param {object} values - option values returned in `values` by parseArgs
* @returns {boolean}
*/ */
function useDefaultValueOption(longOption, optionConfig, values) { function useDefaultValueOption(longOption, optionConfig, values) {
return objectGetOwn(optionConfig, 'default') !== undefined && return objectGetOwn(optionConfig, 'default') !== undefined &&

View file

@ -541,7 +541,7 @@ const validateThisInternalField = hideStackFrames((object, fieldKey, className)
/** /**
* @param {any} hints * @param {any} hints
* @return {string} * @returns {string}
*/ */
const validateLinkHeaderValue = hideStackFrames((hints) => { const validateLinkHeaderValue = hideStackFrames((hints) => {
if (typeof hints === 'string') { if (typeof hints === 'string') {

View file

@ -52,10 +52,10 @@ function isContext(object) {
/** /**
* Retrieves the host-defined option ID based on the provided importModuleDynamically and hint. * Retrieves the host-defined option ID based on the provided importModuleDynamically and hint.
* @param {VmImportModuleDynamicallyCallback | undefined} importModuleDynamically - * @param {VmImportModuleDynamicallyCallback | undefined} importModuleDynamically -
* The importModuleDynamically function or undefined. * The importModuleDynamically function or undefined.
* @param {string} hint - The hint for the option ID. * @param {string} hint - The hint for the option ID.
* @returns {symbol | VmImportModuleDynamicallyCallback} - The host-defined option * @returns {symbol | VmImportModuleDynamicallyCallback} - The host-defined option
* ID. * ID.
*/ */
function getHostDefinedOptionId(importModuleDynamically, hint) { function getHostDefinedOptionId(importModuleDynamically, hint) {
if (importModuleDynamically === vm_dynamic_import_main_context_default || if (importModuleDynamically === vm_dynamic_import_main_context_default ||
@ -92,7 +92,7 @@ function getHostDefinedOptionId(importModuleDynamically, hint) {
* Registers a dynamically imported module for customization. * Registers a dynamically imported module for customization.
* @param {string} referrer - The path of the referrer module. * @param {string} referrer - The path of the referrer module.
* @param {VmImportModuleDynamicallyCallback} importModuleDynamically - The * @param {VmImportModuleDynamicallyCallback} importModuleDynamically - The
* dynamically imported module function to be registered. * dynamically imported module function to be registered.
*/ */
function registerImportModuleDynamically(referrer, importModuleDynamically) { function registerImportModuleDynamically(referrer, importModuleDynamically) {
// If it's undefined or certain known symbol, there's no customization so // If it's undefined or certain known symbol, there's no customization so
@ -117,15 +117,15 @@ function registerImportModuleDynamically(referrer, importModuleDynamically) {
* @param {string} filename - The filename to use for the compiled function. * @param {string} filename - The filename to use for the compiled function.
* @param {number} lineOffset - The line offset to use for the compiled function. * @param {number} lineOffset - The line offset to use for the compiled function.
* @param {number} columnOffset - The column offset to use for the compiled function. * @param {number} columnOffset - The column offset to use for the compiled function.
* @param {Buffer} [cachedData=undefined] - The cached data to use for the compiled function. * @param {Buffer} [cachedData] - The cached data to use for the compiled function.
* @param {boolean} produceCachedData - Whether to produce cached data for the compiled function. * @param {boolean} produceCachedData - Whether to produce cached data for the compiled function.
* @param {ReturnType<import('vm').createContext} [parsingContext=undefined] - The parsing context to use for the * @param {ReturnType<import('node:vm').createContext>} [parsingContext] - The parsing context to use for the
* compiled function. * compiled function.
* @param {object[]} [contextExtensions=[]] - An array of context extensions to use for the compiled function. * @param {object[]} [contextExtensions] - An array of context extensions to use for the compiled function.
* @param {string[]} [params] - An optional array of parameter names for the compiled function. * @param {string[]} [params] - An optional array of parameter names for the compiled function.
* @param {symbol} hostDefinedOptionId - A symbol referenced by the field `host_defined_option_symbol`. * @param {symbol} hostDefinedOptionId - A symbol referenced by the field `host_defined_option_symbol`.
* @param {VmImportModuleDynamicallyCallback} [importModuleDynamically] - * @param {VmImportModuleDynamicallyCallback} [importModuleDynamically] -
* A function to use for dynamically importing modules. * A function to use for dynamically importing modules.
* @returns {object} An object containing the compiled function and any associated data. * @returns {object} An object containing the compiled function and any associated data.
* @throws {TypeError} If any of the arguments are of the wrong type. * @throws {TypeError} If any of the arguments are of the wrong type.
* @throws {ERR_INVALID_ARG_TYPE} If the parsing context is not a valid context object. * @throws {ERR_INVALID_ARG_TYPE} If the parsing context is not a valid context object.
@ -213,6 +213,7 @@ function makeContextifyScript(code,
* @param {ReturnType<makeContextifyScript>} script - The script to run. * @param {ReturnType<makeContextifyScript>} script - The script to run.
* @param {boolean} displayErrors - Whether to display errors. * @param {boolean} displayErrors - Whether to display errors.
* @param {boolean} breakOnFirstLine - Whether to break on the first line. * @param {boolean} breakOnFirstLine - Whether to break on the first line.
* @returns {any}
*/ */
function runScriptInThisContext(script, displayErrors, breakOnFirstLine) { function runScriptInThisContext(script, displayErrors, breakOnFirstLine) {
return ReflectApply( return ReflectApply(

View file

@ -90,12 +90,12 @@ const getNonWritablePropertyDescriptor = (value) => {
/** /**
* @callback TransformerStartCallback * @callback TransformerStartCallback
* @param {TransformStreamDefaultController} controller; * @param {TransformStreamDefaultController} controller
*/ */
/** /**
* @callback TransformerFlushCallback * @callback TransformerFlushCallback
* @param {TransformStreamDefaultController} controller; * @param {TransformStreamDefaultController} controller
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */

View file

@ -84,9 +84,9 @@ function setup() {
* ``` * ```
* @param {object} obj Host objects that can be either cloned or transferred. * @param {object} obj Host objects that can be either cloned or transferred.
* @param {boolean} [cloneable] if the object can be cloned and `@@kClone` is * @param {boolean} [cloneable] if the object can be cloned and `@@kClone` is
* implemented. * implemented.
* @param {boolean} [transferable] if the object can be transferred and * @param {boolean} [transferable] if the object can be transferred and
* `@@kTransfer` is implemented. * `@@kTransfer` is implemented.
*/ */
function markTransferMode(obj, cloneable = false, transferable = false) { function markTransferMode(obj, cloneable = false, transferable = false) {
if ((typeof obj !== 'object' && typeof obj !== 'function') || obj === null) if ((typeof obj !== 'object' && typeof obj !== 'function') || obj === null)

View file

@ -244,8 +244,8 @@ function networkInterfaces() {
} }
/** /**
* @param {number} [pid=0] * @param {number} [pid]
* @param {number} priority * @param {number} [priority]
* @returns {void} * @returns {void}
*/ */
function setPriority(pid, priority) { function setPriority(pid, priority) {
@ -264,7 +264,7 @@ function setPriority(pid, priority) {
} }
/** /**
* @param {number} [pid=0] * @param {number} [pid]
* @returns {number} * @returns {number}
*/ */
function getPriority(pid) { function getPriority(pid) {
@ -283,9 +283,9 @@ function getPriority(pid) {
} }
/** /**
* @param {{ encoding?: string }} [options=utf8] If `encoding` is set to * @param {{ encoding?: string }} [options] If `encoding` is set to
* `'buffer'`, the `username`, `shell`, and `homedir` values will * `'buffer'`, the `username`, `shell`, and `homedir` values will
* be `Buffer` instances. * be `Buffer` instances.
* @returns {{ * @returns {{
* uid: number, * uid: number,
* gid: number, * gid: number,

View file

@ -309,9 +309,9 @@ function addKeyVal(obj, key, value, keyEncoded, valEncoded, decode) {
* @param {string} sep * @param {string} sep
* @param {string} eq * @param {string} eq
* @param {{ * @param {{
* maxKeys?: number; * maxKeys?: number,
* decodeURIComponent?(v: string): string; * decodeURIComponent?: (v: string) => string,
* }} [options] * }} [options]
* @returns {Record<string, string | string[]>} * @returns {Record<string, string | string[]>}
*/ */
function parse(qs, sep, eq, options) { function parse(qs, sep, eq, options) {

View file

@ -1757,7 +1757,7 @@ function findExpressionCompleteTarget(code) {
* @param {any} expr The expression, in AST format to analyze * @param {any} expr The expression, in AST format to analyze
* @param {string} exprStr The string representation of the expression * @param {string} exprStr The string representation of the expression
* @param {(str: string, ctx: any, resourceName: string, cb: (error, evaled) => void) => void} evalFn * @param {(str: string, ctx: any, resourceName: string, cb: (error, evaled) => void) => void} evalFn
* Eval function to use * Eval function to use
* @param {any} ctx The context to use for any code evaluation * @param {any} ctx The context to use for any code evaluation
* @param {(includes: boolean) => void} callback Callback that will be called with the result of the operation * @param {(includes: boolean) => void} callback Callback that will be called with the result of the operation
* @returns {void} * @returns {void}
@ -1827,6 +1827,7 @@ function includesProxiesOrGetters(expr, exprStr, evalFn, ctx, callback) {
/** /**
* Utility to see if a property has a getter associated to it or if * Utility to see if a property has a getter associated to it or if
* the property itself is a proxy object. * the property itself is a proxy object.
* @returns {void}
*/ */
function hasGetterOrIsProxy(obj, astProp, cb) { function hasGetterOrIsProxy(obj, astProp, cb) {
if (!obj || !astProp) { if (!obj || !astProp) {

View file

@ -53,9 +53,9 @@ const kNativeDecoder = Symbol('kNativeDecoder');
/** /**
* StringDecoder provides an interface for efficiently splitting a series of * StringDecoder provides an interface for efficiently splitting a series of
* buffers into a series of JS strings without breaking apart multi-byte * buffers into a series of JS strings without breaking apart multibyte
* characters. * characters.
* @param {string} [encoding=utf-8] * @param {string} [encoding]
*/ */
function StringDecoder(encoding) { function StringDecoder(encoding) {
this.encoding = normalizeEncoding(encoding); this.encoding = normalizeEncoding(encoding);

View file

@ -111,9 +111,9 @@ function escapeStyleCode(code) {
/** /**
* @param {string | string[]} format * @param {string | string[]} format
* @param {string} text * @param {string} text
* @param {object} [options={}] * @param {object} [options]
* @param {boolean} [options.validateStream=true] - Whether to validate the stream. * @param {boolean} [options.validateStream] - Whether to validate the stream.
* @param {Stream} [options.stream=process.stdout] - The stream used for validation. * @param {Stream} [options.stream] - The stream used for validation.
* @returns {string} * @returns {string}
*/ */
function styleText(format, text, { validateStream = true, stream = process.stdout } = {}) { function styleText(format, text, { validateStream = true, stream = process.stdout } = {}) {
@ -163,10 +163,10 @@ function styleText(format, text, { validateStream = true, stream = process.stdou
* functions as prototype setup using normal JavaScript does not work as * functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903). * expected during bootstrapping (see mirror.js in r114903).
* @param {Function} ctor Constructor function which needs to inherit the * @param {Function} ctor Constructor function which needs to inherit the
* prototype. * prototype.
* @param {Function} superCtor Constructor function to inherit prototype from. * @param {Function} superCtor Constructor function to inherit prototype from.
* @throws {TypeError} Will error if either constructor is null, or if * @throws {TypeError} Will error if either constructor is null, or if
* the super constructor lacks a prototype. * the super constructor lacks a prototype.
*/ */
function inherits(ctor, superCtor) { function inherits(ctor, superCtor) {
@ -195,7 +195,7 @@ function inherits(ctor, superCtor) {
* @template S * @template S
* @param {T} target * @param {T} target
* @param {S} source * @param {S} source
* @returns {S extends null ? T : (T & S)} * @returns {(T & S) | null}
*/ */
function _extend(target, source) { function _extend(target, source) {
// Don't do anything if source isn't an object // Don't do anything if source isn't an object
@ -222,12 +222,9 @@ const callbackifyOnRejected = (reason, cb) => {
}; };
/** /**
* @template {(...args: any[]) => Promise<any>} T * Converts a Promise-returning function to callback style
* @param {T} original * @param {Function} original
* @returns {T extends (...args: infer TArgs) => Promise<infer TReturn> ? * @returns {Function}
* ((...params: [...TArgs, ((err: Error, ret: TReturn) => any)]) => void) :
* never
* }
*/ */
function callbackify(original) { function callbackify(original) {
validateFunction(original, 'original'); validateFunction(original, 'original');
@ -328,7 +325,7 @@ const lazySourceMap = getLazy(() => require('internal/source_map/source_map_cach
/** /**
* @typedef {object} CallSite // The call site * @typedef {object} CallSite // The call site
* @property {string} scriptName // The name of the resource that contains the * @property {string} scriptName // The name of the resource that contains the
* script for the function for this StackFrame * script for the function for this StackFrame
* @property {string} functionName // The name of the function associated with this stack frame * @property {string} functionName // The name of the function associated with this stack frame
* @property {number} lineNumber // The number, 1-based, of the line for the associate function call * @property {number} lineNumber // The number, 1-based, of the line for the associate function call
* @property {number} columnNumber // The 1-based column offset on the line for the associated function call * @property {number} columnNumber // The 1-based column offset on the line for the associated function call
@ -359,7 +356,7 @@ function reconstructCallSite(callSite) {
* *
* The call site array to map * The call site array to map
* @param {CallSite[]} callSites * @param {CallSite[]} callSites
* Array of objects with the reconstructed call site * Array of objects with the reconstructed call site
* @returns {CallSite[]} * @returns {CallSite[]}
*/ */
function mapCallSite(callSites) { function mapCallSite(callSites) {

View file

@ -203,7 +203,10 @@ const FLUSH_BOUND_IDX_NORMAL = 0;
const FLUSH_BOUND_IDX_BROTLI = 1; const FLUSH_BOUND_IDX_BROTLI = 1;
const FLUSH_BOUND_IDX_ZSTD = 2; const FLUSH_BOUND_IDX_ZSTD = 2;
// The base class for all Zlib-style streams. /**
* The base class for all Zlib-style streams.
* @class
*/
function ZlibBase(opts, mode, handle, { flush, finishFlush, fullFlush }) { function ZlibBase(opts, mode, handle, { flush, finishFlush, fullFlush }) {
let chunkSize = Z_DEFAULT_CHUNK; let chunkSize = Z_DEFAULT_CHUNK;
let maxOutputLength = kMaxLength; let maxOutputLength = kMaxLength;
@ -283,7 +286,7 @@ ObjectDefineProperty(ZlibBase.prototype, '_closed', {
}); });
/** /**
* @this ZlibBase * @this {ZlibBase}
* @returns {void} * @returns {void}
*/ */
ZlibBase.prototype.reset = function() { ZlibBase.prototype.reset = function() {
@ -291,13 +294,21 @@ ZlibBase.prototype.reset = function() {
return this._handle.reset(); return this._handle.reset();
}; };
// This is the _flush function called by the transform class, /**
// internally, when the last chunk has been written. * @this {ZlibBase}
* This is the _flush function called by the transform class,
* internally, when the last chunk has been written.
* @returns {void}
*/
ZlibBase.prototype._flush = function(callback) { ZlibBase.prototype._flush = function(callback) {
this._transform(Buffer.alloc(0), '', callback); this._transform(Buffer.alloc(0), '', callback);
}; };
// Force Transform compat behavior. /**
* @this {ZlibBase}
* Force Transform compat behavior.
* @returns {void}
*/
ZlibBase.prototype._final = function(callback) { ZlibBase.prototype._final = function(callback) {
callback(); callback();
}; };
@ -350,7 +361,7 @@ ZlibBase.prototype.flush = function(kind, callback) {
}; };
/** /**
* @this import('stream').Transform * @this {import('stream').Transform}
* @param {(err?: Error) => any} [callback] * @param {(err?: Error) => any} [callback]
*/ */
ZlibBase.prototype.close = function(callback) { ZlibBase.prototype.close = function(callback) {

View file

@ -8,12 +8,12 @@ const assert = require('assert');
* @name checkInvocations * @name checkInvocations
* @function * @function
* @param {object} activity including timestamps for each life time event, * @param {object} activity including timestamps for each life time event,
* i.e. init, before ... * i.e. init, before ...
* @param {object} hooks the expected life time event invocations with a count * @param {object} hooks the expected life time event invocations with a count
* indicating how often they should have been invoked, * indicating how often they should have been invoked,
* i.e. `{ init: 1, before: 2, after: 2 }` * i.e. `{ init: 1, before: 2, after: 2 }`
* @param {string} stage the name of the stage in the test at which we are * @param {string} stage the name of the stage in the test at which we are
* checking the invocations * checking the invocations
*/ */
exports.checkInvocations = function checkInvocations(activity, hooks, stage) { exports.checkInvocations = function checkInvocations(activity, hooks, stage) {
const stageInfo = `Checking invocations at stage "${stage}":\n `; const stageInfo = `Checking invocations at stage "${stage}":\n `;

View file

@ -223,9 +223,9 @@ function validateSnapshotNodes(...args) {
* https://chromium.googlesource.com/v8/v8/+/b00e995fb212737802810384ba2b868d0d92f7e5/test/unittests/heap/cppgc-js/unified-heap-snapshot-unittest.cc#134 * https://chromium.googlesource.com/v8/v8/+/b00e995fb212737802810384ba2b868d0d92f7e5/test/unittests/heap/cppgc-js/unified-heap-snapshot-unittest.cc#134
* @param {object[]} nodes Snapshot nodes returned by createJSHeapSnapshot() or a subset filtered from it. * @param {object[]} nodes Snapshot nodes returned by createJSHeapSnapshot() or a subset filtered from it.
* @param {string} rootName Name of the root node. Typically a class name used to filter all native nodes with * @param {string} rootName Name of the root node. Typically a class name used to filter all native nodes with
* this name. For cppgc-managed objects, this is typically the name configured by * this name. For cppgc-managed objects, this is typically the name configured by
* SET_CPPGC_NAME() prefixed with an additional "Node /" prefix e.g. * SET_CPPGC_NAME() prefixed with an additional "Node /" prefix e.g.
* "Node / ContextifyScript" * "Node / ContextifyScript"
* @param {[{ * @param {[{
* node_name?: string, * node_name?: string,
* edge_name?: string, * edge_name?: string,
@ -234,8 +234,8 @@ function validateSnapshotNodes(...args) {
* }]} retainingPath The retaining path specification to search from the root nodes. * }]} retainingPath The retaining path specification to search from the root nodes.
* @param {boolean} allowEmpty Whether the function should fail if no matching nodes can be found. * @param {boolean} allowEmpty Whether the function should fail if no matching nodes can be found.
* @returns {[object]} All the leaf nodes matching the retaining path specification. If none can be found, * @returns {[object]} All the leaf nodes matching the retaining path specification. If none can be found,
* logs the nodes found in the last matching step of the path (if any), and throws an * logs the nodes found in the last matching step of the path (if any), and throws an
* assertion error. * assertion error.
*/ */
function validateByRetainingPathFromNodes(nodes, rootName, retainingPath, allowEmpty = false) { function validateByRetainingPathFromNodes(nodes, rootName, retainingPath, allowEmpty = false) {
let haystack = nodes.filter((n) => n.name === rootName && n.type !== 'string'); let haystack = nodes.filter((n) => n.name === rootName && n.type !== 'string');
@ -328,6 +328,7 @@ function getHeapSnapshotOptionTests() {
/** /**
* Similar to @see {validateByRetainingPathFromNodes} but creates the snapshot from scratch. * Similar to @see {validateByRetainingPathFromNodes} but creates the snapshot from scratch.
* @returns {object[]}
*/ */
function validateByRetainingPath(...args) { function validateByRetainingPath(...args) {
const nodes = createJSHeapSnapshot(); const nodes = createJSHeapSnapshot();

View file

@ -827,7 +827,7 @@ function spawnPromisified(...args) {
* values on tests which are skipped on Windows. * values on tests which are skipped on Windows.
* This function is meant to be used for tagged template strings. * This function is meant to be used for tagged template strings.
* @returns {[string, object | undefined]} An array that can be passed as * @returns {[string, object | undefined]} An array that can be passed as
* arguments to `exec` or `execSync`. * arguments to `exec` or `execSync`.
*/ */
function escapePOSIXShell(cmdParts, ...args) { function escapePOSIXShell(cmdParts, ...args) {
if (common.isWindows) { if (common.isWindows) {

View file

@ -550,6 +550,7 @@ function fires(promise, error, timeoutMs) {
* *
* This function provides a utility to wait until a inspector event for a certain * This function provides a utility to wait until a inspector event for a certain
* time. * time.
* @returns {Promise}
*/ */
function waitUntil(session, eventName, timeout = 1000) { function waitUntil(session, eventName, timeout = 1000) {
const resolvers = Promise.withResolvers(); const resolvers = Promise.withResolvers();

View file

@ -26,6 +26,7 @@ function getBrowserProperties() {
/** /**
* Return one of three expected values * Return one of three expected values
* https://github.com/web-platform-tests/wpt/blob/1c6ff12/tools/wptrunner/wptrunner/tests/test_update.py#L953-L958 * https://github.com/web-platform-tests/wpt/blob/1c6ff12/tools/wptrunner/wptrunner/tests/test_update.py#L953-L958
* @returns {'linux'|'mac'|'win'}
*/ */
function getOs() { function getOs() {
switch (os.type()) { switch (os.type()) {
@ -102,6 +103,7 @@ class WPTReport {
/** /**
* Get or create a ReportResult for a test spec. * Get or create a ReportResult for a test spec.
* @param {WPTTestSpec} spec * @param {WPTTestSpec} spec
* @returns {ReportResult}
*/ */
getResult(spec) { getResult(spec) {
const name = `/${spec.getRelativePath()}${spec.variant}`; const name = `/${spec.getRelativePath()}${spec.variant}`;
@ -113,6 +115,9 @@ class WPTReport {
return result; return result;
} }
/**
* @returns {void}
*/
write() { write() {
this.time_end = Date.now(); this.time_end = Date.now();
const results = Array.from(this.results.values()) const results = Array.from(this.results.values())
@ -191,8 +196,9 @@ class ResourceLoader {
/** /**
* Load a resource in test/fixtures/wpt specified with a URL * Load a resource in test/fixtures/wpt specified with a URL
* @param {string} from the path of the file loading this resource, * @param {string} from the path of the file loading this resource,
* relative to the WPT folder. * relative to the WPT folder.
* @param {string} url the url of the resource being loaded. * @param {string} url the url of the resource being loaded.
* @returns {string}
*/ */
read(from, url) { read(from, url) {
const file = this.toRealFilePath(from, url); const file = this.toRealFilePath(from, url);
@ -202,8 +208,14 @@ class ResourceLoader {
/** /**
* Load a resource in test/fixtures/wpt specified with a URL * Load a resource in test/fixtures/wpt specified with a URL
* @param {string} from the path of the file loading this resource, * @param {string} from the path of the file loading this resource,
* relative to the WPT folder. * relative to the WPT folder.
* @param {string} url the url of the resource being loaded. * @param {string} url the url of the resource being loaded.
* @returns {Promise<{
* ok: string,
* arrayBuffer: function(): Buffer,
* json: function(): object,
* text: function(): string,
* }>}
*/ */
async readAsFetch(from, url) { async readAsFetch(from, url) {
const file = this.toRealFilePath(from, url); const file = this.toRealFilePath(from, url);
@ -284,9 +296,9 @@ class WPTTestSpec {
/** /**
* @param {string} mod name of the WPT module, e.g. * @param {string} mod name of the WPT module, e.g.
* 'html/webappapis/microtask-queuing' * 'html/webappapis/microtask-queuing'
* @param {string} filename path of the test, relative to mod, e.g. * @param {string} filename path of the test, relative to mod, e.g.
* 'test.any.js' * 'test.any.js'
* @param {StatusRule[]} rules * @param {StatusRule[]} rules
* @param {string} variant test file variant * @param {string} variant test file variant
*/ */
@ -326,6 +338,7 @@ class WPTTestSpec {
* @param {string} mod * @param {string} mod
* @param {string} filename * @param {string} filename
* @param {StatusRule[]} rules * @param {StatusRule[]} rules
* @returns {ReturnType<WPTTestSpec['getMeta']>[]}
*/ */
static from(mod, filename, rules) { static from(mod, filename, rules) {
const spec = new WPTTestSpec(mod, filename, rules); const spec = new WPTTestSpec(mod, filename, rules);
@ -436,6 +449,7 @@ class StatusLoader {
/** /**
* Grep for all .*.js file recursively in a directory. * Grep for all .*.js file recursively in a directory.
* @param {string} dir * @param {string} dir
* @returns {any[]}
*/ */
grep(dir) { grep(dir) {
let result = []; let result = [];
@ -561,6 +575,7 @@ class WPTRunner {
/** /**
* @param {WPTTestSpec} spec * @param {WPTTestSpec} spec
* @returns {string}
*/ */
fullInitScript(spec) { fullInitScript(spec) {
const url = new URL(`/${spec.getRelativePath().replace(/\.js$/, '.html')}${spec.variant}`, 'http://wpt'); const url = new URL(`/${spec.getRelativePath().replace(/\.js$/, '.html')}${spec.variant}`, 'http://wpt');
@ -803,7 +818,7 @@ class WPTRunner {
* Report the status of each specific test case (there could be multiple * Report the status of each specific test case (there could be multiple
* in one test file). * in one test file).
* @param {WPTTestSpec} spec * @param {WPTTestSpec} spec
* @param {Test} test The Test object returned by WPT harness * @param {Test} test The Test object returned by WPT harness
* @param {ReportResult} reportResult The report result object * @param {ReportResult} reportResult The report result object
*/ */
resultCallback(spec, test, reportResult) { resultCallback(spec, test, reportResult) {

View file

@ -11,6 +11,7 @@ const { test, suite } = require('node:test');
/** /**
* Convenience wrapper around assert.deepStrictEqual that sets a null * Convenience wrapper around assert.deepStrictEqual that sets a null
* prototype to the expected object. * prototype to the expected object.
* @returns {boolean}
*/ */
function deepStrictEqual(t) { function deepStrictEqual(t) {
return (actual, expected, message) => { return (actual, expected, message) => {

View file

@ -1,6 +1,6 @@
/** /**
* @fileoverview Check that common.hasCrypto is used if crypto, tls, * @file Check that common.hasCrypto is used if crypto, tls,
* https, or http2 modules are required. * https, or http2 modules are required.
* @author Daniel Bevenius <daniel.bevenius@gmail.com> * @author Daniel Bevenius <daniel.bevenius@gmail.com>
*/ */
'use strict'; 'use strict';

View file

@ -1,6 +1,6 @@
/** /**
* @fileoverview Check that common.skipIfEslintMissing is used if * @file Check that common.skipIfEslintMissing is used if
* the eslint module is required. * the eslint module is required.
*/ */
'use strict'; 'use strict';

View file

@ -1,6 +1,6 @@
/** /**
* @fileoverview Check that common.skipIfInspectorDisabled is used if * @file Check that common.skipIfInspectorDisabled is used if
* the inspector module is required. * the inspector module is required.
* @author Daniel Bevenius <daniel.bevenius@gmail.com> * @author Daniel Bevenius <daniel.bevenius@gmail.com>
*/ */
'use strict'; 'use strict';

View file

@ -1,6 +1,6 @@
/** /**
* @fileoverview Check that TypeError[ERR_INVALID_ARG_TYPE] uses * @file Check that TypeError[ERR_INVALID_ARG_TYPE] uses
* lowercase for primitive types * lowercase for primitive types
* @author Weijia Wang <starkwang@126.com> * @author Weijia Wang <starkwang@126.com>
*/ */
'use strict'; 'use strict';

View file

@ -1,12 +1,12 @@
/** /**
* @fileoverview Iterating over arrays should be avoided because it relies on * @file Iterating over arrays should be avoided because it relies on
* user-mutable global methods (`Array.prototype[Symbol.iterator]` * user-mutable global methods (`Array.prototype[Symbol.iterator]`
* and `%ArrayIteratorPrototype%.next`), we should instead use * and `%ArrayIteratorPrototype%.next`), we should instead use
* other alternatives. This file defines a rule that disallow * other alternatives. This file defines a rule that disallow
* array destructuring syntax in favor of object destructuring * array destructuring syntax in favor of object destructuring
* syntax. Note that you can ignore this rule if you are using * syntax. Note that you can ignore this rule if you are using
* the array destructuring syntax over a safe iterable, or * the array destructuring syntax over a safe iterable, or
* actually want to iterate over a user-provided object. * actually want to iterate over a user-provided object.
* @author aduh95 <duhamelantoine1995@gmail.com> * @author aduh95 <duhamelantoine1995@gmail.com>
*/ */
'use strict'; 'use strict';

View file

@ -1,5 +1,5 @@
/** /**
* @fileoverview Ensure modules are not required twice at top level of a module * @file Ensure modules are not required twice at top level of a module
* @author devsnek * @author devsnek
* @author RedYetiDev * @author RedYetiDev
*/ */

View file

@ -1,5 +1,5 @@
/** /**
* @fileoverview Look for unescaped "literal" dots in regular expressions * @file Look for unescaped "literal" dots in regular expressions
* @author Brian White * @author Brian White
*/ */
'use strict'; 'use strict';

View file

@ -1,7 +1,7 @@
/** /**
* @fileOverview Any non-ASCII characters in lib/ will increase the size * @file Any non-ASCII characters in lib/ will increase the size
* of the compiled node binary. This linter rule ensures that * of the compiled node binary. This linter rule ensures that
* any such character is reported. * any such character is reported.
* @author Sarat Addepalli <sarat.addepalli@gmail.com> * @author Sarat Addepalli <sarat.addepalli@gmail.com>
*/ */

View file

@ -1,5 +1,5 @@
/** /**
* @fileoverview Prohibit the `if (err) throw err;` pattern * @file Prohibit the `if (err) throw err;` pattern
* @author Teddy Katz * @author Teddy Katz
*/ */

View file

@ -1,5 +1,5 @@
/** /**
* @fileoverview Prohibit the use of assert operators ( ===, !==, ==, != ) * @file Prohibit the use of assert operators ( ===, !==, ==, != )
*/ */
'use strict'; 'use strict';

View file

@ -1,5 +1,5 @@
/** /**
* @fileoverview Prefer common.mustNotCall(msg) over common.mustCall(fn, 0) * @file Prefer common.mustNotCall(msg) over common.mustCall(fn, 0)
* @author James M Snell <jasnell@gmail.com> * @author James M Snell <jasnell@gmail.com>
*/ */
'use strict'; 'use strict';

View file

@ -1,7 +1,7 @@
/** /**
* @fileoverview We shouldn't use global built-in object for security and * @file We shouldn't use global built-in object for security and
* performance reason. This linter rule reports replaceable codes * performance reason. This linter rule reports replaceable codes
* that can be replaced with primordials. * that can be replaced with primordials.
* @author Leko <leko.noor@gmail.com> * @author Leko <leko.noor@gmail.com>
*/ */
'use strict'; 'use strict';
@ -18,10 +18,16 @@ function toUcFirst(str) {
return str[0].toUpperCase() + str.slice(1); return str[0].toUpperCase() + str.slice(1);
} }
/**
* @returns {boolean}
*/
function isTarget(map, varName) { function isTarget(map, varName) {
return map.has(varName); return map.has(varName);
} }
/**
* @returns {boolean}
*/
function isIgnored(map, varName, propName) { function isIgnored(map, varName, propName) {
return map.get(varName)?.get(propName)?.ignored ?? false; return map.get(varName)?.get(propName)?.ignored ?? false;
} }
@ -38,10 +44,7 @@ function getReportName({ name, parentName, into }) {
/** /**
* Get identifier of object spread assignment * Get identifier of object spread assignment
* * @returns {null | object}
* code: 'const { ownKeys } = Reflect;'
* argument: 'ownKeys'
* return: 'Reflect'
*/ */
function getDestructuringAssignmentParent(scope, node) { function getDestructuringAssignmentParent(scope, node) {
const declaration = scope.set.get(node.name); const declaration = scope.set.get(node.name);

View file

@ -1,7 +1,7 @@
/** /**
* @fileoverview null objects can be created with `ObjectCreate(null)`, or with * @file null objects can be created with `ObjectCreate(null)`, or with
* syntax: `{ __proto__: null }`. This linter rule forces use of * syntax: `{ __proto__: null }`. This linter rule forces use of
* syntax over ObjectCreate. * syntax over ObjectCreate.
* @author Jordan Harband <ljharb@gmail.com> * @author Jordan Harband <ljharb@gmail.com>
*/ */
'use strict'; 'use strict';

View file

@ -1,5 +1,5 @@
/** /**
* @fileoverview Require `common` module first in our tests. * @file Require `common` module first in our tests.
*/ */
'use strict'; 'use strict';

View file

@ -1,5 +1,5 @@
/** /**
* @fileoverview Require usage of specified node modules. * @file Require usage of specified node modules.
* @author Rich Trott * @author Rich Trott
*/ */
'use strict'; 'use strict';

View file

@ -3,15 +3,24 @@
*/ */
'use strict'; 'use strict';
/**
* @returns {boolean}
*/
function isRequireCall(node) { function isRequireCall(node) {
return node.callee.type === 'Identifier' && node.callee.name === 'require'; return node.callee.type === 'Identifier' && node.callee.name === 'require';
} }
module.exports.isRequireCall = isRequireCall; module.exports.isRequireCall = isRequireCall;
/**
* @returns {boolean}
*/
module.exports.isString = function(node) { module.exports.isString = function(node) {
return node && node.type === 'Literal' && typeof node.value === 'string'; return node && node.type === 'Literal' && typeof node.value === 'string';
}; };
/**
* @returns {boolean}
*/
module.exports.isDefiningError = function(node) { module.exports.isDefiningError = function(node) {
return node.expression && return node.expression &&
node.expression.type === 'CallExpression' && node.expression.type === 'CallExpression' &&
@ -20,6 +29,9 @@ module.exports.isDefiningError = function(node) {
node.expression.arguments.length !== 0; node.expression.arguments.length !== 0;
}; };
/**
* @returns {boolean}
*/
module.exports.isDefiningDeprecation = function(node) { module.exports.isDefiningDeprecation = function(node) {
return node.expression && return node.expression &&
node.expression.type === 'CallExpression' && node.expression.type === 'CallExpression' &&
@ -31,17 +43,19 @@ module.exports.isDefiningDeprecation = function(node) {
/** /**
* Returns true if any of the passed in modules are used in * Returns true if any of the passed in modules are used in
* require calls. * require calls.
* @returns {boolean}
*/ */
module.exports.isRequired = function(node, modules) { module.exports.isRequired = function(node, modules) {
return isRequireCall(node) && node.arguments.length !== 0 && return isRequireCall(node) && node.arguments.length !== 0 &&
modules.includes(node.arguments[0].value); modules.includes(node.arguments[0].value);
}; };
const commonModuleRegExp = new RegExp(/^(\.\.\/)*common(\.js)?$/);
/** /**
* Return true if common module is required * Return true if common module is required
* in AST Node under inspection * in AST Node under inspection
* @returns {boolean}
*/ */
const commonModuleRegExp = new RegExp(/^(\.\.\/)*common(\.js)?$/);
module.exports.isCommonModule = function(node) { module.exports.isCommonModule = function(node) {
return isRequireCall(node) && return isRequireCall(node) &&
node.arguments.length !== 0 && node.arguments.length !== 0 &&
@ -51,6 +65,7 @@ module.exports.isCommonModule = function(node) {
/** /**
* Returns true if any of the passed in modules are used in * Returns true if any of the passed in modules are used in
* process.binding() or internalBinding() calls. * process.binding() or internalBinding() calls.
* @returns {boolean}
*/ */
module.exports.isBinding = function(node, modules) { module.exports.isBinding = function(node, modules) {
const isProcessBinding = node.callee.object && const isProcessBinding = node.callee.object &&
@ -64,6 +79,7 @@ module.exports.isBinding = function(node, modules) {
/** /**
* Returns true is the node accesses any property in the properties * Returns true is the node accesses any property in the properties
* array on the 'common' object. * array on the 'common' object.
* @returns {boolean}
*/ */
module.exports.usesCommonProperty = function(node, properties) { module.exports.usesCommonProperty = function(node, properties) {
if (node.name) { if (node.name) {
@ -78,6 +94,7 @@ module.exports.usesCommonProperty = function(node, properties) {
/** /**
* Returns true if the passed in node is inside an if statement block, * Returns true if the passed in node is inside an if statement block,
* and the block also has a call to skip. * and the block also has a call to skip.
* @returns {boolean}
*/ */
module.exports.inSkipBlock = function(node) { module.exports.inSkipBlock = function(node) {
let hasSkipBlock = false; let hasSkipBlock = false;
@ -99,6 +116,9 @@ module.exports.inSkipBlock = function(node) {
return hasSkipBlock; return hasSkipBlock;
}; };
/**
* @returns {boolean}
*/
function hasSkip(expression) { function hasSkip(expression) {
return expression?.callee?.name === 'skip' || expression?.callee?.property?.name === 'skip'; return expression?.callee?.name === 'skip' || expression?.callee?.property?.name === 'skip';
} }

View file

@ -140,7 +140,7 @@ void calculatePackageName(UErrorCode* status) {
* Assumes calculatePackageName was called. * Assumes calculatePackageName was called.
* @param exists set to TRUE if exists, FALSE otherwise. * @param exists set to TRUE if exists, FALSE otherwise.
* Changed from reference to pointer to match node.js style * Changed from reference to pointer to match node.js style
* @return 0 on "OK" (success or resource-missing), * @returns 0 on "OK" (success or resource-missing),
* 1 on "FAILURE" (unexpected error) * 1 on "FAILURE" (unexpected error)
*/ */
int localeExists(const char* loc, UBool* exists) { int localeExists(const char* loc, UBool* exists) {
@ -187,7 +187,7 @@ void printIndent(FILE* bf, int indent) {
/** /**
* Dumps a table resource contents * Dumps a table resource contents
* if lev==0, skips INSTALLEDLOCALES * if lev==0, skips INSTALLEDLOCALES
* @return 0 for OK, 1 for err * @returns 0 for OK, 1 for err
*/ */
int dumpAllButInstalledLocales(int lev, int dumpAllButInstalledLocales(int lev,
icu::LocalUResourceBundlePointer* bund, icu::LocalUResourceBundlePointer* bund,